diff --git "a/058.jsonl" "b/058.jsonl" new file mode 100644--- /dev/null +++ "b/058.jsonl" @@ -0,0 +1,453 @@ +{"seq_id": "27037074643", "text": "# skip_gram, low-level로 구현하기\n\"\"\"\nskipgram 실습 과제\n1. 영어소설 corpus, gutenberg corpus -> 영어소설 10개\n2. working, worked => 1단어인 work로 사용\n3. vocabulary 생성\n4. 소설 문장을 하나씩 읽어서 tri-gram 생성\n5. tri-gram으로 학습 데이터 생성 \n입력 출력\nlove I\nlove you\n\n6. 각 단어를 vocabulary의 index로 표현 (ex) love = 32 index로 표현. 이후 one-hot encoding\n7. 네트워크 구성 - input_dim = vocab_size\nword vector size 32\n8. 단어의 one-hot을 입력하면 -> 은닉층 출력\n9. father, mother, doctor 의 word vector 를 구하고 각 벡터끼리의 코사인 유사도 구하기\n\"\"\"\nfrom nltk.stem import LancasterStemmer\nimport nltk\nfrom sklearn.metrics.pairwise import cosine_similarity\nimport numpy as np\nimport pandas as pd\nfrom tensorflow.keras.layers import Input, Dense, Embedding, Flatten\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.optimizers import Adam\n\nnltk.download('punkt')\nnltk.download('gutenberg')\ntext_id = nltk.corpus.gutenberg.fileids()\nprint(text_id)\n\n# 영어 소설 10개 불러오기\ntext1 = nltk.corpus.gutenberg.raw('austen-emma.txt')\ntext2 = nltk.corpus.gutenberg.raw('austen-persuasion.txt')\ntext3 = nltk.corpus.gutenberg.raw('austen-sense.txt')\ntext4 = nltk.corpus.gutenberg.raw('bible-kjv.txt')\ntext5 = nltk.corpus.gutenberg.raw('blake-poems.txt')\ntext6 = nltk.corpus.gutenberg.raw('bryant-stories.txt')\ntext7 = nltk.corpus.gutenberg.raw('burgess-busterbrown.txt')\ntext8 = nltk.corpus.gutenberg.raw('carroll-alice.txt')\ntext9 = nltk.corpus.gutenberg.raw('chesterton-ball.txt')\ntext10 = nltk.corpus.gutenberg.raw('chesterton-brown.txt')\n\ntext = text1 + ' ' + text2 + ' ' + text3 + ' ' + text4 + ' ' + text5 + ' ' + text6 + ' ' + text7 + ' ' + text8 + ' ' + text9 + ' ' + text10\n\nsentences = nltk.sent_tokenize(text)\nprint(len(sentences))\nprint(sentences[:10])\n\nsen = []\nfor s in sentences:\n s = s.replace('\\n', ' ').replace(\"'\", '').replace('.', '').replace('-', '').replace('!', '').replace('?', '').replace(';', '').replace(',', '').replace('_', '').replace('(', '').replace(')', '').replace(':', '').replace('\"', \"\").replace('[', '').replace(']', '').strip().lower()\n sen.append(s)\n\nstemmer = LancasterStemmer()\nword_tokens = [nltk.word_tokenize(s) for s in sen]\nprint(word_tokens[0])\n\n# stemming을 진행해서 stem 리스트에 저장\nstem = []\ntmp = []\nfor s in word_tokens:\n for t in s:\n tmp.append(stemmer.stem(t))\n stem.append(tmp)\n tmp = []\n\n# trigram을 만들 때 문장의 길이가 3 미만인 경우 에러가 발생하므로 삭제\nfor s in stem:\n if len(s) < 3:\n stem.remove(s)\nprint(len(stem))\n\n# 전체 단어 사전 생성\nall_tokens = []\nfor s in stem:\n for t in s:\n all_tokens.append(t)\nprint(len(all_tokens))\n\n# word -> idx\nfrom tensorflow.keras.preprocessing.text import Tokenizer\n\ntokenizer = Tokenizer()\ntokenizer.fit_on_texts(all_tokens)\n\nword2idx = tokenizer.word_index\nidx2word = {v:k for k, v in word2idx.items()}\n\nto_idx = tokenizer.texts_to_sequences(stem)\n\n# 문장 별로 trigram 생성\ntrigram = []\ntmp = []\nfor s in to_idx:\n # trigram을 만들 수 없는 경우 (1388, 21, None)으로 패딩 pad_right=True\n for a, b, c in nltk.ngrams(s, 3, pad_right=True): \n tmp.append((a, b, c))\n trigram.append(tmp)\n tmp = []\nlen(trigram)\n\n# input 데이터 만들기\ninput = []\noutput = []\n\nfor i in range(len(trigram)):\n for j in range(len(trigram[i])):\n for k in range(2):\n input.append(trigram[i][j][1])\n\n\nprint(input[:200])\n\n# output 데이터 만들기\nfor i in range(len(trigram)):\n for j in range(len(trigram[i])):\n for k in range(0, 3, 2):\n output.append(trigram[i][j][k])\n \nprint(output[:200])\n\ndf = pd.DataFrame({\n 'input' : input,\n 'output' : output\n})\nprint(df)\n\n# 결측값 제거(Nan값 있는 행 제거)\ndf.dropna(axis=0, inplace=True)\n\n# 데이터셋 구성\nX_train = np.array(df['input']).reshape(-1, 1)\ny_train = np.array(df['output']).reshape(-1, 1)\nvocab_size = len(word2idx)+1 # word2idx가 0부터 시작했다면 +1을 안해줘도 됨. Embedding layer는 0부터 처리하므로 +1을 해준다.\nX_train.shape\n\nx_input= Input(batch_shape = (None, X_train.shape[1]))\nhidden = Embedding(input_dim = vocab_size, output_dim = 32)(x_input)\nhidden = Flatten()(hidden)\ny_output = Dense(vocab_size, activation='softmax')(hidden)\n\nmodel = Model(x_input, y_output)\nmodel.compile(loss='sparse_categorical_crossentropy', optimizer=Adam(learning_rate=0.01))\n\n# word --> word2vec을 확인하기 위한 모델 (predict용 모델)\nmodel_w = Model(x_input, hidden)\n\nmodel.summary()\n\nhist = model.fit(X_train, y_train, epochs=30, batch_size=4096, validation_split=0.2)\n\n# father에 stem이 적용됐으므로 idx값을 찾을 때도 stem을 적용해서 찾아야함.\nfather = model_w.predict(np.array(word2idx[stemmer.stem('father')]).reshape(1, 1))\nprint(father)\n\nmother = model_w.predict(np.array(word2idx[stemmer.stem('mother')]).reshape(1, 1))\nprint(mother)\n\ndoctor = model_w.predict(np.array(word2idx[stemmer.stem('doctor')]).reshape(1, 1))\nprint(doctor)\n\nfather_mother = cosine_similarity(mother, father)\nprint(father_mother)\n\nmother_doctor = cosine_similarity(mother, doctor)\nprint(mother_doctor)\n\nfather_doctor = cosine_similarity(father, doctor)\nprint(father_doctor)\n\nprint(father + mother)\n", "repo_name": "dobbytk/NLP_study", "sub_path": "Multicampus/NLP/day21/skip_gram(w2v).py", "file_name": "skip_gram(w2v).py", "file_ext": "py", "file_size_in_byte": 5334, "program_lang": "python", "lang": "ko", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "nltk.download", "line_number": 28, "usage_type": "call"}, {"api_name": "nltk.download", "line_number": 29, "usage_type": "call"}, {"api_name": "nltk.corpus.gutenberg.fileids", "line_number": 30, "usage_type": "call"}, {"api_name": "nltk.corpus", "line_number": 30, "usage_type": "attribute"}, {"api_name": "nltk.corpus.gutenberg.raw", "line_number": 34, "usage_type": "call"}, {"api_name": "nltk.corpus", "line_number": 34, "usage_type": "attribute"}, {"api_name": "nltk.corpus.gutenberg.raw", "line_number": 35, "usage_type": "call"}, {"api_name": "nltk.corpus", "line_number": 35, "usage_type": "attribute"}, {"api_name": "nltk.corpus.gutenberg.raw", "line_number": 36, "usage_type": "call"}, {"api_name": "nltk.corpus", "line_number": 36, "usage_type": "attribute"}, {"api_name": "nltk.corpus.gutenberg.raw", "line_number": 37, "usage_type": "call"}, {"api_name": "nltk.corpus", "line_number": 37, "usage_type": "attribute"}, {"api_name": "nltk.corpus.gutenberg.raw", "line_number": 38, "usage_type": "call"}, {"api_name": "nltk.corpus", "line_number": 38, "usage_type": "attribute"}, {"api_name": "nltk.corpus.gutenberg.raw", "line_number": 39, "usage_type": "call"}, {"api_name": "nltk.corpus", "line_number": 39, "usage_type": "attribute"}, {"api_name": "nltk.corpus.gutenberg.raw", "line_number": 40, "usage_type": "call"}, {"api_name": "nltk.corpus", "line_number": 40, "usage_type": "attribute"}, {"api_name": "nltk.corpus.gutenberg.raw", "line_number": 41, "usage_type": "call"}, {"api_name": "nltk.corpus", "line_number": 41, "usage_type": "attribute"}, {"api_name": "nltk.corpus.gutenberg.raw", "line_number": 42, "usage_type": "call"}, {"api_name": "nltk.corpus", "line_number": 42, "usage_type": "attribute"}, {"api_name": "nltk.corpus.gutenberg.raw", "line_number": 43, "usage_type": "call"}, {"api_name": "nltk.corpus", "line_number": 43, "usage_type": "attribute"}, {"api_name": "nltk.sent_tokenize", "line_number": 47, "usage_type": "call"}, {"api_name": "nltk.stem.LancasterStemmer", "line_number": 56, "usage_type": "call"}, {"api_name": "nltk.word_tokenize", "line_number": 57, "usage_type": "call"}, {"api_name": "tensorflow.keras.preprocessing.text.Tokenizer", "line_number": 85, "usage_type": "call"}, {"api_name": "nltk.ngrams", "line_number": 98, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 124, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 134, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 135, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.Input", "line_number": 139, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.Embedding", "line_number": 140, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.Flatten", "line_number": 141, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.Dense", "line_number": 142, "usage_type": "call"}, {"api_name": "tensorflow.keras.models.Model", "line_number": 144, "usage_type": "call"}, {"api_name": "tensorflow.keras.optimizers.Adam", "line_number": 145, "usage_type": "call"}, {"api_name": "tensorflow.keras.models.Model", "line_number": 148, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 155, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 158, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 161, "usage_type": "call"}, {"api_name": "sklearn.metrics.pairwise.cosine_similarity", "line_number": 164, "usage_type": "call"}, {"api_name": "sklearn.metrics.pairwise.cosine_similarity", "line_number": 167, "usage_type": "call"}, {"api_name": "sklearn.metrics.pairwise.cosine_similarity", "line_number": 170, "usage_type": "call"}]} +{"seq_id": "3714575578", "text": "import torch\r\nimport torch.utils.data as data\r\nimport numpy as np\r\n\r\n\r\nclass Dataset(data.Dataset):\r\n # characterizes a dataset for PyTorch\r\n def __init__(self, list_IDs, pairs, labels, embeddings):\r\n self.list_IDs = list_IDs\r\n self.labels = labels\r\n self.pairs = pairs\r\n self.embeddings = embeddings\r\n\r\n def __len__(self):\r\n return len(self.list_IDs)\r\n\r\n def __getitem__(self, index):\r\n # generates one sample of data\r\n # select sample\r\n ID = self.list_IDs[index]\r\n # data = np.load(r\"H:\\embeddings\\embeddings.npz\")\r\n x1 = self.pairs[ID][0]\r\n x1_t = torch.Tensor(self.embeddings[x1])\r\n x2 = self.pairs[ID][1]\r\n x2_t = torch.Tensor(self.embeddings[x2])\r\n # load data and get label\r\n y = self.labels[ID]\r\n\r\n return x1_t, x2_t, torch.from_numpy(np.array([y], dtype=np.float32))\r\n", "repo_name": "kmmbd/PPI_OneShot", "sub_path": "dataset/loader.py", "file_name": "loader.py", "file_ext": "py", "file_size_in_byte": 901, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "21", "api": [{"api_name": "torch.utils.data.Dataset", "line_number": 6, "usage_type": "attribute"}, {"api_name": "torch.utils.data", "line_number": 6, "usage_type": "name"}, {"api_name": "torch.Tensor", "line_number": 23, "usage_type": "call"}, {"api_name": "torch.Tensor", "line_number": 25, "usage_type": "call"}, {"api_name": "torch.from_numpy", "line_number": 29, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 29, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 29, "usage_type": "attribute"}]} +{"seq_id": "70738086133", "text": "from django.contrib.auth.models import User\nfrom rest_framework import serializers\n\nfrom tasks.models import ChangeOfStatus, Status, Task, Notification, Check\n\nfrom .tasks import send_notification_by_time_to_email\n\n\nclass UserSerializer(serializers.ModelSerializer):\n class Meta:\n model = User\n fields = ('pk', 'username', 'first_name', 'last_name', 'email')\n\n\nclass CheckListSerializer(serializers.ModelSerializer):\n\n class Meta:\n model = Check\n fields = ('pk', 'name', 'done')\n extra_kwargs = {\n 'pk': {'read_only': True}\n }\n\n\nclass StatusSerializer(serializers.ModelSerializer):\n\n class Meta:\n model = Status\n fields = ('pk', 'name')\n\n\nclass NewTaskSerializer(serializers.ModelSerializer):\n check_list = CheckListSerializer(many=True, required=False)\n\n class Meta:\n model = Task\n fields = ('pk',\n 'name',\n 'description',\n 'performer',\n 'observers',\n 'status',\n 'start_time',\n 'end_time',\n 'planned_completion_time',\n 'check_list')\n extra_kwargs = {\n 'pk': {'read_only': True}\n }\n\n def create_check_list(self, task, check_list):\n print(check_list)\n Check.objects.bulk_create([\n Check(task=task, **d) for d in check_list\n ])\n\n def create(self, validated_data):\n check_list = validated_data.pop('check_list', [])\n task = super().create(validated_data)\n self.create_check_list(task, check_list)\n return task\n\n def update(self, instance, validated_data):\n status = validated_data.get('status', None)\n request = self.context.get('request', None)\n if request:\n user = request.user\n if status and status != instance.status:\n observer_users = instance.observers.all()\n text = \"изменен статус на \" + status.name\n\n ChangeOfStatus.objects.create(\n last_status=instance.status,\n next_status=status,\n task=instance,\n changed_by_whom=user\n )\n\n notification = Notification.objects.create(\n task=instance,\n reminder_text=text\n )\n notification.list_of_users_for_whom_this_notification.add(\n *observer_users)\n\n users_email = [user.email for user in observer_users]\n send_notification_by_time_to_email.delay(users_email, text)\n\n return super().update(instance, validated_data)\n\n\nclass TaskSerializer(serializers.ModelSerializer):\n performer = UserSerializer(read_only=True)\n observers = UserSerializer(read_only=True, many=True)\n status = StatusSerializer(read_only=True)\n check_list = CheckListSerializer(many=True, read_only=True)\n\n class Meta:\n model = Task\n fields = ('pk',\n 'name',\n 'description',\n 'performer',\n 'observers',\n 'status',\n 'start_time',\n 'end_time',\n 'planned_completion_time',\n 'check_list')\n# {\n# \"name\": \"12345678\",\n# \"description\": \"kdslknslfgn\",\n# \"performer\": 3,\n# \"observers\": [\n# 2\n# ],\n# \"status\": 1,\n# \"start_time\": \"2021-04-23T03:50:00Z\",\n# \"end_time\": \"2021-04-23T03:50:00Z\",\n# \"planned_completion_time\": \"2021-04-23T03:50:00Z\",\n# \"check_list\": [\n# {\"name\":\"sdfgh\"},\n# {\"name\":\"edrftgyhuj\"},\n# {\"name\":\"123124\"}\n# ]\n# }", "repo_name": "yerkebulan19971212/KitSystem", "sub_path": "tasks/serializer.py", "file_name": "serializer.py", "file_ext": "py", "file_size_in_byte": 3691, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "rest_framework.serializers.ModelSerializer", "line_number": 9, "usage_type": "attribute"}, {"api_name": "rest_framework.serializers", "line_number": 9, "usage_type": "name"}, {"api_name": "django.contrib.auth.models.User", "line_number": 11, "usage_type": "name"}, {"api_name": "rest_framework.serializers.ModelSerializer", "line_number": 15, "usage_type": "attribute"}, {"api_name": "rest_framework.serializers", "line_number": 15, "usage_type": "name"}, {"api_name": "tasks.models.Check", "line_number": 18, "usage_type": "name"}, {"api_name": "rest_framework.serializers.ModelSerializer", "line_number": 25, "usage_type": "attribute"}, {"api_name": "rest_framework.serializers", "line_number": 25, "usage_type": "name"}, {"api_name": "tasks.models.Status", "line_number": 28, "usage_type": "name"}, {"api_name": "rest_framework.serializers.ModelSerializer", "line_number": 32, "usage_type": "attribute"}, {"api_name": "rest_framework.serializers", "line_number": 32, "usage_type": "name"}, {"api_name": "tasks.models.Task", "line_number": 36, "usage_type": "name"}, {"api_name": "tasks.models.Check.objects.bulk_create", "line_number": 53, "usage_type": "call"}, {"api_name": "tasks.models.Check.objects", "line_number": 53, "usage_type": "attribute"}, {"api_name": "tasks.models.Check", "line_number": 53, "usage_type": "name"}, {"api_name": "tasks.models.Check", "line_number": 54, "usage_type": "call"}, {"api_name": "tasks.models.ChangeOfStatus.objects.create", "line_number": 72, "usage_type": "call"}, {"api_name": "tasks.models.ChangeOfStatus.objects", "line_number": 72, "usage_type": "attribute"}, {"api_name": "tasks.models.ChangeOfStatus", "line_number": 72, "usage_type": "name"}, {"api_name": "tasks.models.Notification.objects.create", "line_number": 79, "usage_type": "call"}, {"api_name": "tasks.models.Notification.objects", "line_number": 79, "usage_type": "attribute"}, {"api_name": "tasks.models.Notification", "line_number": 79, "usage_type": "name"}, {"api_name": "tasks.send_notification_by_time_to_email.delay", "line_number": 87, "usage_type": "call"}, {"api_name": "tasks.send_notification_by_time_to_email", "line_number": 87, "usage_type": "name"}, {"api_name": "rest_framework.serializers.ModelSerializer", "line_number": 92, "usage_type": "attribute"}, {"api_name": "rest_framework.serializers", "line_number": 92, "usage_type": "name"}, {"api_name": "tasks.models.Task", "line_number": 99, "usage_type": "name"}]} +{"seq_id": "71540103093", "text": "from pyspark import SparkContext, SQLContext\r\nfrom itertools import chain\r\nfrom pyspark.ml import PipelineModel, Pipeline\r\nimport pyspark\r\nimport pyspark.sql.functions as f\r\nfrom pyspark.sql.types import *\r\nfrom pyspark.ml.tuning import CrossValidatorModel\r\nfrom pyspark.sql import SparkSession\r\nfrom pyspark.sql.functions import split, decode, substring\r\nfrom pyspark.ml.evaluation import MulticlassClassificationEvaluator\r\nfrom pyspark.sql.functions import from_json, udf, split\r\nfrom kafka import KafkaConsumer\r\nimport json\r\nimport pandas as pd\r\nfrom sparknlp import *\r\nprint(pyspark.__version__)\r\n\r\nmyschema = StructType([StructField('id1', StringType(), True),\r\n StructField('ufc1', FloatType(), True),\r\n StructField('date', StringType(), True),\r\n StructField('ufc2', FloatType(), True),\r\n StructField('id2', StringType(), True),\r\n StructField('stars', FloatType(), True),\r\n StructField('text', StringType(), True),\r\n StructField('ufc3', FloatType(), True),\r\n StructField('id3', StringType(), True)])\r\n\r\ndef start_consuming():\r\n spark = SparkSession \\\r\n .builder \\\r\n .appName(\"YelpSub\") \\\r\n .config(\"spark.jars.packages\", \"com.johnsnowlabs.nlp:spark-nlp_2.12:3.4.4\")\\\r\n .getOrCreate()\r\n \r\n model = PipelineModel.load('LogReg_TFIDF_model_final')\r\n print('Done loading the model.')\r\n \r\n ctr = 0\r\n print('Spark session active.')\r\n consumer = KafkaConsumer('yelp-nlp', bootstrap_servers = ['localhost:9092'])\r\n for msg in consumer:\r\n message = json.loads(msg.value)\r\n df_line = pd.json_normalize(message)\r\n if ctr == 0:\r\n df = df_line.copy()\r\n df_line = spark.createDataFrame(df_line, schema = myschema)\r\n df = spark.createDataFrame(df, schema = myschema)\r\n else:\r\n df = df.toPandas()\r\n df = df.append(df_line, ignore_index= True)\r\n df_line = spark.createDataFrame(df_line, schema = myschema)\r\n df = spark.createDataFrame(df, schema = myschema)\r\n ctr += 1\r\n\r\n prediction = model.transform(df)\r\n prediction = prediction.select(['stars', 'prediction'])\r\n prediction.write.format(\"console\").save()\r\n output_df = prediction.withColumn(\"correct\", f.when((f.col('prediction')==1.0) & (f.col('stars')==1.0),1).when((f.col('prediction')==2.0) & (f.col('stars')==2.0),1).when((f.col('prediction')==3.0) & (f.col('stars')==3.0),1).when((f.col('prediction')==4.0) & (f.col('stars')==4.0),1).when((f.col('prediction')==5.0) & (f.col('stars')==5.0),1).otherwise(0))\r\n\r\n f1_eval = MulticlassClassificationEvaluator(labelCol=\"stars\", predictionCol=\"prediction\", metricName='f1')\r\n evaluator = MulticlassClassificationEvaluator(labelCol=\"stars\", predictionCol=\"prediction\", metricName=\"accuracy\")\r\n acc = evaluator.evaluate(prediction) * 100\r\n f1 = f1_eval.evaluate(prediction)\r\n batch = ctr + 1\r\n print(\"Accuracy and F1-score for batch {}: \".format(batch), acc, f1)\r\n print(\"------------------------\")\r\n\r\nstart_consuming()\r\n", "repo_name": "shankhiremath/IIT-Madras-coursework", "sub_path": "CS4830 Big Data Lab/Team 17 project/Code/sub.py", "file_name": "sub.py", "file_ext": "py", "file_size_in_byte": 3166, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "21", "api": [{"api_name": "pyspark.__version__", "line_number": 16, "usage_type": "attribute"}, {"api_name": "pyspark.sql.SparkSession.builder.appName", "line_number": 29, "usage_type": "call"}, {"api_name": "pyspark.sql.SparkSession.builder", "line_number": 29, "usage_type": "attribute"}, {"api_name": "pyspark.sql.SparkSession", "line_number": 29, "usage_type": "name"}, {"api_name": "pyspark.ml.PipelineModel.load", "line_number": 35, "usage_type": "call"}, {"api_name": "pyspark.ml.PipelineModel", "line_number": 35, "usage_type": "name"}, {"api_name": "kafka.KafkaConsumer", "line_number": 40, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 42, "usage_type": "call"}, {"api_name": "pandas.json_normalize", "line_number": 43, "usage_type": "call"}, {"api_name": "pyspark.sql.functions.when", "line_number": 58, "usage_type": "call"}, {"api_name": "pyspark.sql.functions", "line_number": 58, "usage_type": "name"}, {"api_name": "pyspark.sql.functions.col", "line_number": 58, "usage_type": "call"}, {"api_name": "pyspark.ml.evaluation.MulticlassClassificationEvaluator", "line_number": 60, "usage_type": "call"}, {"api_name": "pyspark.ml.evaluation.MulticlassClassificationEvaluator", "line_number": 61, "usage_type": "call"}]} +{"seq_id": "24020366068", "text": "import numpy as np\nimport matplotlib.pyplot as plt\n\ndef draw(x1,x2):\n ln = plt.plot(x1,x2, '-')\n plt.pause(0.0001)\n #ln[0].remove()\n\ndef sigmoid(x):\n return 1/(1+np.exp(-x))\n\ndef calculate_error(line_parameters, points, y):\n sigma = points * line_parameters\n p = sigmoid(sigma)\n one = np.ones_like(y)\n n = np.shape(one)[0]\n cross_entropy = -(np.log(p).T * y + np.log(one-p).T*(one-y))/n\n return cross_entropy\n\ndef gd(line_parameters, points, y, alpha):\n count = 0\n e = 10\n m = points.shape[0]\n while count < 4000:# or e < 0.01:\n count += 1\n p = sigmoid(points*line_parameters)\n g = (points.T * (p - y))/ m\n line_parameters = line_parameters - alpha * g\n w1, w2, b= line_parameters.item(0), line_parameters.item(1), line_parameters.item(2)\n x1 = np.array([points[:,0].min(), points[:,0].max()])\n x2 = -b / w2 + x1 * (-w1 /w2)\n e = calculate_error(line_parameters, points, y)\n draw(x1, x2)\n\ndef main():\n n_pts = 100\n np.random.seed(0)\n bias = np.ones(n_pts)\n top_region = np.array([np.random.normal(10, 2, n_pts), np.random.normal(12, 2, n_pts), bias]).transpose()\n bottom_region = np.array([np.random.normal(5, 2, n_pts), np.random.normal(6, 2, n_pts), bias]).transpose()\n all_points = np.vstack((top_region, bottom_region))\n line_parameters = np.matrix(np.zeros(3)).T\n y = np.array([np.zeros(n_pts), np.ones(n_pts)]).reshape((-1, 1))\n\n fig, ax = plt.subplots(figsize=(4, 4))\n ax.scatter(top_region[:, 0], top_region[:, 1], color='r')\n ax.scatter(bottom_region[:, 0], bottom_region[:, 1], color='b')\n\n gd(line_parameters,all_points, y, 0.06)\n plt.show()\n\nif __name__ == \"__main__\":\n main()", "repo_name": "amir-gmail/Self_Driving_DL", "sub_path": "perceptron_and_deep_nn/perceptron.py", "file_name": "perceptron.py", "file_ext": "py", "file_size_in_byte": 1731, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "matplotlib.pyplot.plot", "line_number": 5, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 5, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.pause", "line_number": 6, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 6, "usage_type": "name"}, {"api_name": "numpy.exp", "line_number": 10, "usage_type": "call"}, {"api_name": "numpy.ones_like", "line_number": 15, "usage_type": "call"}, {"api_name": "numpy.shape", "line_number": 16, "usage_type": "call"}, {"api_name": "numpy.log", "line_number": 17, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 30, "usage_type": "call"}, {"api_name": "numpy.random.seed", "line_number": 37, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 37, "usage_type": "attribute"}, {"api_name": "numpy.ones", "line_number": 38, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 39, "usage_type": "call"}, {"api_name": "numpy.random.normal", "line_number": 39, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 39, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 40, "usage_type": "call"}, {"api_name": "numpy.random.normal", "line_number": 40, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 40, "usage_type": "attribute"}, {"api_name": "numpy.vstack", "line_number": 41, "usage_type": "call"}, {"api_name": "numpy.matrix", "line_number": 42, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 42, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 43, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 43, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 43, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 45, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 45, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 50, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 50, "usage_type": "name"}]} +{"seq_id": "7728085170", "text": "from appium import webdriver\nimport time\n\nfrom selenium.webdriver.support.wait import WebDriverWait\n\ndesired_caps = {}\ndesired_caps['platformName'] = 'Android'\ndesired_caps['platformVersion'] = '5.1.1'\ndesired_caps['deviceName'] = '127.0.0.1:62001'\ndesired_caps['appPackage'] = 'com.android.settings'\ndesired_caps['appActivity'] = '.Settings'\n# desired_caps['appPackage'] = 'com.ss.android.article.news'\n# desired_caps['appActivity'] = '.activity.MainActivity'\n\ndriver = webdriver.Remote('http://127.0.0.1:4723/wd/hub',desired_caps)\n# print(driver.is_app_installed('com.ss.android.article.news'))\n# driver.remove_app('com.ss.android.article.news')\n# print(driver.is_app_installed('com.ss.android.article.news'))\n# try:\n # driver.find_element_by_class_name('android.widget.LinearLayout').click()\n # time.sleep(2)\n # driver.find_element_by_class_name('android.widget.ImageButton').click()\n # time.sleep(2)\n # el_list = driver.find_elements_by_id('com.android.settings:id/title')\n\n # for i in el_class_list :\n # if i.text == '安全':\n # i.click()\n # time.sleep(2)\n # break\n# el_class_list = driver.find_elements_by_class_name('android.widget.TextView')\n# for i in el_class_list:\n# if 'WLAN' in i.text:\n# i.click()\n# time.sleep(2)\n# break\n# except Exception as e:\n# print(e)\n# finally:\n# driver.quit()\n\nprint(time.strftime('%H:%M:%S',time.localtime()))\nel = WebDriverWait(driver,timeout=5,poll_frequency=0.5).until(lambda x: x.find_element_by_xpath(\"//*[contains(@text,'WLA')]\"))\nel.click()\ntime.sleep(2)\nprint(time.strftime('%H:%M:%S',time.localtime()))", "repo_name": "sanmaotexiao/app", "sub_path": "Include/test.py", "file_name": "test.py", "file_ext": "py", "file_size_in_byte": 1669, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "appium.webdriver.Remote", "line_number": 15, "usage_type": "call"}, {"api_name": "appium.webdriver", "line_number": 15, "usage_type": "name"}, {"api_name": "time.strftime", "line_number": 42, "usage_type": "call"}, {"api_name": "time.localtime", "line_number": 42, "usage_type": "call"}, {"api_name": "selenium.webdriver.support.wait.WebDriverWait", "line_number": 43, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 45, "usage_type": "call"}, {"api_name": "time.strftime", "line_number": 46, "usage_type": "call"}, {"api_name": "time.localtime", "line_number": 46, "usage_type": "call"}]} +{"seq_id": "28781835625", "text": "import time\n\nimport numpy as np\nfrom z3 import Solver, sat, Int, Distinct, And\n\n# Taken from: https://rhettinger.github.io/einstein.html#sudoku-puzzles\nPROBLEMS = [\n \"53 7 6 195 98 6 8 6 34 8 3 17 2 6 6 28 419 5 8 79\",\n \" 75 4 5 8 17 6 36 2 7 1 5 1 1 5 8 96 1 82 3 4 9 48 \",\n \" 9 7 4 1 6 2 8 1 43 6 59 1 3 97 8 52 7 6 8 4 7 5 8 2 \",\n \"67 38 921 85 736 1 8 4 7 5 1 8 4 2 6 8 5 175 24 321 61 84\",\n \"27 15 8 3 7 4 7 5 1 7 9 2 6 2 5 8 6 5 4 8 59 41\",\n \"8 64 3 5 7 2 32 8 5 8 5 4 1 7 93 4 9 4 6 72 8\",\n \" 8 9 3 7 2 1 6 8 3 9 5 6 4 5 1 7 9 8 2 5 7 8 1 2 \"\n]\n\nGROUP_SIZE = 3\nGRID_SIZE = GROUP_SIZE**2 # 9\n\ndef print_flattened(flattened):\n LINE = \"|\".join([\"%s\" * GROUP_SIZE] * GROUP_SIZE)\n SEP = \"+\".join([\"-\" * GROUP_SIZE] * GROUP_SIZE)\n print(SEP)\n for y in range(GRID_SIZE):\n offset = y * GRID_SIZE\n print(LINE % tuple(flattened[offset:offset+GRID_SIZE]))\n if (y+1) % GROUP_SIZE == 0:\n print(SEP)\n\n\ndef as_matrix(flattened):\n return np.array([[flattened[y*GRID_SIZE + x] for x in range(GRID_SIZE)] for y in range(GRID_SIZE)])\n\n\ndef print_matrix(matrix):\n LINE = \"|\".join([\"%s\" * GROUP_SIZE] * GROUP_SIZE)\n SEP = \"+\".join([\"-\" * GROUP_SIZE] * GROUP_SIZE)\n print(SEP)\n for y in range(GRID_SIZE):\n offset = y * GRID_SIZE\n print(LINE % tuple(matrix[y]))\n if (y+1) % GROUP_SIZE == 0:\n print(SEP)\n\n\ndef solve_soduko(flattened):\n fact_matrix = as_matrix(flattened)\n symbol_grid = [[Int(f\"x_{y+1}{x+1}\") for x in range(GRID_SIZE)] for y in range(GRID_SIZE)]\n\n known_facts = [symbol_grid[y][x] == int(fact_matrix[y, x])\n for y in range(GRID_SIZE) for x in range(GRID_SIZE)\n if fact_matrix[y, x] != \" \"]\n\n numbers = [And(symbol_grid[y][x] >=1, symbol_grid[y][x] <= 9)\n for y in range(GRID_SIZE) for x in range(GRID_SIZE)]\n\n unique_rows = [Distinct(symbol_grid[y]) for y in range(GRID_SIZE)]\n unique_columns = [Distinct([symbol_grid[y][x] for y in range(GRID_SIZE)])\n for x in range(GRID_SIZE)]\n\n unique_group = []\n for grid_y in range(0, GRID_SIZE, GROUP_SIZE):\n for grid_x in range(0, GRID_SIZE, GROUP_SIZE):\n unique_group.append(Distinct([symbol_grid[grid_y+y][grid_x+x]\n for y in range(GROUP_SIZE) for x in range(GROUP_SIZE)]))\n\n s = Solver()\n s.add(known_facts + numbers + unique_rows + unique_columns + unique_group)\n print(s.check())\n m = s.model()\n solution = [[m[symbol_grid[y][x]] for x in range(GRID_SIZE)] for y in range(GRID_SIZE)]\n return solution\n\nif __name__ ==\"__main__\":\n problem = PROBLEMS[5]\n print_flattened(problem)\n start = time.time()\n solution = solve_soduko(problem)\n print(f\"Solved in {time.time()-start}s\")\n print_matrix(solution)\n\n", "repo_name": "MichelHalmes/z3-experiments", "sub_path": "solve_sudoko.py", "file_name": "solve_sudoko.py", "file_ext": "py", "file_size_in_byte": 3057, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "numpy.array", "line_number": 32, "usage_type": "call"}, {"api_name": "z3.Int", "line_number": 48, "usage_type": "call"}, {"api_name": "z3.And", "line_number": 54, "usage_type": "call"}, {"api_name": "z3.Distinct", "line_number": 57, "usage_type": "call"}, {"api_name": "z3.Distinct", "line_number": 58, "usage_type": "call"}, {"api_name": "z3.Distinct", "line_number": 64, "usage_type": "call"}, {"api_name": "z3.Solver", "line_number": 67, "usage_type": "call"}, {"api_name": "time.time", "line_number": 77, "usage_type": "call"}, {"api_name": "time.time", "line_number": 79, "usage_type": "call"}]} +{"seq_id": "6188038650", "text": "import os\nimport slack\nfrom slack import WebClient\nimport pdb\n\nslack_token = os.environ[\"SLACK_BOT_TOKEN\"]\nrtmclient = slack.RTMClient(token=slack_token)\n\n@slack.RTMClient.run_on(event='message')\ndef say_hello(**payload):\n data = payload['data']\n if 'Hello' in data['text']:\n channel_id = data['channel']\n thread_ts = data['ts']\n user = data['user']\n\n webclient = payload['web_client']\n webclient.chat_postMessage(\n channel=channel_id,\n text=\"Hi <@{}>!\".format(user),\n thread_ts=thread_ts\n )\n\nrtmclient.start()\n", "repo_name": "karapnaran/slack_bot", "sub_path": "starterbot.py", "file_name": "starterbot.py", "file_ext": "py", "file_size_in_byte": 592, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "os.environ", "line_number": 6, "usage_type": "attribute"}, {"api_name": "slack.RTMClient", "line_number": 7, "usage_type": "call"}, {"api_name": "slack.RTMClient.run_on", "line_number": 9, "usage_type": "call"}, {"api_name": "slack.RTMClient", "line_number": 9, "usage_type": "attribute"}]} +{"seq_id": "17910310912", "text": "import os\nimport copy\nimport glob\nfrom Bio.Seq import Seq\nfrom Bio import SeqIO\n\n# Define a function for converting stockholm alignment files to FASTA.\ndef convert_stockholm_to_fasta(stockholm, fasta_aligned, fasta_unaligned):\n \"\"\"Take a path to an alignment in stockholm format and write in FASTA\n format (aligned and unaligned) to given paths.\n \"\"\"\n # Parse stockholm file with Biopython.\n records = list(SeqIO.parse(stockholm, \"stockholm\"))\n \n # Iterate over each \n records_aligned = []\n records_unaligned = []\n for r in records:\n # Clear letter annotations.\n r.letter_annotations = {}\n # Append query title to ID.\n r.id = r.id.rsplit('/', 1)[0] + '__' + \\\n os.path.basename(stockholm).split('_')[0]\n # Clear description.\n r.description = ''\n # Add to aligned SeqRecord list.\n records_aligned.append(copy.deepcopy(r))\n # Remove gap characters.\n r.seq = Seq(str(r.seq).replace('-', ''))\n # Add to unaligned SeqRecord list.\n records_unaligned.append(r)\n \n # Write sequences to output files.\n SeqIO.write(records_aligned, fasta_aligned, \"fasta\")\n SeqIO.write(records_unaligned, fasta_unaligned, \"fasta\")\n\n\n# Convert final stockholm alignment file to FASTA format.\nconvert_stockholm_to_fasta(snakemake.input.alignment,\n snakemake.output.aligned,\n snakemake.output.unaligned\n )\n \n# Compile a list of all intermediate input alignment files.\nintermediate_alignments = \\\nglob.glob(os.path.join(snakemake.input.int_ali_dir, '*.sto'))\n\n# Make output directories for intermediate sequence files.\nos.mkdir(snakemake.output.int_aligned_dir)\nos.mkdir(snakemake.output.int_unaligned_dir)\n\n# Convert each intermediate alignment to FASTA format.\nfor f in intermediate_alignments:\n convert_stockholm_to_fasta(\n f,\n os.path.join(snakemake.output.int_aligned_dir,\n os.path.basename(f).rsplit('.', 1)[0] + \\\n '.afaa'),\n os.path.join(snakemake.output.int_unaligned_dir,\n os.path.basename(f).rsplit('.', 1)[0] + \\\n '.faa')\n )\n\n\n\n\n\n\n\n", "repo_name": "laelbarlow/jackhmmerer", "sub_path": "workflow/scripts/convert_profiles_to_fasta.py", "file_name": "convert_profiles_to_fasta.py", "file_ext": "py", "file_size_in_byte": 2229, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "Bio.SeqIO.parse", "line_number": 13, "usage_type": "call"}, {"api_name": "Bio.SeqIO", "line_number": 13, "usage_type": "name"}, {"api_name": "os.path.basename", "line_number": 23, "usage_type": "call"}, {"api_name": "os.path", "line_number": 23, "usage_type": "attribute"}, {"api_name": "copy.deepcopy", "line_number": 27, "usage_type": "call"}, {"api_name": "Bio.Seq.Seq", "line_number": 29, "usage_type": "call"}, {"api_name": "Bio.SeqIO.write", "line_number": 34, "usage_type": "call"}, {"api_name": "Bio.SeqIO", "line_number": 34, "usage_type": "name"}, {"api_name": "Bio.SeqIO.write", "line_number": 35, "usage_type": "call"}, {"api_name": "Bio.SeqIO", "line_number": 35, "usage_type": "name"}, {"api_name": "glob.glob", "line_number": 46, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 46, "usage_type": "call"}, {"api_name": "os.path", "line_number": 46, "usage_type": "attribute"}, {"api_name": "os.mkdir", "line_number": 49, "usage_type": "call"}, {"api_name": "os.mkdir", "line_number": 50, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 56, "usage_type": "call"}, {"api_name": "os.path", "line_number": 56, "usage_type": "attribute"}, {"api_name": "os.path.basename", "line_number": 57, "usage_type": "call"}, {"api_name": "os.path", "line_number": 57, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 59, "usage_type": "call"}, {"api_name": "os.path", "line_number": 59, "usage_type": "attribute"}, {"api_name": "os.path.basename", "line_number": 60, "usage_type": "call"}, {"api_name": "os.path", "line_number": 60, "usage_type": "attribute"}]} +{"seq_id": "34975765063", "text": "from django import forms\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.contrib.auth import get_user_model\nfrom backend.models import CustomUser, Organization, Jedzenie, Przedmiot, Image, Usluga, Event\nfrom .validator import file_size\n\nclass FormUserRegistration(UserCreationForm):\n telefon = forms.CharField(max_length=12)\n email = forms.EmailField()\n # adres_zamieszkania = forms.CharField()\n # data_urodzenia = forms.DateField()\n # avatar = forms.ImageField()\n # rola = forms.CharField()\n\n\n class Meta:\n model = get_user_model()\n fields = ['first_name', 'last_name', 'username', 'telefon', 'email', 'password1', 'password2', 'adres_zamieszkania', 'data_urodzenia', 'avatar', 'rola']\n # help_texts = {\n # 'username': None,\n # 'password2': None,\n # }\n\n def save(self, commit=True):\n user = super(FormUserRegistration, self).save(commit=False)\n user.email = self.cleaned_data['email']\n user.telefon = self.cleaned_data['telefon']\n user.adres_zamieszkania = self.cleaned_data['adres_zamieszkania']\n user.data_urodzenia = self.cleaned_data['data_urodzenia']\n user.avatar = self.cleaned_data['avatar']\n user.rola = self.cleaned_data['rola']\n if commit:\n user.save()\n return user\n \nclass UserUpdate(forms.ModelForm):\n class Meta:\n model = get_user_model()\n fields = ['first_name', 'last_name', 'telefon', 'email', 'adres_zamieszkania', 'data_urodzenia']\n\nclass FormOrganizationCreate(forms.ModelForm):\n class Meta:\n model = Organization\n fields = ['nazwa', 'opis', 'logo']\n\n\nTITLE_CHOICES = [\n ('Sportowe', 'Sportowe'),\n ('Kulturowe', 'Kulturowe'),\n ('Rozrywkowe', 'Rozrywkowe'),\n]\n\n\nclass FormEventCreate(forms.ModelForm):\n # image = MultipleFileField(label='Zdjęcia dodatkowe', required=False, validators=[file_size], widget=forms.ClearableFileInput(attrs={'multiple': True}))\n class Meta:\n model = Event\n fields = ['event_name', 'event_description', 'event_date', 'event_location', 'type_of_event', 'main_image', 'link_do_miejsca_wydarzenia']\n\n # event_name = forms.CharField(max_length=100, required=False)\n # event_description = forms.CharField(max_length=500, required=False)\n # event_date = forms.DateTimeField()\n # event_location = forms.CharField(max_length=100, required=False)\n # type_of_event = forms.CharField(max_length=30, widget=forms.Select(choices = TITLE_CHOICES),)\n # main_image = forms.ImageField()\n # link_do_miejsca_wydarzenia = forms.URLField(max_length = 200, required=False)\n # x_miejsca = forms.FloatField()\n # y_miejsca = forms.FloatField()\n # image = forms.MultipleFileField(label='Zdjęcia dodatkowe', required=False, validators=[file_size], widget=forms.ClearableFileInput(attrs={'multiple': True}))\n\n # title = forms.CharField(label='Nazwa wydarzenia', max_length=100, widget=forms.TextInput(attrs={'class':'task_window', 'placeholder':'Zawody sportowe'}))\n # description = forms.CharField(label='Opis', max_length=300, widget=forms.Textarea(attrs={'class':'task_window', 'placeholder':'Otwarty turniej piłkarski', 'rows' : 5}))\n # main_image = forms.ImageField(label='Główne zdjęcie', required=False)\n # start_time = forms.DateField(label='Data rozpoczęcia', widget=NumberInput(attrs={'type': 'date', 'class':'task_date'}))\n # start_time_time = forms.TimeField(label=\"\", widget=TimePickerInput)\n # deadline = forms.DateField(label='Przewidywana data zakończenia', widget=NumberInput(attrs={'type': 'date', 'class':'task_date'}))\n # deadline_time = forms.TimeField(label=\"Przewidywana odzina zakończenia\", widget=TimePickerInput)\n # type_of_event = forms.CharField(label='Wybierz rodzaj wydarzenia',\n # widget=forms.Select(choices = TITLE_CHOICES, attrs={'class':'task_window'}),\n # required=True\n # )\n # link_do_miejsca_wydarzenia = forms.URLField(required=False, label='Link', max_length = 200, widget=forms.URLInput(attrs={'class':'task_window'}))\n # x = forms.FloatField(label='Naciśnij na mapę aby wybrać współrzędne geograficzne', required=True, widget=forms.NumberInput(attrs={'id': 'x', 'step': \"0.0000000001\"}))\n # y = forms.FloatField(label='', required=True, widget=forms.NumberInput(attrs={'id': 'y', 'step': \"0.0000000001\"}))\n # image = forms.FileField(label='Zdjęcia dodatkowe', required=False, validators=[file_size], widget=forms.ClearableFileInput(attrs={'multiple': True}))\n\nclass FormJedzenie(forms.ModelForm):\n food_image = forms.ImageField(required=False)\n class Meta:\n model = Jedzenie\n fields = ['food_name', 'food_description', 'food_image']\n\n\nclass FormPrzedmiot(forms.ModelForm):\n item_image = forms.ImageField(required=False)\n class Meta:\n model = Przedmiot\n fields = ['item_name', 'item_description', 'item_image']\n\n\nclass FormUsluga(forms.ModelForm):\n service_image = forms.ImageField(required=False)\n class Meta:\n model = Usluga\n fields = ['service_name', 'service_description', 'service_price', 'service_image']\n\n\n ", "repo_name": "Skiperpol/BESTHACKS2023", "sub_path": "backend/forms.py", "file_name": "forms.py", "file_ext": "py", "file_size_in_byte": 5172, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "django.contrib.auth.forms.UserCreationForm", "line_number": 7, "usage_type": "name"}, {"api_name": "django.forms.CharField", "line_number": 8, "usage_type": "call"}, {"api_name": "django.forms", "line_number": 8, "usage_type": "name"}, {"api_name": "django.forms.EmailField", "line_number": 9, "usage_type": "call"}, {"api_name": "django.forms", "line_number": 9, "usage_type": "name"}, {"api_name": "django.contrib.auth.get_user_model", "line_number": 17, "usage_type": "call"}, {"api_name": "django.forms.ModelForm", "line_number": 36, "usage_type": "attribute"}, {"api_name": "django.forms", "line_number": 36, "usage_type": "name"}, {"api_name": "django.contrib.auth.get_user_model", "line_number": 38, "usage_type": "call"}, {"api_name": "django.forms.ModelForm", "line_number": 41, "usage_type": "attribute"}, {"api_name": "django.forms", "line_number": 41, "usage_type": "name"}, {"api_name": "backend.models.Organization", "line_number": 43, "usage_type": "name"}, {"api_name": "django.forms.ModelForm", "line_number": 54, "usage_type": "attribute"}, {"api_name": "django.forms", "line_number": 54, "usage_type": "name"}, {"api_name": "backend.models.Event", "line_number": 57, "usage_type": "name"}, {"api_name": "django.forms.ModelForm", "line_number": 87, "usage_type": "attribute"}, {"api_name": "django.forms", "line_number": 87, "usage_type": "name"}, {"api_name": "django.forms.ImageField", "line_number": 88, "usage_type": "call"}, {"api_name": "django.forms", "line_number": 88, "usage_type": "name"}, {"api_name": "backend.models.Jedzenie", "line_number": 90, "usage_type": "name"}, {"api_name": "django.forms.ModelForm", "line_number": 94, "usage_type": "attribute"}, {"api_name": "django.forms", "line_number": 94, "usage_type": "name"}, {"api_name": "django.forms.ImageField", "line_number": 95, "usage_type": "call"}, {"api_name": "django.forms", "line_number": 95, "usage_type": "name"}, {"api_name": "backend.models.Przedmiot", "line_number": 97, "usage_type": "name"}, {"api_name": "django.forms.ModelForm", "line_number": 101, "usage_type": "attribute"}, {"api_name": "django.forms", "line_number": 101, "usage_type": "name"}, {"api_name": "django.forms.ImageField", "line_number": 102, "usage_type": "call"}, {"api_name": "django.forms", "line_number": 102, "usage_type": "name"}, {"api_name": "backend.models.Usluga", "line_number": 104, "usage_type": "name"}]} +{"seq_id": "11876998596", "text": "__author = 'Robin'\n\nfrom selenium import webdriver\nimport unittest\n\n\nclass VisitSogouByChrome(unittest.TestCase):\n def setUp(self):\n self.driver = webdriver.Chrome()\n\n def test_captureScreenInCurrentWindow(self):\n url = 'http://www.sogou.com'\n self.driver.get(url)\n try:\n result = self.driver.get_screenshot_as_file('F:\\\\ScreenPicture\\\\pic01.png')\n print(result)\n except IOError as e:\n print(e)\n\n def tearDown(self):\n self.driver.quit()\n\n\nif __name__ == '__main__':\n unittest.main()", "repo_name": "johnsonliu33/SeleniumAuto", "sub_path": "二、WebDriver的API详解/28、对当前浏览器窗口截屏.py", "file_name": "28、对当前浏览器窗口截屏.py", "file_ext": "py", "file_size_in_byte": 569, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "unittest.TestCase", "line_number": 7, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.Chrome", "line_number": 9, "usage_type": "call"}, {"api_name": "selenium.webdriver", "line_number": 9, "usage_type": "name"}, {"api_name": "unittest.main", "line_number": 25, "usage_type": "call"}]} +{"seq_id": "753542029", "text": "import argparse\nimport logging\nimport math\nimport cPickle\nfrom ..corpus import read_corpus, ngrams\n\ndef print_ppl(model, corpus):\n n_sentences = len(corpus)\n n_words = sum(len(sentence) for sentence in corpus)\n n_oovs = 0\n ll = 0\n for sentence in corpus:\n for seq in ngrams(sentence, model.order):\n p = model.prob(seq[:-1], seq[-1])\n if p == 0:\n n_oovs += 1\n else:\n ll += math.log(p)\n ppl = math.exp(-ll/(n_sentences + n_words - n_oovs))\n logging.info('Sentences: %d\\tWords: %d\\tOOVs: %d', n_sentences, n_words, n_oovs)\n logging.info('LL: %.0f\\tppl: %.3f', ll, ppl)\n\ndef main():\n logging.basicConfig(level=logging.INFO, format='%(message)s')\n\n parser = argparse.ArgumentParser(description='Evaluate n-gram model')\n parser.add_argument('--test', help='evaluation corpus', required=True)\n parser.add_argument('--model', help='trained model', required=True)\n\n args = parser.parse_args()\n\n logging.info('Loading model')\n with open(args.model) as model_file:\n model = cPickle.load(model_file)\n\n logging.info('Reading evaluation corpus')\n with open(args.test) as test:\n test_corpus = read_corpus(test, model.vocabulary)\n\n logging.info('Computing perplexity')\n print_ppl(model, test_corpus)\n\nif __name__ == '__main__':\n main()\n", "repo_name": "vchahun/vpyp", "sub_path": "vpyp/ngram/eval.py", "file_name": "eval.py", "file_ext": "py", "file_size_in_byte": 1364, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 25, "dataset": "github-code", "pt": "21", "api": [{"api_name": "corpus.ngrams", "line_number": 13, "usage_type": "call"}, {"api_name": "math.log", "line_number": 18, "usage_type": "call"}, {"api_name": "math.exp", "line_number": 19, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 20, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 21, "usage_type": "call"}, {"api_name": "logging.basicConfig", "line_number": 24, "usage_type": "call"}, {"api_name": "logging.INFO", "line_number": 24, "usage_type": "attribute"}, {"api_name": "argparse.ArgumentParser", "line_number": 26, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 32, "usage_type": "call"}, {"api_name": "cPickle.load", "line_number": 34, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 36, "usage_type": "call"}, {"api_name": "corpus.read_corpus", "line_number": 38, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 40, "usage_type": "call"}]} +{"seq_id": "16359684540", "text": "# Import required Python Libraries\nimport streamlit as st\nimport pandas as pd\nimport plotly.express as px\nimport plotly.graph_objects as go\nimport numpy as np\nimport random\nimport folium\nfrom folium import plugins\nfrom streamlit_folium import folium_static\n\nst.set_page_config(layout = 'wide')\n\n@st.cache\n\n#Load the Wales Accidents Dataset\ndef load_data():\n accident = pd.read_csv(r'wales_accident.csv')\n accident.reset_index(drop=True, inplace=True)\n return accident\n\n#Load Wales Accidents location Dataset\ndef load_location_data():\n accident_location = pd.read_csv(r'location.csv')\n accident_location.reset_index(drop=True, inplace=True)\n return accident_location\n \n#Main Sidebar navigation \npage = st.sidebar.selectbox('Select page',['Home','Breakdown', 'Heat Map', 'Sankey Diagram'])\n\n#Home page\nif page == 'Home':\n accident = load_data()\n st.title('Wales Road Accidents Report')\n st.header('Wales Road Accident records from 2016 to 2020')\n st.markdown('This report aims to provide a documented insight into the analysis of Road Accidents Data of Wales through visuals and text recorded by the Welsh Police force.')\n st.markdown('The former is responsible for the Wales local authorities districts of the United Kingdom.' + \n ' Road accidents are one of the most critical factors contributing to untimely deaths and economic losses to public and private property.' \n ' It is important to find sustainable countermeasures to minimise road accidents.'\n ' The efficiency of accident prevention depends on the reliability of reported data, analysis performed and interpretation of results.')\n st.markdown(' Below is a table containing the number of accident cases recorded by the Welsh police forcel from the year 2016 to 2020.' + \n ' According to the data there were 20881 accident cases within that time period.')\n st.dataframe(accident.head(accident.shape[0]))\n\n#Bar Charts page\nelif page == 'Breakdown':\n wales_accident = load_data()\n st.title('Wales Road Accidents Report')\n st.header('Breakdown of Wales Road Accident Data via Bar Charts')\n st.markdown('This page provides a breakdown of accidents that occured in Wales from 2016 to 2020 by comparing the number of accidents in Wales with various other factors producing a series of barcharts in the process.')\n st.markdown('Hovering on each bar in a bar chart gives the exact number of collision cases recorded based on the criteria that the bar represents')\n accident_cols = ['police_force', 'accident_severity','local_authority_district',\n 'day_of_week','first_road_class', 'road_type','junction_detail', 'junction_control', \n 'second_road_class', 'pedestrian_crossing_human_control', 'pedestrian_crossing_physical_facilities',\n 'light_conditions', 'weather_conditions', 'road_surface_conditions', 'special_conditions_at_site', \n 'carriageway_hazards', 'urban_or_rural_area', 'did_police_officer_attend_scene_of_accident']\n \n #Sidebar navigation for the Bar Charts\n sidebar = st.sidebar\n data_cols = sidebar.selectbox(\"Select Column:\",accident_cols)\n \n\n data = wales_accident.groupby(data_cols)['accident_index'].count().reset_index().sort_values(by='accident_index')\n\n #Display bar chart, colour scale and label\n fig = px.bar(data, x='accident_index', y=data_cols,color='accident_index',color_continuous_scale=px.colors.sequential.Inferno, title=\"Number of accidents per {} (2016-2020)\".format(data_cols.replace('_', ' ')))\n fig.update_xaxes(title_text=\"Number of Accidents\")\n fig.update_yaxes(title_text=data_cols.replace('_', ' '))\n st.plotly_chart(fig,use_container_width=True)\n\n#Heat Map page\nelif page == 'Heat Map':\n st.title('Wales Road Accidents Report')\n st.header('A Heat Map displaying the Magnitude of Accidents Cases recorded in Wales from 2016 to 2020')\n st.markdown('This page contains a heat map of accidents in Wales from the year 2016 to 2020. The region of South Wales has the highest magnitude of accidents in Wales as depicted by the heat map.')\n\n wales_accident_location = load_location_data()\n accident_locations = list(zip( wales_accident_location.latitude, wales_accident_location.longitude))\n def generateHeatMap(default_location=[52.588160, -3.325960], default_zoom_start=7):\n base_map = folium.Map(location=default_location, control_scale=True, tiles=\"Stamen Toner\", zoom_start=default_zoom_start)\n heatmap = plugins.HeatMap(accident_locations, radius=4, blur=2)\n base_map.add_child(heatmap)\n return base_map \n fig = generateHeatMap() \n folium_static(fig, width= 1200)\n\n#Sankey Diagram page\nelse:\n st.title('Wales Road Accidents Report')\n st.header('Visualisation of Wales Road Accident Data via a Sankey (or a Flow) Diagram')\n st.markdown('This page displays a Sankey / flow diagram of accidents in Wales based on some factors such as ' + \n ' the police force that recorded the accident, whether the accident occurred in an Urban or Rural area, the year that the accident happened and the severity of the accident on the victims.')\n st.markdown('Hovering on a flow line in the Sankey Diagram provides the number of accident cases recorded based on a specific factor.')\n\n wales_accident = load_data()\n sankey_df = wales_accident.reindex([\"police_force\",\"urban_or_rural_area\",\"accident_year\",\"accident_severity\"], axis=1)\n col_names = sankey_df.columns.tolist()\n node_labels = []\n num_categorical_vals_per_col = []\n for col in col_names:\n uniques = sankey_df[col].unique().tolist()\n node_labels.extend(uniques)\n num_categorical_vals_per_col.append(len(uniques)) \n source = []\n target = []\n value = []\n colors = []\n for i, num_categories in enumerate(num_categorical_vals_per_col): \n if i == len(num_categorical_vals_per_col)-1:\n break \n start_index = sum(num_categorical_vals_per_col[:i])\n start_index_next = sum(num_categorical_vals_per_col[:i+1])\n end_index_next = sum(num_categorical_vals_per_col[:i+2])\n \n col_name = col_names[i]\n next_col_name = col_names[i+1]\n \n grouped_df = sankey_df.groupby([col_name, next_col_name]).size()\n \n for source_i in range(start_index, start_index_next):\n for target_i in range(start_index_next, end_index_next):\n source.append(source_i)\n target.append(target_i)\n source_label = node_labels[source_i]\n target_label = node_labels[target_i]\n\n try:\n value.append(grouped_df[source_label][target_label])\n except:\n value.append(0)\n \n random_color = list(np.random.randint(256, size=3)) + [random.random()]\n random_color_string = ','.join(map(str, random_color))\n colors.append('rgba({})'.format(random_color_string))\n\n link = dict(source=source, target=target, value=value, color=colors)\n\n fig = go.Figure(data=[go.Sankey(\n node = dict(\n pad = 15,\n thickness = 20,\n line = dict(color = \"black\", width = 0.5),\n label = node_labels,\n color = \"purple\"\n ), \n link = link)])\n fig.update_layout(title_text=\"A Sankey Diagram showing the flow of Accidents in Wales based on Police force, Urbarn or Rural area, Accident Year and Accident Serverity factors\", font_size=10)\n st.plotly_chart(fig,use_container_width=True)", "repo_name": "bunarty/Wales-Road-Accident-Data-Analysis-report", "sub_path": "app.py", "file_name": "app.py", "file_ext": "py", "file_size_in_byte": 7602, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "streamlit.set_page_config", "line_number": 12, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 18, "usage_type": "call"}, {"api_name": "streamlit.cache", "line_number": 14, "usage_type": "attribute"}, {"api_name": "pandas.read_csv", "line_number": 24, "usage_type": "call"}, {"api_name": "streamlit.sidebar.selectbox", "line_number": 29, "usage_type": "call"}, {"api_name": "streamlit.sidebar", "line_number": 29, "usage_type": "attribute"}, {"api_name": "streamlit.title", "line_number": 34, "usage_type": "call"}, {"api_name": "streamlit.header", "line_number": 35, "usage_type": "call"}, {"api_name": "streamlit.markdown", "line_number": 36, "usage_type": "call"}, {"api_name": "streamlit.markdown", "line_number": 37, "usage_type": "call"}, {"api_name": "streamlit.markdown", "line_number": 41, "usage_type": "call"}, {"api_name": "streamlit.dataframe", "line_number": 43, "usage_type": "call"}, {"api_name": "streamlit.title", "line_number": 48, "usage_type": "call"}, {"api_name": "streamlit.header", "line_number": 49, "usage_type": "call"}, {"api_name": "streamlit.markdown", "line_number": 50, "usage_type": "call"}, {"api_name": "streamlit.markdown", "line_number": 51, "usage_type": "call"}, {"api_name": "streamlit.sidebar", "line_number": 59, "usage_type": "attribute"}, {"api_name": "plotly.express.bar", "line_number": 66, "usage_type": "call"}, {"api_name": "plotly.express", "line_number": 66, "usage_type": "name"}, {"api_name": "plotly.express.colors", "line_number": 66, "usage_type": "attribute"}, {"api_name": "streamlit.plotly_chart", "line_number": 69, "usage_type": "call"}, {"api_name": "streamlit.title", "line_number": 73, "usage_type": "call"}, {"api_name": "streamlit.header", "line_number": 74, "usage_type": "call"}, {"api_name": "streamlit.markdown", "line_number": 75, "usage_type": "call"}, {"api_name": "folium.Map", "line_number": 80, "usage_type": "call"}, {"api_name": "folium.plugins.HeatMap", "line_number": 81, "usage_type": "call"}, {"api_name": "folium.plugins", "line_number": 81, "usage_type": "name"}, {"api_name": "streamlit_folium.folium_static", "line_number": 85, "usage_type": "call"}, {"api_name": "streamlit.title", "line_number": 89, "usage_type": "call"}, {"api_name": "streamlit.header", "line_number": 90, "usage_type": "call"}, {"api_name": "streamlit.markdown", "line_number": 91, "usage_type": "call"}, {"api_name": "streamlit.markdown", "line_number": 93, "usage_type": "call"}, {"api_name": "numpy.random.randint", "line_number": 132, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 132, "usage_type": "attribute"}, {"api_name": "random.random", "line_number": 132, "usage_type": "call"}, {"api_name": "plotly.graph_objects.Figure", "line_number": 138, "usage_type": "call"}, {"api_name": "plotly.graph_objects", "line_number": 138, "usage_type": "name"}, {"api_name": "plotly.graph_objects.Sankey", "line_number": 138, "usage_type": "call"}, {"api_name": "streamlit.plotly_chart", "line_number": 148, "usage_type": "call"}]} +{"seq_id": "43324040099", "text": "#!/usr/bin/env python3\n\nimport boto3\nimport csv\n\ndef modify_email(sf_account: str, email: str, new_contact_email: str) -> bool:\n try:\n response = table.update_item(\n Key={\n 'account': sf_account,\n 'email': email \n },\n UpdateExpression=\"set contactEmail = :val\",\n ExpressionAttributeValues={':val': str(new_contact_email)}\n )\n except Exception as exp:\n print(f'Update contact email exception.')\n raise exp\n else:\n return True\n\n\nif __name__ == '__main__':\n session = boto3.Session(profile_name='default')\n dynamoDB = boto3.resource('dynamodb')\n\n table = dynamoDB.Table('a207838-sss-user-lookup-dev')\n sf_account = 'tradmin.us-east-1'\n\n with open('edw-preprod-user-new-email.csv', newline='') as csvfile:\n email_reader = csv.reader(csvfile)\n for row in email_reader:\n print(row[0])\n modify_email(sf_account, row[0], row[1])\n", "repo_name": "FengLiTR/modify-service-user-email", "sub_path": "modify-contactemail-dynamodb.py", "file_name": "modify-contactemail-dynamodb.py", "file_ext": "py", "file_size_in_byte": 990, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "boto3.Session", "line_number": 24, "usage_type": "call"}, {"api_name": "boto3.resource", "line_number": 25, "usage_type": "call"}, {"api_name": "csv.reader", "line_number": 31, "usage_type": "call"}]} +{"seq_id": "20332142043", "text": "from gensim.corpora import Dictionary\nfrom gensim.models import LdaModel\n\nfrom pinkerton.utils import tokenize\nfrom pinkerton.similarity.base import BaseSimilarityComparator\n\n\nclass LDASimilarity(BaseSimilarityComparator):\n\n def __init__(self, **kwargs):\n self.model_kwargs = kwargs or {\n 'passes': 20,\n 'num_topics': 100,\n }\n\n def score(self, entities: list, context: str) -> list:\n\n queries = [\n (i, q['context']) for i, q in enumerate(entities) if q['context']\n ]\n\n context = tokenize(context)\n\n dictionary = Dictionary([context])\n\n vectors = [\n dictionary.doc2bow(\n tokenize(q)\n ) for _, q in queries\n ]\n\n model = LdaModel(id2word=dictionary, **self.model_kwargs)\n\n ents = (\n entities[i] for i, _ in queries\n )\n\n scores = (\n model[vec][-1][1] for vec in vectors if model[vec]\n )\n\n results = zip(ents, scores)\n\n def sort_by_score(item):\n return item[1]\n\n return sorted(results, key=sort_by_score, reverse=True)\n", "repo_name": "datahack-ru/pinkerton", "sub_path": "pinkerton/similarity/lda.py", "file_name": "lda.py", "file_ext": "py", "file_size_in_byte": 1135, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "21", "api": [{"api_name": "pinkerton.similarity.base.BaseSimilarityComparator", "line_number": 8, "usage_type": "name"}, {"api_name": "pinkerton.utils.tokenize", "line_number": 22, "usage_type": "call"}, {"api_name": "gensim.corpora.Dictionary", "line_number": 24, "usage_type": "call"}, {"api_name": "pinkerton.utils.tokenize", "line_number": 28, "usage_type": "call"}, {"api_name": "gensim.models.LdaModel", "line_number": 32, "usage_type": "call"}]} +{"seq_id": "72297177974", "text": "from form import *\r\nfrom telegram_msg import *\r\nfrom payload_model import *\r\n\r\nimport schedule\r\nimport time\r\n\r\nimport os\r\nfrom dotenv.main import load_dotenv\r\nload_dotenv()\r\n\r\ndef auto_submit():\r\n payload = gen_payload_model()\r\n url = os.environ['formurl']\r\n base_url = os.environ['prefilledurl']\r\n \r\n if form_on_off(url)==\"Form OPEN\":\r\n for i in payload:\r\n send_msg_norti(i[0],\"Form OPEN\")\r\n try:\r\n data = submit_form(url,i[1])\r\n send_msg_norti(i[0],data)\r\n send_msg_norti(i[0],prefilled_link_gen(i[0],base_url))\r\n except:\r\n send_msg_norti(i[0],prefilled_link_gen(i[0],base_url))\r\n time.sleep(500)\r\n return 0\r\n\r\n# auto_submit(gen_payload_model())\r\n\r\nschedule.every(6).seconds.do(auto_submit)\r\nwhile True:\r\n \r\n # Checks whether a scheduled task\r\n # is pending to run or not\r\n schedule.run_pending()\r\n time.sleep(1)\r\n ", "repo_name": "karmathecoder/G-Form-automation-telegram-bot", "sub_path": "cronjob_fun.py", "file_name": "cronjob_fun.py", "file_ext": "py", "file_size_in_byte": 965, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "dotenv.main.load_dotenv", "line_number": 10, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 14, "usage_type": "attribute"}, {"api_name": "os.environ", "line_number": 15, "usage_type": "attribute"}, {"api_name": "time.sleep", "line_number": 26, "usage_type": "call"}, {"api_name": "schedule.every", "line_number": 31, "usage_type": "call"}, {"api_name": "schedule.run_pending", "line_number": 36, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 37, "usage_type": "call"}]} +{"seq_id": "35981238645", "text": "import portion\nfrom Diffusion_Process.AbstractInfluenceFunction import AbstractInfluenceFunction\n\nclass EnhancedTipping(AbstractInfluenceFunction):\n\t\n\tdef __init__(self, treshold, bound_update):\n\t\tself._treshold = treshold\n\t\tself._bnd_update = bound_update\n\n\tdef influence(self, neigh, qualified_neigh, nas):\n\t\tbnd = portion.closed(0,1)\n\t\treduced_neigh = 0\n\t\tfor (c, world) in nas:\n\t\t\tif c in neigh:\n\t\t\t\tlabels = c.getLabels()\n\t\t\t\tfor l in labels:\n\t\t\t\t\tif world.isSatisfied(l, portion.closed(1,1)):\n\t\t\t\t\t\treduced_neigh += 1\n\t\t\t\t\t\tbreak\n\n\t\tif reduced_neigh != 0:\n\t\t\tif (len(qualified_neigh) / len(neigh)) > self._treshold:\n\t\t\t\tbnd = self._bnd_update\n\n\t\treturn bnd\n\n", "repo_name": "jnparedes/Netder_experiment", "sub_path": "Diffusion_Process/EnhancedTipping.py", "file_name": "EnhancedTipping.py", "file_ext": "py", "file_size_in_byte": 664, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "21", "api": [{"api_name": "Diffusion_Process.AbstractInfluenceFunction.AbstractInfluenceFunction", "line_number": 4, "usage_type": "name"}, {"api_name": "portion.closed", "line_number": 11, "usage_type": "call"}, {"api_name": "portion.closed", "line_number": 17, "usage_type": "call"}]} +{"seq_id": "20693245123", "text": "#!/usr/bin/python3.4\n# _*_coding:Utf_8 _*\n\nfrom elasticsearch_dsl import DocType, Index, String, Date, Integer, Boolean, Float, Object, GeoPoint\nfrom elasticsearch_dsl.connections import connections\nfrom elasticsearch.exceptions import ConnectionError\nfrom analyzers import emailAnalyzer, fetchReceived, headerSanitizer,emailAnalyzerReceived,getDate\nclass Spam(DocType):\n X_Envelope_From = Object(\n properties = {\n 'email': String(index='not_analyzed'),\n 'header': String(index='not_analyzed'),\n 'localpart': String(index='not_analyzed'),\n 'domain': String(index='not_analyzed'),\n 'location': GeoPoint(),\n 'domain_type': String(index='not_analyzed'),\n 'country_code' : String(index='not_analyzed')\n }\n )\n X_Envelope_To = String(index='not_analyzed')\n X_Spam_Flag = Boolean()\n X_Spam_Score = Float()\n To = String(multi=True, index='not_analyzed')\n Date = Date()\n From = String(index='not_analyzed')\n Reply_To = String(index='not_analyzed')\n X_Priority = Integer()\n #X_Mailer = String()\n MIME_Version = String(index='not_analyzed')\n Subject = String()\n Content_Transfer_Encoding = String(index='not_analyzed')\n Content_Type = String(index='not_analyzed')\n Charset = String(index='not_analyzed')\n Received = String(index='not_analyzed')\n Hops = Integer()\n Received_SPF = String(index = 'not_analyzed')\n DKIM_Signature = String(index = 'not_analyzed')\n ##### HEADERS RAJOUTES SUITE A TRAITEMENT ####\n spfResult = String(index = 'not_analyzed')\n spfTrue = String(index = 'not_analyzed')\n DKIM_Result = String(index = 'not_analyzed')\n DKIM_KeyLength = Integer()\n #############################################\n #Message = String()\n phoneNumbers = String(multi=True, index='not_analyzed')\n URLs = String(multi=True, index='not_analyzed')\n attachmentsTypes = String(multi=True, index='not_analyzed')\n attachmentsSizes = Integer(multi=True)\n\n class Meta:\n index = 'default_index'\n doc_type = 'spam'\n\n def save(self, ** kwargs):\n return super().save(** kwargs)\n\n\ndef indexMail(jsonMail, indexName, nodeIP, nodePort, database):\n # Try connecting to the Elasticsearch node\n try:\n connections.create_connection(hosts=[nodeIP+':'+str(nodePort)],timeout=3)\n\n # Create the mapping if the index doesn't exist\n if not Index(indexName).exists():\n Spam.init(index=indexName)\n\n # Create a new mail and initialize it\n if (jsonMail['X-Envelope-To'] != \"EMPTY\"):\n newMail = Spam(X_Envelope_To=jsonMail['X-Envelope-To'])\n if (jsonMail['X-Envelope-From'] != \"EMPTY\" and jsonMail['X-Envelope-From'] != \"<>\" and jsonMail['X-Envelope-From'] != 'False'):\n newMail.X_Envelope_From.header = jsonMail['X-Envelope-From']\n analyzingResult = emailAnalyzer(jsonMail['X-Envelope-From'], database)\n newMail.X_Envelope_From.email = analyzingResult[0]\n newMail.X_Envelope_From.localpart = analyzingResult[1]\n newMail.X_Envelope_From.domain = analyzingResult[2]\n newMail.X_Envelope_From.domain_type = analyzingResult[4]\n if (analyzingResult[3] != \"\"):\n newMail.X_Envelope_From.location = analyzingResult[3]\n if (analyzingResult[5] != \"\"):\n newMail.X_Envelope_From.country_code = analyzingResult[5]\n if (jsonMail['X-Spam-Flag'] != \"EMPTY\"):\n newMail.X_Spam_Flag = jsonMail['X-Spam-Flag']\n if (jsonMail['To'] != \"EMPTY\"):\n for mail in headerSanitizer(jsonMail['To']):\n newMail.To.append(mail)\n if (jsonMail['From'] != \"EMPTY\"):\n newMail.From = jsonMail['From']\n if (jsonMail['Reply-To'] != \"EMPTY\"):\n newMail.Reply_To = jsonMail['Reply-To']\n if (jsonMail['Content-Transfer-Encoding'] != \"EMPTY\"):\n newMail.Content_Transfer_Encoding = jsonMail['Content-Transfer-Encoding']\n if (jsonMail['Content-Type'] != \"EMPTY\"):\n newMail.Content_Type = jsonMail['Content-Type']\n if (jsonMail['Subject'] != \"EMPTY\") :\n newMail.Subject = jsonMail['Subject']\n if (jsonMail['Charset'] != \"EMPTY\") :\n newMail.Charset = jsonMail['Charset']\n if (jsonMail['Received'] != \"EMPTY\") :\n newMail.Received = jsonMail['Received']\n newMail.Hops = len(fetchReceived(jsonMail['Received']))\n if(jsonMail['X-Envelope-From'] == 'EMPTY' or jsonMail['X-Envelope-From'] == '<>' or jsonMail['X-Envelope-From'] == 'False'):\n analyzingResult = emailAnalyzerReceived(jsonMail['Received'], database)\n newMail.X_Envelope_From.domain = analyzingResult[0]\n newMail.X_Envelope_From.domain_type = analyzingResult[2]\n if (analyzingResult[1] != \"\"):\n newMail.X_Envelope_From.location = analyzingResult[1]\n if (jsonMail.get('Received-SPF','EMPTY') != \"EMPTY\") :\n newMail.Received_SPF = jsonMail['Received-SPF']\n if (jsonMail.get('spfResult','EMPTY') != 'EMPTY'):\n newMail.spfResult = jsonMail['spfResult']\n if(jsonMail.get('spfTrue','EMPTY') != 'EMPTY'):\n newMail.spfTrue = jsonMail['spfTrue']\n if (jsonMail['DKIM-Signature'] != \"EMPTY\") :\n newMail.DKIM_Signature = jsonMail['DKIM-Signature']\n newMail.DKIM_Result = jsonMail['dkimResult']\n if jsonMail['dkimResult'] == 'DKIM OK' and jsonMail.get('dkimKey','EMPTY') != 'EMPTY':\n newMail.DKIM_KeyLength = jsonMail['dkimKey']\n newMail.X_Spam_Score = jsonMail['X-Spam-Score']\n if(jsonMail['Date'] != '' and jsonMail['Date'] != 'EMPTY'):\n newMail.Date = jsonMail['Date']\n else:\n if (getDate(jsonMail['Received']) !='EMPTY'):\n newMail.Date = getDate(jsonMail['Received'])\n newMail.X_Priority = jsonMail['X-Priority']\n newMail.MIME_Version = jsonMail['MIME-Version']\n for phoneNumber in jsonMail['phoneNumbers'] :\n newMail.phoneNumbers.append(phoneNumber)\n for url in jsonMail['URLs'] :\n newMail.URLs.append(url)\n for attachmentType in jsonMail['attachmentsTypes']:\n newMail.attachmentsTypes.append(attachmentType)\n for attachmentSize in jsonMail['attachmentsSizes']:\n newMail.attachmentsSizes.append(attachmentSize)\n #newMail.X_Mailer = jsonMail['X-Mailer']\n #newMail.Message = jsonMail['Message']\n\n # Overwrite the index name for the new mail\n newMail.meta.index = indexName\n # Save index\n result = newMail.save()\n # Close connection to Elasticsearh node\n connections.remove_connection('default')\n return result\n\n except ConnectionError:\n return False\n", "repo_name": "thithib/spamalysis", "sub_path": "indexer.py", "file_name": "indexer.py", "file_ext": "py", "file_size_in_byte": 6960, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "21", "api": [{"api_name": "elasticsearch_dsl.DocType", "line_number": 8, "usage_type": "name"}, {"api_name": "elasticsearch_dsl.Object", "line_number": 9, "usage_type": "call"}, {"api_name": "elasticsearch_dsl.String", "line_number": 11, "usage_type": "call"}, {"api_name": "elasticsearch_dsl.String", "line_number": 12, "usage_type": "call"}, {"api_name": "elasticsearch_dsl.String", "line_number": 13, "usage_type": "call"}, {"api_name": "elasticsearch_dsl.String", "line_number": 14, "usage_type": "call"}, {"api_name": "elasticsearch_dsl.GeoPoint", "line_number": 15, "usage_type": "call"}, {"api_name": "elasticsearch_dsl.String", "line_number": 16, "usage_type": "call"}, {"api_name": "elasticsearch_dsl.String", "line_number": 17, "usage_type": "call"}, {"api_name": "elasticsearch_dsl.String", "line_number": 20, "usage_type": "call"}, {"api_name": "elasticsearch_dsl.Boolean", "line_number": 21, "usage_type": "call"}, {"api_name": "elasticsearch_dsl.Float", "line_number": 22, "usage_type": "call"}, {"api_name": "elasticsearch_dsl.String", "line_number": 23, "usage_type": "call"}, {"api_name": "elasticsearch_dsl.Date", "line_number": 24, "usage_type": "name"}, {"api_name": "elasticsearch_dsl.String", "line_number": 25, "usage_type": "call"}, {"api_name": "elasticsearch_dsl.String", "line_number": 26, "usage_type": "call"}, {"api_name": "elasticsearch_dsl.Integer", "line_number": 27, "usage_type": "call"}, {"api_name": "elasticsearch_dsl.String", "line_number": 29, "usage_type": "call"}, {"api_name": "elasticsearch_dsl.String", "line_number": 30, "usage_type": "call"}, {"api_name": "elasticsearch_dsl.String", "line_number": 31, "usage_type": "call"}, {"api_name": "elasticsearch_dsl.String", "line_number": 32, "usage_type": "call"}, {"api_name": "elasticsearch_dsl.String", "line_number": 33, "usage_type": "call"}, {"api_name": "elasticsearch_dsl.String", "line_number": 34, "usage_type": "call"}, {"api_name": "elasticsearch_dsl.Integer", "line_number": 35, "usage_type": "call"}, {"api_name": "elasticsearch_dsl.String", "line_number": 36, "usage_type": "call"}, {"api_name": "elasticsearch_dsl.String", "line_number": 37, "usage_type": "call"}, {"api_name": "elasticsearch_dsl.String", "line_number": 39, "usage_type": "call"}, {"api_name": "elasticsearch_dsl.String", "line_number": 40, "usage_type": "call"}, {"api_name": "elasticsearch_dsl.String", "line_number": 41, "usage_type": "call"}, {"api_name": "elasticsearch_dsl.Integer", "line_number": 42, "usage_type": "call"}, {"api_name": "elasticsearch_dsl.String", "line_number": 45, "usage_type": "call"}, {"api_name": "elasticsearch_dsl.String", "line_number": 46, "usage_type": "call"}, {"api_name": "elasticsearch_dsl.String", "line_number": 47, "usage_type": "call"}, {"api_name": "elasticsearch_dsl.Integer", "line_number": 48, "usage_type": "call"}, {"api_name": "elasticsearch_dsl.connections.connections.create_connection", "line_number": 61, "usage_type": "call"}, {"api_name": "elasticsearch_dsl.connections.connections", "line_number": 61, "usage_type": "name"}, {"api_name": "elasticsearch_dsl.Index", "line_number": 64, "usage_type": "call"}, {"api_name": "analyzers.emailAnalyzer", "line_number": 72, "usage_type": "call"}, {"api_name": "analyzers.headerSanitizer", "line_number": 84, "usage_type": "call"}, {"api_name": "analyzers.fetchReceived", "line_number": 100, "usage_type": "call"}, {"api_name": "analyzers.emailAnalyzerReceived", "line_number": 102, "usage_type": "call"}, {"api_name": "analyzers.getDate", "line_number": 122, "usage_type": "call"}, {"api_name": "analyzers.getDate", "line_number": 123, "usage_type": "call"}, {"api_name": "elasticsearch_dsl.connections.connections.remove_connection", "line_number": 142, "usage_type": "call"}, {"api_name": "elasticsearch_dsl.connections.connections", "line_number": 142, "usage_type": "name"}, {"api_name": "elasticsearch.exceptions.ConnectionError", "line_number": 145, "usage_type": "name"}]} +{"seq_id": "12950612573", "text": "###author: Ziqiu###\n\nimport zipfile\nimport os\nimport pandas as pd\nimport numpy as np\n\nclass histdata:\n\n def __init__(self):\n self._base_dir = r'E:\\FinanceProjects\\RawData\\Forex\\HistDataZips'\n\n self.currencies = ['eurusd', 'eurchf', 'eurgbp', 'eurjpy',\n 'euraud', 'usdcad', 'usdchf', 'usdjpy',\n 'usdmxn', 'gbpchf', 'gbpjpy', 'gbpusd',\n 'audjpy', 'audusd', 'chfjpy', 'nzdjpy',\n 'nzdusd', 'xauusd', 'eurcad', 'audcad',\n 'cadjpy', 'eurnzd', 'grxeur', 'nzdcad',\n 'sgdjpy', 'usdhkd', 'usdnok', 'usdtry',\n 'xauaud', 'audchf', 'auxaud', 'eurhuf',\n 'eurpln', 'frxeur', 'hkxhkd', 'nzdchf',\n 'spxusd', 'usdhuf', 'usdpln', 'usdzar',\n 'xauchf', 'zarjpy', 'bcousd', 'etxeur',\n 'eurczk', 'eursek', 'gbpaud', 'gbpnzd',\n 'jpxjpy', 'udxusd', 'usdczk', 'usdsek',\n 'wtiusd', 'xaueur', 'audnzd', 'cadchf',\n 'eurdkk', 'eurnok', 'eurtry', 'gbpcad',\n 'nsxusd', 'ukxgbp', 'usddkk', 'usdsgd',\n 'xagusd', 'xaugbp']\n\n self.tick_types = ['LAST', 'BID', 'ASK']\n\n self._start_years = [2000, 2002, 2002, 2002,\n 2002, 2000, 2000, 2000,\n 2010, 2002, 2002, 2000,\n 2002, 2000, 2002, 2006,\n 2005, 2009, 2007, 2007,\n 2007, 2008, 2010, 2008,\n 2008, 2008, 2008, 2010,\n 2009, 2008, 2010, 2010,\n 2010, 2010, 2010, 2008,\n 2010, 2010, 2010, 2010,\n 2009, 2010, 2010, 2010,\n 2010, 2008, 2007, 2008,\n 2010, 2010, 2010, 2008,\n 2010, 2009, 2007, 2008,\n 2008, 2008, 2010, 2007,\n 2010, 2010, 2008, 2008,\n 2009, 2009]\n\n self._start_months = [5, 3, 3, 3,\n 8, 6, 5, 5,\n 11, 8, 5, 5,\n 8, 6, 8, 9,\n 8, 3, 3, 10,\n 3, 3, 11, 3,\n 8, 8, 8, 11,\n 5, 3, 11, 11,\n 11, 11, 11, 3,\n 11, 11, 11, 11,\n 5, 11, 11, 11,\n 11, 8, 9, 3,\n 11, 11, 8, 8,\n 11, 5, 9, 3,\n 8, 8, 11, 9,\n 11, 11, 8, 8,\n 5, 5]\n\n def get_time_of_data(self, currency):\n index = self.currencies.index(currency)\n start_time = pd.datetime(self._start_years[index], self._start_months[index], 1)\n return start_time\n\n def get_data_as_dataframe(self, currency, start_time, end_time, type='LAST'):\n start_year = start_time.year\n start_month = start_time.month\n end_year = end_time.year\n end_month = end_time.month\n years = range(start_year, end_year+1)\n\n base_filename = 'HISTDATA_COM_NT_{}_T_{}{}{}.zip'\n result = pd.DataFrame()\n\n total_months = (13 - start_month) + (12 * (end_year - start_year) - (12 - end_month))\n i = 0\n sm = 1\n em = 12\n for year in years:\n if year == years[0]:\n sm = start_month\n if year == years[-1]:\n em = end_month\n\n months = ['0'+str(i) if i < 10 else str(i) for i in list(range(sm, em+1))]\n print(months)\n for month in months:\n full_file_path = os.path.join(self._base_dir, base_filename.format(currency, type, year, month))\n archive = zipfile.ZipFile(full_file_path)\n\n if result.empty:\n result = pd.read_csv(archive.open(archive.namelist()[0]), header=None, names=['Date-tick', type],\n usecols=[0,1],index_col=['Date-tick'], delimiter=';', parse_dates=True)\n else:\n temp = pd.read_csv(archive.open(archive.namelist()[0]), header=None, names=['Date-tick', type],\n usecols=[0,1],index_col=['Date-tick'], delimiter=';', parse_dates=True)\n result = result.append(temp)\n print('Added month {} of {} total'.format(i, total_months))\n i += 1\n\n return result", "repo_name": "ZiqiuZang/PythonTraining", "sub_path": "data analysis/histdata_interface.py", "file_name": "histdata_interface.py", "file_ext": "py", "file_size_in_byte": 4869, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "pandas.datetime", "line_number": 71, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 82, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 97, "usage_type": "call"}, {"api_name": "os.path", "line_number": 97, "usage_type": "attribute"}, {"api_name": "zipfile.ZipFile", "line_number": 98, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 101, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 104, "usage_type": "call"}]} +{"seq_id": "22805989777", "text": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom matplotlib.animation import FuncAnimation\nfrom pytransform3d.plot_utils import Frame\nfrom pytransform3d.rotations import *\nfrom scipy import integrate as it\n\ndef read_data(file):\n\t'''\n\tArg: txt file as str\n\tFunction: Takes in file, returns list of data lists \n\tFile format: time is final string, makes n-sized\n\t\t\t\t list of n-elements before \n\t'''\n\txs = []\n\tys = []\n\tzs = []\n\n\twith open(file, 'r') as file:\n\t\tfull_data = []\n\t\tfor line in file:\n\t\t\tinstance = []\n\t\t\tfor element in line.split():\n\t\t\t\tinstance.append(float(element))\n\t\t\tfull_data.append(instance)\n\t\treturn full_data\n\ndef integrate(data_T):\n\t'''\n\tArg: transposed data - xs, ys, zs, ts are all in their\n\t\t own lists; ts are always the last element\n\tFunction: integrates to position and/or velocity for\n\t\t\t both linear and angular data\n\t'''\n\n\tintegratedData_1 = []\n\tintegratedData_2 = []\n\n\tfor dimension in data_T[0:3]:\n\t\tts = data_T[3]\n\t\tinitial = dimension[0]\n\t\tintegratedData = it.cumtrapz(np.array(dimension), np.array(ts), initial=initial)\n\t\tintegratedData_1.append(integratedData)\n\t\tprint(integratedData)\n\n\treturn integratedData_1\n\nangvelData = read_data(\"data/attitude.txt\")\nangvelDataTransposed = np.array(angvelData).T\norientationData = np.array(integrate(angvelDataTransposed)).T\n\nprint(orientationData)\n# print(len(orientationData))\n\n# ax = plot_basis(R=np.eye(3), ax_s=2)\n# # axis = 0\n# # angle = np.pi / 2\n\n# # p = np.array([1.0, 1.0, 1.0])\n# # euler = [0, 0, 0]\n# # euler[axis] = angle\n# # R = matrix_from_euler_xyz(euler)\n\ndef update_frame(i, data, frame):\n # angle = 2.0 * np.pi * (step + 1) / n_frames\n roll = data[i][0]\n pitch = data[i][1]\n yaw = data[i][2]\n euler = [roll, pitch, yaw]\n R = matrix_from_euler_xyz(euler)\n A2B = np.eye(4)\n A2B[:3, :3] = R\n frame.set_data(A2B)\n return frame\n\n\nif __name__ == \"__main__\":\n n_frames = 50\n\n fig = plt.figure(figsize=(5, 5))\n\n ax = fig.add_subplot(111, projection=\"3d\")\n ax.set_xlim((-1, 1))\n ax.set_ylim((-1, 1))\n ax.set_zlim((-1, 1))\n ax.set_xlabel(\"X\")\n ax.set_ylabel(\"Y\")\n ax.set_zlabel(\"Z\")\n\n frame = Frame(np.eye(4), label=\"rotating frame\", s=0.5)\n frame.add_frame(ax)\n\n anim = FuncAnimation(\n fig, update_frame, len(orientationData), fargs=(orientationData, frame), interval=100,\n blit=False)\n\n plt.show()\n", "repo_name": "afarah2002/PiRocket", "sub_path": "archives/onboard_test/live_attitude_plotter.py", "file_name": "live_attitude_plotter.py", "file_ext": "py", "file_size_in_byte": 2412, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "scipy.integrate.cumtrapz", "line_number": 43, "usage_type": "call"}, {"api_name": "scipy.integrate", "line_number": 43, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 43, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 50, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 51, "usage_type": "call"}, {"api_name": "numpy.eye", "line_number": 72, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 81, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 81, "usage_type": "name"}, {"api_name": "pytransform3d.plot_utils.Frame", "line_number": 91, "usage_type": "call"}, {"api_name": "numpy.eye", "line_number": 91, "usage_type": "call"}, {"api_name": "matplotlib.animation.FuncAnimation", "line_number": 94, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.show", "line_number": 98, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 98, "usage_type": "name"}]} +{"seq_id": "43549185115", "text": "import argparse\r\nimport subprocess\r\nimport uuid\r\n\r\nfrom loguru import logger\r\n\r\n\r\ndef create_process(executable, consumer):\r\n return (\r\n consumer,\r\n subprocess.Popen(\r\n [\"nohup\", \"python\", \"-m\", executable, consumer], start_new_session=True,\r\n ),\r\n )\r\n\r\n\r\ndef init_argparse() -> argparse.ArgumentParser:\r\n parser = argparse.ArgumentParser()\r\n parser.add_argument(\"exec\", help=\"command or program to execute in workers\")\r\n parser.add_argument(\r\n \"-w\",\r\n \"--workers\",\r\n help=\"number of workers\",\r\n nargs=\"?\",\r\n type=int,\r\n const=15,\r\n default=15,\r\n )\r\n\r\n return parser\r\n\r\n\r\ndef main() -> None:\r\n parser = init_argparse()\r\n args = parser.parse_args()\r\n\r\n processes = [\r\n create_process(args.exec, str(uuid.uuid4())) for _ in range(args.workers)\r\n ]\r\n\r\n for consumer, p in processes:\r\n if p.wait() != 0:\r\n logger.error(f\"There was an error in {consumer}\")\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n", "repo_name": "headsrooms/historedge-backend", "sub_path": "historedge_backend/worker.py", "file_name": "worker.py", "file_ext": "py", "file_size_in_byte": 1039, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "21", "api": [{"api_name": "subprocess.Popen", "line_number": 11, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 18, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 17, "usage_type": "attribute"}, {"api_name": "uuid.uuid4", "line_number": 38, "usage_type": "call"}, {"api_name": "loguru.logger.error", "line_number": 43, "usage_type": "call"}, {"api_name": "loguru.logger", "line_number": 43, "usage_type": "name"}]} +{"seq_id": "17804141991", "text": "\"\"\"\nModule with auxillary\n jit-compiled functions\n for resize of\n CT scans\n\"\"\"\n\nfrom numba import jit\nimport scipy.ndimage\nfrom PIL import Image\nimport numpy as np\n\n\n@jit(nogil=True)\ndef resize_scipy(patient, out_patient, res, order=3, factor=None, padding='edge'):\n \"\"\" Resize 3d scan and put it into out_patient.\n\n Resize engine is scipy.ndimage.interpolation.zoom.\n If factor is not supplied, infer resize factor from out_patient.shape.\n otherwise, use factor for resize and then crop/pad resized array to out_patient.shape.\n\n Parameters\n ----------\n patient : ndarray\n 3D array\n out_patient : ndarray\n resulting array\n res : ndarray\n resulting `skyscraper` for the whole batch.\n used later by `_post`-func in _inbatch_parallel\n order : int\n order of interpolation\n factor : tuple or None\n resize factor along (z,y,x) in int ir float for interpolation.\n If not None, can yield array of shape != out_patient.shape,\n then crop/pad is used\n padding : str\n mode of padding, any mode of np.pad()\n\n Returns\n -------\n tuple\n (res, out_patient.shape), resulting `skyscraper` and shape of\n resized scan inside this `scyscraper`.\n\n Notes\n -----\n Shape of resulting array has to be inferred\n from out_patient\n \"\"\"\n # infer shape of resulting array\n shape = out_patient.shape\n\n # define resize factor, perform resizing and put the result into out_patient\n if factor is None:\n factor = np.array(out_patient.shape) / np.array(patient.shape)\n out_patient[:, :, :] = scipy.ndimage.interpolation.zoom(patient, factor,\n order=order)\n else:\n out_patient[:, :, :] = to_shape((scipy.ndimage.interpolation.\n zoom(patient, factor, order=order)),\n shape=shape, padding=padding)\n\n # return out-array for the whole batch\n # and shape of out_patient\n return res, out_patient.shape\n\n\n@jit(nogil=True)\ndef resize_pil(input_array, output_array, res, axes_pairs=None, shape_resize=None,\n resample=None, padding='edge'):\n \"\"\" Resize 3D scan.\n\n Uses _seq_resize over a pair of axes for applying many 2d-resizes,\n then averages over different pairs for obtaining more precise results.\n\n Parameters\n ----------\n input_array : ndarray\n array to be resized.\n ouput_array : ndarray\n array, where the result should be put.\n res : ndarray\n resulting `skyscraper` for the whole batch.\n used later by `_post`-func in _inbatch_parallel\n axes_pairs : tuple, list of tuples or None\n pairs of axes for 2d resizes, then averaging is performed,\n e.g., ((0,1),(1,2),(0,2))\n if None, defaults to ((0, 1), (1, 2))\n shape_resize : tuple, list, ndarray or None\n shape of array after resize.\n If None, infer shape from `ouput_array.shape`.\n resample : str or None\n type of PIL resize's resampling method, e.g.\n `BILINEAR`, `BICUBIC`,`LANCZOS` or `NEAREST`.\n If None, `BILINEAR` is used.\n padding : str\n mode of padding, any mode of np.pad()\n\n Returns\n -------\n tuple\n (res, out_patient.shape), resulting `skyscraper` and shape of\n resized scan inside this `scyscraper`.\n \"\"\"\n # if resample not given, set to bilinear\n resample = Image.BILINEAR if resample is None else resample\n\n # if axes_pairs not supplied, set the arg to two default axes pairs\n axes_pairs = ((0, 1), (1, 2)) if axes_pairs is None else axes_pairs\n\n # if shape is not supplied, infer it from output_array\n shape_resize = shape_resize if shape_resize is not None else output_array.shape\n\n if tuple(shape_resize) == output_array.shape:\n for axes in axes_pairs:\n output_array[:, :, :] += _seq_resize(input_array, shape_resize, axes, resample)\n else:\n for axes in axes_pairs:\n output_array[:, :, :] += to_shape(_seq_resize(input_array, shape_resize, axes, resample),\n shape=output_array.shape, padding=padding)\n\n # normalize result of resize (average over resizes with different pairs of axes)\n output_array[:, :, :] /= len(axes_pairs)\n\n # for post-function\n return res, output_array.shape\n\n\n@jit(nogil=True)\ndef _seq_resize(input_array, shape, axes, resample):\n \"\"\" Perform 3d-resize based on sequence of 2d-resizes performed on slices.\n\n Parameters\n ----------\n input_array : ndarray\n 3D array\n shape : tuple, list or ndarray\n shape of 3d scan after resize, (z,y,x).\n axes : tuple, list or ndarray\n axes for slicing. E.g., `shape` = (z, y, x) and axes = (0, 1). We first loop over\n 2d-slices [i, :, :] and reshape input to shape = (input_array.shape[0], y, x).\n then loop over slices [:, i, :] and reshape the result to shape = (z, y, x).\n resample : str or None\n type of PIL resize's resampling method, e.g.\n `BILINEAR`, `BICUBIC`,`LANCZOS` or `NEAREST`.\n If None, `BILINEAR` is used.\n\n Returns\n -------\n ndarray\n resized 3D array\n \"\"\"\n result = input_array\n\n # loop over axes\n for axis in axes:\n slice_shape = np.delete(shape, axis)\n result = _slice_and_resize(result, axis, slice_shape, resample)\n\n return result\n\n\n@jit(nogil=True)\ndef _slice_and_resize(input_array, axis, slice_shape, resample):\n \"\"\" Slice 3D array along `axis` and resize each slice to `slice_shape`.\n\n Parameters\n ----------\n input_array : ndarray\n 3D array\n axis : int\n axis along which slices are taken\n slice_shape : tuple,list or ndarray\n (y,x) shape of each slice after resize\n resample : str or None\n type of PIL resize's resampling method, e.g.\n `BILINEAR`, `BICUBIC`,`LANCZOS` or `NEAREST`.\n If None, `BILINEAR` is used.\n\n Returns\n -------\n ndarray\n 3D array in which each slice along chosen axis is resized\n \"\"\"\n # init the resulting array\n result_shape = np.insert(np.array(slice_shape), axis, input_array.shape[axis])\n result = np.zeros(shape=result_shape)\n\n # invert slice shape for PIL.resize\n slice_shape = slice_shape[::-1]\n\n # loop over the axis given by axis\n for i in range(result.shape[axis]):\n slices = np.array([slice(None), slice(None), slice(None)])\n slices[axis] = i\n slices = tuple(slices)\n\n # resize the slice and put the result in result-array\n result[slices] = np.array(Image.fromarray(input_array[slices]).resize(slice_shape, resample=resample))\n\n return result\n\n\ndef to_shape(data, shape, padding):\n \"\"\" Crop or pad 3D array to resize it to `shape`\n\n Parameters\n ----------\n data : ndarray\n 3D array for reshaping\n shape : tuple, list or ndarray\n data shape after crop or pad\n padding : str\n mode of padding, any of the modes of np.pad()\n\n Returns\n -------\n ndarray\n cropped and padded data\n \"\"\"\n # calculate shapes discrepancy\n data_shape = np.asarray(data.shape)\n shape = np.asarray(shape)\n overshoot = data_shape - shape\n\n # calclate crop params and perform crop\n crop_dims = np.maximum(overshoot, 0)\n crop_first = crop_dims // 2\n crop_trailing = crop_dims - crop_first\n slices = [slice(first, dim_shape - trailing)\n for first, trailing, dim_shape in zip(crop_first, crop_trailing, data_shape)]\n data = data[slices]\n\n # calculate padding params and perform padding\n pad_dims = -np.minimum(overshoot, 0)\n pad_first = pad_dims // 2\n pad_trailing = pad_dims - pad_first\n pad_params = [(first, trailing)\n for first, trailing in zip(pad_first, pad_trailing)]\n data = np.pad(data, pad_width=pad_params, mode=padding)\n\n # return cropped/padded array\n return data\n", "repo_name": "analysiscenter/radio", "sub_path": "radio/preprocessing/resize.py", "file_name": "resize.py", "file_ext": "py", "file_size_in_byte": 8000, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 215, "dataset": "github-code", "pt": "21", "api": [{"api_name": "numpy.array", "line_number": 56, "usage_type": "call"}, {"api_name": "scipy.ndimage.ndimage.interpolation.zoom", "line_number": 57, "usage_type": "call"}, {"api_name": "scipy.ndimage.ndimage", "line_number": 57, "usage_type": "attribute"}, {"api_name": "scipy.ndimage", "line_number": 57, "usage_type": "name"}, {"api_name": "scipy.ndimage.ndimage.interpolation.zoom", "line_number": 60, "usage_type": "call"}, {"api_name": "scipy.ndimage.ndimage", "line_number": 60, "usage_type": "attribute"}, {"api_name": "scipy.ndimage", "line_number": 60, "usage_type": "name"}, {"api_name": "numba.jit", "line_number": 14, "usage_type": "call"}, {"api_name": "PIL.Image.BILINEAR", "line_number": 107, "usage_type": "attribute"}, {"api_name": "PIL.Image", "line_number": 107, "usage_type": "name"}, {"api_name": "numba.jit", "line_number": 69, "usage_type": "call"}, {"api_name": "numpy.delete", "line_number": 158, "usage_type": "call"}, {"api_name": "numba.jit", "line_number": 130, "usage_type": "call"}, {"api_name": "numpy.insert", "line_number": 187, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 187, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 188, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 195, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 200, "usage_type": "call"}, {"api_name": "PIL.Image.fromarray", "line_number": 200, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 200, "usage_type": "name"}, {"api_name": "numba.jit", "line_number": 164, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 223, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 224, "usage_type": "call"}, {"api_name": "numpy.maximum", "line_number": 228, "usage_type": "call"}, {"api_name": "numpy.minimum", "line_number": 236, "usage_type": "call"}, {"api_name": "numpy.pad", "line_number": 241, "usage_type": "call"}]} +{"seq_id": "23677211016", "text": "import random \nfrom scipy.spatial import distance\nfrom scipy.stats import mode\nimport numpy\n\n\ndef euc(a, b):\n return distance.euclidean(a, b)\n\n\nclass ScrappyKNN():\n def fit(self, X_train, y_train):\n self.X_train = X_train\n self.y_train = y_train\n \n\n def predict(self, X_test):\n predictions = []\n for row in X_test:\n label = self.closest(row)\n predictions.append(label)\n return predictions\n\n def closest(self, row):\n dist = []\n \n for i in range(1,len(self.X_train)):\n dist.append([euc(row, self.X_train[i]), i])\n dist.sort(key=lambda dist: dist[0])\n k_smallest = dist[:3]\n k_nearest_labels = [self.y_train[i] for distance, i in k_smallest]\n best_index = mode(k_nearest_labels)\n \n return [int(best_index.mode)]\n \n\nfrom sklearn.datasets import load_iris\n\niris = load_iris()\nX = iris.data\ny = iris.target\n\n#split the data\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.5)\n\n\n\n# classifying model \nmy_classifier = ScrappyKNN()\nmy_classifier.fit(X_train, y_train)\n\npredictions = my_classifier.predict(X_test)\n\nfrom sklearn.metrics import accuracy_score\nprint(accuracy_score(y_test, predictions))\n", "repo_name": "dpes-neupane/KNN", "sub_path": "knearestneighbour.py", "file_name": "knearestneighbour.py", "file_ext": "py", "file_size_in_byte": 1322, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "scipy.spatial.distance.euclidean", "line_number": 8, "usage_type": "call"}, {"api_name": "scipy.spatial.distance", "line_number": 8, "usage_type": "name"}, {"api_name": "scipy.spatial.distance", "line_number": 31, "usage_type": "name"}, {"api_name": "scipy.stats.mode", "line_number": 32, "usage_type": "call"}, {"api_name": "sklearn.datasets.load_iris", "line_number": 39, "usage_type": "call"}, {"api_name": "sklearn.model_selection.train_test_split", "line_number": 45, "usage_type": "call"}, {"api_name": "sklearn.metrics.accuracy_score", "line_number": 56, "usage_type": "call"}]} +{"seq_id": "15144826916", "text": "import json\nimport yaml\nimport pprint\nimport psycopg2\nimport re\nfrom psycopg2 import OperationalError\n\n\n# Self Explanatory\ndef create_connection(db_name, db_user, db_password, db_host, db_port):\n connection = None\n\n try:\n connection = psycopg2.connect(\n database=db_name,\n user=db_user,\n password=db_password,\n host=db_host,\n port=db_port,\n )\n except OperationalError as e:\n print(f\"The error '{e}' occurred\")\n\n return connection\n\n\n# Recursively weeds out all the items in a dictionary\ndef unpack_dict(old_dict, new_dict, dup):\n if old_dict:\n new_dict.update({dup + key: value for key, value in old_dict.items() if type(value) != dict\n and type(value) != list})\n temp = (key for key, value in old_dict.items() if type(value) == list or type(value) == dict)\n\n if temp:\n for key in temp:\n unpack_dict(old_dict.get(key), new_dict, dup[:-1] + \"_\" + key + \"_\") if dup != \"\" else \\\n unpack_dict(old_dict.get(key), new_dict, key + \"_\")\n else:\n pass\n\n\n# Helper Function\ndef removekey(d, key):\n r = dict(d)\n del r[key]\n return r\n\n\n# Formats the data headers in a style that PostgreSQL likes\ndef process_headers(args):\n temp = \"rw_mix INT, \\n threads INT, \\n queue_depth INT, \\n blocksize VARCHAR, \\n \"\n temp_iter = iter(args)\n\n while True:\n try:\n arg = next(temp_iter)\n if arg.rfind('.') != -1:\n arg = arg.replace(\".\", \"\")\n if arg.rfind('>=') != -1:\n arg = arg.replace(\">=\", \"greater_\")\n temp += arg + \" decimal, \\n \"\n except StopIteration:\n temp = temp[:-4]\n break\n\n return temp\n\n\n# Inits proper database schemas\ndef set_up_tables(connection, args, name):\n connection = create_connection(\"benchmarking\", \"admin\", \"\", \"frizzle.clients.homelab\", \"5432\")\n connection.autocommit = True\n cursor = connection.cursor()\n temp = \"CREATE TABLE \" + name + \"( \\n\" + args \\\n + \");\"\n\n # DEBUG: Too be removed later\n # print(temp)\n\n try:\n cursor.execute(temp)\n cursor.close()\n connection.commit()\n except psycopg2.errors.DuplicateTable as error:\n pass\n\n\n# Does a simple Insert statement to the database\ndef insert_data(name, headers, data):\n connection = create_connection(\"benchmarking\", \"admin\", \"\", \"frizzle.clients.homelab\", \"5432\")\n connection.autocommit = True\n headers = \"( \\n \" + headers.replace(\"decimal\", \"\").replace(\"INT\", \"\").replace(\"VARCHAR\", \"\") + \")\"\n command = \"INSERT INTO %s %s values %s ;\" % (name, headers, data)\n cursor = connection.cursor()\n\n # DEBUG: Too be removed later\n # print(command)\n\n try:\n cursor.execute(command)\n cursor.close()\n connection.commit()\n except (Exception, psycopg2.DatabaseError) as error:\n print(\"Error\")\n print(type(error))\n finally:\n if connection is not None:\n connection.close()\n\n\ndef export_csv(name, dest):\n connection = create_connection(\"benchmarking\", \"admin\", \"\", \"frizzle.clients.homelab\", \"5432\")\n connection.autocommit = True\n command = \"COPY %s TO %s DELIMITER ',' CSV HEADER;\" % (name, dest)\n cursor = connection.cursor()\n\n # DEBUG: Too be removed later\n # print(command)\n\n try:\n cursor.execute(command)\n cursor.close()\n connection.commit()\n except psycopg2.DatabaseError as error:\n print(type(error))\n finally:\n if connection is not None:\n connection.close()\n\n\n# Main function does all the heavy lifting\ndef parse(json_file, test_name, params):\n with open(json_file, 'r') as output:\n # Opening/loading json file\n results = json.load(output)\n jobs = results.get('jobs')[0]\n # Metadata: All the stuff that is not directly measured Data: All the results from the test runs\n metadata = {key: value for key, value in results.items() if type(value) != dict and type(value) != list}\n metadata.update({key: value for key, value in jobs.items() if type(value) != dict and type(value) != list})\n metadata[\"global_options\"] = results.get('global options')\n # Data: All the results from the test runs\n data = {}\n unpack_dict(jobs, data, \"\")\n data.pop(\"job options_name\")\n # Removing the Duplicate Objects and Processing the Data\n duplicates = {key: value for key, value in data.items() if (metadata.get(key) is not None)}\n gen = (key for key in data if duplicates.get(key) is not None)\n for key in gen:\n data = removekey(data, key)\n # Breaking up the Dictionary into two arrays containing headers + actual data\n data_headers = []\n data_content = [params[0], params[1], params[2],\n params[3]]\n for key, value in data.items():\n data_headers.append(key)\n data_content.append(value)\n # PostgresSQL Connection\n connection = create_connection(\"admin\", \"admin\", \"\", \"frizzle.clients.homelab\", \"5432\")\n connection.autocommit = True\n cursor = connection.cursor()\n\n # Debug code will be removed\n # for key, value in data.items():\n # print(str(key) + \":\" + str(value))\n\n # Dumping metadata to seperate output file\n with open(json_file[:-5] + \"-metadata.yml\", 'w+') as f:\n yaml.dump(metadata, f, allow_unicode=True)\n\n # Executing database insert statement (Creates Tables if it doesnt exist)\n try:\n cursor.execute(\"CREATE DATABASE benchmarking\")\n except psycopg2.errors.DuplicateDatabase as e:\n pass\n finally:\n print(tuple(data_content))\n set_up_tables(data_headers, process_headers(data_headers), test_name)\n insert_data(test_name, process_headers(data_headers), tuple(data_content))\n connection.close()\n return 0\n\n# MORE DEBUG CODE\n# parse(\"16-16-50-512.json\", \"first_test\", {\"test\": \"asdfasdf\"})\n", "repo_name": "deathewillcome3/FIOTester", "sub_path": "processor.py", "file_name": "processor.py", "file_ext": "py", "file_size_in_byte": 6123, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "psycopg2.connect", "line_number": 14, "usage_type": "call"}, {"api_name": "psycopg2.OperationalError", "line_number": 21, "usage_type": "name"}, {"api_name": "psycopg2.errors", "line_number": 84, "usage_type": "attribute"}, {"api_name": "psycopg2.DatabaseError", "line_number": 103, "usage_type": "attribute"}, {"api_name": "psycopg2.DatabaseError", "line_number": 124, "usage_type": "attribute"}, {"api_name": "json.load", "line_number": 135, "usage_type": "call"}, {"api_name": "yaml.dump", "line_number": 168, "usage_type": "call"}, {"api_name": "psycopg2.errors", "line_number": 173, "usage_type": "attribute"}]} +{"seq_id": "40554125665", "text": "import math\nfrom planar_magnetics.geometry import Point\nfrom planar_magnetics.windings import Spiral\nfrom planar_magnetics.cores import Core\nfrom planar_magnetics.kicad import Footprint, Reference, Value\n\n\nclass Transformer:\n \"\"\"A multi-winding planar transformer\n\n Args:\n inner_radius: The inner radius of the windings in mm\n outer_radius: The outer radius of the windings in mm\n stackup: A dictionary of tuples specifying the layer and number of turns for each winding\n core_to_edge: The clearance required between the core surface and the pcb cutouts in\n core_to_pcb: The distance between the core and the pcb surface in the z direction in mm\n board_thickness: The thickness of the PCB in mm\n trace_to_edge: The distance between winding edges and the edge cuts in mm\n \"\"\"\n\n def __init__(\n self,\n inner_radius: float,\n outer_radius: float,\n stackup: dict,\n core_to_edge: float = 0.5,\n trace_to_edge: float = 1,\n core_to_pcb: float = 1,\n board_thickness: float = 1.6,\n opening_width: float = None,\n gap: float = 0,\n ):\n self.inner_radius = inner_radius\n self.outer_radius = outer_radius\n self.stackup = stackup\n self.core_to_edge = core_to_edge\n self.trace_to_edge = trace_to_edge\n self.core_to_pcb = core_to_pcb\n self.board_thickness = board_thickness\n if opening_width is None:\n self.opening_width = outer_radius - inner_radius\n else:\n self.opening_width = opening_width\n\n # create the layers\n self.layers = [\n Spiral(inner_radius, outer_radius, n, s, l) for l, n, s in stackup\n ]\n\n # create the core\n core_to_trace = core_to_edge + trace_to_edge\n self.core = Core(\n centerpost_radius=inner_radius - core_to_trace,\n window_width=(outer_radius - inner_radius) + 2 * core_to_trace,\n window_height=board_thickness + 2 * core_to_pcb,\n opening_width=self.opening_width + 2 * core_to_trace,\n gap=gap,\n )\n\n def to_kicad_footprint(\n self,\n name: str,\n create_core_step: bool = False,\n freecad_path: str = \"C:/Program Files/FreeCAD 0.19/bin\",\n ):\n \"\"\"Export the Cffc inductor design as a KiCAD footprint file (*.kicad_mods)\"\"\"\n\n # add the reference and value silkscreens\n x_loc = self.core.width / 2 + 1\n height_avail = (self.core.width - self.opening_width) / 2\n font_size = min(2, height_avail / 4)\n val_loc = Point(x_loc, self.opening_width / 2 + height_avail / 3)\n ref_loc = Point(x_loc, self.opening_width / 2 + 2 * height_avail / 3)\n reference = Reference(ref_loc, font_size)\n value = Value(val_loc, font_size)\n\n cutouts = self.core.create_pcb_cutouts(Point(0, 0), self.core_to_edge)\n\n # create a footprint from the various elements\n contents = cutouts + self.layers + [reference, value]\n footprint = Footprint(name, contents=contents)\n\n # write the footprint to a file\n fh = open(f\"{name}.kicad_mod\", \"w\")\n fh.write(footprint.__str__())\n fh.close()\n\n if create_core_step:\n self.core.to_step(f\"{name}.step\", self.core_to_pcb - 0.1, 0.1, freecad_path)\n\n def plot(self):\n import matplotlib.pyplot as mp\n\n n_rows = min(2, len(self.layers))\n n_columns = math.ceil(len(self.layers) / 2)\n fig, axes = mp.subplots(n_rows, n_columns)\n\n for layer, ax in zip(self.layers, axes.ravel()):\n layer.plot(ax=ax)\n\n\nif __name__ == \"__main__\":\n\n transformer = Transformer(\n inner_radius=3,\n outer_radius=6,\n stackup=[\n (\"In1.Cu\", 1, 0.1),\n (\"In1.Cu\", 5, 0.1),\n (\"In2.Cu\", 5, 0.1),\n (\"In1.Cu\", 1, 0.1),\n ],\n )\n\n import matplotlib.pyplot as mp\n\n transformer.plot()\n mp.show()\n", "repo_name": "dzimmanck/python-planar-magnetics", "sub_path": "planar_magnetics/transformers/transformers.py", "file_name": "transformers.py", "file_ext": "py", "file_size_in_byte": 3996, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 23, "dataset": "github-code", "pt": "21", "api": [{"api_name": "planar_magnetics.windings.Spiral", "line_number": 47, "usage_type": "call"}, {"api_name": "planar_magnetics.cores.Core", "line_number": 52, "usage_type": "call"}, {"api_name": "planar_magnetics.geometry.Point", "line_number": 72, "usage_type": "call"}, {"api_name": "planar_magnetics.geometry.Point", "line_number": 73, "usage_type": "call"}, {"api_name": "planar_magnetics.kicad.Reference", "line_number": 74, "usage_type": "call"}, {"api_name": "planar_magnetics.kicad.Value", "line_number": 75, "usage_type": "call"}, {"api_name": "planar_magnetics.geometry.Point", "line_number": 77, "usage_type": "call"}, {"api_name": "planar_magnetics.kicad.Footprint", "line_number": 81, "usage_type": "call"}, {"api_name": "math.ceil", "line_number": 95, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 96, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 96, "usage_type": "name"}, {"api_name": "{'mp': 'matplotlib.pyplot'}", "line_number": 104, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.show", "line_number": 118, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 118, "usage_type": "name"}]} +{"seq_id": "24618971765", "text": "\n\n\nfrom time import sleep\nimport cv2\n\n\ncap = cv2.VideoCapture(0)\nframe_size = (640, 480)\nfourcc = cv2.VideoWriter_fourcc(*'XVID')\n\nrecording = False # 녹화 여부\nrecorder = None\ndef start_record():\n global recorder, recording\n start = datatime.now()\n fname = start.strftime('./sample_data/%Y%m%d_%H%M%S.mp4')\n recorder = cv2.VideoWriter(fname, fourcc, 20.0, frame_size)\n recording = True\n print(fname, 'start recording..')\n\ndef stop_record():\n global recorder, recording\n recording = False\n sleep(0.1) # 세그멘테이션 오류 방지\n recorder", "repo_name": "holymoly99/VNC_Raspberry-Pi_WORKSPACE", "sub_path": "mission.py", "file_name": "mission.py", "file_ext": "py", "file_size_in_byte": 579, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "cv2.VideoCapture", "line_number": 8, "usage_type": "call"}, {"api_name": "cv2.VideoWriter_fourcc", "line_number": 10, "usage_type": "call"}, {"api_name": "cv2.VideoWriter", "line_number": 18, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 25, "usage_type": "call"}]} +{"seq_id": "10250137880", "text": "from datetime import time\nimport timeit\n\nimport cv2\nimport os\nimport numpy as np\n\n\n# Display ROI binary mode\ndef binaryMask(frame, x0, y0, width, height):\n # Display box\n cv2.rectangle(frame, (x0, y0), (x0 + width, y0 + height), (0, 255, 0))\n # Extract ROI pixels\n roi = frame[y0 : y0 + height, x0 : x0 + width]\n #\n # Gaussian filtering proces\n gray = cv2.cvtColor(roi, cv2.COLOR_BGR2GRAY)\n # Gaussian blur is essentially a low-pass filter, each pixel of the output image is a weighted sum\n # of the pixels surrounding the corresponding pixel on the original image, and Larger the size of the matrix\n # Gaussian, the larger the standard deviation, the greater the degree of the image blur treated\n blur = cv2.GaussianBlur(\n gray, (5, 5), 2\n ) # Gaussian blur, blur matrix and given Gaussian standard deviation\n\n # When having different brightness of different portions of the same image. In this case, we need to use an\n # adaptive threshold\n # Parameters: src refers to the original image, the original image should be grayscale. x :\n # Refers to the new pixel value that should be given when the pixel value is higher (sometimes less than) the\n # threshold adaptive_method refers to: CV_ADAPTIVE_THRESH_MEAN_C or CV_ADAPTIVE_THRESH_GAUSSIAN_C block_size\n # refers to the pixel neighborhood size used to calculate the threshold : 3, 5, 7, ... param1 refers to the\n # parameters related to the method #\n th3 = cv2.adaptiveThreshold(\n blur, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 11, 2\n )\n ret, res = cv2.threshold(\n th3, 70, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU\n ) # ret or bool type\n\n \" Here you can insert code to call the network \"\n # Binarization process\n kernel = np.ones((3, 3), np.uint8) # Set convolution kernel\n erosion = cv2.erode(\n res, kernel\n ) # etching operation opening operation: the expansion after the first etching,\n # removing isolated dots, glitch\n cv2.imshow(\"erosion\", erosion)\n dilation = cv2.dilate(\n erosion, kernel\n ) # dilation and closing operation: After the first etching expanded,\n # filled pores, small cracks bridging\n cv2.imshow(\"dilation\", dilation)\n # Contour extraction\n binaryimg = cv2.Canny(res, 50, 200) # Binarization, canny detection\n h = cv2.findContours(\n binaryimg, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE\n ) # seek profile\n contours = h[0] # extracted contour\n ret = np.ones(res.shape, np.uint8) # Create a black curtain\n cv2.drawContours(ret, contours, -1, (255, 255, 255), 1) # Draw white outlines\n cv2.imshow(\"ret\", ret)\n\n # Saving gesture\n if saveImg == True and binaryMode == True:\n saveROI(res)\n elif saveImg == True and binaryMode == False:\n saveROI(roi)\n return res\n\n\n# Save ROI image\ndef saveROI(img):\n global path, counter, gesturename, saveImg\n if counter > numofsamples:\n # Restored to its original value, in order to continue recording the back gesture\n saveImg = False\n gesturename = \"\"\n counter = 0\n return\n\n counter += 1\n name = gesturename + str(counter) # to record a gesture of naming\n print(\"Saving img: \", name)\n cv2.imwrite(path + name + \".png\", img) # write files\n time.sleep(0.05)\n\n\n# Set some commonly used parameters\n# Display font size initial position, etc.\nfont = cv2.FONT_HERSHEY_SIMPLEX # normal size sans serif\nsize = 0.5\nfx = 10\nfy = 355\nfh = 18\n# ROI box display position\nx0 = 300\ny0 = 100\n# Recorded gesture image size\nwidth = 300\nheight = 300\n# Number of samples per gestures recorded\nnumofsamples = 300\ncounter = 0 # counter, recording how many pictures have been recorded\n# Memory address and the name of the original folder\ngesturename = \"\"\npath = \"\"\n# Identifier bool type is used to represent some state changing needs\nbinaryMode = False # whether the ROI is displayed as and to binary mode\nsaveImg = False # whether to save the picture\n\n# Create a video capture objects\ncap = cv2.VideoCapture(0) # 0 is (notebook) built-in camera\n\nwhile True:\n start = timeit.default_timer()\n # Reading frame\n (\n ret,\n frame,\n ) = (\n cap.read()\n ) # # first parameter is returned bool type, to indicate whether the reading frame,\n # if False description has read the last one. frame is the read frame picture\n # Image Flip (Without this step, the video display and we just symmetrical)\n frame = cv2.flip(\n frame, 2\n ) # the second parameter is greater than 0 : it indicates along the y -axis inverted\n # Display ROI area # call the function\n roi = binaryMask(frame, x0, y0, width, height)\n\n # Display promp\n cv2.putText(frame, \"Option: \", (fx, fy), font, size, (0, 255, 0)) # label font\n cv2.putText(\n frame, \"b-'Binary mode'/ r- 'RGB mode' \", (fx, fy + fh), font, size, (0, 255, 0)\n ) # labeled Font\n cv2.putText(\n frame, \"s-'new gestures(twice)'\", (fx, fy + 2 * fh), font, size, (0, 255, 0)\n ) # labeled Font\n cv2.putText(\n frame, \"q-'quit'\", (fx, fy + 3 * fh), font, size, (0, 255, 0)\n ) # labeled Font\n\n key = cv2.waitKey(1) & 0xFF # waiting for keyboard input,\n if key == ord(\"b\"): # The ROI is displayed as binary pattern\n # binaryMode = not binaryMode\n binaryMode = True\n print(\"Binary Threshold filter active\")\n elif key == ord(\"r\"): # RGB mode\n binaryMode = False\n\n if key == ord(\"i\"): # adjusted ROI box\n y0 = y0 - 5\n elif key == ord(\"k\"):\n y0 = y0 + 5\n elif key == ord(\"j\"):\n x0 = x0 - 5\n elif key == ord(\"l\"):\n x0 = x0 + 5\n\n if key == ord(\"q\"):\n break\n\n if key == ord(\"s\"):\n \"\"\"Record a new gesture (training set)\"\"\"\n # saveImg = not saveImg # True\n if gesturename != \"\": #\n saveImg = True\n else:\n print(\"Enter a gesture group name first, by enter press 'n'! \")\n saveImg = False\n elif key == ord(\"n\"):\n # Start recording a new gesture\n # First, enter the folder nam\n gesturename = input(\"enter the gesture folder name: \")\n os.makedirs(gesturename)\n\n path = (\n \"./\" + gesturename + \"/\"\n ) # address generation folder used to store the recorded gesture\n\n # Show video frame after treatment\n cv2.imshow(\"frame\", frame)\n if binaryMode:\n cv2.imshow(\"ROI\", roi)\n else:\n cv2.imshow(\"ROI\", frame[y0 : y0 + height, x0 : x0 + width])\n\n stop = timeit.default_timer()\n # display the time it took to run the code\n print(\"Run time:\", start - stop)\n\n\n# Finally, remember to release the catch\ncap.release()\ncv2.destroyAllWindows()\n", "repo_name": "musasali/hand-segmentation", "sub_path": "Segmentation.py", "file_name": "Segmentation.py", "file_ext": "py", "file_size_in_byte": 6762, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "21", "api": [{"api_name": "cv2.rectangle", "line_number": 12, "usage_type": "call"}, {"api_name": "cv2.cvtColor", "line_number": 17, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2GRAY", "line_number": 17, "usage_type": "attribute"}, {"api_name": "cv2.GaussianBlur", "line_number": 21, "usage_type": "call"}, {"api_name": "cv2.adaptiveThreshold", "line_number": 32, "usage_type": "call"}, {"api_name": "cv2.ADAPTIVE_THRESH_GAUSSIAN_C", "line_number": 33, "usage_type": "attribute"}, {"api_name": "cv2.THRESH_BINARY_INV", "line_number": 33, "usage_type": "attribute"}, {"api_name": "cv2.threshold", "line_number": 35, "usage_type": "call"}, {"api_name": "cv2.THRESH_BINARY_INV", "line_number": 36, "usage_type": "attribute"}, {"api_name": "cv2.THRESH_OTSU", "line_number": 36, "usage_type": "attribute"}, {"api_name": "numpy.ones", "line_number": 41, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 41, "usage_type": "attribute"}, {"api_name": "cv2.erode", "line_number": 42, "usage_type": "call"}, {"api_name": "cv2.imshow", "line_number": 46, "usage_type": "call"}, {"api_name": "cv2.dilate", "line_number": 47, "usage_type": "call"}, {"api_name": "cv2.imshow", "line_number": 51, "usage_type": "call"}, {"api_name": "cv2.Canny", "line_number": 53, "usage_type": "call"}, {"api_name": "cv2.findContours", "line_number": 54, "usage_type": "call"}, {"api_name": "cv2.RETR_TREE", "line_number": 55, "usage_type": "attribute"}, {"api_name": "cv2.CHAIN_APPROX_NONE", "line_number": 55, "usage_type": "attribute"}, {"api_name": "numpy.ones", "line_number": 58, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 58, "usage_type": "attribute"}, {"api_name": "cv2.drawContours", "line_number": 59, "usage_type": "call"}, {"api_name": "cv2.imshow", "line_number": 60, "usage_type": "call"}, {"api_name": "cv2.imwrite", "line_number": 83, "usage_type": "call"}, {"api_name": "datetime.time.sleep", "line_number": 84, "usage_type": "call"}, {"api_name": "datetime.time", "line_number": 84, "usage_type": "name"}, {"api_name": "cv2.FONT_HERSHEY_SIMPLEX", "line_number": 89, "usage_type": "attribute"}, {"api_name": "cv2.VideoCapture", "line_number": 111, "usage_type": "call"}, {"api_name": "timeit.default_timer", "line_number": 114, "usage_type": "call"}, {"api_name": "cv2.flip", "line_number": 124, "usage_type": "call"}, {"api_name": "cv2.putText", "line_number": 131, "usage_type": "call"}, {"api_name": "cv2.putText", "line_number": 132, "usage_type": "call"}, {"api_name": "cv2.putText", "line_number": 135, "usage_type": "call"}, {"api_name": "cv2.putText", "line_number": 138, "usage_type": "call"}, {"api_name": "cv2.waitKey", "line_number": 142, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 174, "usage_type": "call"}, {"api_name": "cv2.imshow", "line_number": 181, "usage_type": "call"}, {"api_name": "cv2.imshow", "line_number": 183, "usage_type": "call"}, {"api_name": "cv2.imshow", "line_number": 185, "usage_type": "call"}, {"api_name": "timeit.default_timer", "line_number": 187, "usage_type": "call"}, {"api_name": "cv2.destroyAllWindows", "line_number": 194, "usage_type": "call"}]} +{"seq_id": "75024741493", "text": "from selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.firefox.options import Options\nimport pytz\nfrom datetime import *\nimport requests\nfrom selenium.webdriver.firefox.service import Service\nfrom dotenv import load_dotenv\nimport os\n\nutc = pytz.UTC\n\nclass SpaceJesus:\n def __init__(self, subs):\n \"\"\"Class for the SpaceJesus Raddle bot.\n So far, he can...\n Crawl Raddle for new comments / posts\n Make a comment on a post, given a URL and comment text\n Submit an image given an image URL and a title\n I'm just figuring out functions currently, he doesn't do anything automatically yet.\n Also not sure what to make him do. Also not sure how to make him do things automatically, safely\"\"\"\n\n # Subs can be a single, or multiple chained with plus signs, same as Praw\n # Make a URLs dict to keep track of those pesky URLs\n self.urls = {\n 'posts': f\"https://raddle.me/f/{subs}/new\",\n 'submit': f'https://raddle.me/submit/{subs}',\n 'comments': f'https://raddle.me/f/{subs}/comments',\n 'login': \"http://www.raddle.me/login\"\n }\n\n def make_driver(self):\n\n # Setting up the webdriver arguments to keep it from being displayed at all\n opts = Options()\n opts.add_argument(\"--headless\")\n opts.add_argument(\"--no-sandbox\")\n\n # Where the webdriver file is located\n ff_driver = \"drive\\\\geckodriver\"\n\n # Create a webdriver service object\n driver_service = Service(ff_driver)\n\n # Create the Firefox webdriver with the service object and options\n driver = webdriver.Firefox(service=driver_service, options=opts)\n return driver\n\n def login(self):\n \"\"\"Login to Raddle with Selenium / Firefox\"\"\"\n\n # Load in credentials\n load_dotenv()\n raddle_user = os.getenv('raddle_username')\n raddle_password = os.getenv('raddle_password')\n\n # Pull the Raddle login page\n self.driver.get(self.urls['login'])\n\n # Find the input box for your username and pop it in there\n elem = self.driver.find_element(By.ID, \"login-username\")\n elem.clear()\n elem.send_keys(raddle_user)\n\n # Find the input box for your password and pop it in there\n elem = self.driver.find_element(By.ID, \"login-password\")\n elem.clear()\n elem.send_keys(raddle_password)\n\n # Hit enter and wait until the title is correct\n elem.send_keys(Keys.RETURN)\n wait = WebDriverWait(self.driver, 30)\n wait.until(EC.title_is(\"Raddle\"))\n\n\n def get_new_comments(self):\n \"\"\"Get new comments for the chosen sub\"\"\"\n\n # Log in\n self.driver = self.make_driver()\n self.login()\n\n # Gets the New comments page\n self.driver.get(self.urls['comments'])\n\n # Gets all new comments\n new_comments = self.driver.find_elements(By.CLASS_NAME, 'comment__main')\n\n # Empty dict to hold comments dicts\n comments = []\n\n # Iterate through comments and stick them in a list.\n # Why, not sure yet, probably working up to a stream function.\n for comment in new_comments:\n\n # Get comments timestamp\n ts = comment.find_element(By.TAG_NAME, \"time\").get_attribute('datetime')\n\n # Get commenter\n poster = comment.find_element(By.CLASS_NAME, 'fg-inherit').get_attribute('href')\n\n # Get comments text\n title = comment.find_element(By.CLASS_NAME, 'comment__body').text\n\n # Get the comments URL\n url = comment.find_element(By.CLASS_NAME, 'comment__permalink').get_attribute('href')\n\n commentDict = {\n \"timestamp\": ts,\n \"user\": poster,\n \"title\": title,\n \"url\": url,\n }\n comments.append(commentDict)\n\n return comments\n\n def get_new_posts(self):\n \"\"\" Get a list of new posts from the sub we're watching \"\"\"\n self.driver = self.make_driver()\n self.login()\n\n # Gets the New posts page\n self.driver.get(self.urls['posts'])\n\n # Gets all new posts\n new_posts = self.driver.find_elements(By.CLASS_NAME, 'submission__inner')\n\n # Empty dict to hold post dicts\n posts = []\n\n for post in new_posts:\n\n # Get submission timestamp\n ts = post.find_element(By.CLASS_NAME, 'submission__timestamp').get_attribute('datetime')\n\n # Get poster\n poster = post.find_element(By.CLASS_NAME, 'submission__submitter').get_attribute('href')\n\n # Get post title\n title = post.find_element(By.CLASS_NAME, 'submission__link').text\n\n # Get the post URL\n url = post.find_element(By.CLASS_NAME, 'submission__nav').find_element(By.CLASS_NAME, 'text-sm').get_attribute('href')\n\n post = {\n \"timestamp\": ts,\n \"user\": poster,\n \"title\": title,\n \"url\": url,\n }\n posts.append(post)\n\n return posts\n\n def make_comment_id(self, url):\n \"\"\"Quick and Dirty way to craft an element ID for a post\"\"\"\n\n # Split the URL into sections\n split_strings = url.split(\"/\")\n\n # This function can be used for comments or submissions, figure out which\n if \"-/comment/\" in url:\n comment_id = url.split('-/comment/')[1]\n text = f'reply_to_comment_{comment_id}_comment'\n\n else:\n post_id = split_strings[-2]\n text = f'reply_to_submission_{post_id}_comment'\n\n return text\n\n def post_comment(self, URL, comment):\n \"\"\"Post a comment, given the webdriver object, the comment link, and the text to send\"\"\"\n\n self.driver = self.make_driver()\n self.login()\n\n # Fetch the URL we're given\n self.driver.get(URL)\n\n # Craft the ID we need to find the comment text box\n id_to_check = self.make_comment_id(URL)\n\n # Find the comment text box\n elem = self.driver.find_element(By.ID, id_to_check)\n\n # Type in our nifty-ass comment.\n try:\n elem.send_keys(comment)\n except:\n reply = self.driver.find_element(By.CLASS_NAME, 'comment__reply-link')\n reply.click()\n elem.send_keys(comment)\n\n # Find the submit button. Surprisingly the only button with the \"button\" class on the page.\n elem = self.driver.find_element(By.CLASS_NAME, \"button\")\n\n # Click that bitch\n elem.click()\n\n def download_image(self, image_url):\n \"\"\"Downloads an image from a URL so bot can post images from URLs people give it\"\"\"\n\n # Local dir. Will fix.\n subdir = 'C:\\!Git\\TGS-RABOT-SpaceJesus\\\\pics\\\\'\n\n # Grab the ext\n ext = image_url.split(\".\")[-1]\n if \"/\" in ext:\n ext = ext.replace(\"/\",\"\")\n\n # Name it something random that will probably not be overwritten. Will fix.\n name = str(datetime.now().microsecond) + \".\" + ext\n\n # Grab the image\n data = requests.get(image_url)\n\n # Make a new path\n newpath = subdir+name\n\n # Write the image\n with open(newpath,'wb') as image:\n image.write(data.content)\n\n return newpath\n\n\n def post_image(self, image_url, title):\n \"\"\"Post an image to the sub. Probably used for automating posts for some degree of traffic while we're small.\n Or something.\"\"\"\n # Log in\n self.driver = self.make_driver()\n self.login()\n\n # Download the provided image and get it's location\n img_path = self.download_image(image_url)\n\n # Get the submit page\n self.driver.get(self.urls['submit'])\n\n # Click the \"Image\" button\n elem = self.driver.find_elements(By.CLASS_NAME, \"discreet-tab\")\n IMAGE = elem[1]\n IMAGE.click()\n\n # Find the browse button and send the file. The path was really bitchy about this one, needs work.\n browse_button = self.driver.find_element(By.ID, \"submission_image\")\n browse_button.send_keys(img_path)\n\n # Find the title box and set it\n title_box = self.driver.find_element(By.ID, \"submission_title\")\n title_box.send_keys(title)\n\n # Find the submit button and click it\n submit_button = self.driver.find_element(By.CLASS_NAME, \"button\")\n submit_button.click()\n\n # def stream(self, sub, content_type):\n # self.urls['comments']\n\n\n\n", "repo_name": "maester-of-bots/TGS-RABOT-SpaceJesus", "sub_path": "main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 8786, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "pytz.UTC", "line_number": 14, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.firefox.options.Options", "line_number": 38, "usage_type": "call"}, {"api_name": "selenium.webdriver.firefox.service.Service", "line_number": 46, "usage_type": "call"}, {"api_name": "selenium.webdriver.Firefox", "line_number": 49, "usage_type": "call"}, {"api_name": "selenium.webdriver", "line_number": 49, "usage_type": "name"}, {"api_name": "dotenv.load_dotenv", "line_number": 56, "usage_type": "call"}, {"api_name": "os.getenv", "line_number": 57, "usage_type": "call"}, {"api_name": "os.getenv", "line_number": 58, "usage_type": "call"}, {"api_name": "selenium.webdriver.common.by.By.ID", "line_number": 64, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.by.By", "line_number": 64, "usage_type": "name"}, {"api_name": "selenium.webdriver.common.by.By.ID", "line_number": 69, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.by.By", "line_number": 69, "usage_type": "name"}, {"api_name": "selenium.webdriver.common.keys.Keys.RETURN", "line_number": 74, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.keys.Keys", "line_number": 74, "usage_type": "name"}, {"api_name": "selenium.webdriver.support.ui.WebDriverWait", "line_number": 75, "usage_type": "call"}, {"api_name": "selenium.webdriver.support.expected_conditions.title_is", "line_number": 76, "usage_type": "call"}, {"api_name": "selenium.webdriver.support.expected_conditions", "line_number": 76, "usage_type": "name"}, {"api_name": "selenium.webdriver.common.by.By.CLASS_NAME", "line_number": 90, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.by.By", "line_number": 90, "usage_type": "name"}, {"api_name": "selenium.webdriver.common.by.By.TAG_NAME", "line_number": 100, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.by.By", "line_number": 100, "usage_type": "name"}, {"api_name": "selenium.webdriver.common.by.By.CLASS_NAME", "line_number": 103, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.by.By", "line_number": 103, "usage_type": "name"}, {"api_name": "selenium.webdriver.common.by.By.CLASS_NAME", "line_number": 106, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.by.By", "line_number": 106, "usage_type": "name"}, {"api_name": "selenium.webdriver.common.by.By.CLASS_NAME", "line_number": 109, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.by.By", "line_number": 109, "usage_type": "name"}, {"api_name": "selenium.webdriver.common.by.By.CLASS_NAME", "line_number": 130, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.by.By", "line_number": 130, "usage_type": "name"}, {"api_name": "selenium.webdriver.common.by.By.CLASS_NAME", "line_number": 138, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.by.By", "line_number": 138, "usage_type": "name"}, {"api_name": "selenium.webdriver.common.by.By.CLASS_NAME", "line_number": 141, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.by.By", "line_number": 141, "usage_type": "name"}, {"api_name": "selenium.webdriver.common.by.By.CLASS_NAME", "line_number": 144, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.by.By", "line_number": 144, "usage_type": "name"}, {"api_name": "selenium.webdriver.common.by.By.CLASS_NAME", "line_number": 147, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.by.By", "line_number": 147, "usage_type": "name"}, {"api_name": "selenium.webdriver.common.by.By.ID", "line_number": 189, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.by.By", "line_number": 189, "usage_type": "name"}, {"api_name": "selenium.webdriver.common.by.By.CLASS_NAME", "line_number": 195, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.by.By", "line_number": 195, "usage_type": "name"}, {"api_name": "selenium.webdriver.common.by.By.CLASS_NAME", "line_number": 200, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.by.By", "line_number": 200, "usage_type": "name"}, {"api_name": "datetime.now", "line_number": 217, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 220, "usage_type": "call"}, {"api_name": "selenium.webdriver.common.by.By.CLASS_NAME", "line_number": 246, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.by.By", "line_number": 246, "usage_type": "name"}, {"api_name": "selenium.webdriver.common.by.By.ID", "line_number": 251, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.by.By", "line_number": 251, "usage_type": "name"}, {"api_name": "selenium.webdriver.common.by.By.ID", "line_number": 255, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.by.By", "line_number": 255, "usage_type": "name"}, {"api_name": "selenium.webdriver.common.by.By.CLASS_NAME", "line_number": 259, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.by.By", "line_number": 259, "usage_type": "name"}]} +{"seq_id": "21832755851", "text": "from flask import Flask, render_template\nfrom datetime import datetime\n\napp = Flask(__name__)\napp.config['TEMPLATES_AUTO_RELOAD'] = True # 模板自动加载\n\n@app.route('/')\ndef index(): # put application's code here\n context = {\n 'position': -9,\n # 'signature': None,\n 'signature': '',\n 'persons': ['zhiliao', 'ketang'],\n 'age': \"18\",\n 'article': 'hello zhiliao hello world',\n 'create_time': datetime(2022, 4, 13, 16, 40, 0),\n }\n\n return render_template('index.html', **context)\n\n# 注册cut过滤器\n@app.template_filter('cut')\ndef cut(value):\n value = value.replace(\"hello\", '')\n return value\n\n# 自定义处理时间的过滤器\n@app.template_filter('handle_time')\ndef hand_time(time):\n if isinstance(time, datetime):\n now = datetime.now()\n timestamp = (now - time).total_seconds() # 发表文章间隔 时间\n # print(timestamp)\n if timestamp < 60:\n return '刚刚'\n elif 60 <= timestamp < 60*60:\n minutes = timestamp / 60\n return \"%s分钟前\" % int(minutes)\n elif 60*60 <= timestamp < 60*60*24:\n hours = timestamp / (60*60)\n return '%s小时前' % int(hours)\n elif 60*60*24 <= timestamp < 60*60*24*30:\n days = timestamp / (60*60*24)\n return \"%s天前\" % int(days)\n else:\n return time.strftime('%Y/%m/%d %H:%M')\n else:\n return time\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n", "repo_name": "liu1073811240/flask_study", "sub_path": "03-Jinja2/04-filter_demo/app.py", "file_name": "app.py", "file_ext": "py", "file_size_in_byte": 1548, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "flask.Flask", "line_number": 4, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 16, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 19, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 30, "usage_type": "argument"}, {"api_name": "datetime.datetime.now", "line_number": 31, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 31, "usage_type": "name"}]} +{"seq_id": "18592053671", "text": "\"\"\"\n===================================================================\nDetermining and plotting the altitude/azimuth of a celestial object\n===================================================================\n\nThis example demonstrates coordinate transformations and the creation of\nvisibility curves to assist with observing run planning.\n\nIn this example, we make a `~astropy.coordinates.SkyCoord` instance for M33.\nThe altitude-azimuth coordinates are then found using\n`astropy.coordinates.EarthLocation` and `astropy.time.Time` objects.\n\nThis example is meant to demonstrate the capabilities of the\n`astropy.coordinates` package. For more convenient and/or complex observation\nplanning, consider the `astroplan `_\npackage.\n\n\n*By: Erik Tollerud, Kelle Cruz*\n\n*License: BSD*\n\n\n\"\"\"\n\n##############################################################################\n# Let's suppose you are planning to visit picturesque Bear Mountain State Park\n# in New York, USA. You're bringing your telescope with you (of course), and\n# someone told you M33 is a great target to observe there. You happen to know\n# you're free at 11:00 pm local time, and you want to know if it will be up.\n# Astropy can answer that.\n#\n# Import numpy and matplotlib. For the latter, use a nicer set of plot\n# parameters and set up support for plotting/converting quantities.\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom astropy.visualization import astropy_mpl_style, quantity_support\n\nplt.style.use(astropy_mpl_style)\nquantity_support()\n\n\n##############################################################################\n# Import the packages necessary for finding coordinates and making\n# coordinate transformations\n\nimport astropy.units as u\nfrom astropy.coordinates import AltAz, EarthLocation, SkyCoord\nfrom astropy.time import Time\n\n##############################################################################\n# `astropy.coordinates.SkyCoord.from_name` uses Simbad to resolve object\n# names and retrieve coordinates.\n#\n# Get the coordinates of M33:\n\nm33 = SkyCoord.from_name('M33')\n\n##############################################################################\n# Use `astropy.coordinates.EarthLocation` to provide the location of Bear\n# Mountain and set the time to 11pm EDT on 2012 July 12:\n\nbear_mountain = EarthLocation(lat=41.3*u.deg, lon=-74*u.deg, height=390*u.m)\nutcoffset = -4*u.hour # Eastern Daylight Time\ntime = Time('2012-7-12 23:00:00') - utcoffset\n\n##############################################################################\n# `astropy.coordinates.EarthLocation.get_site_names` and\n# `~astropy.coordinates.EarthLocation.get_site_names` can be used to get\n# locations of major observatories.\n#\n# Use `astropy.coordinates` to find the Alt, Az coordinates of M33 at as\n# observed from Bear Mountain at 11pm on 2012 July 12.\n\nm33altaz = m33.transform_to(AltAz(obstime=time,location=bear_mountain))\nprint(f\"M33's Altitude = {m33altaz.alt:.2}\")\n\n##############################################################################\n# This is helpful since it turns out M33 is barely above the horizon at this\n# time. It's more informative to find M33's airmass over the course of\n# the night.\n#\n# Find the alt,az coordinates of M33 at 100 times evenly spaced between 10pm\n# and 7am EDT:\n\nmidnight = Time('2012-7-13 00:00:00') - utcoffset\ndelta_midnight = np.linspace(-2, 10, 100)*u.hour\nframe_July13night = AltAz(obstime=midnight+delta_midnight,\n location=bear_mountain)\nm33altazs_July13night = m33.transform_to(frame_July13night)\n\n##############################################################################\n# convert alt, az to airmass with `~astropy.coordinates.AltAz.secz` attribute:\n\nm33airmasss_July13night = m33altazs_July13night.secz\n\n##############################################################################\n# Plot the airmass as a function of time:\n\nplt.plot(delta_midnight, m33airmasss_July13night)\nplt.xlim(-2, 10)\nplt.ylim(1, 4)\nplt.xlabel('Hours from EDT Midnight')\nplt.ylabel('Airmass [Sec(z)]')\nplt.show()\n\n##############################################################################\n# Use `~astropy.coordinates.get_sun` to find the location of the Sun at 1000\n# evenly spaced times between noon on July 12 and noon on July 13:\n\nfrom astropy.coordinates import get_sun\n\ndelta_midnight = np.linspace(-12, 12, 1000)*u.hour\ntimes_July12_to_13 = midnight + delta_midnight\nframe_July12_to_13 = AltAz(obstime=times_July12_to_13, location=bear_mountain)\nsunaltazs_July12_to_13 = get_sun(times_July12_to_13).transform_to(frame_July12_to_13)\n\n\n##############################################################################\n# Do the same with `~astropy.coordinates.get_body` to find when the moon is\n# up. Be aware that this will need to download a 10MB file from the internet\n# to get a precise location of the moon.\n\nfrom astropy.coordinates import get_body\n\nmoon_July12_to_13 = get_body(\"moon\", times_July12_to_13)\nmoonaltazs_July12_to_13 = moon_July12_to_13.transform_to(frame_July12_to_13)\n\n##############################################################################\n# Find the alt,az coordinates of M33 at those same times:\n\nm33altazs_July12_to_13 = m33.transform_to(frame_July12_to_13)\n\n##############################################################################\n# Make a beautiful figure illustrating nighttime and the altitudes of M33 and\n# the Sun over that time:\n\nplt.plot(delta_midnight, sunaltazs_July12_to_13.alt, color='r', label='Sun')\nplt.plot(delta_midnight, moonaltazs_July12_to_13.alt, color=[0.75]*3, ls='--', label='Moon')\nplt.scatter(delta_midnight, m33altazs_July12_to_13.alt,\n c=m33altazs_July12_to_13.az.value, label='M33', lw=0, s=8,\n cmap='viridis')\nplt.fill_between(delta_midnight, 0*u.deg, 90*u.deg,\n sunaltazs_July12_to_13.alt < -0*u.deg, color='0.5', zorder=0)\nplt.fill_between(delta_midnight, 0*u.deg, 90*u.deg,\n sunaltazs_July12_to_13.alt < -18*u.deg, color='k', zorder=0)\nplt.colorbar().set_label('Azimuth [deg]')\nplt.legend(loc='upper left')\nplt.xlim(-12*u.hour, 12*u.hour)\nplt.xticks((np.arange(13)*2-12)*u.hour)\nplt.ylim(0*u.deg, 90*u.deg)\nplt.xlabel('Hours from EDT Midnight')\nplt.ylabel('Altitude [deg]')\nplt.show()\n", "repo_name": "astropy/astropy", "sub_path": "examples/coordinates/plot_obs-planning.py", "file_name": "plot_obs-planning.py", "file_ext": "py", "file_size_in_byte": 6283, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 4015, "dataset": "github-code", "pt": "21", "api": [{"api_name": "matplotlib.pyplot.style.use", "line_number": 41, "usage_type": "call"}, {"api_name": "astropy.visualization.astropy_mpl_style", "line_number": 41, "usage_type": "argument"}, {"api_name": "matplotlib.pyplot.style", "line_number": 41, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot", "line_number": 41, "usage_type": "name"}, {"api_name": "astropy.visualization.quantity_support", "line_number": 42, "usage_type": "call"}, {"api_name": "astropy.coordinates.SkyCoord.from_name", "line_number": 59, "usage_type": "call"}, {"api_name": "astropy.coordinates.SkyCoord", "line_number": 59, "usage_type": "name"}, {"api_name": "astropy.coordinates.EarthLocation", "line_number": 65, "usage_type": "call"}, {"api_name": "astropy.units.deg", "line_number": 65, "usage_type": "attribute"}, {"api_name": "astropy.units", "line_number": 65, "usage_type": "name"}, {"api_name": "astropy.units.m", "line_number": 65, "usage_type": "attribute"}, {"api_name": "astropy.units.hour", "line_number": 66, "usage_type": "attribute"}, {"api_name": "astropy.units", "line_number": 66, "usage_type": "name"}, {"api_name": "astropy.time.Time", "line_number": 67, "usage_type": "call"}, {"api_name": "astropy.coordinates.AltAz", "line_number": 77, "usage_type": "call"}, {"api_name": "astropy.time.Time", "line_number": 88, "usage_type": "call"}, {"api_name": "numpy.linspace", "line_number": 89, "usage_type": "call"}, {"api_name": "astropy.units.hour", "line_number": 89, "usage_type": "attribute"}, {"api_name": "astropy.units", "line_number": 89, "usage_type": "name"}, {"api_name": "astropy.coordinates.AltAz", "line_number": 90, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 102, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 102, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlim", "line_number": 103, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 103, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylim", "line_number": 104, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 104, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 105, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 105, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 106, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 106, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 107, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 107, "usage_type": "name"}, {"api_name": "numpy.linspace", "line_number": 115, "usage_type": "call"}, {"api_name": "astropy.units.hour", "line_number": 115, "usage_type": "attribute"}, {"api_name": "astropy.units", "line_number": 115, "usage_type": "name"}, {"api_name": "astropy.coordinates.AltAz", "line_number": 117, "usage_type": "call"}, {"api_name": "astropy.coordinates.get_sun", "line_number": 118, "usage_type": "call"}, {"api_name": "astropy.coordinates.get_body", "line_number": 128, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 140, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 140, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 141, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 141, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 142, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 142, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.fill_between", "line_number": 145, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 145, "usage_type": "name"}, {"api_name": "astropy.units.deg", "line_number": 145, "usage_type": "attribute"}, {"api_name": "astropy.units", "line_number": 145, "usage_type": "name"}, {"api_name": "astropy.units.deg", "line_number": 146, "usage_type": "attribute"}, {"api_name": "astropy.units", "line_number": 146, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.fill_between", "line_number": 147, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 147, "usage_type": "name"}, {"api_name": "astropy.units.deg", "line_number": 147, "usage_type": "attribute"}, {"api_name": "astropy.units", "line_number": 147, "usage_type": "name"}, {"api_name": "astropy.units.deg", "line_number": 148, "usage_type": "attribute"}, {"api_name": "astropy.units", "line_number": 148, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.colorbar", "line_number": 149, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 149, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 150, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 150, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlim", "line_number": 151, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 151, "usage_type": "name"}, {"api_name": "astropy.units.hour", "line_number": 151, "usage_type": "attribute"}, {"api_name": "astropy.units", "line_number": 151, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xticks", "line_number": 152, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 152, "usage_type": "name"}, {"api_name": "numpy.arange", "line_number": 152, "usage_type": "call"}, {"api_name": "astropy.units.hour", "line_number": 152, "usage_type": "attribute"}, {"api_name": "astropy.units", "line_number": 152, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylim", "line_number": 153, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 153, "usage_type": "name"}, {"api_name": "astropy.units.deg", "line_number": 153, "usage_type": "attribute"}, {"api_name": "astropy.units", "line_number": 153, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 154, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 154, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 155, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 155, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 156, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 156, "usage_type": "name"}]} +{"seq_id": "26720962153", "text": "from __future__ import absolute_import, unicode_literals\nimport os\nfrom celery import Celery\n\n\n\n\nbackapp = Celery('sample2',\n broker=os.environ['CELERY_BROKER_URL'],\n backend=os.environ['CELERY_RESULT_BACKEND'],\n include=['sample2.business.math.tasks'])\n\n#backapp.conf.update(frontapp.config)\n\nbackapp.conf.update(\n # enable STARTED status for celery task\n # needed to know if a task exists\n task_track_started=True,\n #result_expires=3600,\n)\n\nif __name__ == '__main__':\n backapp.start()\n", "repo_name": "StudioEtrange/celery-flask-samples", "sub_path": "sample2/back.py", "file_name": "back.py", "file_ext": "py", "file_size_in_byte": 538, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 10, "dataset": "github-code", "pt": "21", "api": [{"api_name": "celery.Celery", "line_number": 8, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 9, "usage_type": "attribute"}, {"api_name": "os.environ", "line_number": 10, "usage_type": "attribute"}]} +{"seq_id": "12423205966", "text": "import pytest\n\nfrom .lib import Phone, Laptop\n\n\n@pytest.fixture(scope='class')\ndef phone():\n phone_data = Phone(\n producer='Samsung',\n year_of_development=2015,\n gsm_modem=True,\n activated=True\n\n )\n yield phone_data\n\n\n@pytest.fixture(scope='class')\ndef laptop():\n laptop_data = Laptop(\n producer='Samsung',\n year_of_development=2020,\n gsm_modem=True,\n battery_is_arranged=True\n )\n yield laptop_data\n", "repo_name": "Nyko1988/Hillel", "sub_path": "HW13/conftest.py", "file_name": "conftest.py", "file_ext": "py", "file_size_in_byte": 473, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "lib.Phone", "line_number": 8, "usage_type": "call"}, {"api_name": "pytest.fixture", "line_number": 6, "usage_type": "call"}, {"api_name": "lib.Laptop", "line_number": 20, "usage_type": "call"}, {"api_name": "pytest.fixture", "line_number": 18, "usage_type": "call"}]} +{"seq_id": "71973446772", "text": "from app import run\nimport logging\n\nlogging.basicConfig(format='%(asctime)s %(message)s')\nlogger = logging.getLogger()\nlogger.setLevel(logging.INFO)\n\n\"\"\"Start real time algo-trading model\"\"\"\nif __name__=='__main__':\n logging.info(f'Starting app')\n run.run()", "repo_name": "astronights/A4_Paper_Trading", "sub_path": "start.py", "file_name": "start.py", "file_ext": "py", "file_size_in_byte": 263, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "logging.basicConfig", "line_number": 4, "usage_type": "call"}, {"api_name": "logging.getLogger", "line_number": 5, "usage_type": "call"}, {"api_name": "logging.INFO", "line_number": 6, "usage_type": "attribute"}, {"api_name": "logging.info", "line_number": 10, "usage_type": "call"}, {"api_name": "app.run.run", "line_number": 11, "usage_type": "call"}, {"api_name": "app.run", "line_number": 11, "usage_type": "name"}]} +{"seq_id": "33601715670", "text": "import nextnanopy as nn\nfrom nextnanopy.utils.misc import mkdir_if_not_exist\nimport sys,os\n#import numpy as np\nimport matplotlib.pyplot as plt\nfrom math import pi,exp\nfrom scipy.constants import hbar,Boltzmann,elementary_charge,electron_mass\n\n#import config_nextnano # This should be your default configuration.\nimport config_nextnano_temp # This could be a modified configuration file.\n# config file is stored in C:\\Users\\\\.nextnanopy-config\n\n#FigFormat = '.pdf'\n#FigFormat = '.svg'\nFigFormat = '.jpg'\n#FigFormat = '.png'\n\n#++++++++++++++++++++++++++++++++++++++++++++++\n# These lines have to be adjusted by the user. \n#++++++++++++++++++++++++++++++++++++++++++++++\n#================================\n# Specify software product here!\n#================================\n#software = 'nextnano++'\nsoftware = 'nextnano3'\n#software = 'nextnano.NEGF'\n#software = 'nextnano.MSB'\n#===========================\n\nfolder_examples_nnp = r'C:\\Program Files\\nextnano\\2021_12_12\\Sample files\\nextnano++ sample files'\nfolder_examples_nn3 = r'C:\\Program Files\\nextnano\\2021_12_12\\Sample files\\nextnano3 sample files'\nfolder_examples_nnNEGF = r'D:\\nextnano.NEGF\\nextnanoNEGF_2020_11_16\\nextnano.NEGF sample files'\nfolder_examples_nnMSB = r'D:\\nextnano.MSB\\nextnano.MSB_2017_12_20\\nextnano\\2017_12_20\\nextnano.MSB sample files'\n\n#++++++++++++++++++++++++++++++++++++++++++++++\n# These lines have to be adjusted by the user. \n#++++++++++++++++++++++++++++++++++++++++++++++\n#folder_examples_nn3 = r'N:\\users\\nextnano\\nextnano GmbH - Tutorials\\Tutorials\\2D The CBR method (Transmission)'\n#===========================\nif(software==\"nextnano++\"):\n subfolder = ''\n # subfolder = r'\\Quantum Mechanics examples'\nelif(software==\"nextnano3\"):\n subfolder = ''\n # subfolder = r'\\Quantum Mechanics examples'\nelif(software==\"nextnano.NEGF\"):\n subfolder = ''\nelif(software==\"nextnano.MSB\"):\n subfolder = ''\n#===========================\n\nsoftware_short_nnp = '_nnp'\nsoftware_short_nn3 = '_nn3'\nsoftware_short_nnNEGF = '_nnNEGF'\nsoftware_short_nnMSB = '_nnMSB'\n\n#===========================\nif(software==\"nextnano++\"):\n software_short = software_short_nnp\nelif(software==\"nextnano3\"):\n software_short = software_short_nn3\nelif(software==\"nextnano.NEGF\"):\n software_short = software_short_nnNEGF\nelif(software==\"nextnano.MSB\"):\n software_short = software_short_nnMSB\n#===========================\n\n#===========================\nif(software==\"nextnano++\"):\n folder_examples = folder_examples_nnp + subfolder # nextnano++\nelif(software==\"nextnano3\"):\n folder_examples = folder_examples_nn3 + subfolder # nextnano3\nelif(software==\"nextnano.NEGF\"):\n folder_examples = folder_examples_nnNEGF + subfolder # nextnano.NEGF\nelif(software==\"nextnano.MSB\"):\n folder_examples = folder_examples_nnMSB + subfolder # nextnano.MSB\n#===========================\n\n#==========================================================================\n# Define input and output folders. If they do not exist, they are created.\n#==========================================================================\nhome_directory = r'C:\\Users\\stefan.birner.NEXTNANO\\Documents\\nextnano'\nfolder_output = nn.config.config[software]['outputdirectory']\nfolder_python_input = os.path.join(home_directory,r'nextnanopy\\input')\nfolder_python_output = os.path.join(home_directory,r'nextnanopy\\output')\n#folder_examples = folder_python_input\n\nmkdir_if_not_exist(folder_output)\nmkdir_if_not_exist(folder_python_output)\n\n#++++++++++++++++++++++++++++++++++++++++++++++++++++++\n# Open reStructured Text file (.rst) for documentation\n#++++++++++++++++++++++++++++++++++++++++++++++++++++++\nfile_docu = open(os.path.join(folder_python_output,'documentation'+'.rst'),\"w+\")\n\nDocuInfo = \"**Automatic documentation: Running simulations, generating figures and reStructured Text (*.rst) using nextnanopy**\"\n\nfile_docu.write(\"\\n\")\nfile_docu.write(\"\\n\")\nfile_docu.write(r\"----------------------\"+\"\\n\") # horizontal line\nfile_docu.write(\"\\n\")\nfile_docu.write(\"\\n\")\nfile_docu.write(r\"--- Begin ---\"+\"\\n\")\nfile_docu.write(\"\\n\")\nfile_docu.write(DocuInfo+\"\\n\")\nfile_docu.write(\"\\n\")\nfile_docu.write(r\"The following documentation and figures were generated automatically using |nextnanopy|.\"+\"\\n\")\nfile_docu.write(\"\\n\")\nfile_docu.write(r\"The following Python script was used: ``intersubband_InfiniteQW_nextnano3.py``\"+\"\\n\")\nfile_docu.write(\"\\n\")\nfile_docu.write(r\"----------------------\"+\"\\n\") # horizontal line\nfile_docu.write(\"\\n\")\n\nfile_docu.write(\"\\n\")\nfile_docu.write(r\"The following figures have been generated using the |nextnano3| software.\"+\"\\n\")\n# Note: The umlaut for Schrödinger is not written correctly!!!\n#file_docu.write(r\"Self-consistent Schrödinger-Poisson calculations have been performed for three different structures.\"+\"\\n\")\nfile_docu.write(r\"Self-consistent Schroedinger-Poisson calculations have been performed for an infinite quantum well.\"+\"\\n\")\nfile_docu.write(\"\\n\")\nfile_docu.write(r\"A single-band effective mass approach has been used, i.e. not |k_dot_p|.\"+\"\\n\")\nfile_docu.write(\"\\n\")\nfile_docu.write(r\"The absorption has been calculated assuming a parabolic energy dispersion :math:`E(k)`.\"+\"\\n\")\nfile_docu.write(\"\\n\")\nfile_docu.write(\"\\n\")\n\n\nfor nn_file in range(1):\n\n print (nn_file)\n\n# sys.exit()\n\n #--------------------------------------------------------\n # Specify input file without file extension '.in'/.'xml'\n #--------------------------------------------------------\n #my_input_file_no_extension_nnp = r'Jogai_AlGaNGaN_FET_JAP2003_GaNcap_Fig6Fig5_1D_nnp'\n #my_input_file_no_extension_nn3 = r'Jogai_AlGaNGaN_FET_JAP2003_GaNcap_Fig6Fig5_1D_nn3'\n #my_input_file_no_extension_nn3 = r'2D_CBR_MamaluySabathilJAP2003_AharonovBohm'\n #my_input_file_no_extension_nn3 = r'2D_CBR_square'\n my_input_file_no_extension_nnp = r'1D_IntersubbandAbsorption_InfiniteWell_GaAs_Chuang_sg_nnp'\n my_input_file_no_extension_nn3 = r'1D_IntersubbandAbsorption_InfiniteWell_GaAs_Chuang_sg_nn3'\n my_input_file_no_extension_nnNEGF = r'THz_QCL_GaAs_AlGaAs_Fathololoumi_OptExpress2012_10K-FAST'\n my_input_file_no_extension_nnMSB = r'1D_Transmission_DoubleBarrier_CBR_paper_MSB'\n \n\n\n #===========================\n if(software==\"nextnano++\"):\n my_input_file_no_extension = my_input_file_no_extension_nnp\n elif(software==\"nextnano3\"):\n my_input_file_no_extension = my_input_file_no_extension_nn3\n elif(software==\"nextnano.NEGF\"):\n my_input_file_no_extension = my_input_file_no_extension_nnNEGF\n elif(software==\"nextnano.MSB\"):\n my_input_file_no_extension = my_input_file_no_extension_nnMSB\n #===========================\n \n if(software==\"nextnano.NEGF\" or software==\"nextnano.MSB\"):\n FileExtension = '.xml' # for nextnano.NEGF and nextnano.MSB\n else:\n FileExtension = '.in' # for nextnano++ and nextnano3\n \n my_input_file = my_input_file_no_extension+FileExtension\n \n # plt.ion() # interactive mode\n \n print(f\"starting nextnano...\")\n input_file_name = os.path.join(folder_examples,my_input_file)\n input_file = nn.InputFile(input_file_name)\n print(input_file)\n\n \n #++++++++++++++++++++++++++++++++++++++++++++++\n # These lines have to be adjusted by the user. \n #++++++++++++++++++++++++++++++++++++++++++++++\n print(f\"List of variables: {input_file.variables}\")\n for var in input_file.variables.values():\n # print(f'${var.name} = {var.value} ! {var.comment}')\n print(f'{var.text}') # --> better method to preview\n \n\n for OuterSweep in range(2):\n\n if (OuterSweep == 0):\n #++++++++++++++++++++++++++++++++++++++++++++++\n # Sweep #1\n #++++++++++++++++++++++++++++++++++++++++++++++\n HeadlineSweep = '**Parameter sweep: Well width**'\n CaptionSweep = 'for different well widths'\n SweepExplanation = ( 'The following figure shows the absorption for different **quantum well widths** (Variable: ``$QuantumWellWidth``). '+\n 'The larger the well, the closer the energy level spacings. '+\n 'Therefore the peak occurs at smaller energies. '+\n 'The larger wells show absorption also for transitions other than E\\ :sub:`21`.' )\n SweepVariable = 'QuantumWellWidth'\n ListOfValues = [10,13,16,19]\n # ListOfValues = [10] # 10 nm [ChuangOpto1995]\n unitC = 'nm' # It would be better to get the units from (DisplyUnit:nm)\n #++++++++++++++++++++++++++++++++++++++++++++++\n elif (OuterSweep == 1):\n # Set back variable of previous sweep.\n input_file.set_variable(SweepVariable, value=ListOfValues[0], comment='<= PYTHON <= ' + comment_original)\n\n #++++++++++++++++++++++++++++++++++++++++++++++\n # Sweep #2\n #++++++++++++++++++++++++++++++++++++++++++++++\n HeadlineSweep = '**Parameter sweep: Doping concentration**'\n CaptionSweep = 'for different doping concentrations' \n SweepExplanation = ( 'The following figure shows the absorption for different **doping concentrations** (Variable: ``$DopingConcentration``). '+\n 'The peak absorption coefficient increases with the doping concentration N\\ :sub:`D`.' )\n SweepVariable = 'DopingConcentration'\n ListOfValues = [0.9e18,1.0e18,1.1e18]\n unitC = 'cm^-3' # It would be better to get the units from (DisplyUnit:cm^-3)\n #++++++++++++++++++++++++++++++++++++++++++++++\n \n comment_original = input_file.variables[SweepVariable].comment\n df_absV=[]\n SweepVariableStringV=[]\n \n docuL = True \n docu_absL = True\n docu_sweepL = True\n \n loop = 0 \n \n for x in ListOfValues:\n \n if (OuterSweep == 0): \n\n loop = loop + 1\n \n if (loop == 1):\n docuL = True\n docu_absL = True\n else:\n docu_absL = False\n elif (OuterSweep == 1): \n docuL = False\n docu_absL = False\n\n \n input_file.set_variable(SweepVariable, value=x, comment='<= PYTHON <= ' + comment_original)\n \n for var in input_file.variables.values():\n # print(f'${var.name} = {var.value} ! {var.comment}')\n # print(f'{var.text}') # --> better method to preview\n print(var.text) # --> better method to preview\n \n SweepVariableCaption = \"(\" + SweepVariable + \" = \" + str(x) + \" \" + unitC + \")\"\n SweepVariableString = SweepVariable+'_'+str(x)\n SweepVariableStringV.append(SweepVariableString)\n \n \n input_file_name_variable = my_input_file_no_extension+'_'+SweepVariableString\n \n my_input_file_new = os.path.join(folder_output,input_file_name_variable+FileExtension)\n print(my_input_file_new)\n \n input_file.save(my_input_file_new,overwrite=True,automkdir=True)\n \n print(f'') \n print(f'=====================================') \n ############################\n # Execute nextnano software\n ############################\n input_file.execute() # Put line into comment if you only want to to post-processing of results\n print(f'=====================================') \n \n #plotL = bool(0) # false\n plotL = bool(1) # true\n \n if(plotL):\n \n print(f'=====================================') \n print(f'Now generate plots in output folder') \n print(folder_output) \n print(f'=====================================') \n \n #++++++++++++++++++++++++++++++++++++++++++++++\n # These lines have to be adjusted by the user. \n #++++++++++++++++++++++++++++++++++++++++++++++\n #===========================\n if(software==\"nextnano++\"):\n file_cb = os.path.join(folder_output,input_file_name_variable+r'\\bias_000_000'+r'\\bandedge_Gamma.dat') \n file_psi = os.path.join(folder_output,input_file_name_variable+r'\\Schroedinger_1band'+r'\\cb1_sg1_deg1_psi_squared_shift.dat') \n file_abs = os.path.join(folder_output,input_file_name_variable+r'\\optics'+r'\\absorption_intraband_cb1_sg1_deg1.dat') \n elif(software==\"nextnano3\"):\n file_cb = os.path.join(folder_output,input_file_name_variable+r'\\band_structure'+r'\\BandEdges.dat') \n file_psi = os.path.join(folder_output,input_file_name_variable+r'\\Schroedinger_1band'+r'\\cb1_sg1_deg1_psi_squared_shift.dat') \n file_abs = os.path.join(folder_output,input_file_name_variable+r'\\optics'+r'\\absorption_intraband_cb1_sg1_deg1.dat') \n #===========================\n \n #===========================\n # Conduction band edge\n #===========================\n print(f\"Read in file:\")\n print(file_cb)\n df_cb = nn.DataFile(file_cb,product=software)\n \n print(f\"Read in file:\")\n print(file_psi)\n df_psi = nn.DataFile(file_psi,product=software)\n \n print(f\"Read in file:\")\n print(file_abs)\n df_abs = nn.DataFile(file_abs,product=software)\n df_absV.append(df_abs)\n \n print(f\"current datafile: \",file_cb)\n print(f\"List of coordinates in the current datafile: {df_cb.coords}\")\n print(f\"List of variables in the current datafile: {df_cb.variables}\")\n \n print(f\"current datafile: \",file_psi)\n print(f\"List of coordinates in the current datafile: {df_psi.coords}\")\n print(f\"List of variables in the current datafile: {df_psi.variables}\")\n \n print(f\"current datafile: \",file_abs)\n print(f\"List of coordinates in the current datafile: {df_abs.coords}\")\n print(f\"List of variables in the current datafile: {df_abs.variables}\")\n \n \n fig_psi, ax_psi = plt.subplots(1)\n \n NameOfStructure = 'Infinite Quantum Well' \n NameOfStructureFile = 'InfiniteQuantumWell'\n Caption = 'an infinite quantum well'\n ax_psi.plot(df_cb.coords['position'].value,df_cb.variables['Gamma_bandedge'].value,label=SweepVariableString)\n ax_psi.plot(df_cb.coords['position'].value,df_cb.variables['FermiLevel_el'].value,label=SweepVariableString)\n ax_psi.plot(df_psi.coords['position'].value,df_psi.variables['psi^2_3'].value,label=SweepVariableString)\n ax_psi.plot(df_psi.coords['position'].value,df_psi.variables['psi^2_2'].value,label=SweepVariableString)\n ax_psi.plot(df_psi.coords['position'].value,df_psi.variables['psi^2_1'].value,label=SweepVariableString)\n ax_psi.legend(['$E_c$','$E_F$','$\\psi_3^2$','$\\psi_2^2$','$\\psi_1^2$'])\n \n ax_psi.set_title(NameOfStructure+\" \"+SweepVariableCaption)\n ax_psi.set_xlabel(f\"{df_psi.coords['position'].name} ({df_psi.coords['position'].unit})\")\n ax_psi.set_ylabel(f\"energy ({df_psi.variables[0].unit})\")\n axes = plt.gca()\n axes.set_ylim([-0.4,1.0])\n fig_psi.tight_layout()\n # plt.show()\n \n \n #---------------------\n # Write documentation\n #---------------------\n image_path = '/images/nextnanoplus/tutorials/intersubband_InfiniteQW/'\n \n if (docuL):\n filename_cb_psi = 'cb_psi'+'_'+NameOfStructureFile+SweepVariableString+software_short+'.jpg'\n fig_psi.savefig(os.path.join(folder_python_output,filename_cb_psi))\n file_docu.write(r\"**\"+NameOfStructure+\"**\"+\" \"+SweepVariableCaption+\"\\n\")\n file_docu.write(\"\\n\")\n \n file_docu.write(r\".. figure:: \"+image_path+filename_cb_psi+\"\\n\")\n file_docu.write(r\" :alt: \"+NameOfStructureFile+\"\\n\")\n file_docu.write(r\" :align: center\"+\"\\n\")\n file_docu.write(\"\\n\")\n file_docu.write(r\" Conduction band edge, Fermi level and confined electron states of \"+Caption +\" \")\n file_docu.write(SweepVariableCaption)\n file_docu.write(\"\\n\")\n file_docu.write(\"\\n\")\n \n \n \n if (docu_absL):\n fig_abs, ax_abs = plt.subplots(1)\n ax_abs.plot(df_abs.variables['photon_energy'].value,df_abs.variables['absorption'].value,label=SweepVariableString)\n \n # ax.plot(df.coords['position'].value,df.variables['T_1_2'].value,label='Transmission')\n # ax.plot(df.variables['energy'].value,df.variables['T_1_2'].value,label='Transmission')\n # ax.plot(df.coords['position'].value,df.variables['FermiLevel_el'].value, label='FermiLevel_el')\n # ax.plot(df.coords['energy'].value,df.variables['Gamma_bandedge'].value,label='Gamma')\n \n # ax.set_xlabel(f\"{df.coords['position'].name} {df.coords['position'].unit}\")\n # ax.set_ylabel(f\"Energy {df.variables['T_1_2'].unit}\")\n \n ax_abs.set_xlabel(f\"photon energy ({df_abs.variables['photon_energy'].unit})\")\n ax_abs.set_ylabel(f\"{df_abs.variables['absorption'].name} ({df_abs.variables['absorption'].unit})\")\n ax_abs.set_title('Absorption of '+NameOfStructure+\" \"+SweepVariableCaption)\n ax_abs.legend(['Absorption'])\n fig_abs.tight_layout()\n # plt.show()\n \n filename_abs = 'absorption'+'_'+NameOfStructureFile+SweepVariableString+software_short+'.jpg'\n fig_abs.savefig(os.path.join(folder_python_output,filename_abs))\n file_docu.write(r\".. figure:: \"+image_path+filename_abs+\"\\n\")\n file_docu.write(r\" :alt: \"+NameOfStructureFile+\"\\n\")\n file_docu.write(r\" :align: center\"+\"\\n\")\n file_docu.write(\"\\n\")\n file_docu.write(r\" Calculated absorption :math:`\\alpha(E)` of \"+Caption +\" \")\n file_docu.write(SweepVariableCaption)\n file_docu.write(\"\\n\")\n file_docu.write(\"\\n\")\n \n #++++++++++++++++++++++++++++++++++++++++++++++\n # These lines have to be adjusted by the user. \n # 2D plot\n #++++++++++++++++++++++++++++++++++++++++++++++\n if(software==\"nextnano3\"):\n # file = os.path.join(folder_output,input_file_name_variable+r'\\Schroedinger_1band'+r'\\2Dcb1_qc1_sg1_deg1_psi_squared_ev001.fld') \n file = os.path.join(folder_output,input_file_name_variable+r'\\optics'+r'\\absorption_position_resolved_intraband_cb1_sg1_deg1.vtr') \n # file = os.path.join(folder_output,input_file_name_variable+r'\\Results'+r'\\LocalDOS_sg1_deg1.vtr')\n datafile_2d = nn.DataFile(file,product=software)\n print(f\"current datafile: \",file)\n print(f\"List of coordinates in the current datafile: {datafile_2d.coords}\")\n print(f\"List of variables in the current datafile: {datafile_2d.variables}\")\n \n x=datafile_2d.coords['x']\n y=datafile_2d.coords['y']\n # z=datafile_2d.variables['psi_squared']\n z=datafile_2d.variables[0]\n \n fig_abs2D, ax_abs2D = plt.subplots(1)\n ###CHECK: ax_abs2D.plot(df_cb.coords['position'].value,df_cb.variables[0].value,label=SweepVariableString,\n ###CHECK: color='white', linestyle='-')\n pcolor = ax_abs2D.pcolormesh(x.value,y.value,z.value.T)\n cbar = fig_abs2D.colorbar(pcolor)\n cbar.set_label(f\"{z.name} ({z.unit})\")\n \n # ax.plot(df_cb.coords['position'].value,df_cb.variables[1].value,color='yellow')\n # for i in range(2,len(ws)):\n # ax.plot(df_cb.coords['position'].value,ws[i],color='yellow')\n \n ax_abs2D.set_xlabel(f\"{df_psi.coords['position'].name} ({df_psi.coords['position'].unit})\")\n ax_abs2D.set_ylabel(f\"photon energy ({df_abs.variables['photon_energy'].unit})\")\n ax_abs2D.set_title('Absorption of '+NameOfStructure+\" \"+SweepVariableCaption)\n fig_abs2D.tight_layout()\n # plt.show()\n \n if (docuL):\n filename_abs2D = 'absorption2D'+'_'+NameOfStructureFile+SweepVariableString+software_short+'.jpg'\n fig_abs2D.savefig(os.path.join(folder_python_output,filename_abs2D))\n file_docu.write(r\".. figure:: \"+image_path+filename_abs2D+\"\\n\")\n file_docu.write(r\" :alt: \"+NameOfStructureFile+\"\\n\")\n file_docu.write(r\" :align: center\"+\"\\n\")\n file_docu.write(\"\\n\")\n file_docu.write(r\" Calculated position resolved absorption :math:`\\alpha(x,E)` of \"+Caption +\" \")\n file_docu.write(SweepVariableCaption)\n file_docu.write(\"\\n\")\n file_docu.write(\"\\n\")\n \n docuL = True\n \n fig, ax = plt.subplots(1)\n \n for i,j in zip(df_absV,SweepVariableStringV):\n ax.plot(i.variables[0].value,i.variables[1].value,label=j)\n \n ax.set_xlabel(f\"photon energy ({df_abs.variables['photon_energy'].unit})\")\n ax.set_ylabel(f\"{df_abs.variables['absorption'].name} ({df_abs.variables['absorption'].unit})\")\n ax.set_title('Absorption of '+NameOfStructure)\n ax.legend()\n fig.tight_layout()\n #plt.show()\n \n if (docu_sweepL):\n filename_abs_sweep = 'absorption'+'_'+NameOfStructureFile+'_sweep_'+SweepVariable+software_short+'.jpg'\n fig.savefig(os.path.join(folder_python_output,filename_abs_sweep))\n file_docu.write(\"\\n\")\n file_docu.write(HeadlineSweep+\"\\n\")\n file_docu.write(\"\\n\")\n file_docu.write(SweepExplanation+\"\\n\")\n file_docu.write(\"\\n\")\n file_docu.write(r\".. figure:: \"+image_path+filename_abs_sweep+\"\\n\")\n file_docu.write(r\" :alt: \"+NameOfStructureFile+\"\\n\")\n file_docu.write(r\" :align: center\"+\"\\n\")\n file_docu.write(\"\\n\")\n file_docu.write(r\" Calculated absorption :math:`\\alpha(E)` of \"+Caption +\" \")\n file_docu.write(CaptionSweep)\n file_docu.write(\"\\n\")\n file_docu.write(\"\\n\")\n\n\n#++++++++++++++++++++++++++++++++++++++++++++++++++++++\n# Close reStructured Text file (.rst) for documentation\n#++++++++++++++++++++++++++++++++++++++++++++++++++++++\nfile_docu.write(\"\\n\")\nfile_docu.write(r\"----------------------\"+\"\\n\") # horizontal line\nfile_docu.write(\"\\n\")\nfile_docu.write(DocuInfo+\"\\n\")\nfile_docu.write(\"\\n\")\nfile_docu.write(r\"--- End ---\"+\"\\n\")\nfile_docu.write(\"\\n\")\nfile_docu.write(r\"----------------------\"+\"\\n\") # horizontal line\nfile_docu.write(\"\\n\")\nfile_docu.write(\"\\n\")\nfile_docu.close() \n\nmass_electron_GaAs = 0.0665 # Chuang\n#temperature = 298.15 # K\ntemperature = 300 # K # Chuang\nkBT = temperature * Boltzmann / elementary_charge # eV\nprint(kBT,' eV') \n\nm0_by_pi_hbar2_eV = electron_mass / (pi * hbar**2 / elementary_charge ) # m0 / (pi hbar^2) = \n\nprint(m0_by_pi_hbar2_eV,' eV^-1 m^-2 ( = 4.177 10^18 eV^-1 m^-2)') \n\nN = 1e18 * 1e6 # doping cm^-3 => m^-3 Chuang\nLz = 10e-9 # 10 nm Chuang\n\nN_s = mass_electron_GaAs * m0_by_pi_hbar2_eV * kBT # Chuang\nE_F_minus_E_1 = kBT * ( exp(N * Lz / N_s) - 1 )\n\nprint(E_F_minus_E_1 * 1e-3, ' meV (Chuang: 78 meV)')\nprint(N_s * 1e-11 * 1e-4 ,' 10^11 cm^-2; Chuang: 7.19 * 10^11 cm^-2') \n \nprint(f'=====================================') \nprint(f'Done nextnanopy.') \nprint(f'=====================================') \n", "repo_name": "nextnanopy/nextnanopy", "sub_path": "templates/intersubband_InfiniteQW_nextnano3.py", "file_name": "intersubband_InfiniteQW_nextnano3.py", "file_ext": "py", "file_size_in_byte": 24003, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 17, "dataset": "github-code", "pt": "21", "api": [{"api_name": "nextnanopy.config", "line_number": 83, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 84, "usage_type": "call"}, {"api_name": "os.path", "line_number": 84, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 85, "usage_type": "call"}, {"api_name": "os.path", "line_number": 85, "usage_type": "attribute"}, {"api_name": "nextnanopy.utils.misc.mkdir_if_not_exist", "line_number": 88, "usage_type": "call"}, {"api_name": "nextnanopy.utils.misc.mkdir_if_not_exist", "line_number": 89, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 94, "usage_type": "call"}, {"api_name": "os.path", "line_number": 94, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 168, "usage_type": "call"}, {"api_name": "os.path", "line_number": 168, "usage_type": "attribute"}, {"api_name": "nextnanopy.InputFile", "line_number": 169, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 255, "usage_type": "call"}, {"api_name": "os.path", "line_number": 255, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 283, "usage_type": "call"}, {"api_name": "os.path", "line_number": 283, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 284, "usage_type": "call"}, {"api_name": "os.path", "line_number": 284, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 285, "usage_type": "call"}, {"api_name": "os.path", "line_number": 285, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 287, "usage_type": "call"}, {"api_name": "os.path", "line_number": 287, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 288, "usage_type": "call"}, {"api_name": "os.path", "line_number": 288, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 289, "usage_type": "call"}, {"api_name": "os.path", "line_number": 289, "usage_type": "attribute"}, {"api_name": "nextnanopy.DataFile", "line_number": 297, "usage_type": "call"}, {"api_name": "nextnanopy.DataFile", "line_number": 301, "usage_type": "call"}, {"api_name": "nextnanopy.DataFile", "line_number": 305, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 321, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 321, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.gca", "line_number": 336, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 336, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 349, "usage_type": "call"}, {"api_name": "os.path", "line_number": 349, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 365, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 365, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 384, "usage_type": "call"}, {"api_name": "os.path", "line_number": 384, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 400, "usage_type": "call"}, {"api_name": "os.path", "line_number": 400, "usage_type": "attribute"}, {"api_name": "nextnanopy.DataFile", "line_number": 402, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 412, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 412, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 431, "usage_type": "call"}, {"api_name": "os.path", "line_number": 431, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 443, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 443, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 457, "usage_type": "call"}, {"api_name": "os.path", "line_number": 457, "usage_type": "attribute"}, {"api_name": "scipy.constants.Boltzmann", "line_number": 491, "usage_type": "name"}, {"api_name": "scipy.constants.elementary_charge", "line_number": 491, "usage_type": "name"}, {"api_name": "scipy.constants.electron_mass", "line_number": 494, "usage_type": "name"}, {"api_name": "math.pi", "line_number": 494, "usage_type": "name"}, {"api_name": "scipy.constants.hbar", "line_number": 494, "usage_type": "name"}, {"api_name": "scipy.constants.elementary_charge", "line_number": 494, "usage_type": "name"}, {"api_name": "math.exp", "line_number": 502, "usage_type": "call"}]} +{"seq_id": "70119542454", "text": "# Importing the libraries\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import ListedColormap\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn import metrics\nfrom sklearn.metrics import confusion_matrix\n\n# https://towardsdatascience.com/knn-in-python-835643e2fb53\n\n# Importing the dataset\ndataset = pd.read_csv('Social_Network_Ads.csv')\nprint(dataset)\nX = dataset.iloc[:, [2, 3]].values\ny = dataset.iloc[:, 4].values\n\n# Splitting the dataset into the Training set and Test set\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state = 0)\n\n# Scale Features because age has smaller increments than salary\nsc = StandardScaler()\nX_train = sc.fit_transform(X_train)\nX_test = sc.transform(X_test)\n\n# find and optimize k\n\ndf_results = pd.DataFrame()\nk_list = []\nf1_list = []\naccuracy_list = []\n\nk = 1\nwhile k < 11:\n classifier = KNeighborsClassifier(n_neighbors=k, metric='minkowski', p=2)\n classifier.fit(X_train, y_train)\n Y_pred = classifier.predict(X_test)\n f1_value = metrics.f1_score(y_test, Y_pred, average='weighted')\n accuracy = metrics.accuracy_score(y_test, Y_pred)\n k_list.append(k)\n f1_list.append(f1_value)\n accuracy_list.append(accuracy)\n k += 1\n\n# print(k_list)\n# print(f1_list)\n# print(accuracy_list)\n\ndf_results['k'] = k_list\ndf_results['f1'] = f1_list\ndf_results['accuracy'] = accuracy_list\n\n# print(df_results)\n\n# Fitting classifier to the Training set\nclassifier = KNeighborsClassifier(n_neighbors = 2)\nclassifier.fit(X_train, y_train)\n\n# Predicting the Test set results\ny_pred = classifier.predict(X_test)\n\n# Making the Confusion Matrix\ncm = confusion_matrix(y_test, y_pred)\n\n#print(y_pred)\n\nX_trans = sc.transform(X)\ny_pred_trans = classifier.predict(X_trans)\n#print(y_pred_trans)\ndataset['results'] = y_pred_trans\ndataset.to_csv('dataset.csv')\n\ntest_data = [[29, 43000]]\ntest_trans = sc.transform(test_data)\ny_pred_test = classifier.predict(test_trans)\nprint(y_pred_test)\n", "repo_name": "ebtrader/corefinta_scratchpad", "sub_path": "knn/social_network_ads/social_network_loop.py", "file_name": "social_network_loop.py", "file_ext": "py", "file_size_in_byte": 2114, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "pandas.read_csv", "line_number": 15, "usage_type": "call"}, {"api_name": "sklearn.model_selection.train_test_split", "line_number": 21, "usage_type": "call"}, {"api_name": "sklearn.preprocessing.StandardScaler", "line_number": 24, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 30, "usage_type": "call"}, {"api_name": "sklearn.neighbors.KNeighborsClassifier", "line_number": 37, "usage_type": "call"}, {"api_name": "sklearn.metrics.f1_score", "line_number": 40, "usage_type": "call"}, {"api_name": "sklearn.metrics", "line_number": 40, "usage_type": "name"}, {"api_name": "sklearn.metrics.accuracy_score", "line_number": 41, "usage_type": "call"}, {"api_name": "sklearn.metrics", "line_number": 41, "usage_type": "name"}, {"api_name": "sklearn.neighbors.KNeighborsClassifier", "line_number": 58, "usage_type": "call"}, {"api_name": "sklearn.metrics.confusion_matrix", "line_number": 65, "usage_type": "call"}]} +{"seq_id": "42344196843", "text": "from __future__ import unicode_literals\n\nimport idna\nfrom mongoengine import BooleanField, StringField\nfrom core.common.utils import tldextract_parser\n\nfrom core.errors import ObservableValidationError\nfrom core.observables import Observable\nfrom core.helpers import refang\n\n\nclass Hostname(Observable):\n main_regex = r\"[-.\\w[\\]]+\\[?\\.\\]?[\\w-]+\"\n regex = r\"(?P
\\W?)(?P\" + main_regex + \")(?P\\W?)\"\n\n    domain = BooleanField()\n    idna = StringField()\n\n    DISPLAY_FIELDS = Observable.DISPLAY_FIELDS + [\n        (\"domain\", \"Domain?\"),\n        (\"idna\", \"IDNA\"),\n    ]\n\n    @classmethod\n    def is_valid(cls, match):\n        # Check that the domain is not preceded or followed by a '/'\n        # This ensures that we do not match URLs\n        if match.group(\"pre\") != \"/\" and match.group(\"post\") != \"/\":\n            # Check that the domain is valid (by checking TLD)\n            value = refang(match.group(\"search\"))\n\n            if len(value) <= 255:\n                parts = tldextract_parser(value)\n                if parts.suffix and parts.domain:\n                    return True\n\n        return False\n\n    def info(self):\n        info = super(Hostname, self).info()\n        info[\"idna\"] = self.idna\n        info[\"domain\"] = self.domain\n        return info\n\n    def normalize(self):\n        self.value = refang(self.value.lower())\n        # Remove trailing dot if existing\n        if self.value.endswith(\".\"):\n            self.value = self.value[:-1]\n        try:\n            self.idna = self.value\n        except idna.core.InvalidCodepoint:\n            pass\n        except Exception as e:\n            raise ObservableValidationError(e.with_traceback())\n", "repo_name": "yeti-platform/yeti", "sub_path": "core/observables/hostname.py", "file_name": "hostname.py", "file_ext": "py", "file_size_in_byte": 1677, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1485, "dataset": "github-code", "pt": "21", "api": [{"api_name": "core.observables.Observable", "line_number": 12, "usage_type": "name"}, {"api_name": "mongoengine.BooleanField", "line_number": 16, "usage_type": "call"}, {"api_name": "mongoengine.StringField", "line_number": 17, "usage_type": "call"}, {"api_name": "core.observables.Observable.DISPLAY_FIELDS", "line_number": 19, "usage_type": "attribute"}, {"api_name": "core.observables.Observable", "line_number": 19, "usage_type": "name"}, {"api_name": "core.helpers.refang", "line_number": 30, "usage_type": "call"}, {"api_name": "core.common.utils.tldextract_parser", "line_number": 33, "usage_type": "call"}, {"api_name": "core.helpers.refang", "line_number": 46, "usage_type": "call"}, {"api_name": "idna.core", "line_number": 52, "usage_type": "attribute"}, {"api_name": "core.errors.ObservableValidationError", "line_number": 55, "usage_type": "call"}]}
+{"seq_id": "42556655727", "text": "'''\nTeam member:\nBrian Allen (ba2542)\nHaozheng Ni (hn2318)\nSerena Zhang (mz2642)\n'''\n#---------Set up --------\nfrom scipy.io import loadmat\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import cm\nimport random\nimport time\n\n# load data\nocr = loadmat('ocr.mat')\n\n#---------Calculate Nearest Neighbor--------\n'''\n# function:nearest neighbors classifier given different training data\n# input: list; sampling size of training data for each iteration of prediction\n# output: list; prediction outcome for test data\n'''\ndef sampling(steps):\n    test_errors=[]\n    for n in steps:\n        #sample n data points from training data\n        sel=random.sample(range(60000),n)\n        trainx=ocr[\"data\"][sel].astype(\"float\")\n        trainy=ocr[\"labels\"][sel].astype(\"float\")\n        testx=ocr[\"testdata\"].astype(\"float\")\n        #predict nearest neighbors of test data using matrix caulculation\n        #store the index of y data in var \"yindex\"\n        result=np.array([])\n        i=np.array([np.einsum('ij,ji->i', trainx,trainx.T)]).T\n        k=np.matmul(trainx,testx.T)\n        squared=i-2*k\n        yindex=np.argmin(squared, axis=0)\n        result=np.append(result,trainy[yindex])\n        #calculate the test error rate\n        #store it in list \"test_errors\"\n        predicted=trainy[yindex]\n        actual=ocr[\"testlabels\"]\n        test_errors.append((np.sum(predicted!=actual))/ocr[\"testlabels\"].shape[0])\n    return test_errors\n'''\ncall the sampling function 10 times\nstore results in list \"avg\"\n'''\nfinal=[]\nsteps=[1000,2000,4000,8000]\nstart_time = time.time()\nfor i in range(10):\n    temp=np.asarray(sampling(steps))\n    final.append(temp)\navg=[sum(e)/len(e) for e in zip(*final)]\nmat=np.vstack(final)\nst=np.std(mat,axis=0)\nprint(\"The model ran for %s seconds\" % (time.time() - start_time))\nprint(\"The means are: \", avg)\nprint(\"The standard deviations for each step are: \", st)\n\n#---------Plot Test Error Rate--------\n# plot the averaged test error rate with sample size increasing\nplt.errorbar(steps,avg,yerr=st,fmt=\"-0\")\nplt.grid()\nplt.xlabel(\"sample size\")\nplt.ylabel(\"test error rate\")\nplt.title(\"Test Error Rate vs Sample Size\")\nplt.savefig('Learning Curve Plot.png')\nplt.show()\n\n", "repo_name": "serenazzz/Machine_Learning_Algos", "sub_path": "Nearest Neighbor & Linear Models/Q1.py", "file_name": "Q1.py", "file_ext": "py", "file_size_in_byte": 2202, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "scipy.io.loadmat", "line_number": 16, "usage_type": "call"}, {"api_name": "random.sample", "line_number": 28, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 34, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 35, "usage_type": "call"}, {"api_name": "numpy.einsum", "line_number": 35, "usage_type": "call"}, {"api_name": "numpy.matmul", "line_number": 36, "usage_type": "call"}, {"api_name": "numpy.argmin", "line_number": 38, "usage_type": "call"}, {"api_name": "numpy.append", "line_number": 39, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 44, "usage_type": "call"}, {"api_name": "time.time", "line_number": 52, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 54, "usage_type": "call"}, {"api_name": "numpy.vstack", "line_number": 57, "usage_type": "call"}, {"api_name": "numpy.std", "line_number": 58, "usage_type": "call"}, {"api_name": "time.time", "line_number": 59, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.errorbar", "line_number": 65, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 65, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.grid", "line_number": 66, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 66, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 67, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 67, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 68, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 68, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 69, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 69, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 70, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 70, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 71, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 71, "usage_type": "name"}]}
+{"seq_id": "16602661483", "text": "import time, getpass, os, json\nfrom selenium import webdriver\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.by import By\nfrom .utils.log_time import log_time\n\nwith open('../config.json', 'r') as file: config = json.load(file)\n\nclass Session():\n  def __init__(self, session_name=\"\"):\n    self.session_name = session_name\n    self.wait_ec_timeout = 0\n    self.current_profile = 1\n    self.current_profile_timeout = 0\n\n\n  ## Create chromdriver instance and direct to HCS Portal login ##\n  def start(self, headless=False):\n    print(f\"[{log_time()}][{self.session_name}] Initializing ChromeDriver\")\n\n    op = webdriver.ChromeOptions()\n    op.add_argument(\"--log-level=3\")\n    op.add_argument(\"--start-maximized\")            ## Required to prevent elements from being \"out of sight\" ##\n    op.add_argument(\"--window-size=1920x1080\")      ###       Mostly required for headless instances        ###\n    if headless: op.add_argument('--headless')\n\n    self.driver = webdriver.Chrome(\"C:/Users/Josh/Desktop/ld/hcs_scraper/portal/chromedriver.exe\", options=op)\n    self.driver.maximize_window()\n    self.driver.get(\"https://hcsportal.allstream.com/login/\")\n\n\n  ##Login into HCS Portal with specified credentials##\n  def login(self):\n    # if not os.environ['USER'] and not os.environ['PW']:\n    #   os.environ['USER'] = getpass.getuser()\n    #   os.environ['PW'] = getpass.getpass()\n    \n    try:\n      self.find_element(\"id\", \"id_username\").send_keys(config[0])\n      self.find_element(\"id\", \"id_password\").send_keys(config[1])\n      self.find_element(\"id\", \"login-button\").click()\n\n    except:\n      print(f\"[{log_time()}][{self.session_name}] Caught Error: Unable to log into HCS Portal\")\n      self.driver.close()\n      self.driver.quit()\n      return\n\n    print(f\"[{log_time()}][{self.session_name}] Successfully logged into HCS Portal.\")\n\n\n  ##Logout of HCS Portal\n  def logout(self):\n    self.find_element(\"id\", \"username\").click()\n    self.find_element(\"xpath\", \"//li[@data-dojo-attach-point='logout']\").click()\n    time.sleep(10)\n    print(f\"[{log_time()}][{self.session_name}] Successfully logged out of HCS Portal.\")\n\n\n  ##Single level, more manageable find_element or find_elements method for selenium##\n  def find_element(self, type, name, element=\"element\"):\n    method = [x for x in dir(self.driver) if f\"find_{element}_by_{type}\" in x]\n    function = getattr(self.driver, method[0])\n    return function(name)\n\n\n  ##Waits for element to render to DOM before acting##\n  def wait_ec(self, element, name):\n    method = [x for x in dir(By) if element.upper() in x]\n    function = getattr(By, method[0])\n\n    try:\n      WebDriverWait(self.driver, 60).until(\n        EC.presence_of_element_located((function, name)))\n      self.wait_ec_timeout = 0\n\n    except:\n      self.wait_ec_timeout+=1\n      \n      if self.wait_ec_timeout > 3:\n        print(f\"[{log_time()}][{self.session_name}] WaitEC timed out too many times. Ending session...\")\n        self.logout()\n        time.sleep(5)\n        self.driver.close()\n        self.driver.quit()\n        return\n\n      print(f\"[{log_time()}][{self.session_name}] WaitEC timed out waiting for {name}.\")\n      print(f\"[{log_time()}][{self.session_name}] Retrying {self.wait_ec_timeout} of 3 times.\")\n      self.driver.refresh()\n      self.wait_ec(element, name)\n\n\n  ##Changes profile type to focus##\n  ##Acceptable profiles [Lines, Phones, Subscribers, Voicemail]##\n  def change_profile(self, profile):\n    self.wait_ec(\"xpath\", \"//button[contains(@id, 'app_button_Button_')]\")\n    self.find_element(\"id\", \"app_newMenu_item_3\").click()\n    elements = self.find_element(\"class_name\", \"submenu\").find_elements_by_xpath(\".//*\")\n    \n    for e in elements:\n      if e.text == profile:\n        e.click()\n        break\n\n    print(f\"[{log_time()}][{self.session_name}] Focused profile changed to {profile.title()}.\")\n\n\n  ##Change location of profile list##\n  def change_location(self, string):\n    self.find_element(\"id\", \"dropdown_app_view_simpleControls_Dropdown_1_chosen\").click()\n    self.find_element(\"id\", \"id-app_view_simpleControls_Dropdown_1-chosen-search\").send_keys(string)\n    elements = self.find_element(\"class_name\", \"active-result\", \"elements\")\n    for item in elements:\n      if string in item.text: \n        item.click()\n\n\n  ##Adds specified filter to current profile list## \n  def add_filter(self, string):\n    self.find_element(\"xpath\", \"//button[@data-dojo-attach-point='gridFilterDOM']\").click()\n    self.wait_ec(\"id\", \"dijit_form_TextBox_0\")\n    self.find_element(\"id\", \"dijit_form_TextBox_0\").send_keys(string)\n    self.find_element(\"xpath\", \"//button[@data-dojo-attach-point='applyFilterButton']\").click()\n    print(f\"[{log_time()}][{self.session_name}] Added filter: {string}\")\n\n\n  ##Changes total items to render per page##\n  ##Acceptabele ints [25, 50, 100, 200, 500, 1000, 2000]##\n  def change_total(self, int):\n    self.wait_ec(\"id\", \"gridPerPage\")\n    self.find_element(\"id\", \"gridPerPage\").click()\n    self.find_element(\"xpath\", f\"//tr[@aria-label='{int} ']\").click()\n    print(f\"[{log_time()}][{self.session_name}] Changed page total to {int}.\")\n\n\n  ##Navigates to desired page## \n  def navigate_page(self):\n    print(f\"[{log_time()}][{self.session_name}] Navigating to next page...\")\n    self.wait_ec(\"xpath\", \"//li[contains(@id, 'app_simpleGrid_row')]\")\n    if self.find_element(\"id\", \"gridPageNext\").get_attribute(\"disabled\"): return False\n    self.find_element(\"id\", \"gridPageNext\").click()\n    time.sleep(5)\n    return True\n\n\n  ##Downloads all JSON files from profiles page##\n  def get_json(self):\n    def get_progress():\n      return self.find_element(\"id\", \"app_progressII_Progress_2\").get_attribute(\"style\")\n\n    try:\n      self.wait_ec(\"xpath\", \"//li[contains(@id, 'app_simpleGrid_row_')]\")\n      list = self.find_element(\"xpath\", \"//input[contains(@id, 'dijit_form_CheckBox_')]\", \"elements\")\n      list[0].click()\n\n      action = self.find_element(\"xpath\", \"//div[@class='btn-group dropdownButtonContainer menuButtonContainer']\")\n      self.driver.execute_script(\"arguments[0].setAttribute('class','btn-group dropdownButtonContainer menuButtonContainer open')\", action)\n      self.wait_ec(\"xpath\", \"//ul[@id='id_dropdown_button_row-gridMenu']\")\n      ddl = self.find_element(\"xpath\", \"//ul[@id='id_dropdown_button_row-gridMenu']\").find_elements_by_tag_name(\"li\")\n      for item in ddl:\n        if item.text == \"Export\": item.click()\n      self.wait_ec(\"xpath\", \"//div[@item='0']\")\n      self.find_element(\"xpath\", \"//div[@item='0']\").click()\n      self.find_element(\"xpath\", \"//button[@class='btn btn-primary btn-xs no-border']\").click()\n      time.sleep(1)\n      while str(get_progress()) == \"visibility: visible; height: 80px; z-index: 999;\": pass\n      time.sleep(1.5)\n\n    ##Catches any timeouts or errors and saves current position, then recalls get_json##\n    except Exception as e:\n      print(f\"[{log_time()}][{self.session_name}] Exception: {e}\")\n      self.logout()\n      self.driver.close()\n      self.driver.quit()\n      return", "repo_name": "JoshSetterstrom/hcs_scraper", "sub_path": "portal/session.py", "file_name": "session.py", "file_ext": "py", "file_size_in_byte": 7119, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "json.load", "line_number": 8, "usage_type": "call"}, {"api_name": "utils.log_time.log_time", "line_number": 20, "usage_type": "call"}, {"api_name": "selenium.webdriver.ChromeOptions", "line_number": 22, "usage_type": "call"}, {"api_name": "selenium.webdriver", "line_number": 22, "usage_type": "name"}, {"api_name": "selenium.webdriver.Chrome", "line_number": 28, "usage_type": "call"}, {"api_name": "selenium.webdriver", "line_number": 28, "usage_type": "name"}, {"api_name": "utils.log_time.log_time", "line_number": 45, "usage_type": "call"}, {"api_name": "utils.log_time.log_time", "line_number": 50, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 57, "usage_type": "call"}, {"api_name": "utils.log_time.log_time", "line_number": 58, "usage_type": "call"}, {"api_name": "selenium.webdriver.common.by.By", "line_number": 70, "usage_type": "argument"}, {"api_name": "selenium.webdriver.common.by.By", "line_number": 71, "usage_type": "argument"}, {"api_name": "selenium.webdriver.support.ui.WebDriverWait", "line_number": 74, "usage_type": "call"}, {"api_name": "selenium.webdriver.support.expected_conditions.presence_of_element_located", "line_number": 75, "usage_type": "call"}, {"api_name": "selenium.webdriver.support.expected_conditions", "line_number": 75, "usage_type": "name"}, {"api_name": "utils.log_time.log_time", "line_number": 82, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 84, "usage_type": "call"}, {"api_name": "utils.log_time.log_time", "line_number": 89, "usage_type": "call"}, {"api_name": "utils.log_time.log_time", "line_number": 90, "usage_type": "call"}, {"api_name": "utils.log_time.log_time", "line_number": 107, "usage_type": "call"}, {"api_name": "utils.log_time.log_time", "line_number": 126, "usage_type": "call"}, {"api_name": "utils.log_time.log_time", "line_number": 135, "usage_type": "call"}, {"api_name": "utils.log_time.log_time", "line_number": 140, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 144, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 167, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 169, "usage_type": "call"}, {"api_name": "utils.log_time.log_time", "line_number": 173, "usage_type": "call"}]}
+{"seq_id": "75039842933", "text": "import azure.mgmt.batchai as batchai\nfrom datetime import datetime\nfrom util import bai, fileshare\nfrom iteration_utilities import grouper\nimport argparse\nimport os\nimport time\nimport logging\nfrom logging.handlers import RotatingFileHandler\nimport sys\n\nif __name__ == '__main__':\n\n  # set up parser\n  parser = argparse.ArgumentParser( \\\n    description='Script for creating a set of BatchAI jobs.')\n  parser.add_argument(\n    '--content-images-blob-dir', \n    dest='content_images_blob_dir', \n    help='The name of the content images directory in blob.',\n    default=os.getenv('FS_CONTENT_DIR')\n  )\n  parser.add_argument(\n    '--job-batch-size',\n    dest='job_batch_size',\n    help='The number of images to process for BatchAI job.',\n    default=os.getenv('JOB_BATCH_SIZE')\n  )\n  parser.add_argument(\n    '--log-path',\n    dest='log_path',\n    help='The path of the log file to create.',\n    default=None\n  )\n\n  args = parser.parse_args()\n  content_images_blob_dir = args.content_images_blob_dir\n  job_batch_size = args.job_batch_size\n  log_path = args.log_path\n\n  # set up logger\n  handler_format = logging.Formatter(\n    \"%(asctime)s - %(name)s - %(levelname)s - %(message)s\"\n  )\n\n  logger = logging.getLogger(__name__)\n  logger.setLevel(logging.DEBUG)\n\n  console_handler = logging.StreamHandler(sys.stdout)\n  console_handler.setFormatter(handler_format)\n  logger.addHandler(console_handler)\n\n  if log_path is not None:\n    file_handler = RotatingFileHandler(\n      os.path.join(log_path, 'create_job.log'), \n      maxBytes=20000\n    )\n    file_handler.setFormatter(handler_format)\n    logger.addHandler(file_handler)\n\n  logger.propagate = False\n\n  # set date to be used by experiment name, output/logging dirname\n  now = datetime.utcnow()\n\n  # set up batch AI client with credentials\n  bai_client = bai.setup_bai()\n  fs_client = fileshare.setup_file_share()\n  \n  # get a reference to the cluster we want to use\n  cluster = bai.get_cluster(bai_client, os.getenv('CLUSTER_NAME'))\n\n  # create an experiment \n  experiment_name = now.strftime(\n    \"{0}_%m_%d_%Y_%H%M%S\".format(os.getenv('EXPERIMENT_PREFIX'))\n  )\n  experiment = bai.create_experiment(bai_client, experiment_name)\n\n  # create name output dir\n  output_images_dir = now.strftime(\n    \"{0}_{1}_%m_%d_%Y_%H%M%S\".format(\n      os.getenv('FS_OUTPUT_DIR_PREFIX'),\n      content_images_blob_dir\n    )\n  )\n\n  # create name of log dir\n  logger_dir = now.strftime(\n    \"{0}_{1}_%m_%d_%Y_%H%M%S\".format(\n      os.getenv('FS_LOGGER_DIR_PREFIX'),\n      content_images_blob_dir\n    )\n  )\n\n  # create mounted output images dir in storage\n  fileshare.create_dir(\n    blob_service=fs_client,\n    blob_dir_name=output_images_dir\n  )\n\n  # create mounted logging dir in storage\n  fileshare.create_dir(\n    blob_service=fs_client,\n    blob_dir_name=logger_dir\n  )\n\n  # set up input directories to access for the jobs\n  mapping = [\n    ('STYLE_IMG', os.getenv('FS_STYLE_IMAGE')),\n    ('SCRIPT', os.getenv('FS_SCRIPT')),\n    ('CONTENT_IMGS', content_images_blob_dir),\n    ('OUTPUT_IMGS', output_images_dir),\n    ('LOGGER', logger_dir)\n  ]\n    \n  input_dirs = []\n  for dir_id, dir_name in mapping:\n    input_dirs.append(\n      batchai.models.InputDirectory(\n        id=dir_id,\n        path='$AZ_BATCHAI_MOUNT_ROOT/{0}/{1}'.format(\n          os.getenv('CLUSTER_CONTAINER_MNT_PATH'),\n          dir_name\n        )\n      )\n    )\n\n  # create array of content img names inside content img dir\n  content_img_names = fileshare.list_blobs_in_dir(\n    blob_service=fs_client, \n    blob_dir_name=content_images_blob_dir\n  )\n\n  # create a job per chunk\n  t0 = time.time()\n  for group_i, img_name_group in \\\n      enumerate(grouper(\n        content_img_names, \n        int(job_batch_size)\n      )):\n        \n    img_list_str = ','.join(img_name_group)\n\n    # set the job name [ex job_01_01_2000_111111]\n    job_name = datetime.utcnow().strftime(\n      \"{0}{1}_%m_%d_%Y_%H%M%S\".format(\n        os.getenv('JOB_NAME_PREFIX'),\n        group_i\n      )\n    )\n\n    # create params for the job\n    job_params = bai.create_job_params(\n      cluster=cluster,\n      input_dirs=input_dirs,\n      output_dirs=None,\n      container_image=\"pytorch/pytorch:0.4_cuda9_cudnn7\",\n      command_line=(\"python $AZ_BATCHAI_INPUT_SCRIPT \" + \\\n        \"--style-image $AZ_BATCHAI_INPUT_STYLE_IMG \" + \\\n        \"--content-image-dir $AZ_BATCHAI_INPUT_CONTENT_IMGS \" + \\\n        \"--content-image-list {2} \" \\\n        \"--output-image-dir $AZ_BATCHAI_INPUT_OUTPUT_IMGS \" + \\\n\t\t\t\t\"--style-weight {3} \" + \\\n\t\t\t\t\"--content-weight {4} \" + \\\n\t\t\t\t\"--num-steps {5} \" + \\\n\t\t\t\t\"--image-size {6} \" + \\\n        \"--log-path $AZ_BATCHAI_INPUT_LOGGER \" + \\\n        \"--log-file {7}\").format(\n          os.getenv('FS_SCRIPT_NAME'),\n          os.getenv('FS_STYLE_IMG_NAME'),\n          img_list_str,\n          os.getenv('STYLE_WEIGHT'),\n          os.getenv('CONTENT_WEIGHT'),\n          os.getenv('NUM_STEPS'),\n          os.getenv('IMAGE_SIZE'),\n          job_name # use job_name as log_file name too\n        ),\n      job_prep_command_line=\"pip install scikit-image\"\n    )\n\n    # create job\n    job = bai.create_job(\n      bai_client, \n      job_name, \n      job_params, \n      experiment_name,\n      async_job=True\n    )\n\n    logger.debug(\"Created job #{}, named {}, with {} images.\" \\\n      .format(group_i, job_name, len(img_name_group))\n    )\n\n  # log total time to create jobs\n  t1 = time.time()\n  create_jobs_time = t1 - t0\n  logger.debug(\n    \"Time (in seconds) it took to create all BatchAI jobs: {}\" \\\n    .format(create_jobs_time)\n  )\n  logger.debug(\n    \"Time (in seconds) it takes to create a single BatchAI job \" + \\\n    \"on average: {}\".format(create_jobs_time/group_i)\n  )\n\n\n", "repo_name": "Azure/batch-scoring-for-dl-models", "sub_path": "az/create_job.py", "file_name": "create_job.py", "file_ext": "py", "file_size_in_byte": 5665, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 16, "dataset": "github-code", "pt": "21", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 15, "usage_type": "call"}, {"api_name": "os.getenv", "line_number": 21, "usage_type": "call"}, {"api_name": "os.getenv", "line_number": 27, "usage_type": "call"}, {"api_name": "logging.Formatter", "line_number": 42, "usage_type": "call"}, {"api_name": "logging.getLogger", "line_number": 46, "usage_type": "call"}, {"api_name": "logging.DEBUG", "line_number": 47, "usage_type": "attribute"}, {"api_name": "logging.StreamHandler", "line_number": 49, "usage_type": "call"}, {"api_name": "sys.stdout", "line_number": 49, "usage_type": "attribute"}, {"api_name": "logging.handlers.RotatingFileHandler", "line_number": 54, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 55, "usage_type": "call"}, {"api_name": "os.path", "line_number": 55, "usage_type": "attribute"}, {"api_name": "datetime.datetime.utcnow", "line_number": 64, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 64, "usage_type": "name"}, {"api_name": "util.bai.setup_bai", "line_number": 67, "usage_type": "call"}, {"api_name": "util.bai", "line_number": 67, "usage_type": "name"}, {"api_name": "util.fileshare.setup_file_share", "line_number": 68, "usage_type": "call"}, {"api_name": "util.fileshare", "line_number": 68, "usage_type": "name"}, {"api_name": "util.bai.get_cluster", "line_number": 71, "usage_type": "call"}, {"api_name": "util.bai", "line_number": 71, "usage_type": "name"}, {"api_name": "os.getenv", "line_number": 71, "usage_type": "call"}, {"api_name": "os.getenv", "line_number": 75, "usage_type": "call"}, {"api_name": "util.bai.create_experiment", "line_number": 77, "usage_type": "call"}, {"api_name": "util.bai", "line_number": 77, "usage_type": "name"}, {"api_name": "os.getenv", "line_number": 82, "usage_type": "call"}, {"api_name": "os.getenv", "line_number": 90, "usage_type": "call"}, {"api_name": "util.fileshare.create_dir", "line_number": 96, "usage_type": "call"}, {"api_name": "util.fileshare", "line_number": 96, "usage_type": "name"}, {"api_name": "util.fileshare.create_dir", "line_number": 102, "usage_type": "call"}, {"api_name": "util.fileshare", "line_number": 102, "usage_type": "name"}, {"api_name": "os.getenv", "line_number": 109, "usage_type": "call"}, {"api_name": "os.getenv", "line_number": 110, "usage_type": "call"}, {"api_name": "azure.mgmt.batchai.models.InputDirectory", "line_number": 119, "usage_type": "call"}, {"api_name": "azure.mgmt.batchai.models", "line_number": 119, "usage_type": "attribute"}, {"api_name": "azure.mgmt.batchai", "line_number": 119, "usage_type": "name"}, {"api_name": "os.getenv", "line_number": 122, "usage_type": "call"}, {"api_name": "util.fileshare.list_blobs_in_dir", "line_number": 129, "usage_type": "call"}, {"api_name": "util.fileshare", "line_number": 129, "usage_type": "name"}, {"api_name": "time.time", "line_number": 135, "usage_type": "call"}, {"api_name": "iteration_utilities.grouper", "line_number": 137, "usage_type": "call"}, {"api_name": "datetime.datetime.utcnow", "line_number": 145, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 145, "usage_type": "name"}, {"api_name": "os.getenv", "line_number": 147, "usage_type": "call"}, {"api_name": "util.bai.create_job_params", "line_number": 153, "usage_type": "call"}, {"api_name": "util.bai", "line_number": 153, "usage_type": "name"}, {"api_name": "os.getenv", "line_number": 169, "usage_type": "call"}, {"api_name": "os.getenv", "line_number": 170, "usage_type": "call"}, {"api_name": "os.getenv", "line_number": 172, "usage_type": "call"}, {"api_name": "os.getenv", "line_number": 173, "usage_type": "call"}, {"api_name": "os.getenv", "line_number": 174, "usage_type": "call"}, {"api_name": "os.getenv", "line_number": 175, "usage_type": "call"}, {"api_name": "util.bai.create_job", "line_number": 182, "usage_type": "call"}, {"api_name": "util.bai", "line_number": 182, "usage_type": "name"}, {"api_name": "time.time", "line_number": 195, "usage_type": "call"}]}
+{"seq_id": "73672896693", "text": "\"\"\"\nTest script for flexivaidk.so\nAuthor: Flexiv\n\"\"\"\n\nimport argparse\nimport json\nimport logging\nimport os\nimport sys\nimport time\n\n# Import Flexiv AIDK Python library\nsys.path.insert(0, \"../lib_py/\")\nimport flexivaidk as aidk\n\ntry:\n    import flexivrdk\nexcept Exception:\n    print(\"please put flexivrdk.so in current directory\")\n\nlogging.basicConfig(level=logging.INFO)\n\n\ndef main(\n    project,\n    config,\n    keys,\n    ai_ip=\"127.0.0.1\",\n    robot_ip=\"192.168.2.100\",\n    local_ip=\"192.168.2.101\",\n    detect_timeout=10,\n):\n    # use rdk to get camera pose\n    robot = flexivrdk.Robot(robot_ip, local_ip)\n    while not robot.isConnected():\n        time.sleep(0.001)\n    robot_states = flexivrdk.RobotStates()\n    robot.getRobotStates(robot_states)\n    camera_pose = robot_states.camPose\n    logging.info(\"camera pose: {}\".format(camera_pose))\n\n    # use aidk to get grasp pose\n    client = aidk.AIDKClient(ai_ip, detect_timeout)\n\n    # AI state check\n    while not client.is_ready():\n        time.sleep(0.5)\n    ai_status = client.get_current_state()\n    logging.info(\"Current state code: {}\".format(ai_status.status_code))\n    logging.info(\"Current state name: {}\".format(ai_status.status_name))\n    logging.info(\"Current state message: {}\".format(ai_status.status_message))\n\n    tic = time.time()\n    config[\"camera_pose\"] = camera_pose\n    state = client.detect(\n        **config,\n    )\n    infer_time = time.time() - tic\n    logging.info(\n        \"detect: %.1f ms, %.1f Hz, instruction %d\",\n        1000 * infer_time,\n        1 / infer_time,\n        config[\"instruction_id\"],\n    )\n    logging.info(\"state: %s\", state)\n    logging.info(\n        \"current detected object names: %s, current detected object nums: %s\",\n        client.get_detected_obj_names(),\n        client.get_detected_obj_nums(),\n    )\n\n    key = \"obj_pose\"\n    parse_state, result_list = client.parse_result(config[\"obj_name\"], key, -1)\n    grasp_pose = result_list[0].vect[0]\n    logging.info(\"grasp pose: {}\".format(grasp_pose))\n    key = \"double_value\"\n    parse_state, result_list = client.parse_result(config[\"obj_name\"], key, -1)\n    width = result_list[0].double_value\n    logging.info(\"grasp width: {}\".format(width))\n\n\nif __name__ == \"__main__\":\n    parser = argparse.ArgumentParser(description=\"Test Noema\")\n    parser.add_argument(\n        \"--config\",\n        help=\"config file path\",\n        default=\"config/TUTORIAL.json\",\n        type=str,\n    )\n    parser.add_argument(\n        \"--detect-timeout\",\n        help=\"Timeout of detect command request.\",\n        type=float,\n        default=10,\n    )\n    parser.add_argument(\"--ai-ip\", help=\"Ip in a.b.c.d.\", type=str, default=\"localhost\")\n    parser.add_argument(\n        \"--robot-ip\", help=\"Ip in a.b.c.d.\", type=str, default=\"192.168.2.100\"\n    )\n    parser.add_argument(\n        \"--local-ip\", help=\"Ip in a.b.c.d.\", type=str, default=\"192.168.2.101\"\n    )\n\n    args = parser.parse_args()\n\n    assert os.path.exists(args.config), \"Test config file %s not exist!\" % args.config\n\n    with open(args.config, \"r\") as f:\n        config = json.load(f)\n\n    logging.info(str(args))\n    logging.info(\"Test config:\\n%s\", config)\n\n    main(\n        config[\"project\"],\n        config[\"command\"],\n        config[\"keys\"],\n        args.ai_ip,\n        args.robot_ip,\n        args.local_ip,\n    )\n", "repo_name": "flexivrobotics/flexiv_aidk", "sub_path": "example_py/test_grasping_with_rdk.py", "file_name": "test_grasping_with_rdk.py", "file_ext": "py", "file_size_in_byte": 3317, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "sys.path.insert", "line_number": 14, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 14, "usage_type": "attribute"}, {"api_name": "logging.basicConfig", "line_number": 22, "usage_type": "call"}, {"api_name": "logging.INFO", "line_number": 22, "usage_type": "attribute"}, {"api_name": "flexivrdk.Robot", "line_number": 35, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 37, "usage_type": "call"}, {"api_name": "flexivrdk.RobotStates", "line_number": 38, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 41, "usage_type": "call"}, {"api_name": "flexivaidk.AIDKClient", "line_number": 44, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 48, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 50, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 51, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 52, "usage_type": "call"}, {"api_name": "time.time", "line_number": 54, "usage_type": "call"}, {"api_name": "time.time", "line_number": 59, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 60, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 66, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 67, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 76, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 80, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 84, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 107, "usage_type": "call"}, {"api_name": "os.path", "line_number": 107, "usage_type": "attribute"}, {"api_name": "json.load", "line_number": 110, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 112, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 113, "usage_type": "call"}]}
+{"seq_id": "15413746041", "text": "import requests\nfrom flask import Flask, jsonify, request, render_template\nfrom blockchain import Blockchain\nimport utils\n\n\nip = input(\"输入这个节点的 IP: \")\n# ip = '127.0.0.1:5000'\nROOT = set()\nROOT.add('127.0.0.1:5000')\nblockchain = Blockchain(utils.get_magic_param()[0], utils.get_magic_param()[1], ip, ROOT)  # 实例化类\n\napp = Flask(__name__)\n\n\n\ndef get_render_assets():\n    public_key = utils.tuple2string(blockchain.public_key)\n    secret_key = str(blockchain.private_key)\n    amount = blockchain.amount\n    hypoamount = blockchain.hypoamount\n    networks = list(blockchain.neighbor)\n    chains = []\n    for obj in blockchain.chain:\n        temp = {}\n        temp['index'] = str(obj['index'])\n        if temp['index'] == '0':\n            temp['owner'] = \"世界\"\n            temp['number'] = \"世界\"\n            temp['time'] = str(obj['timestamp'])\n        else:\n            if obj['transactions'][0][0]['recipient'] == str(blockchain.public_key):\n                temp['owner'] = \"我\"\n            else:\n                temp['owner'] = \"别人\"\n            temp['number'] = str(len(obj['transactions']))\n            temp['time'] = str(obj['timestamp'])\n        chains.append(temp)\n    children = list(blockchain.children)\n    return public_key, secret_key, amount, hypoamount, networks, chains, children\n\n\n@app.route('/', methods=['GET'])\ndef web_index():\n    public_key, secret_key, amount, hypoamount, networks, chains, children = get_render_assets()\n\n    return render_template('index.html',\n                           public_key=public_key,\n                           secret_key=secret_key,\n                           amount=amount,\n                           hypoamount=hypoamount,\n                           node_length=str(len(networks) + 1),\n                           localip=blockchain.ip,\n                           networks=networks,\n                           block_length=str(len(blockchain.chain)),\n                           chain=chains,\n                           children=children)\n\n\n# 更新网络\n@app.route('/get_map', methods=['GET'])\ndef get_map():\n    blockchain.update_neighbor()\n    public_key, secret_key, amount, hypoamount, networks, chains, children = get_render_assets()\n\n    return render_template('index.html',\n                           public_key=public_key,\n                           secret_key=secret_key,\n                           amount=amount,\n                           hypoamount=hypoamount,\n                           node_length=str(len(networks) + 1),\n                           localip=blockchain.ip,\n                           networks=networks,\n                           block_length=str(len(blockchain.chain)),\n                           chain=chains,\n                           children=children)\n\n\n@app.route('/receive_transaction', methods=['GET'])\ndef receive_transaction():\n    blockchain.receive_transaction()\n    public_key, secret_key, amount, hypoamount, networks, chains, children = get_render_assets()\n\n    return render_template('index.html',\n                           public_key=public_key,\n                           secret_key=secret_key,\n                           amount=amount,\n                           hypoamount=hypoamount,\n                           node_length=str(len(networks) + 1),\n                           localip=blockchain.ip,\n                           networks=networks,\n                           block_length=str(len(blockchain.chain)),\n                           chain=chains,\n                           children=children)\n\n\n@app.route('/consensus', methods=['GET'])\ndef consensus():\n    blockchain.resolve_conflicts()\n    public_key, secret_key, amount, hypoamount, networks, chains, children = get_render_assets()\n\n    return render_template('index.html',\n                           public_key=public_key,\n                           secret_key=secret_key,\n                           amount=amount,\n                           hypoamount=hypoamount,\n                           node_length=str(len(networks) + 1),\n                           localip=blockchain.ip,\n                           networks=networks,\n                           block_length=str(len(blockchain.chain)),\n                           chain=chains,\n                           children=children)\n\n\n# 操作返回界面类\n@app.route('/mine', methods=['POST'])\ndef mine():\n    values = request.form\n    values.to_dict()\n    if 'coop' in values and values['coop'] == 'on':\n        blockchain.coop_batch = int(values['coop_batch'])\n        blockchain.proof_of_work(coop=True)\n    else:\n        blockchain.proof_of_work()\n    public_key, secret_key, amount, hypoamount, networks, chains, children = get_render_assets()\n\n    return render_template('index.html',\n                           public_key=public_key,\n                           secret_key=secret_key,\n                           amount=amount,\n                           hypoamount=hypoamount,\n                           node_length=str(len(networks) + 1),\n                           localip=blockchain.ip,\n                           networks=networks,\n                           block_length=str(len(blockchain.chain)),\n                           chain=chains,\n                           children=children)\n\n\n@app.route('/transaction', methods=['POST'])  # 自身交易池\ndef transaction():\n    values = request.form\n    values.to_dict()\n    if values['recipient'] == '' or values['amount'] == '':\n        public_key, secret_key, amount, hypoamount, networks, chains, children = get_render_assets()\n\n        return render_template('index.html',\n                               public_key=public_key,\n                               secret_key=secret_key,\n                               amount=amount,\n                               hypoamount=hypoamount,\n                               node_length=str(len(networks) + 1),\n                               localip=blockchain.ip,\n                               networks=networks,\n                               block_length=str(len(blockchain.chain)),\n                               chain=chains,\n                               children=children,\n                               message='缺少参数')\n    else:\n        if blockchain.sub_transactions(str(utils.string2tuple(values['recipient'])), int(values['amount'])):\n            blockchain.hypoamount -= int(values['amount'])\n            public_key, secret_key, amount, hypoamount, networks, chains, children = get_render_assets()\n\n            return render_template('index.html',\n                                   public_key=public_key,\n                                   secret_key=secret_key,\n                                   amount=amount,\n                                   hypoamount=hypoamount,\n                                   node_length=str(len(networks) + 1),\n                                   localip=blockchain.ip,\n                                   networks=networks,\n                                   block_length=str(len(blockchain.chain)),\n                                   chain=chains,\n                                   children=children,\n                                   message='成功')\n        else:\n            public_key, secret_key, amount, hypoamount, networks, chains, children = get_render_assets()\n\n            return render_template('index.html',\n                                   public_key=public_key,\n                                   secret_key=secret_key,\n                                   amount=amount,\n                                   hypoamount=hypoamount,\n                                   node_length=str(len(networks) + 1),\n                                   localip=blockchain.ip,\n                                   networks=networks,\n                                   block_length=str(len(blockchain.chain)),\n                                   chain=chains,\n                                   children=children,\n                                   message='余额不足')\n\n\n@app.route('/register_nodes', methods=['POST'])\ndef register_nodes():\n    values = request.form\n    values.to_dict()\n    n = values['node']\n    if n is None:\n        return render_template('index.html', log='请提供一个正确的ip', chain=blockchain.chain)\n    else:\n        if n not in blockchain.neighbor:\n            blockchain.neighbor.add(n)\n            log = {\n                '新节点注册成功'\n                '邻居节点': list(blockchain.neighbor),\n            }\n            return render_template('index.html', log=log, chain=blockchain.chain)\n\n\n\n# # 展示界面类\n# @app.route('/show_network', methods=['GET'])\n# def show_network():\n#     a = list(blockchain.neighbor)\n#     a.append(blockchain.ip)\n#     log = {\n#         '节点列表': a,\n#         '节点数量': len(a),\n#     }\n#     return render_template('index.html', log=log, chain=blockchain.chain)\n\n\n# @app.route('/show_transaction', methods=['GET'])\n# def show_transaction():\n#     return render_template('index.html', log=blockchain.current_transactions, chain=blockchain.chain)\n\n\n# 接口类\n@app.route('/net_work', methods=['GET'])\ndef net_work():\n    a = list(blockchain.neighbor)\n    a.append(blockchain.ip)\n    response = {\n        'node_list': a,\n        'node_number': len(a), }\n    return jsonify(response), 200\n\n\n@app.route('/transaction_pool', methods=['GET'])\ndef transaction_pool():\n    return jsonify(blockchain.current_transactions)\n\n\n@app.route('/chain', methods=['GET'])\ndef chain():\n    response = {\n        'chain': blockchain.chain,\n        'length': len(blockchain.chain),\n    }\n    return jsonify(response), 200\n\n\n@app.route('/register_childs', methods=['POST'])\ndef register_childs():\n    values = request.form\n    values.to_dict()\n    n = values['node']\n    if n is not None:\n        if n not in blockchain.children:\n            blockchain.children.add(n)\n    return \"200\"\n\n\n@app.route('/connect_parent', methods=['POST'])\ndef connect_parent():\n    values = request.form\n    values.to_dict()\n    if 'coop_parent' in values:\n        if values['coop_parent'] is not None:\n            blockchain.coop_ip = values['coop_parent']\n            requests.post(f'http://{blockchain.coop_ip}/register_childs', {'node': blockchain.ip})\n\n    public_key, secret_key, amount, hypoamount, networks, chains, children = get_render_assets()\n\n    return render_template('index.html',\n                           public_key=public_key,\n                           secret_key=secret_key,\n                           amount=amount,\n                           hypoamount=hypoamount,\n                           node_length=str(len(networks) + 1),\n                           localip=blockchain.ip,\n                           networks=networks,\n                           block_length=str(len(blockchain.chain)),\n                           chain=chains,\n                           children=children)\n\n\n@app.route('/mission', methods=['GET'])\ndef mission():\n    values = request.form\n    values.to_dict()\n    # 分配新任务\n    batch_start = blockchain.current_batch\n    blockchain.current_batch += blockchain.coop_batch\n    batch_end = blockchain.current_batch\n    return jsonify({'start': batch_start, 'end': batch_end})\n\n@app.route('/start_work', methods=['POST'])\ndef start_work():\n    values = request.data\n    blockchain.coop_status = False\n    blockchain.solve_mini_mission(values)\n    return \"200\"\n\n\n@app.route('/stop_work', methods=['POST'])\ndef stop_work():\n    blockchain.coop_status = True\n    return \"200\"\n\n\n@app.route('/coop_status', methods=['GET'])\ndef coop_status():\n    if blockchain.coop_status:\n        return jsonify({'status': '1', 'proof': str(blockchain.coop_proof)})\n    else:\n        return jsonify({'status': '0'})\n\n\nhost = blockchain.ip.split(':')[0]\nport = blockchain.ip.split(':')[1]\napp.run(host=host, port=int(port))\n", "repo_name": "Soptq/e-money-demo", "sub_path": "app.py", "file_name": "app.py", "file_ext": "py", "file_size_in_byte": 11801, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "blockchain.Blockchain", "line_number": 11, "usage_type": "call"}, {"api_name": "utils.get_magic_param", "line_number": 11, "usage_type": "call"}, {"api_name": "flask.Flask", "line_number": 13, "usage_type": "call"}, {"api_name": "utils.tuple2string", "line_number": 18, "usage_type": "call"}, {"api_name": "blockchain.public_key", "line_number": 18, "usage_type": "attribute"}, {"api_name": "blockchain.private_key", "line_number": 19, "usage_type": "attribute"}, {"api_name": "blockchain.amount", "line_number": 20, "usage_type": "attribute"}, {"api_name": "blockchain.hypoamount", "line_number": 21, "usage_type": "attribute"}, {"api_name": "blockchain.neighbor", "line_number": 22, "usage_type": "attribute"}, {"api_name": "blockchain.chain", "line_number": 24, "usage_type": "attribute"}, {"api_name": "blockchain.public_key", "line_number": 32, "usage_type": "attribute"}, {"api_name": "blockchain.children", "line_number": 39, "usage_type": "attribute"}, {"api_name": "flask.render_template", "line_number": 47, "usage_type": "call"}, {"api_name": "blockchain.ip", "line_number": 53, "usage_type": "attribute"}, {"api_name": "blockchain.chain", "line_number": 55, "usage_type": "attribute"}, {"api_name": "blockchain.update_neighbor", "line_number": 63, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 66, "usage_type": "call"}, {"api_name": "blockchain.ip", "line_number": 72, "usage_type": "attribute"}, {"api_name": "blockchain.chain", "line_number": 74, "usage_type": "attribute"}, {"api_name": "blockchain.receive_transaction", "line_number": 81, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 84, "usage_type": "call"}, {"api_name": "blockchain.ip", "line_number": 90, "usage_type": "attribute"}, {"api_name": "blockchain.chain", "line_number": 92, "usage_type": "attribute"}, {"api_name": "blockchain.resolve_conflicts", "line_number": 99, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 102, "usage_type": "call"}, {"api_name": "blockchain.ip", "line_number": 108, "usage_type": "attribute"}, {"api_name": "blockchain.chain", "line_number": 110, "usage_type": "attribute"}, {"api_name": "flask.request.form", "line_number": 118, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 118, "usage_type": "name"}, {"api_name": "blockchain.coop_batch", "line_number": 121, "usage_type": "attribute"}, {"api_name": "blockchain.proof_of_work", "line_number": 122, "usage_type": "call"}, {"api_name": "blockchain.proof_of_work", "line_number": 124, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 127, "usage_type": "call"}, {"api_name": "blockchain.ip", "line_number": 133, "usage_type": "attribute"}, {"api_name": "blockchain.chain", "line_number": 135, "usage_type": "attribute"}, {"api_name": "flask.request.form", "line_number": 142, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 142, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 147, "usage_type": "call"}, {"api_name": "blockchain.ip", "line_number": 153, "usage_type": "attribute"}, {"api_name": "blockchain.chain", "line_number": 155, "usage_type": "attribute"}, {"api_name": "blockchain.sub_transactions", "line_number": 160, "usage_type": "call"}, {"api_name": "utils.string2tuple", "line_number": 160, "usage_type": "call"}, {"api_name": "blockchain.hypoamount", "line_number": 161, "usage_type": "attribute"}, {"api_name": "flask.render_template", "line_number": 164, "usage_type": "call"}, {"api_name": "blockchain.ip", "line_number": 170, "usage_type": "attribute"}, {"api_name": "blockchain.chain", "line_number": 172, "usage_type": "attribute"}, {"api_name": "flask.render_template", "line_number": 179, "usage_type": "call"}, {"api_name": "blockchain.ip", "line_number": 185, "usage_type": "attribute"}, {"api_name": "blockchain.chain", "line_number": 187, "usage_type": "attribute"}, {"api_name": "flask.request.form", "line_number": 195, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 195, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 199, "usage_type": "call"}, {"api_name": "blockchain.chain", "line_number": 199, "usage_type": "attribute"}, {"api_name": "blockchain.neighbor", "line_number": 201, "usage_type": "attribute"}, {"api_name": "blockchain.neighbor.add", "line_number": 202, "usage_type": "call"}, {"api_name": "blockchain.neighbor", "line_number": 202, "usage_type": "attribute"}, {"api_name": "blockchain.neighbor", "line_number": 205, "usage_type": "attribute"}, {"api_name": "flask.render_template", "line_number": 207, "usage_type": "call"}, {"api_name": "blockchain.chain", "line_number": 207, "usage_type": "attribute"}, {"api_name": "blockchain.neighbor", "line_number": 231, "usage_type": "attribute"}, {"api_name": "blockchain.ip", "line_number": 232, "usage_type": "attribute"}, {"api_name": "flask.jsonify", "line_number": 236, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 241, "usage_type": "call"}, {"api_name": "blockchain.current_transactions", "line_number": 241, "usage_type": "attribute"}, {"api_name": "blockchain.chain", "line_number": 247, "usage_type": "attribute"}, {"api_name": "blockchain.chain", "line_number": 248, "usage_type": "attribute"}, {"api_name": "flask.jsonify", "line_number": 250, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 255, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 255, "usage_type": "name"}, {"api_name": "blockchain.children", "line_number": 259, "usage_type": "attribute"}, {"api_name": "blockchain.children.add", "line_number": 260, "usage_type": "call"}, {"api_name": "blockchain.children", "line_number": 260, "usage_type": "attribute"}, {"api_name": "flask.request.form", "line_number": 266, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 266, "usage_type": "name"}, {"api_name": "blockchain.coop_ip", "line_number": 270, "usage_type": "attribute"}, {"api_name": "requests.post", "line_number": 271, "usage_type": "call"}, {"api_name": "blockchain.coop_ip", "line_number": 271, "usage_type": "attribute"}, {"api_name": "blockchain.ip", "line_number": 271, "usage_type": "attribute"}, {"api_name": "flask.render_template", "line_number": 275, "usage_type": "call"}, {"api_name": "blockchain.ip", "line_number": 281, "usage_type": "attribute"}, {"api_name": "blockchain.chain", "line_number": 283, "usage_type": "attribute"}, {"api_name": "flask.request.form", "line_number": 290, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 290, "usage_type": "name"}, {"api_name": "blockchain.current_batch", "line_number": 293, "usage_type": "attribute"}, {"api_name": "blockchain.current_batch", "line_number": 294, "usage_type": "attribute"}, {"api_name": "blockchain.coop_batch", "line_number": 294, "usage_type": "attribute"}, {"api_name": "blockchain.current_batch", "line_number": 295, "usage_type": "attribute"}, {"api_name": "flask.jsonify", "line_number": 296, "usage_type": "call"}, {"api_name": "flask.request.data", "line_number": 300, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 300, "usage_type": "name"}, {"api_name": "blockchain.coop_status", "line_number": 301, "usage_type": "attribute"}, {"api_name": "blockchain.solve_mini_mission", "line_number": 302, "usage_type": "call"}, {"api_name": "blockchain.coop_status", "line_number": 308, "usage_type": "attribute"}, {"api_name": "blockchain.coop_status", "line_number": 314, "usage_type": "attribute"}, {"api_name": "flask.jsonify", "line_number": 315, "usage_type": "call"}, {"api_name": "blockchain.coop_proof", "line_number": 315, "usage_type": "attribute"}, {"api_name": "flask.jsonify", "line_number": 317, "usage_type": "call"}, {"api_name": "blockchain.ip.split", "line_number": 320, "usage_type": "call"}, {"api_name": "blockchain.ip", "line_number": 320, "usage_type": "attribute"}, {"api_name": "blockchain.ip.split", "line_number": 321, "usage_type": "call"}, {"api_name": "blockchain.ip", "line_number": 321, "usage_type": "attribute"}]}
+{"seq_id": "16113008847", "text": "import numpy as np\nimport os\nimport glob\nimport FVD\nimport ESACCI as ec\nimport GIMMS as gm\nfrom netCDF4 import Dataset\nimport matplotlib\nmatplotlib.use(\"TkAgg\")\nfrom matplotlib import pyplot as plt\nfrom skimage.measure import block_reduce\nfrom scipy.stats import skew\nfrom scipy.stats.kde import gaussian_kde\nfrom scipy.optimize import curve_fit\n\ndef plot_scene(data, ylab, mask=None, title=None, vmin=None, vmax=None, ):\n    # map data\n    fig, ax = plt.subplots()\n    fig.set_size_inches(14,6)\n    if mask is not None:\n        data[(~np.isfinite(data)) & (mask<0)] = -9999\n        data[mask==0] = float('nan')\n    heatmap = ax.pcolor(data, cmap=plt.cm.Spectral_r, vmin=vmin, vmax=vmax)\n    heatmap.cmap.set_under('lightgray')\n    bar = fig.colorbar(heatmap, extend='both')\n    bar.ax.set_ylabel(ylab, rotation=270)\n    ax.invert_yaxis()\n    plt.axis('off')\n    plt.tight_layout()\n    plt.savefig('../../plots/drivers_' + title + '.png')\n    plt.close(fig)\n    return\n\ndef plot_hist(dataFp, dataFm, title, xlab=None):\n    dataFp[dataFp==-9999] = float('nan')\n    dataFp = dataFp[np.isfinite(dataFp)].reshape(-1,1)\n\n    dataFm[dataFm==-9999] = float('nan')\n    dataFm = dataFm[np.isfinite(dataFm)].reshape(-1,1)\n    print(dataFm)\n\n    mx = np.nanmax([np.nanmax(dataFp), np.nanmax(dataFm)])\n    mn = np.nanmin([np.nanmin(dataFp), np.nanmin(dataFm)])\n\n    #kde_Fp = gaussian_kde(dataFp)\n    #kde_Fm = gaussian_kde(dataFm)\n    x = np.linspace(mn, mx, 100)\n\n    plt.figure(figsize=(6,3))\n    plt.hist([dataFm,dataFp], bins=30, range=[mn-0.25,mx+0.25],\n        color=['orangered','cornflowerblue'], ec='white', rwidth=0.92, label=['F-','F+'])\n    #plt.hist(dataFp, bins=30, range=[mn,mx], color='royalblue', ec='white', rwidth=0.85, alpha=0.5)\n    #plt.plot(x, kde_Fp(x))\n    if xlab is None:\n        plt.xlabel('skewness')\n    else:\n        plt.xlabel('pearson correlation')\n    plt.ylabel('number of pixels')\n    if title=='skew_ndvi':\n        plt.ylim([0,12000])\n    plt.legend(loc='upper right')\n    plt.tight_layout()\n    plt.savefig('../../plots/drivers_dist_' + title + '.png')\n    #plt.show()\n    return\n\ndef make_subplots(xdata, ydata, quads,label=None):\n    fig, axs = plt.subplots(2,2)\n    fig.set_size_inches(6,6)\n\n    xFp = np.copy(xdata)\n    xFp[quads!=2] = float('nan')\n\n    yFp = np.copy(ydata)\n    yFp[quads!=2] = float('nan')\n\n    xFm = np.copy(xdata)\n    xFm[quads!=1] = float('nan')\n\n    yFm = np.copy(ydata)\n    yFm[quads!=1] = float('nan')\n\n    axs[0,0].scatter(xFp[:360,:], yFp[:360,:], c='gray', s=2, marker='.')\n    axs[0,0].set_title('NH F+')\n    axs[0,0].set_ylim([0,3])\n    axs[0,1].scatter(xFp[360:,:], yFp[360:,:], c='gray', s=2, marker='.')\n    axs[0,1].set_title('SH F+')\n    axs[0,1].set_ylim([0,3])\n    axs[1,0].scatter(xFm[:360,:], yFm[:360,:], c='gray', s=2, marker='.')\n    axs[1,0].set_title('NH F-')\n    axs[1,0].set_ylim([-2,0])\n    axs[1,1].scatter(xFm[360:,:], yFm[360:,:], c='gray', s=2, marker='.')\n    axs[1,1].set_title('SH F-')\n    axs[1,1].set_ylim([-2,0])\n    plt.tight_layout()\n    plt.show()\n    return\n\ndef make_subplots_colored_by_lat(xdata, ydata, quads,label):\n    fig, axs = plt.subplots(3, gridspec_kw={\"height_ratios\":[1, 1, 0.05]})\n    fig.set_size_inches(3.5,6.5)\n\n    xFp = np.copy(xdata)\n    xFp[quads!=2] = float('nan')\n\n    yFp = np.copy(ydata)\n    yFp[quads!=2] = float('nan')\n\n    xFm = np.copy(xdata)\n    xFm[quads!=1] = float('nan')\n\n    yFm = np.copy(ydata)\n    yFm[quads!=1] = float('nan')\n\n    lats = np.repeat(np.arange(0,720).reshape(-1,1),1440,axis=1)\n    mx = np.nanmax([np.nanmax(xFp), np.nanmax(xFm)])\n    mn = np.nanmin([np.nanmin(xFp), np.nanmin(xFm)])\n\n    axs[0].scatter(xFp, yFp, c=lats, cmap=plt.cm.rainbow, s=3, marker='.', alpha=0.7)\n    axs[0].set_title('F+', position=(0.9,0.85), fontweight='bold')\n    axs[0].set_ylim([0,3])\n    axs[0].set_xlim([mn*0.9,mx*1.1])\n    axs[0].set_xlabel(label)\n    axs[0].set_ylabel('cumulative\\nndvi change')\n    c = axs[1].scatter(xFm, yFm, c=lats, cmap=plt.cm.rainbow, s=3, marker='.', alpha=0.7)\n    axs[1].set_title('F-', position=(0.9,0.05), fontweight='bold')\n    axs[1].set_ylim([-2,0])\n    axs[1].set_xlim([mn*0.9,mx*1.1])\n    axs[1].set_xlabel(label)\n    axs[1].set_ylabel('cumulative\\nndvi change')\n\n    cbar = fig.colorbar(c, cax=axs[2], orientation='horizontal', pad=0.25, ticks=[100,300,500])\n    cbar.ax.set_xticklabels(['65N','15N','35S'])\n    cbar.set_label('latitude')\n    plt.tight_layout()\n    plt.savefig('../../plots/latitude_plots/lat_' + label + '.png', dpi=300)\n    plt.close(fig)\n    return\n\ndef main():\n    os.chdir(\"matfiles\")\n    mask = FVD.loadmat('land_mask.mat') # mask for land surface\n    npx = np.nansum(mask==0)\n\n    pct = 15\n    val = 0.1\n    nrows = 720\n    ncols = 1440\n    nobs = 12\n\n    corr_sm_ndvi = FVD.loadmat('corr.mat')\n    skew_sm = FVD.loadmat('skew_sm.mat')\n    skew_ndvi = FVD.loadmat('skew_ndvi.mat')\n    skew_temp = FVD.loadmat('skew_temp.mat')\n    skew_rad = FVD.loadmat('skew_rad.mat')\n    skew_prec = FVD.loadmat('skew_prec.mat')\n    skew_PET = FVD.loadmat('skew_PET.mat')\n    skew_vpd = FVD.loadmat('skew_vpd.mat')\n    skew_LAI = FVD.loadmat('skew_LAI.mat')\n\n    temp_mean = FVD.loadmat('temp_mean.mat')\n    rad_mean = FVD.loadmat('rad_mean.mat')\n    prec_mean = FVD.loadmat('prec_mean.mat')\n    PET_mean = FVD.loadmat('PET_mean.mat')\n    vpd_mean = FVD.loadmat('vpd_mean.mat')\n    lai_mean = FVD.loadmat('lai_mean.mat')\n    ndvi_mean = FVD.loadmat('ndvi_mean.mat')\n\n    temp_std = FVD.loadmat('temp_std.mat')\n    rad_std = FVD.loadmat('rad_std.mat')\n    prec_std = FVD.loadmat('prec_std.mat')\n    PET_std = FVD.loadmat('PET_std.mat')\n    vpd_std = FVD.loadmat('vpd_std.mat')\n    lai_std = FVD.loadmat('lai_std.mat')\n    ndvi_std = FVD.loadmat('ndvi_std.mat')\n\n    temp_D = FVD.loadmat('temp_D.mat')\n    rad_D = FVD.loadmat('rad_D.mat')\n    prec_D = FVD.loadmat('prec_D.mat')\n    PET_D = FVD.loadmat('PET_D.mat')\n    vpd_D = FVD.loadmat('vpd_D.mat')\n    lai_D = FVD.loadmat('lai_D.mat')\n    ndvi_D = FVD.loadmat('ndvi_D.mat')\n\n    sm_num_controlled = FVD.loadmat('sm_numerator_monthly_controlled_fixed.mat')\n    sm_den_controlled = FVD.loadmat('sm_denominator_monthly_controlled_fixed.mat')\n\n    sm_den_controlled_copy = np.copy(sm_den_controlled)\n    sm_num_controlled_copy = np.copy(sm_num_controlled)\n\n    sm_den_controlled_copy[(abs(sm_den_controlled) List[str]:\n    files = glob.glob(os.path.join(path, 'time.*'))\n    return files\n\n\ndef get_massive_files(path) -> List[str]:\n    files = glob.glob(os.path.join(path, 'valgrind.*'))\n    return files\n\n\ndef main():\n    path = os.getenv('REPORTS', 'reports')\n    files = get_files(path)\n    parseds = [TimeParser(file) for file in files]\n    with open(os.path.join(path, 'times.csv'), 'w', newline='') as csvfile:\n        writer = csv.DictWriter(csvfile, fieldnames=TimeParser.__all__)\n        writer.writeheader()\n        writer.writerows([parsed.__dict__ for parsed in parseds])\n\n    parseds = [MassiveParser(file) for file in get_massive_files(path)]\n    with open(os.path.join(path, 'massive.csv'), 'w', newline='') as csvfile:\n        writer = csv.DictWriter(csvfile, fieldnames=MassiveParser.__all__)\n        writer.writeheader()\n        writer.writerows([parsed.__dict__ for parsed in parseds])\n\n\nif __name__ == '__main__':\n    main()\n", "repo_name": "guionardo/code-battle", "sub_path": "src/parser/main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 1097, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "glob.glob", "line_number": 12, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 12, "usage_type": "call"}, {"api_name": "os.path", "line_number": 12, "usage_type": "attribute"}, {"api_name": "typing.List", "line_number": 11, "usage_type": "name"}, {"api_name": "glob.glob", "line_number": 17, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 17, "usage_type": "call"}, {"api_name": "os.path", "line_number": 17, "usage_type": "attribute"}, {"api_name": "typing.List", "line_number": 16, "usage_type": "name"}, {"api_name": "os.getenv", "line_number": 22, "usage_type": "call"}, {"api_name": "time_parser.TimeParser", "line_number": 24, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 25, "usage_type": "call"}, {"api_name": "os.path", "line_number": 25, "usage_type": "attribute"}, {"api_name": "csv.DictWriter", "line_number": 26, "usage_type": "call"}, {"api_name": "time_parser.TimeParser.__all__", "line_number": 26, "usage_type": "attribute"}, {"api_name": "time_parser.TimeParser", "line_number": 26, "usage_type": "name"}, {"api_name": "massive_parser.MassiveParser", "line_number": 30, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 31, "usage_type": "call"}, {"api_name": "os.path", "line_number": 31, "usage_type": "attribute"}, {"api_name": "csv.DictWriter", "line_number": 32, "usage_type": "call"}, {"api_name": "massive_parser.MassiveParser.__all__", "line_number": 32, "usage_type": "attribute"}, {"api_name": "massive_parser.MassiveParser", "line_number": 32, "usage_type": "name"}]}
+{"seq_id": "18767939493", "text": "import streamlit as st\nimport preprocessing,helper\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport plotly.express as px \nimport time\n\n\nst.sidebar.image('https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTc1ImonWhZlgau0PiWRBhWd0eLHSv_I7LZ1A&usqp=CAU' , width=300 )\nst.sidebar.title(\"WELCOME To Whatsapp chat Analyzer :smile:\")\n\nst.sidebar.header(' Please uploade *.txtfile of your chat without media *' )\nst.sidebar.text(\"* This code only support 12hours format of chat\")\n\nuploaded_file = st.sidebar.file_uploader(\"Choose a file\")\n\n# if st.sidebar.button(\"Show DataFrame of chat\"):\n\nif uploaded_file is not None:\n        # To read file as bytes:\n    byte = uploaded_file.getvalue()\n    data = byte.decode('utf-8')\n\n    df = preprocessing.preprocess(data)\n\n          #fetch users\n    user_list = df['User'].unique().tolist()\n    user_list.remove('group notification')\n    user_list.insert(0, \"Overall analysis\")\n\n    selected_user = st.sidebar.selectbox('Show analysis wrt', user_list)\n\n    if st.sidebar.button(\"Click me \"):\n        st.write(\"Pleasewait.....\")\n        progress = st.progress(0)\n        for i in range(100):\n            time.sleep(0.02)\n            progress.progress(i+1)\n\n        st.markdown('''# Analysis wrt '''+ selected_user +'*')\n\n        num,num_words, num_media, num_links,num_of_deleted = helper.fetch(selected_user, df)\n\n        col1, col2, col3, col4 ,col5 = st.columns(5)\n\n        with col1:\n            st.subheader(\"Total messages\")\n            st.subheader(num)\n\n        with col2:\n            st.subheader(\"Total words \")\n            st.subheader(num_words)\n\n        with col3:\n            st.subheader(\"Media shared\")\n            st.subheader(num_media)\n\n        with col4:\n            st.subheader(\"Links shared\")\n            st.subheader(num_links)\n\n        with col5:\n            st.subheader(\"Deleted messages\")\n            st.markdown(num_of_deleted)\n\n\n        #timeline\n\n        timeline = helper.montly_user(selected_user,df)\n        st.title(\"Monthly Traffic\")\n        st.write(\"This line chart graph show the frequency of messages from the starting of group till now \")\n\n        fig = px.line(x= 'Time' , y ='User_messages', data_frame = timeline)\n        fig.update_layout(paper_bgcolor = \"black\")\n        # fig, ax = plt.subplots(figsize=(25,7))\n        # sns.lineplot(x= timeline[\"Time\"] ,y = timeline[\"User_messages\"])\n        # ax.grid(True)\n        # plt.xticks(rotation = \"vertical\")\n        st.plotly_chart(fig)\n\n        # most busy days\n\n        wdf = helper.weekly_activity(selected_user,df)\n        st.title(\"Busy days in week\")\n        st.text(\"This graph show the days in week where chating frequency is high\")\n        fig, ax = plt.subplots()\n        sns.countplot(x=\"Day name\", data = wdf, palette='prism')\n        plt.legend(bbox_to_anchor=(1.02, 1), loc='upper left', borderaxespad=0)\n        ax.grid(True)\n        st.pyplot(fig)\n        \n    \n        #finding bussiestuser\n        if selected_user == 'Overall analysis': # its only applicable on gouplevel\n            # st.title(\"Top 10 busy users\")\n\n            x = helper.fetch_mostbusy(df)\n\n            col1, col2 = st.columns(2)\n            #seabornplot\n\n            with col1:\n                st.title(\"Top 10 busy users\")\n                st.text(\"Most Chatty peoples\")\n                fig, ax = plt.subplots()\n                sns.barplot(x=x.values,y = x.index)\n                ax.grid(True)\n                st.pyplot(fig)\n\n            with col2:\n                st.header(\"Percentage%  of top 10 users\")\n                fig, ax = plt.subplots()\n                plt.pie(x.values, labels = x.index, autopct='%1.2f%%',shadow=True)\n                st.pyplot(fig)\n\n            # wprd cloud\n        st.title(\"WORD CLOUD :cloud:\")\n        st.text(\"Word Clouds display the most prominent or frequent words used in a chat\")\n        st.subheader(\"Words used in group [\"+ selected_user+']')\n        df_wc = helper.create_wordcloud(selected_user,df)\n        fig, ax = plt.subplots()\n        plt.axis(\"off\")\n        ax.imshow(df_wc)\n        st.pyplot(fig)\n\n\n        # most common words\n        st.header(\"Most common words\")\n        st.title(\"Bar chart of Popular words\")\n        most_common_df = helper.most_common(selected_user,df)\n        fig, ax = plt.subplots()\n        sns.barplot(x = most_common_df[1], y = most_common_df[0] ,palette='prism_r')\n        # ax.barh(most_common_df[0],most_common_df[1])\n        ax.grid(True)\n        st.pyplot(fig)\n\n        emoj_df = helper.emojifind(selected_user,df)\n        st.title(\"Top 10 Emojis [\"+ selected_user+']')\n        st.text(\"Pie chart of Commonly used emojies\")\n        fig = px.pie(emoj_df , values = \"index\" , names = 0 )\n        fig.update_layout(paper_bgcolor = \"black\")\n\n        st.write(fig)\n\n\n\n        mdf = helper.weekly_activity(selected_user,df)\n        st.title(\"Busy month[\" + selected_user +']')\n        st.text(\"This graph show the month where chating frequency is high\")\n        fig, ax = plt.subplots()\n        sns.countplot(x=\"Month\", data = wdf, palette='prism')\n        plt.legend(bbox_to_anchor=(1.02, 1), loc='upper left', borderaxespad=0)\n        plt.xticks(rotation= 'vertical')\n        ax.grid(True)\n        st.pyplot(fig)\n\n        st.title(\"Hourly activity Heatmap\")\n        st.text(\"This is a heatmap shows busy hours, lighter shades means the high messages frequency \")\n        hour_activ = helper.heat_activity(selected_user,df)\n        fig, ax = plt.subplots(figsize=(20,8))\n        \n        sns.heatmap(hour_activ)\n        st.pyplot(fig)\n\n    st.sidebar.header(\"Created by Shivam sharma\")\n    st.sidebar.subheader('Contact:'+\"shivamsharma38391@gmail.com\")\n    st.sidebar.subheader(\"LINKEDIN profile:\")\n    st.sidebar.write(\"https://www.linkedin.com/in/shivam-sharma-6499061a9/\")\n    st.sidebar.subheader(\"Github Profile\")\n    st.sidebar.write(\"https://github.com/Shivam38391\")\n    st.sidebar.text(\"Special thanks to Nitish sir\")", "repo_name": "Shivam38391/whatsappchatanalyzerbyshiv", "sub_path": "app.py", "file_name": "app.py", "file_ext": "py", "file_size_in_byte": 5931, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "21", "api": [{"api_name": "streamlit.sidebar.image", "line_number": 9, "usage_type": "call"}, {"api_name": "streamlit.sidebar", "line_number": 9, "usage_type": "attribute"}, {"api_name": "streamlit.sidebar.title", "line_number": 10, "usage_type": "call"}, {"api_name": "streamlit.sidebar", "line_number": 10, "usage_type": "attribute"}, {"api_name": "streamlit.sidebar.header", "line_number": 12, "usage_type": "call"}, {"api_name": "streamlit.sidebar", "line_number": 12, "usage_type": "attribute"}, {"api_name": "streamlit.sidebar.text", "line_number": 13, "usage_type": "call"}, {"api_name": "streamlit.sidebar", "line_number": 13, "usage_type": "attribute"}, {"api_name": "streamlit.sidebar.file_uploader", "line_number": 15, "usage_type": "call"}, {"api_name": "streamlit.sidebar", "line_number": 15, "usage_type": "attribute"}, {"api_name": "preprocessing.preprocess", "line_number": 24, "usage_type": "call"}, {"api_name": "streamlit.sidebar.selectbox", "line_number": 31, "usage_type": "call"}, {"api_name": "streamlit.sidebar", "line_number": 31, "usage_type": "attribute"}, {"api_name": "streamlit.sidebar.button", "line_number": 33, "usage_type": "call"}, {"api_name": "streamlit.sidebar", "line_number": 33, "usage_type": "attribute"}, {"api_name": "streamlit.write", "line_number": 34, "usage_type": "call"}, {"api_name": "streamlit.progress", "line_number": 35, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 37, "usage_type": "call"}, {"api_name": "streamlit.markdown", "line_number": 40, "usage_type": "call"}, {"api_name": "helper.fetch", "line_number": 42, "usage_type": "call"}, {"api_name": "streamlit.columns", "line_number": 44, "usage_type": "call"}, {"api_name": "streamlit.subheader", "line_number": 47, "usage_type": "call"}, {"api_name": "streamlit.subheader", "line_number": 48, "usage_type": "call"}, {"api_name": "streamlit.subheader", "line_number": 51, "usage_type": "call"}, {"api_name": "streamlit.subheader", "line_number": 52, "usage_type": "call"}, {"api_name": "streamlit.subheader", "line_number": 55, "usage_type": "call"}, {"api_name": "streamlit.subheader", "line_number": 56, "usage_type": "call"}, {"api_name": "streamlit.subheader", "line_number": 59, "usage_type": "call"}, {"api_name": "streamlit.subheader", "line_number": 60, "usage_type": "call"}, {"api_name": "streamlit.subheader", "line_number": 63, "usage_type": "call"}, {"api_name": "streamlit.markdown", "line_number": 64, "usage_type": "call"}, {"api_name": "helper.montly_user", "line_number": 69, "usage_type": "call"}, {"api_name": "streamlit.title", "line_number": 70, "usage_type": "call"}, {"api_name": "streamlit.write", "line_number": 71, "usage_type": "call"}, {"api_name": "plotly.express.line", "line_number": 73, "usage_type": "call"}, {"api_name": "plotly.express", "line_number": 73, "usage_type": "name"}, {"api_name": "streamlit.plotly_chart", "line_number": 79, "usage_type": "call"}, {"api_name": "helper.weekly_activity", "line_number": 83, "usage_type": "call"}, {"api_name": "streamlit.title", "line_number": 84, "usage_type": "call"}, {"api_name": "streamlit.text", "line_number": 85, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 86, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 86, "usage_type": "name"}, {"api_name": "seaborn.countplot", "line_number": 87, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 88, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 88, "usage_type": "name"}, {"api_name": "streamlit.pyplot", "line_number": 90, "usage_type": "call"}, {"api_name": "helper.fetch_mostbusy", "line_number": 97, "usage_type": "call"}, {"api_name": "streamlit.columns", "line_number": 99, "usage_type": "call"}, {"api_name": "streamlit.title", "line_number": 103, "usage_type": "call"}, {"api_name": "streamlit.text", "line_number": 104, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 105, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 105, "usage_type": "name"}, {"api_name": "seaborn.barplot", "line_number": 106, "usage_type": "call"}, {"api_name": "streamlit.pyplot", "line_number": 108, "usage_type": "call"}, {"api_name": "streamlit.header", "line_number": 111, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 112, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 112, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.pie", "line_number": 113, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 113, "usage_type": "name"}, {"api_name": "streamlit.pyplot", "line_number": 114, "usage_type": "call"}, {"api_name": "streamlit.title", "line_number": 117, "usage_type": "call"}, {"api_name": "streamlit.text", "line_number": 118, "usage_type": "call"}, {"api_name": "streamlit.subheader", "line_number": 119, "usage_type": "call"}, {"api_name": "helper.create_wordcloud", "line_number": 120, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 121, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 121, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.axis", "line_number": 122, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 122, "usage_type": "name"}, {"api_name": "streamlit.pyplot", "line_number": 124, "usage_type": "call"}, {"api_name": "streamlit.header", "line_number": 128, "usage_type": "call"}, {"api_name": "streamlit.title", "line_number": 129, "usage_type": "call"}, {"api_name": "helper.most_common", "line_number": 130, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 131, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 131, "usage_type": "name"}, {"api_name": "seaborn.barplot", "line_number": 132, "usage_type": "call"}, {"api_name": "streamlit.pyplot", "line_number": 135, "usage_type": "call"}, {"api_name": "helper.emojifind", "line_number": 137, "usage_type": "call"}, {"api_name": "streamlit.title", "line_number": 138, "usage_type": "call"}, {"api_name": "streamlit.text", "line_number": 139, "usage_type": "call"}, {"api_name": "plotly.express.pie", "line_number": 140, "usage_type": "call"}, {"api_name": "plotly.express", "line_number": 140, "usage_type": "name"}, {"api_name": "streamlit.write", "line_number": 143, "usage_type": "call"}, {"api_name": "helper.weekly_activity", "line_number": 147, "usage_type": "call"}, {"api_name": "streamlit.title", "line_number": 148, "usage_type": "call"}, {"api_name": "streamlit.text", "line_number": 149, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 150, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 150, "usage_type": "name"}, {"api_name": "seaborn.countplot", "line_number": 151, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 152, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 152, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xticks", "line_number": 153, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 153, "usage_type": "name"}, {"api_name": "streamlit.pyplot", "line_number": 155, "usage_type": "call"}, {"api_name": "streamlit.title", "line_number": 157, "usage_type": "call"}, {"api_name": "streamlit.text", "line_number": 158, "usage_type": "call"}, {"api_name": "helper.heat_activity", "line_number": 159, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 160, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 160, "usage_type": "name"}, {"api_name": "seaborn.heatmap", "line_number": 162, "usage_type": "call"}, {"api_name": "streamlit.pyplot", "line_number": 163, "usage_type": "call"}, {"api_name": "streamlit.sidebar.header", "line_number": 165, "usage_type": "call"}, {"api_name": "streamlit.sidebar", "line_number": 165, "usage_type": "attribute"}, {"api_name": "streamlit.sidebar.subheader", "line_number": 166, "usage_type": "call"}, {"api_name": "streamlit.sidebar", "line_number": 166, "usage_type": "attribute"}, {"api_name": "streamlit.sidebar.subheader", "line_number": 167, "usage_type": "call"}, {"api_name": "streamlit.sidebar", "line_number": 167, "usage_type": "attribute"}, {"api_name": "streamlit.sidebar.write", "line_number": 168, "usage_type": "call"}, {"api_name": "streamlit.sidebar", "line_number": 168, "usage_type": "attribute"}, {"api_name": "streamlit.sidebar.subheader", "line_number": 169, "usage_type": "call"}, {"api_name": "streamlit.sidebar", "line_number": 169, "usage_type": "attribute"}, {"api_name": "streamlit.sidebar.write", "line_number": 170, "usage_type": "call"}, {"api_name": "streamlit.sidebar", "line_number": 170, "usage_type": "attribute"}, {"api_name": "streamlit.sidebar.text", "line_number": 171, "usage_type": "call"}, {"api_name": "streamlit.sidebar", "line_number": 171, "usage_type": "attribute"}]}
+{"seq_id": "10561847015", "text": "# Import required libraries\nimport pandas as pd\nimport dash\nimport dash_html_components as html\nimport dash_core_components as dcc\nfrom dash.dependencies import Input, Output, State\nimport plotly.graph_objects as go\nimport plotly.express as px\nfrom dash import no_update\n\n# Create a dash application\napp = dash.Dash(__name__)\n\n# REVIEW1: Clear the layout and do not display exception till callback gets executed\napp.config.suppress_callback_exceptions = True\n\n# Read the airline data into pandas dataframe\nspacex_df =  pd.read_csv(\"https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBM-DS0321EN-SkillsNetwork/datasets/spacex_launch_dash.csv\")\n\napp.layout = html.Div(children=[html.H1('SpaceX Launch Records Dashboard',style={'textAlign': 'center', 'color': '#503D36', 'font-size': 40}),\n                      html.Div(\n                                         dcc.Dropdown(id='site-dropdown',\n                                         options=[\n                                         {'label': 'All Sites', 'value': 'ALL'},\n                                         {'label': 'CCAFS LC-40', 'value': 'CCAFS LC-40'},\n                                         {'label': 'CCAFS SLC-40', 'value': 'CCAFS SLC-40'},\n                                         {'label': 'KSC LC-39A', 'value': 'KSC LC-39A'},\n                                         {'label': 'VAFB SLC-4E', 'value': 'VAFB SLC-4E'}\n                                         ],\n                                         value='ALL',\n                                         placeholder=\"Select a Launch Site here\",\n                                         searchable=True\n                                         )),\n\n                                         html.Div(dcc.Graph(id='success-pie-chart')),\n\n\n                     html.Div([      html.Div(html.H2('Payload range (kg):', style={'margin-right': '2em'})), \n                         \n                                         \n                                     dcc.RangeSlider(id='payload-slider',\n                                                    min=0, max=10000, step=1000,\n                                                    marks={0: '0',2500: '2500',5000: '5000',10000: '10000'},\n                                                    value=[spacex_df[\"Payload Mass (kg)\"].min(), spacex_df[\"Payload Mass (kg)\"].max()])\n                              ]),\n                                     \n                                     html.Div(dcc.Graph(id='success-payload-scatter-chart'))\n                       ])\n\n# Function decorator to specify function input and output\n@app.callback([Output(component_id='success-pie-chart', component_property='figure'),\n              Output(component_id='success-payload-scatter-chart', component_property='figure')],\n              [Input(component_id='site-dropdown', component_property='value'),\n               Input(component_id=\"payload-slider\", component_property=\"value\")] )              \n\ndef get_pie_chart(entered_site,slider_range):\n    filtered_df = spacex_df\n    low, high = slider_range\n    mask = (filtered_df[\"Payload Mass (kg)\"] > low) & (filtered_df[\"Payload Mass (kg)\"] < high)\n    if entered_site == 'ALL':\n        fig1 = px.pie(filtered_df, values='class',names='Launch Site', title='Total Success Launches by site')\n        fig2 = px.scatter(filtered_df[mask], x='Payload Mass (kg)', y=\"class\", title='Correlation between Payload and Success for all Sites',color=\"Booster Version Category\")\n        return [fig1,fig2]\n    else:\n        # return the outcomes piechart for a selected site\n        filtered_df = spacex_df[spacex_df[\"Launch Site\"]==entered_site]\n        fig1 = px.pie(filtered_df, names='class', title=\"Total Success Launches for site\" + \" \" + str(entered_site))\n        fig2 = px.scatter(filtered_df[mask], x='Payload Mass (kg)', y=\"class\", title='Correlation between Payload and Success for Site'+ \" \" + str(entered_site),color=\"Booster Version Category\")\n        return [fig1,fig2]\n\n\n# Run the application                   \nif __name__ == '__main__':\n    app.run_server()", "repo_name": "WaelChmaisani/Applied-Data-Science-Project", "sub_path": "Spacex_Falcon9_Dash.py", "file_name": "Spacex_Falcon9_Dash.py", "file_ext": "py", "file_size_in_byte": 4079, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "dash.Dash", "line_number": 12, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 18, "usage_type": "call"}, {"api_name": "dash_html_components.Div", "line_number": 20, "usage_type": "call"}, {"api_name": "dash_html_components.H1", "line_number": 20, "usage_type": "call"}, {"api_name": "dash_html_components.Div", "line_number": 21, "usage_type": "call"}, {"api_name": "dash_core_components.Dropdown", "line_number": 22, "usage_type": "call"}, {"api_name": "dash_html_components.Div", "line_number": 35, "usage_type": "call"}, {"api_name": "dash_core_components.Graph", "line_number": 35, "usage_type": "call"}, {"api_name": "dash_html_components.Div", "line_number": 38, "usage_type": "call"}, {"api_name": "dash_html_components.H2", "line_number": 38, "usage_type": "call"}, {"api_name": "dash_core_components.RangeSlider", "line_number": 41, "usage_type": "call"}, {"api_name": "dash_html_components.Div", "line_number": 47, "usage_type": "call"}, {"api_name": "dash_core_components.Graph", "line_number": 47, "usage_type": "call"}, {"api_name": "plotly.express.pie", "line_number": 61, "usage_type": "call"}, {"api_name": "plotly.express", "line_number": 61, "usage_type": "name"}, {"api_name": "plotly.express.scatter", "line_number": 62, "usage_type": "call"}, {"api_name": "plotly.express", "line_number": 62, "usage_type": "name"}, {"api_name": "plotly.express.pie", "line_number": 67, "usage_type": "call"}, {"api_name": "plotly.express", "line_number": 67, "usage_type": "name"}, {"api_name": "plotly.express.scatter", "line_number": 68, "usage_type": "call"}, {"api_name": "plotly.express", "line_number": 68, "usage_type": "name"}, {"api_name": "dash.dependencies.Output", "line_number": 51, "usage_type": "call"}, {"api_name": "dash.dependencies.Output", "line_number": 52, "usage_type": "call"}, {"api_name": "dash.dependencies.Input", "line_number": 53, "usage_type": "call"}, {"api_name": "dash.dependencies.Input", "line_number": 54, "usage_type": "call"}]}
+{"seq_id": "12536691511", "text": "import re\nfrom typing import List\nfrom datetime import datetime\nfrom requests import get\nfrom bs4 import BeautifulSoup\nfrom json import loads\nfrom .utils import retry\nfrom .core import PackageEvent, TrackerInterface\nfrom .errors import UnsupportedTrackingNumber\n\n\nclass CainiaoTracker(TrackerInterface):\n\n    __regex__ = re.compile('([A-Z]{2}[0-9]{9}[A-Z]{2}|[A-Z][0-9]{14})')\n\n    @staticmethod\n    @retry\n    def __service_call__(tracking_number: str) -> str:\n        url = 'https://global.cainiao.com/detail.htm'\n        params = {'mailNoList': tracking_number}\n        with get(url, params) as response:\n            return response.text\n\n    def supports(self, tracking_number: str) -> bool:\n        return self.__regex__.fullmatch(tracking_number)\n\n    def track(self, tracking_number: str) -> List[PackageEvent]:\n        if not self.supports(tracking_number):\n            raise UnsupportedTrackingNumber(self, tracking_number)\n\n        response = self.__service_call__(tracking_number)\n\n        soup = BeautifulSoup(response, 'html.parser')\n        element = soup.find(id='waybill_list_val_box')\n        if not element:\n            return []\n\n        json = loads(element.text)\n\n        return [\n            PackageEvent\n            (\n                event_datetime=datetime.fromisoformat(detail.get('time')),\n                event_description=detail.get('desc'),\n                is_delivery_event=(detail.get('status') == 'SIGNIN')\n            )\n            for data in json.get('data', [])\n            for section in [data.get('section1', {}), data.get('section2', {})]\n            for detail in section.get('detailList', [])\n        ]\n", "repo_name": "eltonlika/package_tracking", "sub_path": "package/trackers/cainiao.py", "file_name": "cainiao.py", "file_ext": "py", "file_size_in_byte": 1644, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "core.TrackerInterface", "line_number": 12, "usage_type": "name"}, {"api_name": "re.compile", "line_number": 14, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 21, "usage_type": "call"}, {"api_name": "utils.retry", "line_number": 17, "usage_type": "name"}, {"api_name": "errors.UnsupportedTrackingNumber", "line_number": 29, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 33, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 38, "usage_type": "call"}, {"api_name": "core.PackageEvent", "line_number": 41, "usage_type": "call"}, {"api_name": "datetime.datetime.fromisoformat", "line_number": 43, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 43, "usage_type": "name"}, {"api_name": "json.get", "line_number": 47, "usage_type": "call"}, {"api_name": "typing.List", "line_number": 27, "usage_type": "name"}, {"api_name": "core.PackageEvent", "line_number": 27, "usage_type": "name"}]}
+{"seq_id": "24230786029", "text": "from django.conf.urls.defaults import *\nfrom django.views.generic.simple import direct_to_template\nfrom django.utils.translation import ugettext_lazy as _\n\nimport views\nimport utils\n\nurlpatterns = patterns('',\n\n    url(r'^$', views.index, name=\"home\"),\n    \n    url(_(r'^sale/$'), views.sale, name=\"sale\"),\n    url(r'^basket/$', views.basket, name=\"basket\"),\n    url(r'^basket/add/(\\w+)$', views.add_to_basket, name=\"add_to_basket\"),\n    url(r'^basket/add/multiple/$', views.add_to_basket_multiple, name=\"add_to_basket_multiple\"),\n    url(r'^basket/remove_discount/$', views.remove_discount, name=\"remove_discount\"),\n    url(r'^basket/reduce/(\\w+)$', views.reduce_quantity, name=\"reduce_quantity\"),\n    url(r'^basket/reduce/monthly/(\\w+)$', views.reduce_quantity_monthly, name=\"reduce_quantity_monthly\"),\n    url(r'^basket/increase/(\\w+)$', views.increase_quantity, name=\"increase_quantity\"),\n    url(r'^basket/remove/(\\w+)$', views.remove_from_basket, name=\"remove_from_basket\"),\n    \n    \n    # monthly order specific\n    url(r'^basket/add/(?P\\w+)/monthly/(?P\\w+)/$', views.add_to_basket_monthly, name=\"add_to_basket_monthly\"),\n    url(r'^change_monthly_frequency/(?P\\w+)/$', utils._change_monthly_frequency, name=\"change_monthly_frequency\"),\n    url(r'^monthly-order-save/$', views.monthly_order_save, name=\"monthly_order_save\"),\n\n\n    url(r'^contact-form-submit/$', views.contact_form_submit, name=\"contact_form_submit\"),\n    url(r'^order/step-one/$', views.order_step_one, name=\"order_step_one\"),\n    url(r'^order/confirm/$', views.order_confirm, name=\"order_confirm\"),\n    url(r'^order/complete/fake/$', views.order_complete_fake, name=\"order_complete_fake\"),\n    url(r'^order/complete/(?P[\\w-]+)/$', views.order_complete, name=\"order_complete\"),\n    url(r'^order/complete/$', views.order_complete, name=\"order_complete\"),\n    url(r'^fake/checkout/(\\w+)/$', views.fake_checkout, name=\"fake_checkout\"),\n    url(r'^order/repeat/(?P[\\w-]+)/$', views.order_repeat, name=\"order_repeat\"),\n    url(r'^order/review/(?P[\\w-]+)/$', views.review_order, name=\"review_order\"),\n    url(r'^order/(?P[\\w-]+)/friend/$', views.order_url_friend, name=\"order_url_friend\"),\n    url(r'^order/(?P[\\w-]+)/$', views.order_url, name=\"order_url\"),\n    url(r'^reviews/$', views.reviews, name=\"reviews\"),\n    url(r'^not-me/$', views.not_you, name=\"not_you\"),\n        \n    url(r'^delete_notify_out_of_stock/(\\w+)/$', views.delete_notify_out_of_stock, name=\"delete_notify_out_of_stock\"),\n    url(r'^notify-product-out-of-stock/$', views.notify_out_of_stock, name=\"notify_out_of_stock\"),\n    \n    url(r'^currency/$', utils._set_currency, name=\"set_currency\"),\n    \n    # get objects by ID urls\n    url(r'^page/(?P[\\w-]+)/$', views.page_by_id, name=\"page_by_id\"),\n    url(r'^product/(?P[\\w-]+)/$', views.product_by_id, name=\"product_by_id\"),\n    url(r'^category/(?P[\\w-]+)/$', views.category_by_id, name=\"category_by_id\"),\n\n    \n    \n)\n\n", "repo_name": "minrivertea/minrivertea", "sub_path": "shop/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 2979, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "21", "api": [{"api_name": "views.index", "line_number": 10, "usage_type": "attribute"}, {"api_name": "django.utils.translation.ugettext_lazy", "line_number": 12, "usage_type": "call"}, {"api_name": "views.sale", "line_number": 12, "usage_type": "attribute"}, {"api_name": "views.basket", "line_number": 13, "usage_type": "attribute"}, {"api_name": "views.add_to_basket", "line_number": 14, "usage_type": "attribute"}, {"api_name": "views.add_to_basket_multiple", "line_number": 15, "usage_type": "attribute"}, {"api_name": "views.remove_discount", "line_number": 16, "usage_type": "attribute"}, {"api_name": "views.reduce_quantity", "line_number": 17, "usage_type": "attribute"}, {"api_name": "views.reduce_quantity_monthly", "line_number": 18, "usage_type": "attribute"}, {"api_name": "views.increase_quantity", "line_number": 19, "usage_type": "attribute"}, {"api_name": "views.remove_from_basket", "line_number": 20, "usage_type": "attribute"}, {"api_name": "views.add_to_basket_monthly", "line_number": 24, "usage_type": "attribute"}, {"api_name": "utils._change_monthly_frequency", "line_number": 25, "usage_type": "attribute"}, {"api_name": "views.monthly_order_save", "line_number": 26, "usage_type": "attribute"}, {"api_name": "views.contact_form_submit", "line_number": 29, "usage_type": "attribute"}, {"api_name": "views.order_step_one", "line_number": 30, "usage_type": "attribute"}, {"api_name": "views.order_confirm", "line_number": 31, "usage_type": "attribute"}, {"api_name": "views.order_complete_fake", "line_number": 32, "usage_type": "attribute"}, {"api_name": "views.order_complete", "line_number": 33, "usage_type": "attribute"}, {"api_name": "views.order_complete", "line_number": 34, "usage_type": "attribute"}, {"api_name": "views.fake_checkout", "line_number": 35, "usage_type": "attribute"}, {"api_name": "views.order_repeat", "line_number": 36, "usage_type": "attribute"}, {"api_name": "views.review_order", "line_number": 37, "usage_type": "attribute"}, {"api_name": "views.order_url_friend", "line_number": 38, "usage_type": "attribute"}, {"api_name": "views.order_url", "line_number": 39, "usage_type": "attribute"}, {"api_name": "views.reviews", "line_number": 40, "usage_type": "attribute"}, {"api_name": "views.not_you", "line_number": 41, "usage_type": "attribute"}, {"api_name": "views.delete_notify_out_of_stock", "line_number": 43, "usage_type": "attribute"}, {"api_name": "views.notify_out_of_stock", "line_number": 44, "usage_type": "attribute"}, {"api_name": "utils._set_currency", "line_number": 46, "usage_type": "attribute"}, {"api_name": "views.page_by_id", "line_number": 49, "usage_type": "attribute"}, {"api_name": "views.product_by_id", "line_number": 50, "usage_type": "attribute"}, {"api_name": "views.category_by_id", "line_number": 51, "usage_type": "attribute"}]}
+{"seq_id": "71790903732", "text": "#coding:utf-8\n\nimport sys\nimport numpy as np\nimport json\n\nspliter = ','\ndata_name = 'iris'\nlabel_0 = 1\nlabel_1 = 2\ndata_path = sys.path[0] + '/../dataset/%s.data'\nX0_lim = 5000\nX1_lim = 5000\nwith open(data_path%data_name) as haber_data_f:\n    lines = haber_data_f.read().split('\\n')\n\nhaber_data = {\n    'X_1':[],\n    'X_0':[]\n}\n\nfor line in lines:\n    if ''==line:\n        break\n    vals = line.split(spliter)\n    vec = [float(vals[0]), float(vals[2]), float(vals[3])]\n    label = int(vals[4])\n    if label==label_0 and len(haber_data['X_0']) < X0_lim:\n        haber_data['X_0'].append(vec)\n    elif label==label_1 and len(haber_data['X_1']) < X1_lim:\n        haber_data['X_1'].append(vec)\n\nout_path = sys.path[0] + '/../dataset/%s.json'\nwith open(out_path%data_name, 'w') as out:\n    json.dump(haber_data, out)\n", "repo_name": "deadoggy/PatternRecognitionAssignments", "sub_path": "Assignment1/sourcecode/dataprocess.py", "file_name": "dataprocess.py", "file_ext": "py", "file_size_in_byte": 812, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "sys.path", "line_number": 11, "usage_type": "attribute"}, {"api_name": "sys.path", "line_number": 33, "usage_type": "attribute"}, {"api_name": "json.dump", "line_number": 35, "usage_type": "call"}]}
+{"seq_id": "22958273453", "text": "# -*- coding: utf-8 -*-\nimport pprint\nimport sys\nimport types\nimport msgpack\nimport BaseThreadedModule\nimport Decorators\n\n\n@Decorators.ModuleDocstringParser\nclass MsgPackParser(BaseThreadedModule.BaseThreadedModule):\n    \"\"\"\n    Decode:\n     It will parse the msgpack data and create or replace fields in the internal data dictionary with\n     the corresponding json fields.\n    Encode:\n     Encode selected fields or all to msgpack format.\n\n    Configuration template:\n\n    - MsgPackParser:\n        action:                                 # \n        mode:                                   # \n        source_fields:                          # \n        target_field:                           # \n        keep_original:                          # \n        receivers:\n          - NextModule\n    \"\"\"\n\n    module_type = \"parser\"\n    \"\"\"Set module type\"\"\"\n\n    def configure(self, configuration):\n        # Call parent configure method\n        BaseThreadedModule.BaseThreadedModule.configure(self, configuration)\n        self.source_fields = self.getConfigurationValue('source_fields')\n        # Allow single string as well.\n        if isinstance(self.source_fields, types.StringTypes):\n            self.source_fields = [self.source_fields]\n        self.target_field = self.getConfigurationValue('target_field')\n        self.drop_original = not self.getConfigurationValue('keep_original')\n        if self.getConfigurationValue('action') == 'decode':\n            if self.getConfigurationValue('mode') == 'line':\n                self.handleEvent = self.decodeEventLine\n            else:\n                self.unpacker = msgpack.Unpacker()\n                self.handleEvent = self.decodeEventStream\n        else:\n            self.handleEvent = self.encodeEvent\n\n    def decodeEventStream(self, event):\n        for source_field in self.source_fields:\n            if source_field not in event:\n                continue\n            self.unpacker.feed(event[source_field])\n            for decoded_data in self.unpacker:\n                if self.drop_original:\n                    event.pop(source_field, None)\n                if self.target_field:\n                    event.update({self.target_field: decoded_data})\n                else:\n                    try:\n                        event.update(decoded_data)\n                    except:\n                        etype, evalue, etb = sys.exc_info()\n                        self.logger.warning(\"Could not update event with msgpack data: %s. Exception: %s, Error: %s.\" % (decoded_data, etype, evalue))\n                yield event\n\n    def decodeEventLine(self, event):\n        for source_field in self.source_fields:\n            if source_field not in event:\n                continue\n            try:\n                decoded_data = msgpack.unpackb(event[source_field])\n            except:\n                etype, evalue, etb = sys.exc_info()\n                self.logger.warning(\"Could not parse msgpack event data: %s. Exception: %s, Error: %s.\" % (event[source_field], etype, evalue))\n                continue\n            if self.drop_original:\n                event.pop(source_field, None)\n            if self.target_field:\n                event.update({self.target_field: decoded_data})\n            else:\n                try:\n                    event.update(decoded_data)\n                except:\n                    etype, evalue, etb = sys.exc_info()\n                    self.logger.warning(\"Could not update event with msgpack data: %s. Exception: %s, Error: %s.\" % (decoded_data, etype, evalue))\n        yield event\n\n    def encodeEvent(self, event):\n        if self.source_fields == ['all']:\n            encode_data = event\n        else:\n            encode_data = []\n            for source_field in self.source_fields:\n                if source_field not in event:\n                    continue\n                encode_data.append({source_field: event[source_field]})\n                if self.drop_original:\n                    event.pop(source_field, None)\n        try:\n            encode_data = msgpack.packb(encode_data)\n        except:\n            etype, evalue, etb = sys.exc_info()\n            self.logger.warning(\"Could not msgpack encode event data: %s. Exception: %s, Error: %s.\" % (event, etype, evalue))\n            yield event\n            return\n        if self.source_fields == ['all']:\n            event = encode_data\n        else:\n            event.update({self.target_field: encode_data})\n        yield event", "repo_name": "lukebeer/GambolPutty", "sub_path": "gambolputty/parser/MsgPackParser.py", "file_name": "MsgPackParser.py", "file_ext": "py", "file_size_in_byte": 4757, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "github-code", "pt": "21", "api": [{"api_name": "BaseThreadedModule.BaseThreadedModule", "line_number": 11, "usage_type": "attribute"}, {"api_name": "BaseThreadedModule.BaseThreadedModule.configure", "line_number": 36, "usage_type": "call"}, {"api_name": "BaseThreadedModule.BaseThreadedModule", "line_number": 36, "usage_type": "attribute"}, {"api_name": "types.StringTypes", "line_number": 39, "usage_type": "attribute"}, {"api_name": "msgpack.Unpacker", "line_number": 47, "usage_type": "call"}, {"api_name": "sys.exc_info", "line_number": 66, "usage_type": "call"}, {"api_name": "msgpack.unpackb", "line_number": 75, "usage_type": "call"}, {"api_name": "sys.exc_info", "line_number": 77, "usage_type": "call"}, {"api_name": "sys.exc_info", "line_number": 88, "usage_type": "call"}, {"api_name": "msgpack.packb", "line_number": 104, "usage_type": "call"}, {"api_name": "sys.exc_info", "line_number": 106, "usage_type": "call"}, {"api_name": "Decorators.ModuleDocstringParser", "line_number": 10, "usage_type": "attribute"}]}
+{"seq_id": "28344110847", "text": "## @package MenuItem\n#  Contains the function for every item/button in the MenuView and FlightView\n\nimport pygame\nfrom Colors import *\n\nclass MenuItem(pygame.font.Font):\n    \"\"\"Class which facilitate the construction of a button or menu\n    \"\"\"\n\n    ## The constructor.\n    #  @param Text The name of the button.\n    #  @param Font(optional) The font which should be used for the button - default None\n    #  @param FontSize(optional) The font size - default 30\n    #  @param PosX(optional) The horizontal position of the item in pixels - default 0\n    #  @param PosY(optional) The vertical position of the item in pixels - default 0\n    def __init__(self, Text, Font=None, FontSize=30, FontColor=WHITE, PosX=0, PosY=0):\n        pygame.font.Font.__init__(self, Font, FontSize)\n        self.Text = Text\n        self.FontSize = FontSize\n        self.FontColor = FontColor\n        self.Label = self.render(self.Text, 1, self.FontColor) # The font object\n        self.Width = self.Label.get_rect().width\n        self.Height = self.Label.get_rect().height\n        self.Dimensions = (self.Width, self.Height)\n        self.PosX = PosX\n        self.PosY = PosY\n        self.Position = PosX, PosY\n\n    ## Verifies if the mouse is over the item.\n    #  @param PosX The x position of the mouse pointer\n    #  @param PosY The y position of the mouse pointer\n    def IsMouseSelection(self, PosX, PosY):\n        if (PosX >= self.PosX and PosX <= self.PosX + self.Width) and \\\n                (PosY >= self.PosY and PosY <= self.PosY + self.Height):\n            return True\n        return False\n\n    ## Sets the position of the item\n    #  @param X The x position\n    #  @param Y The y position\n    def SetPosition(self, X, Y):\n        self.Position = (X, Y)\n        self.PosX = X\n        self.PosY = Y\n\n    ## Sets the font color of the item\n    #  @param RGB The color in RGB format (r,g,b)\n    def SetFontColor(self, RGB):\n        self.FontColor = RGB\n        self.Label = self.render(self.Text, 1, self.FontColor)\n\n    ## Sets the function pointer which should fire when\n    #  @param RGB The color in RGB format (r,g,b)\n    def SetAction(self, Func):\n        self.action = Func", "repo_name": "caee/MIDroneControl", "sub_path": "ArduinoScript/DroneMenu/MenuItem.py", "file_name": "MenuItem.py", "file_ext": "py", "file_size_in_byte": 2167, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "21", "api": [{"api_name": "pygame.font", "line_number": 7, "usage_type": "attribute"}, {"api_name": "pygame.font.Font.__init__", "line_number": 18, "usage_type": "call"}, {"api_name": "pygame.font", "line_number": 18, "usage_type": "attribute"}]}
+{"seq_id": "23292296139", "text": "from transformers import AutoTokenizer, BertTokenizer\n\nfrom fairseq.models import FairseqEncoderDecoderModel\n\n# parser = options.get_interactive_generation_parser()\n# parser.batch_size = 1\n# args = options.parse_args_and_arch(parser)\n#\n# cfg = convert_namespace_to_omegaconf(args)\n\n\n# task = tasks.setup_task(cfg.task)\n# TestModel.build_model(args, self)\n\nde2en = FairseqEncoderDecoderModel.from_pretrained(\n    './model/',\n    checkpoint_file='checkpoint_best.pt',\n    # data_name_or_path='data-bin/wmt17_zh_en_full',\n    # bpe='bert',\n    # pretrained_bpe='./download_prepare/12k-vocab-models/',\n    # pretrained_bpe_src='jhu-clsp/bibert-ende',\n    vocab_file='./download_prepare/data_mixed_ft/de-en-databin/dict.en.txt'\n)\nsrc = '\"Comfortable\", danke.'\n\npretrained_lm = 'jhu-clsp/bibert-ende'\ntry:\n    tokenizer = AutoTokenizer.from_pretrained(pretrained_lm)\nexcept:\n    tokenizer = BertTokenizer.from_pretrained(pretrained_lm)\n\n# src = src.strip()\n# toks = tokenizer.tokenize(src)\n# toks = \" \".join(toks)\n#\n# print('[TOKs]', toks)\n#\n# result = de2en.translate(toks)\n#\n# print(result)\n\n\n# DATAPATH=./download_prepare/data_mixed_ft/\n# STPATH=${DATAPATH}de-en-databin/\n# MODELPATH=./models/dual-ft/\n# PRE_SRC=jhu-clsp/bibert-ende\n# PRE=./download_prepare/12k-vocab-models/\n# CUDA_VISIBLE_DEVICES=0 fairseq-generate \\\n# ${STPATH} --path ${MODELPATH}checkpoint_best.pt --bpe bert --pretrained_bpe ${PRE} --pretrained_bpe_src ${PRE_SRC} \\\n# --beam 4 --lenpen 0.6 --remove-bpe --vocab_file=${STPATH}/dict.en.txt \\\n# --max-len-a 1 --max-len-b 50|tee ${STPATH}/generate-dual-fine.out\n\nimport re\ndef untokenize(text):\n    \"\"\"\n    Untokenizing a text undoes the tokenizing operation, restoring\n    punctuation and spaces to the places that people expect them to be.\n    Ideally, `untokenize(tokenize(text))` should be identical to `text`,\n    except for line breaks.\n    \"\"\"\n    # text = ' '.join(words)\n    step1 = text.replace(\"`` \", '\"').replace(\" ''\", '\"').replace('. . .',  '...')\n    step2 = step1.replace(\" ( \", \" (\").replace(\" ) \", \") \")\n    step3 = re.sub(r' ([.,:;?!%]+)([ \\'\"`])', r\"\\1\\2\", step2)\n    step4 = re.sub(r' ([.,:;?!%]+)$', r\"\\1\", step3)\n    step5 = step4.replace(\" '\", \"'\").replace(\" n't\", \"n't\").replace(\n         \"can not\", \"cannot\")\n    step6 = step5.replace(\" ` \", \" '\")\n    return step6.strip().capitalize()\n\ndef translate(src):\n  psrc = src.strip()\n  toks = tokenizer.tokenize(psrc)\n  toks = \" \".join(toks)\n  # print('[TOKs]', toks)\n  pred = de2en.translate(toks)\n  # result = tokenizer.decode(pred)\n  result = untokenize(pred)\n  return result\n\nif __name__ == '__main__':\n  while True:\n    src = input(\">> \")\n    print(translate(src))", "repo_name": "he1ght/NMT_Serving", "sub_path": "realtime_generate.py", "file_name": "realtime_generate.py", "file_ext": "py", "file_size_in_byte": 2655, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "fairseq.models.FairseqEncoderDecoderModel.from_pretrained", "line_number": 15, "usage_type": "call"}, {"api_name": "fairseq.models.FairseqEncoderDecoderModel", "line_number": 15, "usage_type": "name"}, {"api_name": "transformers.AutoTokenizer.from_pretrained", "line_number": 28, "usage_type": "call"}, {"api_name": "transformers.AutoTokenizer", "line_number": 28, "usage_type": "name"}, {"api_name": "transformers.BertTokenizer.from_pretrained", "line_number": 30, "usage_type": "call"}, {"api_name": "transformers.BertTokenizer", "line_number": 30, "usage_type": "name"}, {"api_name": "re.sub", "line_number": 64, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 65, "usage_type": "call"}]}
+{"seq_id": "32168128762", "text": "from datetime import (\n    datetime,\n)\n\nfrom rest_framework.response import (\n    Response,\n)\nfrom rest_framework.views import (\n    APIView,\n)\n\nfrom currency.models import (\n    CurrencyList,\n)\nfrom currency.parcers import (\n    ParcerValueCurrency,\n)\n\n\nclass CurrencyValueViewSet(APIView):\n\n    def get(self, request):\n        date_first = self.request.query_params.get('date1')\n        date_second = self.request.query_params.get('date2')\n        code = self.request.query_params.get('code')\n\n        try:\n            date_first = datetime.strptime(date_first, '%Y-%m-%d')\n            date_first = datetime.strftime(date_first, '%d/%m/%Y')\n\n            date_second = datetime.strptime(date_second, '%Y-%m-%d')\n            date_second = datetime.strftime(date_second, '%d/%m/%Y')\n\n        except (ValueError, TypeError):\n            return Response({'Error': f'Неверный формат даты'})\n\n\n        return Response(\n            self.calc_diff_numbers(\n                date_first=date_first,\n                date_second=date_second,\n                code=code,\n            )\n        )\n\n    @staticmethod\n    def calc_diff_numbers(date_first, date_second, code):\n        \"\"\"\n        Возвращает курсы валют на указанные даты и разницу курсов.\n        \"\"\"\n\n        currency = CurrencyList.objects.filter(\n            code=code\n        )\n\n        result = {}\n\n        if currency:\n\n            num_first = ParcerValueCurrency(\n                date=date_first,\n            ).find_value_currency(\n                code=code,\n            )\n            num_second = ParcerValueCurrency(\n                date=date_second,\n            ).find_value_currency(\n                code=code,\n            )\n\n            result = {\n                date_first: num_first,\n                date_second: num_second,\n            }\n\n            if num_first and num_second:\n                result['difference'] = num_first - num_second\n            else:\n                result['Error'] = 'Не найдено значение валюты на указанную дату'\n\n        else:\n            result['Error'] = 'Неверный код валюты.'\n\n        return result\n", "repo_name": "formika92/APIcurrency", "sub_path": "currency/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 2218, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "rest_framework.views.APIView", "line_number": 20, "usage_type": "name"}, {"api_name": "datetime.datetime.strptime", "line_number": 28, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 28, "usage_type": "name"}, {"api_name": "datetime.datetime.strftime", "line_number": 29, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 29, "usage_type": "name"}, {"api_name": "datetime.datetime.strptime", "line_number": 31, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 31, "usage_type": "name"}, {"api_name": "datetime.datetime.strftime", "line_number": 32, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 32, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 35, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 38, "usage_type": "call"}, {"api_name": "currency.models", "line_number": 52, "usage_type": "name"}, {"api_name": "currency.models.CurrencyList.objects.filter", "line_number": 52, "usage_type": "call"}, {"api_name": "currency.models.CurrencyList.objects", "line_number": 52, "usage_type": "attribute"}, {"api_name": "currency.models.CurrencyList", "line_number": 52, "usage_type": "name"}, {"api_name": "currency.models", "line_number": 58, "usage_type": "name"}, {"api_name": "currency.parcers.ParcerValueCurrency", "line_number": 60, "usage_type": "call"}, {"api_name": "currency.parcers.ParcerValueCurrency", "line_number": 65, "usage_type": "call"}]}
+{"seq_id": "72690833974", "text": "import torch\nimport torch.nn as nn\nlayer=nn.Conv2d(1,3,kernel_size=3,stride=1,padding=1)\nx=torch.rand(1,1,28,28)\ny=layer(x)\nprint(y.shape)\nlayer1=nn.MaxPool2d(kernel_size=2,stride=2)\ny1=layer1(y)\nprint(y1.shape)\nlayer2=nn.Upsample(scale_factor=2,mode='nearest')#upsample增加尺寸,它是复制数据\ny2=layer2(y1)\nprint(y2.shape)", "repo_name": "hang803/CNN", "sub_path": "pooling.py", "file_name": "pooling.py", "file_ext": "py", "file_size_in_byte": 333, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "torch.nn.Conv2d", "line_number": 3, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 3, "usage_type": "name"}, {"api_name": "torch.rand", "line_number": 4, "usage_type": "call"}, {"api_name": "torch.nn.MaxPool2d", "line_number": 7, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 7, "usage_type": "name"}, {"api_name": "torch.nn.Upsample", "line_number": 10, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 10, "usage_type": "name"}]}
+{"seq_id": "18512698845", "text": "from django.conf.urls import patterns, include, url\n\nfrom django.contrib import admin\nfrom django.views.generic import RedirectView\nfrom annet.settings import MEDIA_ROOT, STATIC_URL\n\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n                       # Examples:\n                       url(r'^admin', include(admin.site.urls)),\n                       url(r'^login', \"AnnetBox.views.login\"),\n                       url(r'^services', \"AnnetBox.views.services\"),\n                       url(r'^logout', \"AnnetBox.views.logout\"),\n                       url(r'^signup', \"AnnetBox.views.signup\"),\n                       url(r'^portfolio', \"AnnetBox.views.portfolio\"),\n                       url(r'^contacts', \"AnnetBox.views.contacts\"),\n                       url(r'^about', \"AnnetBox.views.about\"),\n                       url(r'^stats', \"AnnetBox.views.stats\"),\n                       url(r'^tickets', \"AnnetBox.views.tickets\"),\n                       url(r'^media/(?P.*)$', 'django.views.static.serve', {\n                           'document_root': MEDIA_ROOT,\n                       }),\n                       (r'^favicon\\.ico$', RedirectView.as_view(url='/images/favicon.ico')),\n                       (r\"\", \"AnnetBox.views.main\", ),\n\n)\n", "repo_name": "thuesdays/annet", "sub_path": "annet/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 1244, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "21", "api": [{"api_name": "django.contrib.admin.autodiscover", "line_number": 7, "usage_type": "call"}, {"api_name": "django.contrib.admin", "line_number": 7, "usage_type": "name"}, {"api_name": "django.conf.urls.patterns", "line_number": 9, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 11, "usage_type": "call"}, {"api_name": "django.conf.urls.include", "line_number": 11, "usage_type": "call"}, {"api_name": "django.contrib.admin.site", "line_number": 11, "usage_type": "attribute"}, {"api_name": "django.contrib.admin", "line_number": 11, "usage_type": "name"}, {"api_name": "django.conf.urls.url", "line_number": 12, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 13, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 14, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 15, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 16, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 17, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 18, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 19, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 20, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 21, "usage_type": "call"}, {"api_name": "annet.settings.MEDIA_ROOT", "line_number": 22, "usage_type": "name"}, {"api_name": "django.views.generic.RedirectView.as_view", "line_number": 24, "usage_type": "call"}, {"api_name": "django.views.generic.RedirectView", "line_number": 24, "usage_type": "name"}]}
+{"seq_id": "25433826746", "text": "# -*- coding: utf-8 -*-\nimport logging\nimport os\nfrom multiprocessing.pool import ThreadPool\nfrom subprocess import PIPE, STDOUT, Popen, run\n\nfrom box import Box, BoxError\n\n__all__ = [\"FlixError\", \"ff_version\", \"Flix\", \"guess_bit_depth\"]\n\nhere = os.path.abspath(os.path.dirname(__file__))\n\nlogger = logging.getLogger(\"fastflix\")\n\n\nclass FlixError(Exception):\n    \"\"\"This fastflix won't fly\"\"\"\n\n\ndef ff_version(ff, throw=True):\n    res = Flix.execute(f'\"{ff}\" -version')\n    if res.returncode != 0:\n        if throw:\n            raise FlixError(f'\"{ff}\" file not found')\n        else:\n            return False\n    return res.stdout.decode(\"utf-8\").split(\" \", 4)[2]\n\n\ndef guess_bit_depth(pix_fmt, color_primaries):\n    eight = (\n        \"bgr0\",\n        \"bgra\",\n        \"gbrp\",\n        \"gray\",\n        \"monob\",\n        \"monow\",\n        \"nv12\",\n        \"nv12m\",\n        \"nv16\",\n        \"nv20le\",\n        \"nv21\",\n        \"pal8\",\n        \"rgb24\",\n        \"rgb48le\",\n        \"rgba\",\n        \"rgba64le\",\n        \"ya8\",\n        \"yuv410p\",\n        \"yuv411p\",\n        \"yuv420p\",\n        \"yuv422p\",\n        \"yuv440p\",\n        \"yuv444p\",\n        \"yuva420p\",\n        \"yuva422p\",\n        \"yuva444p\",\n        \"yuvj420p\",\n        \"yuvj422p\",\n        \"yuvj444p\",\n    )\n\n    ten = (\"yuv420p10le\", \"yuv422p10le\", \"yuv444p10le\", \"gbrp10le\", \"gray10le\")\n\n    twelve = (\"yuv420p12le\", \"yuv422p12le\", \"yuv444p12le\", \"gbrp12le\", \"gray12le\")\n\n    if pix_fmt in eight:\n        return 8\n    if pix_fmt in ten:\n        return 10\n    if pix_fmt in twelve:\n        return 12\n\n    if color_primaries == \"bt2020\":\n        return 10\n    else:\n        return 8\n\n\nclass Flix:\n    def __init__(self, ffmpeg=\"ffmpeg\", ffprobe=\"ffprobe\"):\n        self.ffmpeg = ffmpeg\n        self.ffprobe = ffprobe\n        self.tp = ThreadPool(processes=4)\n        self.config, self.filters, self.ffmpeg_version = self.ffmpeg_configuration()\n        self.ffprobe_version = ff_version(ffprobe, True)\n\n    def probe(self, file):\n        command = f'\"{self.ffprobe}\" -v quiet -print_format json -show_format -show_streams \"{file}\"'\n        logger.debug(f\"running probe command: {command}\")\n        result = self.execute(command)\n        try:\n            return Box.from_json(result.stdout.decode(\"utf-8\"))\n        except BoxError:\n            logger.error(f\"Could not decode output: {result.stderr}\")\n            raise FlixError(result.stderr)\n\n    def ffmpeg_configuration(self):\n        res = self.execute(f'\"{self.ffmpeg}\" -version')\n        if res.returncode != 0:\n            raise FlixError(f'\"{self.ffmpeg}\" file not found')\n        output = res.stdout.decode(\"utf-8\")\n        config = []\n        version = output.split(\" \", 4)[2]\n        line_denote = \"configuration: \"\n        for line in output.split(\"\\n\"):\n            if line.startswith(line_denote):\n                config = [x[9:].strip() for x in line[len(line_denote) :].split(\" \") if x.startswith(\"--enable\")]\n\n        filter_output = self.execute(f'\"{self.ffmpeg}\" -hide_banner -filters').stdout.decode(\"utf-8\")\n\n        filters = []\n        for i, line in enumerate(filter_output.split(\"\\n\")):\n            if i < 8 or not line.strip():\n                continue\n            filters.append(line.strip().split(\" \")[1])\n\n        return config, filters, version\n\n    def extract_attachment(self, args):\n        file, stream, work_dir, file_name = args\n        self.execute(f'{self.ffmpeg} -y -i \"{file}\" -map 0:{stream} -c copy \"{file_name}\"', work_dir=work_dir)\n\n    def parse(self, file, work_dir=None, extract_covers=False):\n        data = self.probe(file)\n        if \"streams\" not in data:\n            raise FlixError(\"Not a video file\")\n        streams = Box({\"video\": [], \"audio\": [], \"subtitle\": [], \"attachment\": [], \"data\": []})\n\n        covers = []\n        for track in data.streams:\n            if track.codec_type == \"video\" and track.get(\"disposition\", {}).get(\"attached_pic\"):\n                filename = track.get(\"tags\", {}).get(\"filename\", \"\")\n                if filename.rsplit(\".\", 1)[0] in (\"cover\", \"small_cover\", \"cover_land\", \"small_cover_land\"):\n                    covers.append((file, track.index, work_dir, filename))\n                streams.attachment.append(track)\n            elif track.codec_type in streams:\n                streams[track.codec_type].append(track)\n            else:\n                logger.error(f\"Unknown codec: {track.codec_type}\")\n\n        if extract_covers:\n            self.tp.map(self.extract_attachment, covers)\n\n        for stream in streams.video:\n            if \"bits_per_raw_sample\" in stream:\n                stream.bit_depth = int(stream.bits_per_raw_sample)\n            else:\n                stream.bit_depth = guess_bit_depth(stream.pix_fmt, stream.get(\"color_primaries\"))\n        return streams, data.format\n\n    @staticmethod\n    def generate_filters(\n        disable_hdr=False, scale_width=None, scale_height=None, crop=None, scale=None, scale_filter=\"lanczos\"\n    ):\n        filter_list = []\n        if crop:\n            filter_list.append(f\"crop={crop}\")\n        if scale:\n            filter_list.append(f\"scale={scale}:flags={scale_filter}\")\n        elif scale_width:\n            filter_list.append(f\"scale={scale_width}:-1:flags={scale_filter}\")\n        elif scale_height:\n            filter_list.append(f\"scale=-1:{scale_height}:flags={scale_filter}\")\n\n        if disable_hdr:\n            filter_list.append(\n                \"zscale=t=linear:npl=100,format=gbrpf32le,zscale=p=bt709,tonemap=tonemap=hable:desat=0,\"\n                \"zscale=t=bt709:m=bt709:r=tv,format=yuv420p\"\n            )\n\n        return \",\".join(filter_list)\n\n    def generate_thumbnail_command(self, source, output, video_track, start_time=0, filters=None):\n        start = \"\"\n        if start_time:\n            start = f\"-ss {start_time}\"\n        return (\n            f'\"{self.ffmpeg}\" {start} -loglevel error -i \"{source}\" '\n            f' -vf {filters + \",\" if filters else \"\"}scale=\"min(320\\\\,iw):-1\" '\n            f\"-map 0:{video_track} -an -y -map_metadata -1 \"\n            f'-vframes 1 \"{output}\"'\n        )\n\n    @staticmethod\n    def execute(command, work_dir=None):\n        logger.debug(f\"running command: {command}\")\n        return run(command, stdout=PIPE, stderr=PIPE, stdin=PIPE, shell=True, cwd=work_dir)\n\n    def get_audio_encoders(self):\n        cmd = run(\n            [f\"{self.ffmpeg}\", \"-hide_banner\", \"-encoders\"],\n            stdin=PIPE,\n            stdout=PIPE,\n            stderr=STDOUT,\n            encoding=\"utf-8\",\n            universal_newlines=True,\n        )\n        encoders = []\n        start_line = \" ------\"\n        started = False\n        for line in cmd.stdout.splitlines():\n            if started:\n                if line.strip().startswith(\"A\"):\n                    encoders.append(line.strip().split(\" \")[1])\n            elif line.startswith(start_line):\n                started = True\n        return encoders\n\n    def parse_hdr_details(self, video_source, video_track=0):\n        command = (\n            f'\"{self.ffprobe}\" -select_streams v:{video_track} -print_format json -show_frames '\n            '-read_intervals \"%+#1\" '\n            '-show_entries \"frame=color_space,color_primaries,color_transfer,side_data_list,pix_fmt\" '\n            f'-i \"{video_source}\"'\n        )\n\n        result = run(command, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE)\n        try:\n            data = Box.from_json(result.stdout.decode(\"utf-8\"), default_box=True, default_box_attr=None)\n        except BoxError:\n            # Could not parse details\n            logger.error(\n                \"COULD NOT PARSE FFPROBE HDR METADATA, PLEASE OPEN ISSUE WITH THESE DETAILS:\"\n                f\"\\nSTDOUT: {result.stdout.decode('utf-8')}\\nSTDERR: {result.stderr.decode('utf-8')}\"\n            )\n            return\n        if \"frames\" not in data or not len(data.frames):\n            return\n        data = data.frames[0]\n        if not data.get(\"side_data_list\"):\n            return\n\n        master_display = None\n        cll = None\n\n        def s(a, v):\n            return int(a.get(v, \"0\").split(\"/\")[0])\n\n        for item in data[\"side_data_list\"]:\n            if item.side_data_type == \"Mastering display metadata\":\n                master_display = Box(\n                    red=f\"({s(item, 'red_x')},{s(item, 'red_y')})\",\n                    green=f\"({s(item, 'green_x')},{s(item, 'green_y')})\",\n                    blue=f\"({s(item, 'blue_x')},{s(item, 'blue_y')})\",\n                    white=f\"({s(item, 'white_point_x')},{s(item, 'white_point_y')})\",\n                    luminance=f\"({s(item, 'max_luminance')},{s(item, 'min_luminance')})\",\n                )\n            if item.side_data_type == \"Content light level metadata\":\n                cll = f\"{item.max_content},{item.max_average}\"\n\n        return Box(\n            pix_fmt=data.pix_fmt,\n            color_space=data.color_space,\n            color_primaries=data.color_primaries,\n            color_transfer=data.color_transfer,\n            master_display=master_display,\n            cll=cll,\n        )\n", "repo_name": "buckeytuker/FastFlix", "sub_path": "fastflix/flix.py", "file_name": "flix.py", "file_ext": "py", "file_size_in_byte": 9026, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "github-code", "pt": "21", "api": [{"api_name": "os.path.abspath", "line_number": 11, "usage_type": "call"}, {"api_name": "os.path", "line_number": 11, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 11, "usage_type": "call"}, {"api_name": "logging.getLogger", "line_number": 13, "usage_type": "call"}, {"api_name": "multiprocessing.pool.ThreadPool", "line_number": 84, "usage_type": "call"}, {"api_name": "box.Box.from_json", "line_number": 93, "usage_type": "call"}, {"api_name": "box.Box", "line_number": 93, "usage_type": "name"}, {"api_name": "box.BoxError", "line_number": 94, "usage_type": "name"}, {"api_name": "box.Box", "line_number": 128, "usage_type": "call"}, {"api_name": "subprocess.run", "line_number": 188, "usage_type": "call"}, {"api_name": "subprocess.PIPE", "line_number": 188, "usage_type": "name"}, {"api_name": "subprocess.run", "line_number": 191, "usage_type": "call"}, {"api_name": "subprocess.PIPE", "line_number": 193, "usage_type": "name"}, {"api_name": "subprocess.PIPE", "line_number": 194, "usage_type": "name"}, {"api_name": "subprocess.STDOUT", "line_number": 195, "usage_type": "name"}, {"api_name": "subprocess.run", "line_number": 218, "usage_type": "call"}, {"api_name": "subprocess.PIPE", "line_number": 218, "usage_type": "name"}, {"api_name": "box.Box.from_json", "line_number": 220, "usage_type": "call"}, {"api_name": "box.Box", "line_number": 220, "usage_type": "name"}, {"api_name": "box.BoxError", "line_number": 221, "usage_type": "name"}, {"api_name": "box.Box", "line_number": 242, "usage_type": "call"}, {"api_name": "box.Box", "line_number": 252, "usage_type": "call"}]}
+{"seq_id": "3958394579", "text": "from pyunity import Logger\nfrom . import SceneTestCase\nimport contextlib\nimport io\n\nclass TestLevel(SceneTestCase):\n    def testInit(self):\n        l = Logger.Level(\"A\")\n        assert l.abbr == \"A\"\n        assert l == Logger.Level(\"A\")\n        assert l != Logger.Level(\"B\")\n        assert l != \"A\"\n\nclass TestLogger(SceneTestCase):\n    def testLog(self):\n        with Logger.TempRedirect(silent=True) as r:\n            Logger.Log(\"Test\")\n        assert r.get() == \"Test\\n\"\n\n        with Logger.TempRedirect(silent=True) as r:\n            Logger.LogLine(Logger.WARN, \"Test\")\n        assert r.get() == \"Warning: Test\\n\"\n\n        with Logger.TempRedirect() as r:\n            Logger.Log(\"Test\")\n        assert r.get() == f\"Changed stream to {r.stream}\\nTest\\n\"\n\n    def testError(self):\n        stream = io.StringIO()\n        with contextlib.redirect_stderr(stream):\n            Logger.LogLine(Logger.ERROR, \"Error\")\n        assert stream.getvalue() == \"Error\\n\"\n\n        stream = io.StringIO()\n        try:\n            raise Exception\n        except Exception as e:\n            with contextlib.redirect_stderr(stream):\n                Logger.LogException(e)\n        text = stream.getvalue()\n        assert text.endswith(\"Exception\\n\")\n        assert text.startswith(\"Traceback (most recent call last):\\n  \")\n\n        with self.assertRaises(Exception) as exc:\n            Logger.TempRedirect().get()\n        assert exc.value == \"Context manager not used\"\n\n    def testMultiline(self):\n        with Logger.TempRedirect(silent=True) as r:\n            Logger.Log(\"Test\\n\\nTest2\")\n        assert r.get() == \"Test\\n\\nTest2\\n\"\n", "repo_name": "pyunity/pyunity", "sub_path": "tests/pyunity/testLogger/testLogger.py", "file_name": "testLogger.py", "file_ext": "py", "file_size_in_byte": 1618, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 237, "dataset": "github-code", "pt": "21", "api": [{"api_name": "pyunity.Logger.Level", "line_number": 8, "usage_type": "call"}, {"api_name": "pyunity.Logger", "line_number": 8, "usage_type": "name"}, {"api_name": "pyunity.Logger.Level", "line_number": 10, "usage_type": "call"}, {"api_name": "pyunity.Logger", "line_number": 10, "usage_type": "name"}, {"api_name": "pyunity.Logger.Level", "line_number": 11, "usage_type": "call"}, {"api_name": "pyunity.Logger", "line_number": 11, "usage_type": "name"}, {"api_name": "pyunity.Logger.TempRedirect", "line_number": 16, "usage_type": "call"}, {"api_name": "pyunity.Logger", "line_number": 16, "usage_type": "name"}, {"api_name": "pyunity.Logger.Log", "line_number": 17, "usage_type": "call"}, {"api_name": "pyunity.Logger", "line_number": 17, "usage_type": "name"}, {"api_name": "pyunity.Logger.TempRedirect", "line_number": 20, "usage_type": "call"}, {"api_name": "pyunity.Logger", "line_number": 20, "usage_type": "name"}, {"api_name": "pyunity.Logger.LogLine", "line_number": 21, "usage_type": "call"}, {"api_name": "pyunity.Logger", "line_number": 21, "usage_type": "name"}, {"api_name": "pyunity.Logger.WARN", "line_number": 21, "usage_type": "attribute"}, {"api_name": "pyunity.Logger.TempRedirect", "line_number": 24, "usage_type": "call"}, {"api_name": "pyunity.Logger", "line_number": 24, "usage_type": "name"}, {"api_name": "pyunity.Logger.Log", "line_number": 25, "usage_type": "call"}, {"api_name": "pyunity.Logger", "line_number": 25, "usage_type": "name"}, {"api_name": "io.StringIO", "line_number": 29, "usage_type": "call"}, {"api_name": "contextlib.redirect_stderr", "line_number": 30, "usage_type": "call"}, {"api_name": "pyunity.Logger.LogLine", "line_number": 31, "usage_type": "call"}, {"api_name": "pyunity.Logger", "line_number": 31, "usage_type": "name"}, {"api_name": "pyunity.Logger.ERROR", "line_number": 31, "usage_type": "attribute"}, {"api_name": "io.StringIO", "line_number": 34, "usage_type": "call"}, {"api_name": "contextlib.redirect_stderr", "line_number": 38, "usage_type": "call"}, {"api_name": "pyunity.Logger.LogException", "line_number": 39, "usage_type": "call"}, {"api_name": "pyunity.Logger", "line_number": 39, "usage_type": "name"}, {"api_name": "pyunity.Logger.TempRedirect", "line_number": 45, "usage_type": "call"}, {"api_name": "pyunity.Logger", "line_number": 45, "usage_type": "name"}, {"api_name": "pyunity.Logger.TempRedirect", "line_number": 49, "usage_type": "call"}, {"api_name": "pyunity.Logger", "line_number": 49, "usage_type": "name"}, {"api_name": "pyunity.Logger.Log", "line_number": 50, "usage_type": "call"}, {"api_name": "pyunity.Logger", "line_number": 50, "usage_type": "name"}]}
+{"seq_id": "3801771934", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon May 18 21:40:32 2020\n\n@author: alberto\n\n\nAdd functionality to the keyboard with the list of notes.\n    Set an alert\n    \nAdd functionality to, instead of deleting, sending the alerts to a list of done alerts\n        \nAdd the functionality to undo the last change (editing a note/description, or deleting it)\n        \nAdd a command /createlist to create a new list.\n    The names of the lists must be in a separate file, which is read when the program\n    is run, so it can be modified.\n\nAdd a command /deletelist to delete a list.\n\n\"\"\"\n\n# Import my other Python script\nfrom poza_methods import *\n\nfrom telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackQueryHandler\n#from telegram import ChatAction\nfrom telegram import InlineKeyboardButton, InlineKeyboardMarkup, ParseMode\nfrom telegram.error import NetworkError\n\nimport logging\n\nimport threading # Needed for the \\stop command\n# from subprocess import Popen, PIPE # Needed for the \\battery command\n# from socket import socket, AF_INET, SOCK_DGRAM # Needed for the \\localIP command\n\n# Needed to read the callback_query data as Python code\nimport ast\n\n# Read the tokens\nTOKEN = ''\nCHAT_ID = ''\nwith open(\"token\", \"r\") as f:\n    # The information in the first two lines is not important\n    for i in range(2):\n        f.readline()\n    # The third line is the token\n    TOKEN = f.readline().strip()\n    # The fourth line is the chat id\n    CHAT_ID = f.readline().strip()\n\n# File where the tasks are programed\nFILE_TASKS = './Files/tarefas.txt'\n# List of tasks\nTASKS = ['baño', 'cociña', 'sala e corredor', 'descansar']\n# Time interval for the periodic function, in seconds\nALERTS_TIME_INTERVAL = 3600\n\n# Get the dictionary of IDs from the file\nIDs = read_ids('./Files/IDs.txt')\n\n\n\n\n#Prefix of the files to store the lists of notes\n#FILE_PREFIX = './Lists/list_{}.txt'\n#File to store the alerts that have already been sent\n#FILE_DELETED_PREFIX = './Lists/list_deleted_{}.txt'\n#File where the programmed alerts will be stored\n#FILE_ALERTS = '../AlertBot/single_alerts.txt'\n\n#Format to print the datetime objects in the Telegram messages\n#FORMAT_DATETIME = '%d/%m/%y %H:%M'\n\n# # # Time interval for uploading backups to Dropbox\n# BACKUPS_HOURS_INTERVAL = 8\n# # Global variable with the time for the next backup.\n# time_next_backup_global = datetime.datetime.now()\n\n#Global variable to store the alerts in memory.\n#NOTES = []\n\n#Boolean variable to be set to true when we want to set an alert, so the updater\n#listens for a time string\n#BOOL_SET_ALERT = False\n#Boolean variables that will be set to True when a note or its description is \n#going to be edited in the chat\n#BOOL_EDIT_NOTE = False\n#BOOL_EDIT_NOTE_DESCR = False\n#Variable to store the index of the note to edit\n#INDEX_NOTE = 0\n#Variable to store the name of the list in which is the alert that we are editing\n#LIST_NOTE = ''\n#Variable to store the ID of the message that will be modified after editing a note\n#MESSAGE_ID_EDIT = 0\n\n\n\n# The Updater class continuously fetches new updates from telegram and passes \n# them on to the Dispatcher class\nupdater = Updater(token = TOKEN, use_context=True)\n\n# # The Dispatcher is created automatically with the Updater.\n# # For quicker access, we can introduce it locally\n# dispatcher = updater.dispatcher\n\n# Set up the logging module, so you will know when things don't work as expected\n# This is used to print in the terminal the errors that are not caused by the \n# Telegram API (eg, Python errors)\nlogging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',\n                    level=logging.INFO)\n\ndef error_callback(update, context):\n    try:\n        raise context.error\n    except NetworkError:\n        # Stop the bot if the internet connection fails\n        print(\"Connection error\")\n        pass\n        \nupdater.dispatcher.add_error_handler(error_callback)\n\n\n\n##################   COMMANDS   ##########################    \n\ndef startFunction(update, context):\n    '''Function that replies with a text, simply to let the user know that the bot\n    is working as an AlertBot.\n    This will be called with the /start command.'''\n    # context.bot.send_message(chat_id=update.effective_chat.id, \n    #                          text=\"Hi! This is working as an AlertBot now.\")\n    update.message.reply_text(text = 'Ei! Aquí Poza de Bar!',\n                              parse_mode = ParseMode.MARKDOWN)\n    print(update.message)\n    \n    \ndef helpFunction(update, context):\n    '''Function that replies with a text, simply to let the user know the available\n    commeands.\n    This will be called with the /help command.'''\n    message = 'De momento isto non ten comandos.'\n    update.message.reply_text(text = message, parse_mode = ParseMode.MARKDOWN)\n\n\n#######################\n\n# Function to stop the execution of the bot.\ndef shutdown():\n    print(\"Stopping bot...\")\n    updater.stop()\n    updater.is_idle = False\n    # # Stop the process that sends the alerts periodically\n    # backupsProcess.stop()\n    \n# The following function is called with the /stop command\n# It executes shutdown() in a new thread, stopping the execution of the bot\ndef stopFunction(update, context):\n    threading.Thread(target = shutdown).start()\n    \n    update.message.reply_text(text = 'Stopping bot...')\n    \n    \n    \n    \n###################### Handle the lists #####################\n\ndef keyboardNotesList(notes, listname):\n    '''Create a keyboard with the list of notes given.'''\n    return InlineKeyboardMarkup([[InlineKeyboardButton(notes[i][0], \n                                                       callback_data=\"{'type':'note', 'i':\" + \\\n                                                           str(i) + \", 'list':'\" + listname + \"'}\")]\n                                        for i in range(len(notes))] + \\\n                                       [[InlineKeyboardButton('Cancel', callback_data=\"{'type':'act', 'act':'cancel'}\")]])\n\n\ndef messageNoteText(listname, note):\n    '''Get the text to be sent to the Telegram client, showing the note, its list\n    and its description, if it exists.'''\n    if note[1]:\n        return \"List *{}*.\\n\\n*{}*\\n{}\".format(listname, note[0], note[1])\n    else:\n        return \"List *{}*.\\n\\n*{}*\".format(listname, note[0])\n    \n\ndef checkNotesList(update, context, listname):\n    '''Send a message with all the notes that are in the list, as a keyboard.'''\n    global NOTES\n    try:\n        # Read the notes\n        NOTES = readNotes(FILE_PREFIX, listname)\n        if len(NOTES) == 0:\n            update.message.reply_text('There are no notes in this list.')\n            return\n        # Send a keyboard with all the notes\n        update.message.reply_text('Notes in *' + listname + '* list:', parse_mode=ParseMode.MARKDOWN, \n                                  reply_markup=keyboardNotesList(NOTES, listname))\n    \n    except FileNotFoundError:\n        update.message.reply_text('There are no notes in this list.')\n\n        return\n    \n\ndef inlineButtonPress(update, context):\n    # What to do when a button in an inline keyboard is pressed.\n    \n    # Get the callback query that has been sent\n    query = update.callback_query\n    # CallbackQueries need to be answered, even if no notification to the user is needed\n    # Some clients may have trouble otherwise. See https://core.telegram.org/bots/api#callbackquery\n    query.answer()\n    \n    # Read the data in the query as Python code (it is a dictionary, written as a string)\n    data = ast.literal_eval(query.data)\n    \n    # The variable alerts is the global one\n    global NOTES\n    global BOOL_SET_ALERT\n    global BOOL_EDIT_NOTE\n    global BOOL_EDIT_NOTE_DESCR\n    global INDEX_NOTE\n    global LIST_NOTE\n    global MESSAGE_ID_EDIT\n    \n    # Check if the user pressed a button that is an alert (the keyboard created by checkAlertList)\n    if data['type'] == 'note':\n        # Display a new keyboard that allows to edit or delete the alert        \n        keyboard = [[InlineKeyboardButton('Edit', callback_data=\"{'type':'act', 'act':'edit', 'i':\" + str(data['i']) + \", 'list':'\" + str(data['list']) + \"'}\"), \n                  InlineKeyboardButton('Delete', callback_data=\"{'type':'act', 'act':'delete', 'i':\" + str(data['i']) + \", 'list':'\" + str(data['list']) + \"'}\"),\n                  InlineKeyboardButton('Set alert', callback_data=\"{'type':'act', 'act':'alert', 'i':\" + str(data['i']) + \", 'list':'\" + str(data['list']) + \"'}\")],\n                  [InlineKeyboardButton('Back', callback_data=\"{'type':'act', 'act':'back', 'list':'\" + str(data['list']) + \"'}\"),\n                  InlineKeyboardButton('Cancel', callback_data=\"{'type':'act', 'act':'cancel'}\")]]\n        \n        query.edit_message_text(text=messageNoteText(data['list'], NOTES[data['i']]), \n                                parse_mode = ParseMode.MARKDOWN,\n                                reply_markup = InlineKeyboardMarkup(keyboard))\n        \n    # Check if the user pressed a button to perform an action on an alert.\n    if data['type'] == 'act':\n        \n        # Check the all the possible actions\n        \n        if data['act'] == 'edit':\n            \n            # Keyboard to choose whether we want to edit the note or the description\n            keyboard = [[InlineKeyboardButton('Edit note', callback_data=\"{'type':'act', 'act':'editN', 'i':\" + str(data['i']) + \", 'list':'\" + str(data['list']) + \"'}\"),\n                         InlineKeyboardButton('Edit description', callback_data=\"{'type':'act', 'act':'editD', 'i':\" + str(data['i']) + \", 'list':'\" + str(data['list']) + \"'}\")],\n                        [InlineKeyboardButton('Back', callback_data=\"{'type':'act', 'act':'back', 'list':'\" + str(data['list']) + \"'}\"),\n                         InlineKeyboardButton('Cancel', callback_data=\"{'type':'act', 'act':'cancel'}\")]]\n            \n            query.edit_message_text(text=messageNoteText(data['list'], NOTES[data['i']]),\n                                    parse_mode=ParseMode.MARKDOWN,\n                                    reply_markup = InlineKeyboardMarkup(keyboard))\n        \n        elif data['act'] == 'editN':\n            # Set to true the boolean variable to edit a note\n            BOOL_EDIT_NOTE = True\n            # Store the index and the list of the note in the global variables\n            INDEX_NOTE = data['i']\n            LIST_NOTE = data['list']\n            # Store the ID of the previous message, so it can be modified later\n            MESSAGE_ID_EDIT = query.message.message_id\n            \n            keyboardEdit = [[InlineKeyboardButton('Cancel', callback_data=\"{'type':'act', 'act':'cancel'}\")]]\n            # Prompt the user to write the new text for the alert.\n            query.edit_message_text(text=messageNoteText(data['list'], NOTES[data['i']]) + '\\n\\nWrite the new note.',\n                                    parse_mode=ParseMode.MARKDOWN,\n                                    reply_markup=InlineKeyboardMarkup(keyboardEdit))\n        \n        elif data['act'] == 'editD':\n            # Set to true the boolean variable to edit a note\n            BOOL_EDIT_NOTE_DESCR = True\n            # Store the index and the list of the note in the global variables\n            INDEX_NOTE = data['i']\n            LIST_NOTE = data['list']\n            # Store the ID of the previous message, so it can be modified later\n            MESSAGE_ID_EDIT = query.message.message_id\n            \n            keyboardEdit = [[InlineKeyboardButton('Cancel', callback_data=\"{'type':'act', 'act':'cancel'}\")]]\n            # Prompt the user to write the new text for the alert.\n            query.edit_message_text(text=messageNoteText(data['list'], NOTES[data['i']]) + '\\n\\nWrite the new description.',\n                                    parse_mode=ParseMode.MARKDOWN,\n                                    reply_markup=InlineKeyboardMarkup(keyboardEdit))\n        \n        elif data['act'] == 'alert':\n            # Set to true the boolean variable to set an alert.\n            BOOL_SET_ALERT = True\n            # Store the index and the list of the note in the global variables\n            INDEX_NOTE = data['i']\n            LIST_NOTE = data['list']\n            # Store the ID of the previous message, so it can be modified later\n            MESSAGE_ID_EDIT = query.message.message_id\n            \n            keyboardEdit = [[InlineKeyboardButton('Cancel', callback_data=\"{'type':'act', 'act':'cancel'}\")]]\n            # Prompt the user to write the new text for the alert.\n            query.edit_message_text(text=messageNoteText(data['list'], NOTES[data['i']]) + '\\n\\nWrite the time for the alert.',\n                                    parse_mode=ParseMode.MARKDOWN,\n                                    reply_markup=InlineKeyboardMarkup(keyboardEdit))\n        \n        elif data['act'] == 'delete':\n            \n            '''IMPLEMENT'''\n        #     # Add this alert to the file with the sent alerts, so it is ignored when\n        #     # downloading the backup.\n        #     # Notice that the alerts have to be passed as a list\n        #     updateSentAlerts((alerts[int(data['index'])],), FILE_ALERTS_SENT)\n            \n            # Remove this note from the list\n            NOTES.remove(NOTES[int(data['i'])])\n            # Write the edited list of notes to the file\n            updateNotes(FILE_PREFIX, data['list'], NOTES)\n            \n            # Show again the keyboard with the list of notes\n            query.edit_message_text(\"Notes in *{}* list, edited:\".format(data['list']), parse_mode=ParseMode.MARKDOWN, \n                                      reply_markup = keyboardNotesList(NOTES, data['list'])) \n        \n            \n        elif data['act'] == 'back':\n            # Show again the keyboard with the list of notes\n            query.edit_message_text(\"Notes in *{}* list:\".format(data['list']), parse_mode=ParseMode.MARKDOWN, \n                                      reply_markup = keyboardNotesList(NOTES, data['list'])) \n            \n        elif data['act'] == 'cancel':\n            # Delete this message\n            query.bot.delete_message(query.message.chat_id, query.message.message_id)\n            # Set the boolean variables to edit or to program alerts to false\n            BOOT_SET_ALERT = False\n            BOOL_EDIT_NOTE = False\n            BOOL_EDIT_NOTE_DESCR = False\n\n\n#def manageCommandFunction(update, context):\n    #'''This will read the messages that start with / and are not one of the commands\n    #defined previously.\n        #If it is /: add something to the list.\n        #If it is /s: view everything in the list, as a keyboard.\n        #Otherwise, reply with a message of 'Unknown command or list'.\n    #'''\n    ## Get the first element of the message, without the '/', which is the first character\n    #command = update.message.text.split(' ')[0][1:].lower()\n    \n    ## Check if the command is in the list of lists\n    #if command in LISTS:\n        #try:\n            ## The rest of the message is the text\n            #text = update.message.text.split(' ', 1)[1].strip()\n            \n            ## Try to find a description, separated from the main text by the first \\n.\n            #try:\n                #text, description = text.split('\\n', 1)\n            #except ValueError:\n                ## There was no description\n                #description = None\n                #pass\n            \n            ## If the text contains a comma, it cannot be stored in the csv file\n            #if ',' in text:\n                #update.message.reply_text('The text cannot contain any comma.')\n                #return\n            \n            ## Add the text to the list\n            #addNote(FILE_PREFIX, listname=command, text=text, description=description)\n            ## Notify the user\n            #update.message.reply_text('Note saved successfully.')\n            \n        #except IndexError:\n            ## If there is no more text than the command, notify the user.\n            #update.message.reply_text('You should write the text for the note.')\n        \n    ## Check if the command minus the last letter (which would be an 's') is in the list of lists\n    #elif command[:-1] in LISTS:\n        #'''IMPLEMENT'''\n        ## Send the user a message with all the notes in the list.\n        #checkNotesList(update, context, command[:-1])\n    \n    ## If the command does not correspond to any list, notify the user.    \n    #else:    \n        #update.message.reply_text('List unknown.')\n        \n\n\n#####################   TEXT RECOGNITION   ######################\n\n    \ndef listenTextFunction(update, context):\n    '''When any text message is received, the bot will reply telling the user\n    what they have to clean this week.\n    If it is Friday, Saturday, Sunday or Monday, they will give the option to \n    flag the task as done.'''\n    update.message.reply_text(text='Tócache limpar *adlkf*', parse_mode=ParseMode.MARKDOWN)\n        \n\n\n##############################################################\n\n# Add the handlers for the commands defined above\nupdater.dispatcher.add_handler(CommandHandler('start', startFunction))\nupdater.dispatcher.add_handler(CommandHandler('stop', stopFunction))\nupdater.dispatcher.add_handler(CommandHandler('help', helpFunction))\n# MessageHandler with a command filter to reply to all commands that were not \n# recognized by the previous handlers.\n#updater.dispatcher.add_handler(MessageHandler(Filters.command, manageCommandFunction))\n\n## Add the handler for clicks in the buttons of inline keyboards\nupdater.dispatcher.add_handler(CallbackQueryHandler(inlineButtonPress))\n\n## Add the handler for reading text\nupdater.dispatcher.add_handler(MessageHandler(Filters.text, listenTextFunction))\n\n\n\n\n\n# Notify the user that the bot is working\nupdater.dispatcher.bot.send_message(chat_id = CHAT_ID, text = \"Aquí Poza de Bar!\")\n\n\n\n## Start the process that looks for alerts that are due and sends the messages\n## to the user\n## This is stopped with the /stop command, by the line sendAlertsProcess.stop()\n## in the function shutdown()\n## I also add sendAlertsProcess.stop() at the end of the code, so this is stopped\n## if I press Ctrl+C\n# sendAlertsProcess = myTimer(sendAlerts, wait_seconds = ALERTS_TIME_INTERVAL,\n#                             args = (updater, CHAT_ID, FILE_ALERTS, FILE_ALERTS_SENT, \n#                                     BACKUPS_HOURS_INTERVAL, ParseMode.MARKDOWN))\n#\n# #sendAlertsProcess = threading.Timer(ALERTS_TIME_INTERVAL, sendAlerts)\n# sendAlertsProcess.start()\n\n# Start the bot\nupdater.start_polling()\n\n# Keep the bot executing until pressing Ctrl+C\nupdater.idle()\n\n# Stop the process that sends the alerts.\nsendAlertsProcess.stop()\n\n\n\n\n# Stop the bot\n# updater.stop()\n", "repo_name": "AlbertoRivadulla/Telegram-Bots", "sub_path": "Bots/PozaDeBot/main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 18747, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "telegram.ext.Updater", "line_number": 102, "usage_type": "call"}, {"api_name": "logging.basicConfig", "line_number": 111, "usage_type": "call"}, {"api_name": "logging.INFO", "line_number": 112, "usage_type": "attribute"}, {"api_name": "telegram.error.NetworkError", "line_number": 117, "usage_type": "name"}, {"api_name": "telegram.ParseMode.MARKDOWN", "line_number": 135, "usage_type": "attribute"}, {"api_name": "telegram.ParseMode", "line_number": 135, "usage_type": "name"}, {"api_name": "telegram.ParseMode.MARKDOWN", "line_number": 144, "usage_type": "attribute"}, {"api_name": "telegram.ParseMode", "line_number": 144, "usage_type": "name"}, {"api_name": "threading.Thread", "line_number": 160, "usage_type": "call"}, {"api_name": "telegram.InlineKeyboardMarkup", "line_number": 171, "usage_type": "call"}, {"api_name": "telegram.InlineKeyboardButton", "line_number": 171, "usage_type": "call"}, {"api_name": "telegram.InlineKeyboardButton", "line_number": 175, "usage_type": "call"}, {"api_name": "telegram.ParseMode.MARKDOWN", "line_number": 197, "usage_type": "attribute"}, {"api_name": "telegram.ParseMode", "line_number": 197, "usage_type": "name"}, {"api_name": "ast.literal_eval", "line_number": 216, "usage_type": "call"}, {"api_name": "telegram.InlineKeyboardButton", "line_number": 230, "usage_type": "call"}, {"api_name": "telegram.InlineKeyboardButton", "line_number": 231, "usage_type": "call"}, {"api_name": "telegram.InlineKeyboardButton", "line_number": 232, "usage_type": "call"}, {"api_name": "telegram.InlineKeyboardButton", "line_number": 233, "usage_type": "call"}, {"api_name": "telegram.InlineKeyboardButton", "line_number": 234, "usage_type": "call"}, {"api_name": "telegram.ParseMode.MARKDOWN", "line_number": 237, "usage_type": "attribute"}, {"api_name": "telegram.ParseMode", "line_number": 237, "usage_type": "name"}, {"api_name": "telegram.InlineKeyboardMarkup", "line_number": 238, "usage_type": "call"}, {"api_name": "telegram.InlineKeyboardButton", "line_number": 248, "usage_type": "call"}, {"api_name": "telegram.InlineKeyboardButton", "line_number": 249, "usage_type": "call"}, {"api_name": "telegram.InlineKeyboardButton", "line_number": 250, "usage_type": "call"}, {"api_name": "telegram.InlineKeyboardButton", "line_number": 251, "usage_type": "call"}, {"api_name": "telegram.ParseMode.MARKDOWN", "line_number": 254, "usage_type": "attribute"}, {"api_name": "telegram.ParseMode", "line_number": 254, "usage_type": "name"}, {"api_name": "telegram.InlineKeyboardMarkup", "line_number": 255, "usage_type": "call"}, {"api_name": "telegram.InlineKeyboardButton", "line_number": 266, "usage_type": "call"}, {"api_name": "telegram.ParseMode.MARKDOWN", "line_number": 269, "usage_type": "attribute"}, {"api_name": "telegram.ParseMode", "line_number": 269, "usage_type": "name"}, {"api_name": "telegram.InlineKeyboardMarkup", "line_number": 270, "usage_type": "call"}, {"api_name": "telegram.InlineKeyboardButton", "line_number": 281, "usage_type": "call"}, {"api_name": "telegram.ParseMode.MARKDOWN", "line_number": 284, "usage_type": "attribute"}, {"api_name": "telegram.ParseMode", "line_number": 284, "usage_type": "name"}, {"api_name": "telegram.InlineKeyboardMarkup", "line_number": 285, "usage_type": "call"}, {"api_name": "telegram.InlineKeyboardButton", "line_number": 296, "usage_type": "call"}, {"api_name": "telegram.ParseMode.MARKDOWN", "line_number": 299, "usage_type": "attribute"}, {"api_name": "telegram.ParseMode", "line_number": 299, "usage_type": "name"}, {"api_name": "telegram.InlineKeyboardMarkup", "line_number": 300, "usage_type": "call"}, {"api_name": "telegram.ParseMode.MARKDOWN", "line_number": 316, "usage_type": "attribute"}, {"api_name": "telegram.ParseMode", "line_number": 316, "usage_type": "name"}, {"api_name": "telegram.ParseMode.MARKDOWN", "line_number": 322, "usage_type": "attribute"}, {"api_name": "telegram.ParseMode", "line_number": 322, "usage_type": "name"}, {"api_name": "telegram.ParseMode.MARKDOWN", "line_number": 392, "usage_type": "attribute"}, {"api_name": "telegram.ParseMode", "line_number": 392, "usage_type": "name"}, {"api_name": "telegram.ext.CommandHandler", "line_number": 399, "usage_type": "call"}, {"api_name": "telegram.ext.CommandHandler", "line_number": 400, "usage_type": "call"}, {"api_name": "telegram.ext.CommandHandler", "line_number": 401, "usage_type": "call"}, {"api_name": "telegram.ext.CallbackQueryHandler", "line_number": 407, "usage_type": "call"}, {"api_name": "telegram.ext.MessageHandler", "line_number": 410, "usage_type": "call"}, {"api_name": "telegram.ext.Filters.text", "line_number": 410, "usage_type": "attribute"}, {"api_name": "telegram.ext.Filters", "line_number": 410, "usage_type": "name"}]}
+{"seq_id": "42604077738", "text": "from time import sleep\nfrom datetime import datetime, timedelta\nimport requests\nimport json\nfrom pySerialTransfer import pySerialTransfer as txfer\n\n# api parameters\nlatitude = 0\nlongitude = 0\napi_key = ''\nunits = 'metric'\nurl = 'https://api.openweathermap.org/data/2.5/weather?lat={}&lon={}&appid={}&units={}'.format(latitude, longitude, api_key, units)\n# global variable\nlast_api_call = None\nlast_package = 0\nnetwork_connection = True\n\n# validate api call timing, limit call frequency to avoid api lockdown\ndef validate_api_call() -> bool:\n    global last_api_call\n    # if first loop or if 5 minutes had elapsed since last API call\n    if last_api_call is None or datetime.now() > last_api_call + timedelta(minutes = 5):\n        last_api_call = datetime.now()\n        return True\n    else:\n        return False\n\n# call weather api and return json data\ndef call_weather_api():\n    global network_connection\n    if validate_api_call():\n        try:\n            response = requests.get(url, timeout = 5)\n            print('status code: {}'.format(response.status_code))\n            network_connection = True\n            if response.status_code == 200:\n                return response.json()\n        except:\n            network_connection = False\n            print('Network connection error', datetime.now())\n            return -1 # network connection error\n    if network_connection:\n        return None # skip weather API call, display time as usual\n    else:\n        return -1\n\n# build data package as numerical value\ndef build_data_package():\n    global last_package\n    # api call\n    data = call_weather_api()\n    if data is None:\n        return (last_package // 10**7 % 10) * 10**7 + (last_package // 10**6 % 10) * 10**6 + datetime.now().hour * 10**4 + datetime.now().minute * 10**2 + (last_package // 10 % 10) * 10 + (last_package % 10)\n    elif data == -1:\n        package = -88888801\n        return package\n\n    # process data\n    temp = data['main']['temp']\n    weather = data['weather'][0]['id']\n    sunrise = datetime.fromtimestamp(data['sys']['sunrise'])\n    sunset = datetime.fromtimestamp(data['sys']['sunset'])\n    negative = temp < 0\n    temp = int(round(abs(temp)))\n\n    # build package value\n    package = 0\n    if weather < 800:\n        package += 1\n    if datetime.now() > sunrise and datetime.now() < sunset:\n        package += 10\n    package += datetime.now().hour * 10**4 + datetime.now().minute * 10**2\n    package += temp * 10**6\n    if negative:\n        package *= -1\n    # update last_package\n    last_package = package\n    # return package\n    print('package value: {}, timestamp: {}'.format(package, datetime.now()))\n    return package\n\n# program call\nif __name__ == '__main__':\n    link = txfer.SerialTransfer('/dev/ttyACM0')\n    link.open()\n    sleep(5)\n    while True:\n        package = build_data_package()\n        # print(package)\n        sendSize = link.tx_obj(package)\n        link.send(sendSize)\n        sleep(3)\n    link.close()\n", "repo_name": "taiyipan/desktop_weather_clock", "sub_path": "monitor_statistics.py", "file_name": "monitor_statistics.py", "file_ext": "py", "file_size_in_byte": 2967, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "datetime.datetime.now", "line_number": 22, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 22, "usage_type": "name"}, {"api_name": "datetime.timedelta", "line_number": 22, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 23, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 23, "usage_type": "name"}, {"api_name": "requests.get", "line_number": 33, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 40, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 40, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 53, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 53, "usage_type": "name"}, {"api_name": "datetime.datetime.fromtimestamp", "line_number": 61, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 61, "usage_type": "name"}, {"api_name": "datetime.datetime.fromtimestamp", "line_number": 62, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 62, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 70, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 70, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 72, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 72, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 79, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 79, "usage_type": "name"}, {"api_name": "pySerialTransfer.pySerialTransfer.SerialTransfer", "line_number": 84, "usage_type": "call"}, {"api_name": "pySerialTransfer.pySerialTransfer", "line_number": 84, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 86, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 92, "usage_type": "call"}]}
+{"seq_id": "37909799089", "text": "import pandas as pd\nfrom sklearn.linear_model import ElasticNet\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.preprocessing import MinMaxScaler, LabelEncoder\n\n\n# Scaling\ndef scaling(df):\n    scaled_df = pd.DataFrame(MinMaxScaler().fit_transform(df))\n    scaled_df.columns = df.columns.values\n    scaled_df.index = df.index.values\n\n    return scaled_df\n\n\n# Encoding\ndef encoder(df):\n    cleaned_df = df.copy()\n    features = ['sex', 'smoker', 'region']\n    for feature in features:\n        cleaned_df[feature] = LabelEncoder().fit_transform(cleaned_df[feature])\n\n    return cleaned_df\n\n\ndef elastic_net_regression(x, y):\n    # Build model\n    en = ElasticNet()\n    # Hyper-parameter\n    params = {'alpha': [1e-15, 1e-10, 1e-8, 1e-4, 1e-3, 1e-2, 1, 5, 10, 20],\n              'l1_ratio': [0.1, 0.3, 0.5, 0.7, 0.9]}\n\n    # Do k-fold cross validation and tune parameter\n    en_gscv = GridSearchCV(estimator=en, param_grid=params, scoring='neg_mean_squared_error', cv=10)\n\n    en_gscv.fit(x, y)\n\n    print('Elastic Net Regression')\n    print('Best parameter: ', en_gscv.best_params_)\n    print('Mean squared error: ', en_gscv.best_score_)\n    print('=======================================\\n')\n\n\n# Import dataset\ndf = pd.read_csv('insurance.csv')\n\n# Encode dataset\nencoded_df = encoder(df)\n# Scale dataset\nscaled_df = scaling(encoded_df)\n\n# Separate predict columns and target column\nx = scaled_df.drop(['charges'], axis=1)\ny = scaled_df['charges']\n\nelastic_net_regression(x, y)\n", "repo_name": "choib1ack/Machine_Learning", "sub_path": "Programming Homework/200929_#2_PHW_Regression/regression2.py", "file_name": "regression2.py", "file_ext": "py", "file_size_in_byte": 1489, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "pandas.DataFrame", "line_number": 9, "usage_type": "call"}, {"api_name": "sklearn.preprocessing.MinMaxScaler", "line_number": 9, "usage_type": "call"}, {"api_name": "sklearn.preprocessing.LabelEncoder", "line_number": 21, "usage_type": "call"}, {"api_name": "sklearn.linear_model.ElasticNet", "line_number": 28, "usage_type": "call"}, {"api_name": "sklearn.model_selection.GridSearchCV", "line_number": 34, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 45, "usage_type": "call"}]}
+{"seq_id": "34340481131", "text": "import numpy as np\nimport pytest\n\nfrom darts.logging import get_logger\nfrom darts.tests.conftest import tfm_kwargs\nfrom darts.utils import timeseries_generation as tg\n\nlogger = get_logger(__name__)\n\ntry:\n    from darts.models.forecasting.nbeats import NBEATSModel\n    from darts.models.forecasting.nhits import NHiTSModel\n\n    TORCH_AVAILABLE = True\nexcept ImportError:\n    logger.warning(\"Torch not available. Nbeats and NHiTs tests will be skipped.\")\n    TORCH_AVAILABLE = False\n\n\nif TORCH_AVAILABLE:\n\n    class TestNbeatsNhitsModel:\n        def test_creation(self):\n            with pytest.raises(ValueError):\n                # if a list is passed to the `layer_widths` argument, it must have a length equal to `num_stacks`\n                NBEATSModel(\n                    input_chunk_length=1,\n                    output_chunk_length=1,\n                    num_stacks=3,\n                    layer_widths=[1, 2],\n                )\n\n            with pytest.raises(ValueError):\n                NHiTSModel(\n                    input_chunk_length=1,\n                    output_chunk_length=1,\n                    num_stacks=3,\n                    layer_widths=[1, 2],\n                )\n\n        def test_fit(self):\n            large_ts = tg.constant_timeseries(length=100, value=1000)\n            small_ts = tg.constant_timeseries(length=100, value=10)\n\n            for model_cls in [NBEATSModel, NHiTSModel]:\n                # Test basic fit and predict\n                model = model_cls(\n                    input_chunk_length=1,\n                    output_chunk_length=1,\n                    n_epochs=10,\n                    num_stacks=1,\n                    num_blocks=1,\n                    layer_widths=20,\n                    random_state=42,\n                    **tfm_kwargs\n                )\n                model.fit(large_ts[:98])\n                pred = model.predict(n=2).values()[0]\n\n                # Test whether model trained on one series is better than one trained on another\n                model2 = model_cls(\n                    input_chunk_length=1,\n                    output_chunk_length=1,\n                    n_epochs=10,\n                    num_stacks=1,\n                    num_blocks=1,\n                    layer_widths=20,\n                    random_state=42,\n                    **tfm_kwargs\n                )\n                model2.fit(small_ts[:98])\n                pred2 = model2.predict(n=2).values()[0]\n                assert abs(pred2 - 10) < abs(pred - 10)\n\n                # test short predict\n                pred3 = model2.predict(n=1)\n                assert len(pred3) == 1\n\n        def test_multivariate(self):\n            # testing a 2-variate linear ts, first one from 0 to 1, second one from 0 to 0.5, length 100\n            series_multivariate = tg.linear_timeseries(length=100).stack(\n                tg.linear_timeseries(length=100, start_value=0, end_value=0.5)\n            )\n\n            for model_cls in [NBEATSModel, NHiTSModel]:\n                model = model_cls(\n                    input_chunk_length=3,\n                    output_chunk_length=1,\n                    n_epochs=20,\n                    random_state=42,\n                    **tfm_kwargs\n                )\n\n                model.fit(series_multivariate)\n                res = model.predict(n=2).values()\n\n                # the theoretical result should be [[1.01, 1.02], [0.505, 0.51]].\n                # We just test if the given result is not too far on average.\n                assert abs(\n                    np.average(res - np.array([[1.01, 1.02], [0.505, 0.51]])) < 0.03\n                )\n\n                # Test Covariates\n                series_covariates = tg.linear_timeseries(length=100).stack(\n                    tg.linear_timeseries(length=100, start_value=0, end_value=0.1)\n                )\n                model = model_cls(\n                    input_chunk_length=3,\n                    output_chunk_length=4,\n                    n_epochs=5,\n                    random_state=42,\n                    **tfm_kwargs\n                )\n                model.fit(series_multivariate, past_covariates=series_covariates)\n\n                res = model.predict(\n                    n=3, series=series_multivariate, past_covariates=series_covariates\n                ).values()\n\n                assert len(res) == 3\n                assert abs(np.average(res)) < 5\n\n        def test_nhits_sampling_sizes(self):\n            # providing bad sizes or shapes should fail\n            with pytest.raises(ValueError):\n\n                # wrong number of coeffs for stacks and blocks\n                NHiTSModel(\n                    input_chunk_length=1,\n                    output_chunk_length=1,\n                    num_stacks=1,\n                    num_blocks=2,\n                    pooling_kernel_sizes=((1,), (1,)),\n                    n_freq_downsample=((1,), (1,)),\n                )\n            with pytest.raises(ValueError):\n                NHiTSModel(\n                    input_chunk_length=1,\n                    output_chunk_length=1,\n                    num_stacks=2,\n                    num_blocks=2,\n                    pooling_kernel_sizes=((1, 1), (1, 1)),\n                    n_freq_downsample=((2, 1), (2, 2)),\n                )\n\n            # it shouldn't fail with the right number of coeffs\n            _ = NHiTSModel(\n                input_chunk_length=1,\n                output_chunk_length=1,\n                num_stacks=2,\n                num_blocks=2,\n                pooling_kernel_sizes=((2, 1), (2, 1)),\n                n_freq_downsample=((2, 1), (2, 1)),\n            )\n\n            # default freqs should be such that last one is 1\n            model = NHiTSModel(\n                input_chunk_length=1,\n                output_chunk_length=1,\n                num_stacks=2,\n                num_blocks=2,\n            )\n            assert model.n_freq_downsample[-1][-1] == 1\n\n        def test_logtensorboard(self, tmpdir_module):\n            ts = tg.constant_timeseries(length=50, value=10)\n\n            # testing if both the modes (generic and interpretable) runs with tensorboard\n            architectures = [True, False]\n            for architecture in architectures:\n                # Test basic fit and predict\n                model = NBEATSModel(\n                    input_chunk_length=1,\n                    output_chunk_length=1,\n                    n_epochs=1,\n                    log_tensorboard=True,\n                    work_dir=tmpdir_module,\n                    generic_architecture=architecture,\n                    pl_trainer_kwargs={\n                        \"log_every_n_steps\": 1,\n                        **tfm_kwargs[\"pl_trainer_kwargs\"],\n                    },\n                )\n                model.fit(ts)\n                model.predict(n=2)\n\n        def test_activation_fns(self):\n            ts = tg.constant_timeseries(length=50, value=10)\n\n            for model_cls in [NBEATSModel, NHiTSModel]:\n                model = model_cls(\n                    input_chunk_length=1,\n                    output_chunk_length=1,\n                    n_epochs=10,\n                    num_stacks=1,\n                    num_blocks=1,\n                    layer_widths=20,\n                    random_state=42,\n                    activation=\"LeakyReLU\",\n                    **tfm_kwargs\n                )\n                model.fit(ts)\n\n                with pytest.raises(ValueError):\n                    model = model_cls(\n                        input_chunk_length=1,\n                        output_chunk_length=1,\n                        n_epochs=10,\n                        num_stacks=1,\n                        num_blocks=1,\n                        layer_widths=20,\n                        random_state=42,\n                        activation=\"invalid\",\n                        **tfm_kwargs\n                    )\n                    model.fit(ts)\n", "repo_name": "unit8co/darts", "sub_path": "darts/tests/models/forecasting/test_nbeats_nhits.py", "file_name": "test_nbeats_nhits.py", "file_ext": "py", "file_size_in_byte": 7894, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 6665, "dataset": "github-code", "pt": "21", "api": [{"api_name": "darts.logging.get_logger", "line_number": 8, "usage_type": "call"}, {"api_name": "pytest.raises", "line_number": 24, "usage_type": "call"}, {"api_name": "darts.models.forecasting.nbeats.NBEATSModel", "line_number": 26, "usage_type": "call"}, {"api_name": "pytest.raises", "line_number": 33, "usage_type": "call"}, {"api_name": "darts.models.forecasting.nhits.NHiTSModel", "line_number": 34, "usage_type": "call"}, {"api_name": "darts.utils.timeseries_generation.constant_timeseries", "line_number": 42, "usage_type": "call"}, {"api_name": "darts.utils.timeseries_generation", "line_number": 42, "usage_type": "name"}, {"api_name": "darts.utils.timeseries_generation.constant_timeseries", "line_number": 43, "usage_type": "call"}, {"api_name": "darts.utils.timeseries_generation", "line_number": 43, "usage_type": "name"}, {"api_name": "darts.models.forecasting.nbeats.NBEATSModel", "line_number": 45, "usage_type": "name"}, {"api_name": "darts.models.forecasting.nhits.NHiTSModel", "line_number": 45, "usage_type": "name"}, {"api_name": "darts.tests.conftest.tfm_kwargs", "line_number": 55, "usage_type": "name"}, {"api_name": "darts.tests.conftest.tfm_kwargs", "line_number": 69, "usage_type": "name"}, {"api_name": "darts.utils.timeseries_generation.linear_timeseries", "line_number": 81, "usage_type": "call"}, {"api_name": "darts.utils.timeseries_generation", "line_number": 81, "usage_type": "name"}, {"api_name": "darts.utils.timeseries_generation.linear_timeseries", "line_number": 82, "usage_type": "call"}, {"api_name": "darts.utils.timeseries_generation", "line_number": 82, "usage_type": "name"}, {"api_name": "darts.models.forecasting.nbeats.NBEATSModel", "line_number": 85, "usage_type": "name"}, {"api_name": "darts.models.forecasting.nhits.NHiTSModel", "line_number": 85, "usage_type": "name"}, {"api_name": "darts.tests.conftest.tfm_kwargs", "line_number": 91, "usage_type": "name"}, {"api_name": "numpy.average", "line_number": 100, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 100, "usage_type": "call"}, {"api_name": "darts.utils.timeseries_generation.linear_timeseries", "line_number": 104, "usage_type": "call"}, {"api_name": "darts.utils.timeseries_generation", "line_number": 104, "usage_type": "name"}, {"api_name": "darts.utils.timeseries_generation.linear_timeseries", "line_number": 105, "usage_type": "call"}, {"api_name": "darts.utils.timeseries_generation", "line_number": 105, "usage_type": "name"}, {"api_name": "darts.tests.conftest.tfm_kwargs", "line_number": 112, "usage_type": "name"}, {"api_name": "numpy.average", "line_number": 121, "usage_type": "call"}, {"api_name": "pytest.raises", "line_number": 125, "usage_type": "call"}, {"api_name": "darts.models.forecasting.nhits.NHiTSModel", "line_number": 128, "usage_type": "call"}, {"api_name": "pytest.raises", "line_number": 136, "usage_type": "call"}, {"api_name": "darts.models.forecasting.nhits.NHiTSModel", "line_number": 137, "usage_type": "call"}, {"api_name": "darts.models.forecasting.nhits.NHiTSModel", "line_number": 147, "usage_type": "call"}, {"api_name": "darts.models.forecasting.nhits.NHiTSModel", "line_number": 157, "usage_type": "call"}, {"api_name": "darts.utils.timeseries_generation.constant_timeseries", "line_number": 166, "usage_type": "call"}, {"api_name": "darts.utils.timeseries_generation", "line_number": 166, "usage_type": "name"}, {"api_name": "darts.models.forecasting.nbeats.NBEATSModel", "line_number": 172, "usage_type": "call"}, {"api_name": "darts.tests.conftest.tfm_kwargs", "line_number": 181, "usage_type": "name"}, {"api_name": "darts.utils.timeseries_generation.constant_timeseries", "line_number": 188, "usage_type": "call"}, {"api_name": "darts.utils.timeseries_generation", "line_number": 188, "usage_type": "name"}, {"api_name": "darts.models.forecasting.nbeats.NBEATSModel", "line_number": 190, "usage_type": "name"}, {"api_name": "darts.models.forecasting.nhits.NHiTSModel", "line_number": 190, "usage_type": "name"}, {"api_name": "darts.tests.conftest.tfm_kwargs", "line_number": 200, "usage_type": "name"}, {"api_name": "pytest.raises", "line_number": 204, "usage_type": "call"}, {"api_name": "darts.tests.conftest.tfm_kwargs", "line_number": 214, "usage_type": "name"}]}
+{"seq_id": "10942148451", "text": "#!/usr/bin/env python\n#\n# Python because it comes on Mac and Linux - Node must be installed.\n#\n\nimport sys\nimport os\nimport os.path\nimport json\nimport shutil\nimport hashlib\nimport tempfile\nimport zipfile\nimport subprocess\nimport base64\nimport shutil\nimport functools\n\nclass Sandbox:\n    '''\n    A temporary directory for staging a lambda package.\n\n    We import files, write new files, and run commands in the Sandbox to\n    produce the image we want to zip for the lambda.\n    '''\n    FILE_STRING_MTIME = 1493649512\n\n    def __init__(self):\n        self.dir = tempfile.mkdtemp(suffix='lambda-packager')\n\n    def run_command(self, cmd):\n        cwd = os.getcwd()\n        os.chdir(self.dir)\n        result = os.system(cmd)\n        os.chdir(cwd)\n        return result\n\n    def import_path(self, path):\n        if os.path.isdir(path):\n            shutil.copytree(path, os.path.join(\n                self.dir, os.path.basename(path)))\n        else:\n            shutil.copy2(path, self.dir)\n\n    def add_file_string(self, path, contents):\n        full_path = os.path.join(self.dir, path)\n        with open(full_path, 'w') as f:\n            f.write(contents)\n        os.utime(full_path, (self.FILE_STRING_MTIME, self.FILE_STRING_MTIME))\n\n    def fix_time(self, full_path):\n        os.utime(full_path, (self.FILE_STRING_MTIME, self.FILE_STRING_MTIME))\n\n    def files(self):\n        result = []\n        for root, dirs, files in os.walk(self.dir):\n            for name in files:\n                if root == self.dir:\n                    dest = name\n                else:\n                    #raise Exception(\"self : {}, dst : {}\".format(self.dir, root[len(self.dir)+1:]))\n                    dest = os.path.join(root[len(self.dir) + 1:], name)\n                result.append(dest)\n            for name in dirs:\n                if root == self.dir:\n                    dest = name\n                    result.append(dest)\n                else:\n                    dest = os.path.join(root[len(self.dir) + 1:], name)\n                result.append(dest)\n        result = list(set(result))\n        result.sort()\n        return result\n\n    def zip(self, output_filename):\n        zf = zipfile.ZipFile(output_filename, 'w')\n        for filename in self.files():\n            zf.write(os.path.join(self.dir, filename), filename)\n        zf.close()\n\n\n    def delete(self):\n        try:\n            shutil.rmtree(self.dir)\n        except:\n            pass\n\n    def rewrite_python_dist_info_record(self):\n        # pylint: disable=unused-variable\n        for root, dirs, files in os.walk(self.dir):\n            for f in files:\n                if f == 'RECORD':\n                    #raise Exception('record filename: {}'.format(f))\n                    if root.endswith('.dist-info'):\n                        fpath = os.path.join(root, f)\n                        with open(fpath, 'r') as rf:\n                            lines = sorted(rf.readlines())\n                        self.add_file_string(fpath, os.linesep.join(lines))\n\n\n    def clean_pycache(self):\n        # pylint: disable=unused-variable\n        for root, dirs, files in os.walk(self.dir):\n            for dir in dirs:\n                if dir == '__pycache__':\n                    shutil.rmtree(os.path.join(root,dir))\n                    self.fix_time(root)\n\n    def clean_setup_tool(self):\n        # pylint: disable=unused-variable\n        for root, dirs, files in os.walk(self.dir):\n            for dir in dirs:\n                if dir.startswith('setuptools'):\n                    shutil.rmtree(os.path.join(root,dir))\n                    self.fix_time(root)\n\nclass SandboxMtimeDecorator:\n    '''A decorator for Sandbox which sets all files newly created by some command to `mtime'.'''\n\n    def __init__(self, sb, mtime):\n        self.sb = sb\n        self.mtime = mtime\n        # use fixed time, avoid scenario, if we clone lamba source repo, the requirements mtime will change\n        # though nothing may be changed\n        #self.mtime = sb.FILE_STRING_MTIME\n        self.before_files = set(self.sb.files())\n\n    def __getattr__(self, name):\n        return getattr(self.sb, name)\n\n    def run_command(self, cmd):\n        self.sb.run_command(cmd)\n        all_paths =[]\n        for filename in set(self.sb.files()).difference(self.before_files):\n            if os.path.exists(os.path.join(self.sb.dir, filename)):\n                all_paths.append(os.path.join(self.sb.dir, filename))\n\n        #sort the path so parent timestamp not changed after children\n        sorted_paths =sorted(all_paths, key=lambda p : p.count(os.path.sep), reverse=True)\n        for path in sorted_paths:\n            os.utime(path,(self.mtime, self.mtime))\n\n\nclass RequirementsCollector:\n    def __init__(self, code):\n        self.code = code\n\n    def _source_path(self):\n        return os.path.join(os.getcwd(), os.path.dirname(self.code))\n\n    def _source_requirements_file(self):\n        # pylint: disable=no-member\n        return os.path.join(self._source_path(), self._requirements_file())\n\n    def _requirements_mtime(self):\n        return os.stat(self._source_requirements_file()).st_mtime\n\n    @staticmethod\n    def collector(code):\n        code_type = os.path.splitext(code)[1]\n        if code_type == '.py':\n            return PythonRequirementsCollector(code)\n        elif code_type == '.js':\n            return NodeRequirementsCollector(code)\n        elif code_type == '.rb':\n            return RubyRequirementsCollector(code)\n        else:\n            raise Exception(\"Unknown code type '{}'\".format(code_type))\n\n\nclass PythonRequirementsCollector(RequirementsCollector):\n    def _requirements_file(self):\n        return 'requirements.txt'\n\n    def collect(self, sb):\n        requirements_file = self._source_requirements_file()\n        if not os.path.isfile(requirements_file):\n            return\n        mtime = self._requirements_mtime()\n        sb.add_file_string('setup.cfg', \"[install]\\nprefix=\\n\")\n        sbm = SandboxMtimeDecorator(sb, mtime)\n        # before files initialized\n        sbm.run_command(\n            'pip3 install -r {} -t {}/ >/dev/null'.format(requirements_file, sb.dir))\n\n        # set time.time() result to a fixed time\n        sbm.run_command(\n            'python -c \\'import time, compileall; time.time = lambda: {}; compileall.compile_dir(\".\", force=True)\\' >/dev/null'.format(sb.FILE_STRING_MTIME))\n\n        sb.rewrite_python_dist_info_record()\n        #remove setup tools, not needed\n        sb.clean_setup_tool()\n\n\nclass NodeRequirementsCollector(RequirementsCollector):\n    def _requirements_file(self):\n        return 'package.json'\n\n    def collect(self, sb):\n        requirements_file = self._source_requirements_file()\n        if not os.path.isfile(requirements_file):\n            return\n        sb.import_path(self._source_requirements_file())\n        sbm = SandboxMtimeDecorator(sb, self._requirements_mtime())\n        sbm.run_command('npm install --production >/dev/null 2>&1')\n        for filename in sbm.files():\n            if not filename.endswith('package.json'):\n                continue\n            full_path = os.path.join(sbm.dir, filename)\n            mtime = os.stat(full_path).st_mtime\n            with open(full_path, 'rb') as f:\n                contents = f.read()\n            contents = contents.replace(sb.dir.encode('utf-8'), '/tmp/lambda-package'.encode('utf-8'))\n            with open(full_path, 'wb') as f:\n                f.write(contents)\n            os.utime(full_path, (mtime, mtime))\n\nclass RubyRequirementsCollector(RequirementsCollector):\n    def _requirements_file(self):\n        return 'Gemfile'\n\n    def collect(self, sb):\n        requirements_file = self._source_requirements_file()\n        if not os.path.isfile(requirements_file):\n            return\n        sb.import_path(self._source_requirements_file())\n        sbm = SandboxMtimeDecorator(sb, self._requirements_mtime())\n        sbm.run_command('mkdir vendor')\n        sbm.run_command('rbenv exec bundle install --path vendor/bundle --deployment')\n        for filename in sbm.files():\n            if not filename.endswith('Gemfile'):\n                continue\n            full_path = os.path.join(sbm.dir, filename)\n            mtime = os.stat(full_path).st_mtime\n            with open(full_path, 'rb') as f:\n                contents = f.read()\n            contents = contents.replace(sb.dir.encode('utf-8'), '/tmp/lambda-package'.encode('utf-8'))\n            with open(full_path, 'wb') as f:\n                f.write(contents)\n            os.utime(full_path, (mtime, mtime))\n\nclass Packager:\n    def __init__(self, input_values):\n        self.input = input_values\n        self.code = self.input[\"code\"]\n        self.extra_files = []\n\n        if len(self.input.get('extra_files', '')) > 0:\n            self.extra_files = self.input['extra_files'].split(',')\n\n    def output_filename(self):\n        if self.input.get('output_filename', '') != '':\n            return self.input['output_filename']\n        return os.path.splitext(self.code)[0] + \".zip\"\n\n    def paths_to_import(self):\n        yield self.code\n        source_dir = os.path.dirname(self.code)\n        for extra_file in self.extra_files:\n            yield os.path.join(source_dir, extra_file)\n\n    def package(self):\n        sb = Sandbox()\n        for path in self.paths_to_import():\n            sb.import_path(path)\n        RequirementsCollector.collector(self.code).collect(sb)\n        sb.zip(self.output_filename())\n        sb.delete()\n\n    def output_base64sha256(self):\n        sha256 = hashlib.sha256()\n        with open(self.output_filename(), 'rb') as f:\n            sha256.update(f.read())\n        hash_b64= base64.b64encode(sha256.digest()).decode('utf-8')\n        return hash_b64\n\n    def output(self):\n        return {\n            \"code\": self.code,\n            \"output_filename\": self.output_filename(),\n            \"output_base64sha256\": self.output_base64sha256()\n        }\n\n\ndef main():\n    packager = Packager(json.load(sys.stdin))\n    packager.package()\n    json.dump(packager.output(), sys.stdout)\n\n\nif __name__ == '__main__':\n    main()\n", "repo_name": "kanithehandsome/terraform-package-lambda", "sub_path": "packager.py", "file_name": "packager.py", "file_ext": "py", "file_size_in_byte": 10071, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "github-code", "pt": "21", "api": [{"api_name": "tempfile.mkdtemp", "line_number": 29, "usage_type": "call"}, {"api_name": "os.getcwd", "line_number": 32, "usage_type": "call"}, {"api_name": "os.chdir", "line_number": 33, "usage_type": "call"}, {"api_name": "os.system", "line_number": 34, "usage_type": "call"}, {"api_name": "os.chdir", "line_number": 35, "usage_type": "call"}, {"api_name": "os.path.isdir", "line_number": 39, "usage_type": "call"}, {"api_name": "os.path", "line_number": 39, "usage_type": "attribute"}, {"api_name": "shutil.copytree", "line_number": 40, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 40, "usage_type": "call"}, {"api_name": "os.path", "line_number": 40, "usage_type": "attribute"}, {"api_name": "os.path.basename", "line_number": 41, "usage_type": "call"}, {"api_name": "os.path", "line_number": 41, "usage_type": "attribute"}, {"api_name": "shutil.copy2", "line_number": 43, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 46, "usage_type": "call"}, {"api_name": "os.path", "line_number": 46, "usage_type": "attribute"}, {"api_name": "os.utime", "line_number": 49, "usage_type": "call"}, {"api_name": "os.utime", "line_number": 52, "usage_type": "call"}, {"api_name": "os.walk", "line_number": 56, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 62, "usage_type": "call"}, {"api_name": "os.path", "line_number": 62, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 69, "usage_type": "call"}, {"api_name": "os.path", "line_number": 69, "usage_type": "attribute"}, {"api_name": "zipfile.ZipFile", "line_number": 76, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 78, "usage_type": "call"}, {"api_name": "os.path", "line_number": 78, "usage_type": "attribute"}, {"api_name": "shutil.rmtree", "line_number": 84, "usage_type": "call"}, {"api_name": "os.walk", "line_number": 90, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 95, "usage_type": "call"}, {"api_name": "os.path", "line_number": 95, "usage_type": "attribute"}, {"api_name": "os.linesep.join", "line_number": 98, "usage_type": "call"}, {"api_name": "os.linesep", "line_number": 98, "usage_type": "attribute"}, {"api_name": "os.walk", "line_number": 103, "usage_type": "call"}, {"api_name": "shutil.rmtree", "line_number": 106, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 106, "usage_type": "call"}, {"api_name": "os.path", "line_number": 106, "usage_type": "attribute"}, {"api_name": "os.walk", "line_number": 111, "usage_type": "call"}, {"api_name": "shutil.rmtree", "line_number": 114, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 114, "usage_type": "call"}, {"api_name": "os.path", "line_number": 114, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 135, "usage_type": "call"}, {"api_name": "os.path", "line_number": 135, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 135, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 136, "usage_type": "call"}, {"api_name": "os.path", "line_number": 136, "usage_type": "attribute"}, {"api_name": "os.path", "line_number": 139, "usage_type": "attribute"}, {"api_name": "os.utime", "line_number": 141, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 149, "usage_type": "call"}, {"api_name": "os.path", "line_number": 149, "usage_type": "attribute"}, {"api_name": "os.getcwd", "line_number": 149, "usage_type": "call"}, {"api_name": "os.path.dirname", "line_number": 149, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 153, "usage_type": "call"}, {"api_name": "os.path", "line_number": 153, "usage_type": "attribute"}, {"api_name": "os.stat", "line_number": 156, "usage_type": "call"}, {"api_name": "os.path.splitext", "line_number": 160, "usage_type": "call"}, {"api_name": "os.path", "line_number": 160, "usage_type": "attribute"}, {"api_name": "os.path.isfile", "line_number": 177, "usage_type": "call"}, {"api_name": "os.path", "line_number": 177, "usage_type": "attribute"}, {"api_name": "os.path.isfile", "line_number": 201, "usage_type": "call"}, {"api_name": "os.path", "line_number": 201, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 209, "usage_type": "call"}, {"api_name": "os.path", "line_number": 209, "usage_type": "attribute"}, {"api_name": "os.stat", "line_number": 210, "usage_type": "call"}, {"api_name": "os.utime", "line_number": 216, "usage_type": "call"}, {"api_name": "os.path.isfile", "line_number": 224, "usage_type": "call"}, {"api_name": "os.path", "line_number": 224, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 233, "usage_type": "call"}, {"api_name": "os.path", "line_number": 233, "usage_type": "attribute"}, {"api_name": "os.stat", "line_number": 234, "usage_type": "call"}, {"api_name": "os.utime", "line_number": 240, "usage_type": "call"}, {"api_name": "os.path.splitext", "line_number": 254, "usage_type": "call"}, {"api_name": "os.path", "line_number": 254, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 258, "usage_type": "call"}, {"api_name": "os.path", "line_number": 258, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 260, "usage_type": "call"}, {"api_name": "os.path", "line_number": 260, "usage_type": "attribute"}, {"api_name": "hashlib.sha256", "line_number": 271, "usage_type": "call"}, {"api_name": "base64.b64encode", "line_number": 274, "usage_type": "call"}, {"api_name": "json.load", "line_number": 286, "usage_type": "call"}, {"api_name": "sys.stdin", "line_number": 286, "usage_type": "attribute"}, {"api_name": "json.dump", "line_number": 288, "usage_type": "call"}, {"api_name": "sys.stdout", "line_number": 288, "usage_type": "attribute"}]}
+{"seq_id": "11246807091", "text": "import copy\r\nfrom typing import Any, Callable, Dict, Iterable, List, TypeVar\r\n\r\nfrom ..typing import DEFAULT_LIFECYCLE_NAMES, T_Dispatcher\r\n\r\nT = TypeVar(\"T\")\r\nI = TypeVar(\"I\")\r\n\r\nLF_TEMPLATE = {i: list() for i in DEFAULT_LIFECYCLE_NAMES}\r\n\r\n\r\nclass DII_NestableIterable:\r\n    iterable: List\r\n    indexes: List\r\n\r\n    def __init__(self, iterable: List) -> None:\r\n        self.iterable = iterable\r\n        self.indexes = [[0, 0]]\r\n\r\n    def __iter__(self):\r\n        dis_set_index, dis_index = self.indexes[-1]\r\n        dis_set_index_offset = dis_set_index + bool(dis_set_index)\r\n        dis_index_offset = dis_index + bool(dis_index)\r\n\r\n        current_indexes = [dis_set_index_offset, dis_index_offset]\r\n        self.indexes.append(current_indexes)\r\n\r\n        for content in self.iterable[dis_set_index_offset:]:\r\n            for i in content[dis_index_offset:]:\r\n                yield i\r\n                current_indexes[1] += 1\r\n            current_indexes[0] += 1\r\n\r\n        self.indexes.pop()\r\n\r\n\r\nclass ExecutionContext:\r\n    __slots__ = {\"event\", \"_index\", \"lifecycle_refs\", \"dispatchers\"}\r\n\r\n    _index: int\r\n    lifecycle_refs: Dict[str, List[Callable]]\r\n    dispatchers: List[T_Dispatcher]\r\n\r\n    def __init__(self, dispatchers: List[T_Dispatcher]) -> None:\r\n        self._index = 0\r\n        self.dispatchers = dispatchers\r\n\r\n        self.lifecycle_refs = {i: [] for i in DEFAULT_LIFECYCLE_NAMES}\r\n\r\n\r\nclass ParameterContext:\r\n    __slots__ = {\"name\", \"annotation\", \"default\", \"dispatchers\", \"path\"}\r\n\r\n    name: str\r\n    annotation: Any\r\n    default: Any\r\n\r\n    dispatchers: List[T_Dispatcher]\r\n\r\n    def __init__(self, name, annotation, default, dispatchers, using_path) -> None:\r\n        self.name = name\r\n        self.annotation = annotation\r\n        self.default = default\r\n        self.dispatchers = dispatchers\r\n        self.path = DII_NestableIterable(using_path)\r\n\r\n    def __repr__(self) -> str:\r\n        return (\r\n            \"len(background):\n            continue\n        delta = len(background) / (ngroup + 1)\n        x=id_group * delta + np.random.randint(delta)\n        if x-tot_size > len(background):\n            continue\n\n        pos = int(x)\n\n        for start,size,end,add_end,clean,orientation,length_increase,hsi,hei in zip(starts_w,sizes_w,ends_w,add_ends,cleans,orientations,length_increases,hs,he):\n            #print(clean)\n            #print(start,size,end,add_end,clean,orientation,length_increase,h)\n            new_gene =  generate_gene_signal(w=[start,size,end],h=[hsi,hei],\n                                                                       end=add_end,clean=clean,\n                                                                       orientation=orientation,\n                                                                      length_increase=length_increase)\n            if len(new_gene) == len( background[pos:pos+start+size+end]):\n                background [pos:pos+start+size+end] = new_gene\n\n\n            plus = np.random.poisson(30,1)[0]\n            if np.random.randint(0,10,1)[0] == 0:\n                plus = np.random.randint(1,2)\n            pos = int(pos +plus)\n\n    #Large bump\n    for i in np.random.randint(31,len(background)-31,15):\n        #print(i)\n        size = np.random.randint(20,30)\n        #print(\"Adding\")\n        new_gene = signal_shape_gauss(2*size) * 4*np.mean(background) *np.random.rand()\n        if len(new_gene) == len(background[i-size:i+size]):\n            background[i-size:i+size] *= new_gene\n    print(\"End\",np.sum(background))\n    return background", "repo_name": "organic-chemistry/repli1D", "sub_path": "src/repli1d/profile_generation.py", "file_name": "profile_generation.py", "file_ext": "py", "file_size_in_byte": 4749, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "21", "api": [{"api_name": "sklearn.gaussian_process.kernels.RBF", "line_number": 11, "usage_type": "call"}, {"api_name": "numpy.linspace", "line_number": 13, "usage_type": "call"}, {"api_name": "sklearn.gaussian_process.GaussianProcessRegressor", "line_number": 15, "usage_type": "call"}, {"api_name": "numpy.newaxis", "line_number": 16, "usage_type": "attribute"}, {"api_name": "numpy.newaxis", "line_number": 18, "usage_type": "attribute"}, {"api_name": "scipy.interpolate.interp1d", "line_number": 24, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 25, "usage_type": "call"}, {"api_name": "numpy.min", "line_number": 27, "usage_type": "call"}, {"api_name": "scipy.signal.gaussian", "line_number": 35, "usage_type": "call"}, {"api_name": "scipy.signal", "line_number": 35, "usage_type": "name"}, {"api_name": "numpy.max", "line_number": 37, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 44, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 44, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 49, "usage_type": "call"}, {"api_name": "numpy.float", "line_number": 49, "usage_type": "attribute"}, {"api_name": "numpy.arange", "line_number": 59, "usage_type": "call"}, {"api_name": "numpy.exp", "line_number": 60, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 74, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 77, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 78, "usage_type": "call"}, {"api_name": "numpy.random.poisson", "line_number": 78, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 78, "usage_type": "attribute"}, {"api_name": "numpy.random.randint", "line_number": 78, "usage_type": "call"}, {"api_name": "numpy.random.choice", "line_number": 80, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 80, "usage_type": "attribute"}, {"api_name": "numpy.random.poisson", "line_number": 81, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 81, "usage_type": "attribute"}, {"api_name": "numpy.random.poisson", "line_number": 82, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 82, "usage_type": "attribute"}, {"api_name": "numpy.random.poisson", "line_number": 83, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 83, "usage_type": "attribute"}, {"api_name": "numpy.random.randint", "line_number": 84, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 84, "usage_type": "attribute"}, {"api_name": "numpy.random.randint", "line_number": 85, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 85, "usage_type": "attribute"}, {"api_name": "numpy.random.randint", "line_number": 86, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 86, "usage_type": "attribute"}, {"api_name": "numpy.random.poisson", "line_number": 87, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 87, "usage_type": "attribute"}, {"api_name": "numpy.random.poisson", "line_number": 88, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 88, "usage_type": "attribute"}, {"api_name": "numpy.random.poisson", "line_number": 89, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 89, "usage_type": "attribute"}, {"api_name": "numpy.sum", "line_number": 94, "usage_type": "call"}, {"api_name": "numpy.random.rand", "line_number": 95, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 95, "usage_type": "attribute"}, {"api_name": "numpy.random.randint", "line_number": 102, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 102, "usage_type": "attribute"}, {"api_name": "numpy.random.poisson", "line_number": 119, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 119, "usage_type": "attribute"}, {"api_name": "numpy.random.randint", "line_number": 120, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 120, "usage_type": "attribute"}, {"api_name": "numpy.random.randint", "line_number": 121, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 121, "usage_type": "attribute"}, {"api_name": "numpy.random.randint", "line_number": 125, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 125, "usage_type": "attribute"}, {"api_name": "numpy.random.randint", "line_number": 127, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 127, "usage_type": "attribute"}, {"api_name": "numpy.mean", "line_number": 129, "usage_type": "call"}, {"api_name": "numpy.random.rand", "line_number": 129, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 129, "usage_type": "attribute"}, {"api_name": "numpy.sum", "line_number": 132, "usage_type": "call"}]}
+{"seq_id": "74906291893", "text": "import tkinter as tk\nfrom tkinter.filedialog import asksaveasfile\nimport numpy as np\nfrom tkinter import *\nimport random\nfrom timer import Timer\nfrom fits import FitsLaw\nimport math\nimport datetime\n\nTODAY_DATE = datetime.datetime.today().strftime(\"%d-%m-%Y-%H-%M\")\nprint(TODAY_DATE)\n\nmovement_log = open(f\"movement_log_{TODAY_DATE}\" + \".txt\", \"w\")\n \nstats_log = open(f\"stats_log_{TODAY_DATE}.csv\", \"w\")\nstats_log.write(\"Time, Click X, Click Y, Target X, Target Y, Target Number, Distance to TargetX, Distance to TargetY, Select X, Select Y, From X, From Y\\n\")\n\nstats2_log = open(f\"stats2_log_{TODAY_DATE}.txt\", \"w\")\n\nruns_log = open(f\"runs_log_{TODAY_DATE}.csv\", \"w\")\nruns_log.write(\"Run, Throughput, Ballistic Time, Select Time, Number of Targets\\n\")\n\n# Create a dictionary of gestures and their corresponding numbers\nthroughputs = {\"Gesture 1\": [],  \"Gesture 2\": [], \"Gesture 3\": []}\nballistics = {\"Gesture 1\": [], \"Gesture 2\": [], \"Gesture 3\": []}\nselects = {\"Gesture 1\": [],  \"Gesture 2\": [], \"Gesture 3\": []}\n\ntimer = Timer()\ntimer2 = Timer()    \n\nglobal fits\nfits = None\nselection_coordinates = []\n\nwindow = tk.Tk()\nwindow.title(\"Testing GUI\")\n'''window.attributes('-fullscreen',True)\nwidth = window.winfo_width()\nheight = window.winfo_height()'''\n\nwidth = 1500\nheight = 800\n\n\n\ntargets = 0\nblock = 0\ntrial = 0\n\nTRIALS = 5\nBLOCKS = 3\n\nbuttons_d = []\n\ndef distance(x1, y1, x2, y2):\n    return ((x1-x2)**2 + (y1-y2)**2)**0.5\n\ndef pause(event):\n    print(\"Paused\")\n    timer.pause()\n    timer2.pause()\n    stats2_log.write(f\"Pause\\n\")\n    stats_log.write(f\"Pause\\n\")\n\n    pause_button.config(text=\"Paused!\")\n\n\ndef continue_timer(event):\n    print(\"Continued\")\n    timer.continue_timer()\n    timer2.continue_timer()\n    continue_button.config(text=\"Continuing...\")\n\ndef change_gesture():\n    runs_log.write(f\"Change Gesture\\n\")\n    stats2_log.write(f\"Change Gesture\\n\")\n    stats_log.write(f\"Change Gesture\\n\")\n\n    change_gesture_button.config(text=\"Changed!\")\n\n\n\ndef remove_button(event, button_id):\n    global targets\n\n    print(\"This is the button id: \", button_id)\n    '''if buttons_d[targets] != event.widget: # Can't click on this button\n        return'''\n    \n    # Write click to movement log\n    x,y = window.winfo_pointerx(), window.winfo_pointery()\n    movement_log.write(\n        f\"Click at ({x}, {y}) target {targets}. Time: {timer.get_elapsed()}\\n\")\n\n    checkpoint = timer.stop()\n    timer.start()\n    print(\"checkpoint:\", checkpoint)\n    \n    click_checkpoint = timer2.get_elapsed()\n    timer2.start()\n    #print(click_checkpoint)\n    fits.time_to_select += [click_checkpoint]\n    \n    \n    stats2_log.write(f\"Select: {button_id}, {x}, {y}, {click_checkpoint}, {fits.f}\\n\")\n\n    fits.to = event.widget.winfo_rootx(), event.widget.winfo_rooty()\n    fits.select = x,y\n\n    # write stats to stats log\n    stats_log.write(  # Time, Click X, Click Y, Target X, Target Y, Target Number, Distance to TargetX, Distance to TargetY, Select X, Select Y, From X, From Y, Select time, Ballistic Time\n        f\"{checkpoint}, {x}, {y}, {event.widget.winfo_rootx()}, {event.widget.winfo_rooty()}, {button_id}, {fits.to[0]}, {fits.to[1]}, {fits.select[0]}, {fits.select[1]}, {fits.f[0]}, {fits.f[1]}\\n\")\n\n\n    fits.update()\n    fits.f = x,y\n    fits.times += [checkpoint]\n\n    targets += 1\n\n    if targets == 10:\n        global trial\n        trial += 1\n        event.widget.place_forget()\n        reset(None, True)\n\n\n    event.widget.place_forget()\n\ndef place_directional_targets():\n\n    top_left_corner = (width//2 , height//2 )\n    print(\"top left corner: \", top_left_corner)\n    # place button in top left corner\n    button.place(x=top_left_corner[0], y=top_left_corner[1], anchor=\"center\")\n    \n    newbutton = tk.Button(window, text=\"New\", width=10, height=2, highlightbackground='red', bg='green', fg=\"black\", font=(\"Arial\", 20))\n\n    # Places 3 buttons in a circle around the center of the screen 200 pixels away at 45 degree intervals\n    arc = 0\n    for i in range(3):\n        arc += 45\n        x = top_left_corner[0] + 200*math.cos(math.radians(arc))\n        y = top_left_corner[1] + 200*math.sin(math.radians(arc))\n        print(\"new x: \", x, \"new y: \", y)\n\n        newbutton = tk.Button(window, text=\"New\", width=8, height=2, highlightbackground='red', bg='green', fg=\"black\", font=(\"Arial\", 20))\n        newbutton.bind(\"<1>\", remove_button)\n        newbutton.place(x=x, y=y, anchor=\"center\")\n\n\n    \ndef place_simple_targets():\n    x = 0\n    for j in [2,4]:\n        for i in range(1,10,2):\n            target = tk.Button(window, text=f\"Target {x+1}\", width=8, height=2, highlightbackground='gray', bg=\"gray\", fg=\"black\", font=(\"Arial\", 15))\n            buttons_d[x] = target\n            target.place(x=100*i, y=100*j, anchor=\"center\")\n            target.bind(\"<1>\", remove_button)\n            target.bind(\"\", mouseover)\n            x+=1\n\ndef place_circle_targets():\n    # Place 10 targets in a circle around the center of the screen\n    global buttons_d\n\n    for i in range(10):\n        arc = i*36\n        x = width//2+70 + 350*math.cos(math.radians(arc))\n        y = height//2 + 350*math.sin(math.radians(arc))\n\n        target = tk.Button(window, text=f\"Target {i+1}\", width=12, height=4, highlightbackground='gray', bg=\"gray\", fg=\"black\", font=(\"Arial\", 16))\n        buttons_d += [target]\n        target.place(x=x, y=y, anchor=\"center\")\n        target.bind(\"<1>\", lambda event, id=i: remove_button(event, id))\n        target.bind(\"\", lambda event, id=i: mouseover(event, id))\n\n\n    # place a pause button in the top left of the screen\n    pause_button.place(x=100, y=50, anchor=\"center\")\n\n    \n\n    # place a continue button next to the pause button\n    continue_button.place(x=200, y=50, anchor=\"center\")\n\n\n    \ndef increase_size():\n    width = button.winfo_width()\n    height = button.winfo_height()\n    button.config(width=width+1, height=height+1)\n\ndef decrease_size():\n    button.config(width=button.winfo_width()-1, height=button.winfo_height()-1)\n\ndef start_test():\n    global targets\n    targets = 0\n\n    timer.start()\n    timer2.start()\n\n    throughput_label.place_forget()\n    ballistic_time_label.place_forget()\n    select_time_label.place_forget()\n    start_button.place_forget()\n    instructions.place_forget()\n    change_gesture_button.place_forget()\n\n\n    # Get cursor's current x and y coordinates\n    x,y = window.winfo_pointerx(), window.winfo_pointery()\n    dist = distance(x, y, width//2, 50)\n    global fits\n    fits = FitsLaw(8, dist)\n    fits.f = (x,y)\n    \n    place_circle_targets()\n\ndef reset(event, remove_buttons=False):\n        global throughputs, ballistics, selects, gestures, trial, block, buttons_d, targets\n\n        if remove_buttons:\n            print(\"removing buttons\")\n            for button in buttons_d:\n                button.place_forget()\n            buttons_d.clear()\n            \n                \n        button.place_forget()\n        start_button.place(x=width//2, y=height//2+75, anchor=\"center\")\n\n        \"\"\"Show how many trials left in this block\n        instructions.config(text=f\"Trial {trial} of {TRIALS} for this gesture\")\n        instructions.place(x=width//2, y=height//2-75, anchor=\"center\")\"\"\"\n\n    \n        stats = fits.get_average_times()\n        throughput = fits.calculate_modified_law(timer.stop())\n        timer.start()\n\n        current_gesture = \"Gesture \" + str(block+1)\n        throughputs[current_gesture] += [throughput]\n        ballistics[current_gesture] += [stats[0]]\n        selects[current_gesture] += [stats[1]]\n\n        # Write to runs log\n        runs_log.write(f\"{trial+1}, {throughput}, {stats[0]}, {stats[1]}, {targets}\\n\")\n\n        \n        ''' if trial == TRIALS: \n                trial = 0\n                block += 1\n        '''\n\n        average_throughput = np.mean(throughputs[current_gesture])\n        average_ballistic = np.mean(ballistics[current_gesture])\n        average_select = np.mean(selects[current_gesture])\n        print(average_throughput, average_ballistic, average_select)\n\n        throughput_label.config(text=f\"Throughput: {round(average_throughput,2)}\")\n        ballistic_time_label.config(text=f\"Average time to get to target: {round(average_ballistic,2)} s\")\n        select_time_label.config(text=f\"Average time to select target: {round(average_select,2)} s\")\n\n        throughput_label.place(x=width//2, y=height//2-145, anchor=\"center\")\n        ballistic_time_label.place(x=width//2, y=height//2-100, anchor=\"center\")\n        select_time_label.place(x=width//2, y=height//2-60, anchor=\"center\")\n\n        change_gesture_button.config(text=f\"Change gesture\")\n        change_gesture_button.place(\n            x=width//2, y=height//2+150, anchor=\"center\")\n\n\n            \n\n        \"\"\"if block == BLOCKS: # Finished all blocks\n            finished_label = tk.Label(window, text=\"Test Complete\", font=(\"Helvetica\", 18))\n            finished_label.place(x=width//2, y=height//2-150, anchor=\"center\")\n\n            gesture_label.place_forget()\n\n            results_file = asksaveasfile(mode='w', defaultextension=\".csv\")\n    \n            with results_file as f:\n                f.write(\"Gesture, Throughput, Ballistic Time, Select Time\\n\")\n                for block in range(BLOCKS):\n                    gesture_name = \"Gesture \" + str(block+1)\n                    f.write(f\"{gesture_name}, {round(np.mean(throughputs[gesture_name]),2)}, {round(np.mean(ballistics[gesture_name]),2)}, {round(np.mean(selects[gesture_name]),2)}\\n\")\n                  \"\"\"\n                  \n                  \n\nbutton = tk.Button(window, text=\"Target\", width=8, height=2, highlightbackground='#3E4149', fg=\"white\", font=(\"Arial\", 15))\n\nstart_button = tk.Button(window, text=\"Start\", width=10, height=2, highlightbackground='red', bg='red', fg=\"white\", font=(\"Arial\", 20),command=start_test)\nstart_button.place(x=width//2, y=height//2+75, anchor=\"center\")\n\npause_button = tk.Button(window, text=\"Pause\", width=8, height=2, highlightbackground='red', bg='blue', fg=\"white\", font=(\"Arial\", 15))\npause_button.bind(\"<1>\", pause)\npause_button.bind(\"p\", pause)\n\n\ncontinue_button = tk.Button(window, text=\"Continue\", width=6, height=2, highlightbackground='red', bg='green', fg=\"white\", font=(\"Arial\", 15))\ncontinue_button.bind(\"<1>\", continue_timer)\ncontinue_button.bind('c', continue_timer)\n\n#Create label\ninstructions = tk.Label(window, text=\"Click the start button below to start\", font=(\"Helvetica\", 18))\ninstructions.place(x=width//2, y=height//2-75, anchor=\"center\")\n\nthroughput_label = tk.Label(window, font=(\"Helvetica\", 22))\nballistic_time_label = tk.Label(window, font=(\"Helvetica\", 18))\nselect_time_label    = tk.Label(window, font=(\"Helvetica\", 18))\n\nchange_gesture_button = tk.Button(window, text=\"Change Gesture\", width=20, height=2, highlightbackground='red', bg='pink', fg=\"black\", font=(\"Arial\", 20), command=change_gesture)\nchange_gesture_button.place(x=width//2, y=height//2+170, anchor=\"center\")\n\n# button to reset in the top right corner\nreset_button = tk.Button(window, text=\"Reset\", width=8, height=2, highlightbackground='red', bg='red', fg=\"white\", font=(\"Arial\", 20), command=lambda : reset(None, True))\nreset_button.place(x=width-20, y=0, anchor=\"ne\")\n\ndef mouseover(event, button_id):\n    if event.widget == buttons_d[targets]:\n        enter_checkpoint = timer2.stop()\n        timer2.start()\n        fits.ballistic_times += [enter_checkpoint]\n        # get x and y coordinates of event\n        x,y = event.x, event.y\n        # write to stats2 log the button that was clicked and the x and y coordinates of the mouse and the ballistics time\n        stats2_log.write(f\"Ballistic: {button_id}, {x}, {y}, {enter_checkpoint}\\n\")\n        \n\n\ndef key(event):\n    window.event_generate('', warp=True, x=width//2, y=height//2)\n\n\ndef motion(event):\n    x, y = event.x, event.y\n    movement_log.write(f\"{x}, {y}\\n\")\n\nwindow.bind('', motion)\n\nwindow.bind('', key)\n# Bind the reset funtion to clicking q\nbutton.bind(\"\", mouseover)\n\n'''window.bind('

', lambda event: pause(event))\nwindow.bind('', lambda event: continue_timer(event))'''\n\nwindow.geometry(f'{width}x{height}')\nwindow.mainloop()\nstats_log.close()\nruns_log.close()\nmovement_log.close()\n", "repo_name": "Farid-Karimli/MouseTestingGUI", "sub_path": "gui.py", "file_name": "gui.py", "file_ext": "py", "file_size_in_byte": 12194, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "21", "api": [{"api_name": "datetime.datetime.today", "line_number": 11, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 11, "usage_type": "attribute"}, {"api_name": "timer.Timer", "line_number": 29, "usage_type": "call"}, {"api_name": "timer.Timer", "line_number": 30, "usage_type": "call"}, {"api_name": "tkinter.Tk", "line_number": 36, "usage_type": "call"}, {"api_name": "timer.pause", "line_number": 61, "usage_type": "call"}, {"api_name": "timer.continue_timer", "line_number": 71, "usage_type": "call"}, {"api_name": "timer.get_elapsed", "line_number": 94, "usage_type": "call"}, {"api_name": "timer.stop", "line_number": 96, "usage_type": "call"}, {"api_name": "timer.start", "line_number": 97, "usage_type": "call"}, {"api_name": "fits.time_to_select", "line_number": 103, "usage_type": "attribute"}, {"api_name": "fits.f", "line_number": 106, "usage_type": "attribute"}, {"api_name": "fits.to", "line_number": 108, "usage_type": "attribute"}, {"api_name": "fits.select", "line_number": 109, "usage_type": "attribute"}, {"api_name": "fits.to", "line_number": 113, "usage_type": "attribute"}, {"api_name": "fits.select", "line_number": 113, "usage_type": "attribute"}, {"api_name": "fits.f", "line_number": 113, "usage_type": "attribute"}, {"api_name": "fits.update", "line_number": 116, "usage_type": "call"}, {"api_name": "fits.f", "line_number": 117, "usage_type": "attribute"}, {"api_name": "fits.times", "line_number": 118, "usage_type": "attribute"}, {"api_name": "tkinter.Button", "line_number": 138, "usage_type": "call"}, {"api_name": "math.cos", "line_number": 144, "usage_type": "call"}, {"api_name": "math.radians", "line_number": 144, "usage_type": "call"}, {"api_name": "math.sin", "line_number": 145, "usage_type": "call"}, {"api_name": "math.radians", "line_number": 145, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 148, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 158, "usage_type": "call"}, {"api_name": "math.cos", "line_number": 171, "usage_type": "call"}, {"api_name": "math.radians", "line_number": 171, "usage_type": "call"}, {"api_name": "math.sin", "line_number": 172, "usage_type": "call"}, {"api_name": "math.radians", "line_number": 172, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 174, "usage_type": "call"}, {"api_name": "timer.start", "line_number": 203, "usage_type": "call"}, {"api_name": "fits.FitsLaw", "line_number": 218, "usage_type": "call"}, {"api_name": "fits.f", "line_number": 219, "usage_type": "attribute"}, {"api_name": "fits.get_average_times", "line_number": 241, "usage_type": "call"}, {"api_name": "fits.calculate_modified_law", "line_number": 242, "usage_type": "call"}, {"api_name": "timer.stop", "line_number": 242, "usage_type": "call"}, {"api_name": "timer.start", "line_number": 243, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 259, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 260, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 261, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 296, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 298, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 301, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 306, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 311, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 314, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 315, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 316, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 318, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 322, "usage_type": "call"}, {"api_name": "fits.ballistic_times", "line_number": 329, "usage_type": "attribute"}]} +{"seq_id": "70486241334", "text": "from collections import defaultdict\nfrom pprint import pprint\nfrom typing import List\nimport csv\nfrom concurrent.futures import ThreadPoolExecutor\nimport argparse\nimport os\n\nimport numpy as np\nimport openreview\nfrom tqdm import tqdm\n\nfrom utils import try_except\n\nparser = argparse.ArgumentParser(description='ICLR AC Statistics')\nparser.add_argument('--username', type=str, help=\"User's e-mail\")\nparser.add_argument('--password', type=str, help=\"User's password\")\nargs = parser.parse_args()\n\n# add credentials\nCLIENT = openreview.Client(baseurl='https://api.openreview.net',\n username=args.username,\n password=args.password)\n\nsubmissions = list(openreview.tools.iterget_notes(CLIENT, invitation='ICLR.cc/2021/Conference/-/Blind_Submission'))\nsubmissions += list(openreview.tools.iterget_notes(CLIENT, invitation='ICLR.cc/2021/Conference/-/Withdrawn_Submission'))\npbar = tqdm(total=len(submissions), desc='Retrieving ratings review status...')\nquality_dict = {'N/A': -1, 'Poor - not very helpful': 0, 'Good': 1, 'Outstanding': 2}\n\nTDDATE = 1605484800000 # 2020-11-16 00:00:00\n\n\ndef get_position(c: openreview.Note) -> str:\n if \"Area_Chair\" in c.signatures[0]:\n return \"Area_Chair\"\n elif \"AnonReviewer\" in c.signatures[0]:\n return \"AnonReviewer\"\n elif \"Authors\" in c.signatures[0]:\n return \"Authors\"\n elif \"Program_Chairs\" in c.signatures[0]:\n return \"Program_Chairs\"\n else:\n return \"Others\"\n\n\ndef get_author_id(note):\n if not hasattr(note, \"tauthor\"):\n return \"my_work\"\n try:\n ac_email = note.tauthor\n ac_profile = CLIENT.search_profiles(emails=[note.tauthor])\n return ac_profile[ac_email].id\n except:\n return note.tauthor\n\n\n@try_except\ndef get_status(s):\n pbar.update(1)\n # reviews = client.get_notes(forum=s.id, invitation=f'ICLR.cc/2021/Conference/Paper{s.number}/-/Official_Review')\n # rratings = client.get_notes(forum=s.id, invitation=f'ICLR.cc/2021/Conference/Paper{s.number}/.*/-/Review_Rating')\n\n withdraws: List[openreview.Note] = CLIENT.get_notes(\n forum=s.id, invitation=f'ICLR.cc/2021/Conference/Paper{s.number}/-/Withdraw',\n )\n if len(withdraws) > 0:\n withdraw = True\n else:\n withdraw = False\n\n meta_reviews: List[openreview.Note] = CLIENT.get_notes(\n forum=s.id, invitation=f'ICLR.cc/2021/Conference/Paper{s.number}/-/Meta_Review',\n )\n if len(meta_reviews) != 0:\n mr = meta_reviews[0]\n ac_id = get_author_id(mr)\n meta_review_length = len(mr.content[\"metareview\"])\n else:\n ac_id = None\n meta_review_length = np.nan\n\n comments: List[openreview.Note] = CLIENT.get_notes(\n forum=s.id, invitation=f'ICLR.cc/2021/Conference/Paper{s.number}/-/Official_Comment',\n )\n\n position_to_comment_length_list = defaultdict(list)\n for c in reversed(comments):\n pos = get_position(c)\n if ac_id is None and pos == \"Area_Chair\":\n ac_id = get_author_id(c)\n comment_length = len(c.content[\"comment\"])\n position_to_comment_length_list[pos].append(comment_length)\n\n return s.number, s.id, withdraw, ac_id, meta_review_length, position_to_comment_length_list\n\n\ndef get_stats(comment_length_list: List[int]):\n if len(comment_length_list) == 0:\n return [0, np.nan, np.nan, np.nan, np.nan, np.nan]\n return [\n len(comment_length_list),\n float(np.mean(comment_length_list)),\n float(np.std(comment_length_list)),\n float(np.min(comment_length_list)),\n float(np.max(comment_length_list)),\n float(np.median(comment_length_list)),\n ]\n\n\nif __name__ == '__main__':\n\n futures = []\n with ThreadPoolExecutor() as executor:\n for i, s in enumerate(submissions):\n futures.append(executor.submit(get_status, s))\n pbar.close()\n\n os.makedirs(\"../data\", exist_ok=True)\n with open(\"../data/ac_stats.csv\", \"w\", newline=\"\\n\") as f:\n errors = []\n writer = csv.writer(f, delimiter=\",\")\n writer.writerow([\n \"paper_id\", \"paper_url\", \"withdraw\", \"ac_id\", \"meta_review_length\",\n \"#AC\", \"mean_AC\", \"std_AC\", \"min_AC\", \"max_AC\", \"median_AC\",\n \"#Reviewer\", \"mean_Reviewer\", \"std_Reviewer\", \"min_Reviewer\", \"max_Reviewer\", \"median_Reviewer\",\n \"#Authors\", \"mean_Authors\", \"std_Authors\", \"min_Authors\", \"max_Authors\", \"median_Authors\",\n \"#PC\", \"mean_PC\", \"std_PC\", \"min_PC\", \"max_PC\", \"median_PC\",\n \"#ETC\", \"mean_ETC\", \"std_ETC\", \"min_ETC\", \"max_ETC\", \"median_ETC\",\n ])\n for future in futures:\n ret = future.result()\n if ret[0] is not None:\n paper_no, paper_url, wd, ac_id, mlr, pos_to_cll = future.result()\n pprint(pos_to_cll)\n row = [\n paper_no,\n paper_url,\n \"withdraw\" if wd else \"not_withdraw\",\n ac_id,\n mlr,\n *get_stats(pos_to_cll[\"Area_Chair\"]),\n *get_stats(pos_to_cll[\"AnonReviewer\"]),\n *get_stats(pos_to_cll[\"Authors\"]),\n *get_stats(pos_to_cll[\"Program_Chairs\"]),\n *get_stats(pos_to_cll[\"Others\"]),\n ]\n print(row)\n print(\"-----\")\n writer.writerow(row)\n else:\n errors.append(ret)\n print(\"Errors -- \")\n pprint(errors)\n\n\n\n", "repo_name": "dongkwan-kim/iclr-2021-sv", "sub_path": "src/ac_stats.py", "file_name": "ac_stats.py", "file_ext": "py", "file_size_in_byte": 5524, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 15, "usage_type": "call"}, {"api_name": "openreview.Client", "line_number": 21, "usage_type": "call"}, {"api_name": "openreview.tools.iterget_notes", "line_number": 25, "usage_type": "call"}, {"api_name": "openreview.tools", "line_number": 25, "usage_type": "attribute"}, {"api_name": "openreview.tools.iterget_notes", "line_number": 26, "usage_type": "call"}, {"api_name": "openreview.tools", "line_number": 26, "usage_type": "attribute"}, {"api_name": "tqdm.tqdm", "line_number": 27, "usage_type": "call"}, {"api_name": "openreview.Note", "line_number": 33, "usage_type": "attribute"}, {"api_name": "typing.List", "line_number": 63, "usage_type": "name"}, {"api_name": "openreview.Note", "line_number": 63, "usage_type": "attribute"}, {"api_name": "typing.List", "line_number": 71, "usage_type": "name"}, {"api_name": "openreview.Note", "line_number": 71, "usage_type": "attribute"}, {"api_name": "numpy.nan", "line_number": 80, "usage_type": "attribute"}, {"api_name": "typing.List", "line_number": 82, "usage_type": "name"}, {"api_name": "openreview.Note", "line_number": 82, "usage_type": "attribute"}, {"api_name": "collections.defaultdict", "line_number": 86, "usage_type": "call"}, {"api_name": "utils.try_except", "line_number": 57, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 97, "usage_type": "name"}, {"api_name": "numpy.nan", "line_number": 99, "usage_type": "attribute"}, {"api_name": "numpy.mean", "line_number": 102, "usage_type": "call"}, {"api_name": "numpy.std", "line_number": 103, "usage_type": "call"}, {"api_name": "numpy.min", "line_number": 104, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 105, "usage_type": "call"}, {"api_name": "numpy.median", "line_number": 106, "usage_type": "call"}, {"api_name": "concurrent.futures.ThreadPoolExecutor", "line_number": 113, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 118, "usage_type": "call"}, {"api_name": "csv.writer", "line_number": 121, "usage_type": "call"}, {"api_name": "pprint.pprint", "line_number": 134, "usage_type": "call"}, {"api_name": "pprint.pprint", "line_number": 153, "usage_type": "call"}]} +{"seq_id": "24858981727", "text": "from rest_framework.exceptions import ValidationError\nfrom django.contrib.auth import authenticate\nfrom rest_framework import viewsets, status, permissions\nfrom rest_framework.permissions import IsAuthenticated, IsAdminUser\nfrom rest_framework.response import Response\nfrom rest_framework_simplejwt.views import TokenObtainPairView\nfrom rest_framework.decorators import permission_classes, api_view\nfrom .models import Customer, Pay_inf, Add_info, Order, OrderItem, Clinic, Rent ,Transaction\nfrom .seriallizer import (OrderSeriallizer, ClinicSeriallizer, CustomerSerializer,\n OrderItemSeriallizer, RentSeriallizer, AddInfoSeriallizer, PayInfoSeriallizer,TransactionSeriallizer)\nfrom Products.api import CustomPagination\nfrom django.contrib.auth.models import User\nfrom .token import account_activation_token\nfrom django.http import JsonResponse\nfrom django.utils.http import urlsafe_base64_decode, urlsafe_base64_encode\nfrom django.core.mail import EmailMessage\nfrom django.contrib.sites.shortcuts import get_current_site\nfrom django.template.loader import render_to_string\nfrom django.urls import reverse\nfrom django.utils.encoding import force_bytes, force_str\nfrom rest_framework.permissions import AllowAny\nfrom django.middleware.csrf import get_token\nfrom rest_framework.exceptions import ValidationError\nfrom retry import retry\nfrom requests.exceptions import Timeout\n\nclass OrderViewSet(viewsets.ModelViewSet):\n queryset = Order.objects.all()\n serializer_class = OrderSeriallizer\n lookup_field = 'pk'\n pagination_class = CustomPagination\n # permission_classes = [permissions.IsAuthenticated, permissions.IsAdminUser]\n\n\nclass ClinicViewSet(viewsets.ModelViewSet):\n queryset = Clinic.objects.all()\n serializer_class = ClinicSeriallizer\n lookup_field = 'pk'\n pagination_class = CustomPagination\n # permission_classes = [permissions.IsAuthenticated, permissions.IsAdminUser]\n\n\nclass CustomerViewSet(viewsets.ModelViewSet):\n queryset = Customer.objects.all()\n serializer_class = CustomerSerializer\n lookup_field = 'pk'\n pagination_class = CustomPagination\n permission_classes = [permissions.IsAuthenticated, permissions.IsAdminUser]\n\n\nclass RentViewSet(viewsets.ModelViewSet):\n queryset = Rent.objects.all()\n serializer_class = RentSeriallizer\n lookup_field = 'pk'\n pagination_class = CustomPagination\n\n\nclass OrderItemViewSet(viewsets.ModelViewSet):\n queryset = OrderItem.objects.all()\n serializer_class = OrderItemSeriallizer\n lookup_field = 'pk'\n\n\nclass PayInfoViewSet(viewsets.ModelViewSet):\n queryset = Pay_inf.objects.all()\n serializer_class = PayInfoSeriallizer\n lookup_field = 'pk'\n\n\nclass AddInfoViewSet(viewsets.ModelViewSet):\n queryset = Add_info.objects.all()\n serializer_class = AddInfoSeriallizer\n lookup_field = 'pk'\n\n\nclass MyObtainToken(TokenObtainPairView):\n def post(self, request, *args, **kwargs):\n username = request.data.get(\"username\")\n password = request.data.get(\"password\")\n if not username or not password:\n return Response({\"error\": \"Both username and password are required.\"}, status=status.HTTP_400_BAD_REQUEST)\n\n user = authenticate(username=username, password=password)\n if user is not None:\n token = super().post(request, *args, **kwargs).data\n return Response({\"token\": token})\n else:\n return Response({\"error\": \"Invalid username or password.\"}, status=status.HTTP_401_UNAUTHORIZED)\n\n\n@api_view(['GET'])\ndef check_email(request):\n email = request.GET.get('username')\n print(email)\n try:\n customer = Customer.objects.get(email=email)\n except:\n return Response({\"msg\": \"email Not found.\"}, status=status.HTTP_400_BAD_REQUEST)\n if customer:\n print(customer)\n return Response({\"msg\": \"email found.\"}, status=status.HTTP_200_OK)\n return Response({\"msg\": \"email Not found.\"}, status=status.HTTP_400_BAD_REQUEST)\n\n\n\n\n# @api_view(['POST'])\n# @permission_classes([AllowAny])\n# def register(request):\n# serializer = CustomerSerializer(data=request.data)\n#\n# if serializer.is_valid():\n# serializer.save()\n# return Response(serializer.data, status=status.HTTP_201_CREATED)\n# return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n@api_view(['POST'])\n@permission_classes([AllowAny])\ndef register(request):\n try:\n serializer = CustomerSerializer(data=request.data)\n\n if serializer.is_valid():\n customer = serializer.save()\n\n # Send activation email with retries\n custom_activation_url = \"localhost:3000/activate\"\n mail_subject = 'Please Activate Your Account!'\n message = render_to_string('acc_active_email.html', {\n 'user': customer,\n 'domain': custom_activation_url,\n 'uid': urlsafe_base64_encode(force_bytes(customer.pk)),\n 'token': account_activation_token.make_token(customer),\n })\n to_email = serializer.validated_data.get('email')\n\n # Retry sending email in case of Timeout\n @retry(Timeout, delay=1, max_delay=5, backoff=2, jitter=(1, 2), tries=3)\n def send_email():\n email = EmailMessage(\n mail_subject, message, to=[to_email]\n )\n email.send()\n\n send_email()\n\n # Provide a success response with a redirect URL and message\n redirect_url = reverse('activate', args=[urlsafe_base64_encode(force_bytes(customer.pk)),\n account_activation_token.make_token(customer)])\n success_message = 'Check your email to activate your account.'\n return Response({\n 'redirect_url': redirect_url,\n 'success_message': success_message,\n }, status=status.HTTP_201_CREATED)\n else:\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n except ValidationError as e:\n return JsonResponse({'error': str(e)}, status=400)\n\n except Exception as e:\n return JsonResponse({'error': 'An error occurred while processing your request.'}, status=500)\n\n\ndef activate_account(request, uidb64, token):\n try:\n uid = urlsafe_base64_decode(uidb64).decode()\n user = User.objects.get(pk=uid)\n except (TypeError, ValueError, OverflowError, User.DoesNotExist):\n user = None\n\n if user is not None and account_activation_token.check_token(user, token):\n user.is_active = True\n user.save()\n return JsonResponse({'message': 'Activation successful'})\n else:\n return JsonResponse({'error': 'Invalid activation link'}, status=400)\n\n\ndef get_csrf_token(request):\n token = get_token(request)\n return JsonResponse({'csrfToken': token})\n \n@api_view(['POST'])\n@permission_classes([IsAuthenticated])\ndef add_clinic(request):\n title = request.data.get('title')\n location = request.data.get('location')\n area = request.data.get('area')\n price = request.data.get('price')\n image = request.data.get('image')\n desc = request.data.get('desc')\n customer_id = request.auth.payload.get(\"user_id\")\n customer = Customer.objects.get(pk=customer_id)\n # Validate required fields\n if not all([title, location, area, price, image]):\n raise ValidationError(\n {\"msg\": \"Missing required fields.\"}, code=status.HTTP_400_BAD_REQUEST)\n # Validate numeric fields\n try:\n area = float(area)\n price = float(price)\n except ValueError:\n raise ValidationError(\n {\"msg\": \"Invalid numeric values for area or price.\"}, code=status.HTTP_400_BAD_REQUEST)\n Clinic.objects.create(title=title, desc=desc, user=customer,\n location=location, area=area, price=price, image=image)\n return Response({\"msg\": \"Clinic added.\"}, status=status.HTTP_201_CREATED)\n\n\n@api_view(['GET'])\n@permission_classes([IsAuthenticated])\ndef get_user_clinic(request):\n customer_id = request.auth.payload.get(\"user_id\")\n clinics = Clinic.objects.filter(user=customer_id)\n serializer = ClinicSeriallizer(clinics, many=True)\n serialized_clinics = serializer.data\n return Response({\"clinics\": serialized_clinics}, status=status.HTTP_200_OK)\n\n\n@api_view(['GET'])\ndef get_all_clinics(request):\n paginator = CustomPagination()\n clinics = Clinic.objects.all()\n paginated_clinics = paginator.paginate_queryset(clinics, request)\n\n # Serialize the paginated products\n serializer = ClinicSeriallizer(paginated_clinics, many=True)\n serialized_clinicis = serializer.data\n\n # Return the paginated response\n return paginator.get_paginated_response(serialized_clinicis)\n\n\n@api_view(['DELETE'])\n@permission_classes([IsAuthenticated])\ndef delete_clinic(request):\n customer_id = request.auth.payload.get('user_id')\n customer = Customer.objects.get(pk=customer_id)\n clinic_id = request.data.get('clinic_id')\n try:\n clinic = Clinic.objects.get(pk=clinic_id)\n except Clinic.DoesNotExist:\n return Response({\"msg\": \"Clinic not found.\"}, status=status.HTTP_404_NOT_FOUND)\n\n if customer == clinic.user:\n clinic.delete()\n return Response({\"msg\": \"Clinic deleted.\"}, status=status.HTTP_204_NO_CONTENT)\n else:\n return Response({\"msg\": \"Not authorized to delete this clinic.\"}, status=status.HTTP_403_FORBIDDEN)\n\n\n@api_view(['DELETE'])\n@permission_classes([IsAuthenticated, IsAdminUser])\ndef delete_user(request):\n try:\n customer_email = request.data.get('customer_email')\n customer = Customer.objects.get(email=customer_email)\n user = User.objects.get(email=customer_email)\n customer.delete()\n user.delete()\n except:\n return Response({\"msg\": \"Can not find user or customer.\"}, status=status.HTTP_400_BAD_REQUEST)\n return Response({\"msg\": \"User Found.\"}, status=status.HTTP_204_NO_CONTENT)\n\n@api_view(['GET'])\n@permission_classes([IsAuthenticated])\ndef userdata(request):\n customer_id = request.auth.payload.get('user_id')\n try:\n customer = Customer.objects.get(pk=customer_id)\n except Customer.DoesNotExist:\n return Response({\"msg\": \"Can not find user or customer.\"}, status=status.HTTP_400_BAD_REQUEST)\n serialized_customer = CustomerSerializer(customer).data\n return Response(serialized_customer, status=status.HTTP_200_OK)\n\n@api_view(['PUT'])\n@permission_classes([IsAuthenticated])\ndef update_customer(request):\n customer_id = request.auth.payload.get('user_id')\n customer = Customer.objects.get(pk=customer_id)\n user = User.objects.get(pk=customer_id)\n password = request.data.get('vertifypassword')\n\n if user.check_password(password):\n try:\n phone = request.data.get('phone')\n image = request.data.get('image')\n username = request.data.get('username')\n new_password = request.data.get('password')\n\n if phone:\n customer.phone = phone\n if image:\n customer.image = image\n if username:\n user.username = username\n user.email = username\n customer.name = username\n if new_password:\n user.set_password(new_password)\n\n customer.save()\n user.save()\n\n return Response({\"msg\": \"Data has been modified\"}, status=status.HTTP_200_OK)\n except Exception as e:\n return Response({\"msg\": \"Error updating data\", \"error\": str(e)}, status=status.HTTP_400_BAD_REQUEST)\n else:\n return Response({\"msg\": \"Wrong data\"}, status=status.HTTP_400_BAD_REQUEST)\n\n\n\n@api_view(['GET'])\n@permission_classes([IsAuthenticated])\ndef get_user_order(request):\n customer_id = request.auth.payload.get(\"user_id\")\n orders = Order.objects.filter(user=customer_id)\n serializer = OrderSeriallizer(orders, many=True)\n serialized_orders = serializer.data\n return Response({\"orders\": serialized_orders}, status=status.HTTP_200_OK)\n\n\n@api_view(['GET'])\n@permission_classes([IsAuthenticated])\ndef get_user_rent(request):\n customer_id = request.auth.payload.get(\"user_id\")\n rents = Rent.objects.filter(renter=customer_id)\n serializer = RentSeriallizer(rents, many=True)\n serialized_rents = serializer.data\n return Response({\"rents\": serialized_rents}, status=status.HTTP_200_OK)\n\n@api_view(['GET'])\n@permission_classes([IsAuthenticated])\ndef get_user_transaction(request):\n customer_id = request.auth.payload.get(\"user_id\")\n transactions = Transaction.objects.filter(user=customer_id)\n serializer = TransactionSeriallizer(transactions, many=True)\n serialized_transactions = serializer.data\n return Response({\"transactions\": serialized_transactions}, status=status.HTTP_200_OK)\n\n\n@api_view(['GET'])\ndef get_all_orders(request):\n paginator = CustomPagination()\n orders = Order.objects.all()\n paginated_orders = paginator.paginate_queryset(orders, request)\n\n serializer = OrderSeriallizer(paginated_orders, many=True)\n serialized_orders = serializer.data\n\n return Response({\"orders\": serialized_orders}, status=status.HTTP_200_OK)\n\n\n@api_view(['GET'])\ndef get_all_rents(request):\n paginator = CustomPagination()\n rents = Rent.objects.all()\n paginated_rents = paginator.paginate_queryset(rents, request)\n\n serializer = RentSeriallizer(paginated_rents, many=True)\n serialized_rents = serializer.data\n\n return Response({\"rents\": serialized_rents}, status=status.HTTP_200_OK)\n\n\n@api_view(['GET'])\ndef get_all_transactions(request):\n paginator = CustomPagination()\n transactions = Transaction.objects.all()\n paginated_transactions = paginator.paginate_queryset(transactions, request)\n\n serializer = TransactionSeriallizer(paginated_transactions, many=True)\n serialized_transactions = serializer.data\n\n return Response({\"transactions\": serialized_transactions}, status=status.HTTP_200_OK)\n\n\ndef get_items_in_order(order_id):\n items = OrderItem.objects.filter(order_id=order_id)\n return items\n\n", "repo_name": "mohammedaliem/DentiBask-Back", "sub_path": "User/api.py", "file_name": "api.py", "file_ext": "py", "file_size_in_byte": 14171, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "github-code", "pt": "21", "api": [{"api_name": "rest_framework.viewsets.ModelViewSet", "line_number": 27, "usage_type": "attribute"}, {"api_name": "rest_framework.viewsets", "line_number": 27, "usage_type": "name"}, {"api_name": "models.Order.objects.all", "line_number": 28, "usage_type": "call"}, {"api_name": "models.Order.objects", "line_number": 28, "usage_type": "attribute"}, {"api_name": "models.Order", "line_number": 28, "usage_type": "name"}, {"api_name": "seriallizer.OrderSeriallizer", "line_number": 29, "usage_type": "name"}, {"api_name": "Products.api.CustomPagination", "line_number": 31, "usage_type": "name"}, {"api_name": "rest_framework.viewsets.ModelViewSet", "line_number": 35, "usage_type": "attribute"}, {"api_name": "rest_framework.viewsets", "line_number": 35, "usage_type": "name"}, {"api_name": "models.Clinic.objects.all", "line_number": 36, "usage_type": "call"}, {"api_name": "models.Clinic.objects", "line_number": 36, "usage_type": "attribute"}, {"api_name": "models.Clinic", "line_number": 36, "usage_type": "name"}, {"api_name": "seriallizer.ClinicSeriallizer", "line_number": 37, "usage_type": "name"}, {"api_name": "Products.api.CustomPagination", "line_number": 39, "usage_type": "name"}, {"api_name": "rest_framework.viewsets.ModelViewSet", "line_number": 43, "usage_type": "attribute"}, {"api_name": "rest_framework.viewsets", "line_number": 43, "usage_type": "name"}, {"api_name": "models.Customer.objects.all", "line_number": 44, "usage_type": "call"}, {"api_name": "models.Customer.objects", "line_number": 44, "usage_type": "attribute"}, {"api_name": "models.Customer", "line_number": 44, "usage_type": "name"}, {"api_name": "seriallizer.CustomerSerializer", "line_number": 45, "usage_type": "name"}, {"api_name": "Products.api.CustomPagination", "line_number": 47, "usage_type": "name"}, {"api_name": "rest_framework.decorators.permission_classes", "line_number": 48, "usage_type": "name"}, {"api_name": "rest_framework.permissions.IsAuthenticated", "line_number": 48, "usage_type": "attribute"}, {"api_name": "rest_framework.permissions", "line_number": 48, "usage_type": "name"}, {"api_name": "rest_framework.permissions.IsAdminUser", "line_number": 48, "usage_type": "attribute"}, {"api_name": "rest_framework.viewsets.ModelViewSet", "line_number": 51, "usage_type": "attribute"}, {"api_name": "rest_framework.viewsets", "line_number": 51, "usage_type": "name"}, {"api_name": "models.Rent.objects.all", "line_number": 52, "usage_type": "call"}, {"api_name": "models.Rent.objects", "line_number": 52, "usage_type": "attribute"}, {"api_name": "models.Rent", "line_number": 52, "usage_type": "name"}, {"api_name": "seriallizer.RentSeriallizer", "line_number": 53, "usage_type": "name"}, {"api_name": "Products.api.CustomPagination", "line_number": 55, "usage_type": "name"}, {"api_name": "rest_framework.viewsets.ModelViewSet", "line_number": 58, "usage_type": "attribute"}, {"api_name": "rest_framework.viewsets", "line_number": 58, "usage_type": "name"}, {"api_name": "models.OrderItem.objects.all", "line_number": 59, "usage_type": "call"}, {"api_name": "models.OrderItem.objects", "line_number": 59, "usage_type": "attribute"}, {"api_name": "models.OrderItem", "line_number": 59, "usage_type": "name"}, {"api_name": "seriallizer.OrderItemSeriallizer", "line_number": 60, "usage_type": "name"}, {"api_name": "rest_framework.viewsets.ModelViewSet", "line_number": 64, "usage_type": "attribute"}, {"api_name": "rest_framework.viewsets", "line_number": 64, "usage_type": "name"}, {"api_name": "models.Pay_inf.objects.all", "line_number": 65, "usage_type": "call"}, {"api_name": "models.Pay_inf.objects", "line_number": 65, "usage_type": "attribute"}, {"api_name": "models.Pay_inf", "line_number": 65, "usage_type": "name"}, {"api_name": "seriallizer.PayInfoSeriallizer", "line_number": 66, "usage_type": "name"}, {"api_name": "rest_framework.viewsets.ModelViewSet", "line_number": 70, "usage_type": "attribute"}, {"api_name": "rest_framework.viewsets", "line_number": 70, "usage_type": "name"}, {"api_name": "models.Add_info.objects.all", "line_number": 71, "usage_type": "call"}, {"api_name": "models.Add_info.objects", "line_number": 71, "usage_type": "attribute"}, {"api_name": "models.Add_info", "line_number": 71, "usage_type": "name"}, {"api_name": "seriallizer.AddInfoSeriallizer", "line_number": 72, "usage_type": "name"}, {"api_name": "rest_framework_simplejwt.views.TokenObtainPairView", "line_number": 76, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 81, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_400_BAD_REQUEST", "line_number": 81, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 81, "usage_type": "name"}, {"api_name": "django.contrib.auth.authenticate", "line_number": 83, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 86, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 88, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_401_UNAUTHORIZED", "line_number": 88, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 88, "usage_type": "name"}, {"api_name": "models.Customer.objects.get", "line_number": 96, "usage_type": "call"}, {"api_name": "models.Customer.objects", "line_number": 96, "usage_type": "attribute"}, {"api_name": "models.Customer", "line_number": 96, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 98, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_400_BAD_REQUEST", "line_number": 98, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 98, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 101, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_200_OK", "line_number": 101, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 101, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 102, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_400_BAD_REQUEST", "line_number": 102, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 102, "usage_type": "name"}, {"api_name": "rest_framework.decorators.api_view", "line_number": 91, "usage_type": "call"}, {"api_name": "seriallizer.CustomerSerializer", "line_number": 121, "usage_type": "call"}, {"api_name": "django.template.loader.render_to_string", "line_number": 129, "usage_type": "call"}, {"api_name": "django.utils.http.urlsafe_base64_encode", "line_number": 132, "usage_type": "call"}, {"api_name": "django.utils.encoding.force_bytes", "line_number": 132, "usage_type": "call"}, {"api_name": "token.account_activation_token.make_token", "line_number": 133, "usage_type": "call"}, {"api_name": "token.account_activation_token", "line_number": 133, "usage_type": "name"}, {"api_name": "django.core.mail.EmailMessage", "line_number": 140, "usage_type": "call"}, {"api_name": "retry.retry", "line_number": 138, "usage_type": "call"}, {"api_name": "requests.exceptions.Timeout", "line_number": 138, "usage_type": "argument"}, {"api_name": "django.urls.reverse", "line_number": 148, "usage_type": "call"}, {"api_name": "django.utils.http.urlsafe_base64_encode", "line_number": 148, "usage_type": "call"}, {"api_name": "django.utils.encoding.force_bytes", "line_number": 148, "usage_type": "call"}, {"api_name": "token.account_activation_token.make_token", "line_number": 149, "usage_type": "call"}, {"api_name": "token.account_activation_token", "line_number": 149, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 151, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_201_CREATED", "line_number": 154, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 154, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 156, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_400_BAD_REQUEST", "line_number": 156, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 156, "usage_type": "name"}, {"api_name": "rest_framework.exceptions.ValidationError", "line_number": 158, "usage_type": "name"}, {"api_name": "django.http.JsonResponse", "line_number": 159, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 162, "usage_type": "call"}, {"api_name": "rest_framework.decorators.api_view", "line_number": 117, "usage_type": "call"}, {"api_name": "rest_framework.decorators.permission_classes", "line_number": 118, "usage_type": "call"}, {"api_name": "rest_framework.permissions.AllowAny", "line_number": 118, "usage_type": "name"}, {"api_name": "django.utils.http.urlsafe_base64_decode", "line_number": 167, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.User.objects.get", "line_number": 168, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.User.objects", "line_number": 168, "usage_type": "attribute"}, {"api_name": "django.contrib.auth.models.User", "line_number": 168, "usage_type": "name"}, {"api_name": "django.contrib.auth.models.User.DoesNotExist", "line_number": 169, "usage_type": "attribute"}, {"api_name": "django.contrib.auth.models.User", "line_number": 169, "usage_type": "name"}, {"api_name": "token.account_activation_token.check_token", "line_number": 172, "usage_type": "call"}, {"api_name": "token.account_activation_token", "line_number": 172, "usage_type": "name"}, {"api_name": "django.http.JsonResponse", "line_number": 175, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 177, "usage_type": "call"}, {"api_name": "django.middleware.csrf.get_token", "line_number": 181, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 182, "usage_type": "call"}, {"api_name": "models.Customer.objects.get", "line_number": 194, "usage_type": "call"}, {"api_name": "models.Customer.objects", "line_number": 194, "usage_type": "attribute"}, {"api_name": "models.Customer", "line_number": 194, "usage_type": "name"}, {"api_name": "rest_framework.exceptions.ValidationError", "line_number": 197, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_400_BAD_REQUEST", "line_number": 198, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 198, "usage_type": "name"}, {"api_name": "rest_framework.exceptions.ValidationError", "line_number": 204, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_400_BAD_REQUEST", "line_number": 205, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 205, "usage_type": "name"}, {"api_name": "models.Clinic.objects.create", "line_number": 206, "usage_type": "call"}, {"api_name": "models.Clinic.objects", "line_number": 206, "usage_type": "attribute"}, {"api_name": "models.Clinic", "line_number": 206, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 208, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_201_CREATED", "line_number": 208, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 208, "usage_type": "name"}, {"api_name": "rest_framework.decorators.api_view", "line_number": 184, "usage_type": "call"}, {"api_name": "rest_framework.decorators.permission_classes", "line_number": 185, "usage_type": "call"}, {"api_name": "rest_framework.permissions.IsAuthenticated", "line_number": 185, "usage_type": "name"}, {"api_name": "models.Clinic.objects.filter", "line_number": 215, "usage_type": "call"}, {"api_name": "models.Clinic.objects", "line_number": 215, "usage_type": "attribute"}, {"api_name": "models.Clinic", "line_number": 215, "usage_type": "name"}, {"api_name": "seriallizer.ClinicSeriallizer", "line_number": 216, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 218, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_200_OK", "line_number": 218, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 218, "usage_type": "name"}, {"api_name": "rest_framework.decorators.api_view", "line_number": 211, "usage_type": "call"}, {"api_name": "rest_framework.decorators.permission_classes", "line_number": 212, "usage_type": "call"}, {"api_name": "rest_framework.permissions.IsAuthenticated", "line_number": 212, "usage_type": "name"}, {"api_name": "Products.api.CustomPagination", "line_number": 223, "usage_type": "call"}, {"api_name": "models.Clinic.objects.all", "line_number": 224, "usage_type": "call"}, {"api_name": "models.Clinic.objects", "line_number": 224, "usage_type": "attribute"}, {"api_name": "models.Clinic", "line_number": 224, "usage_type": "name"}, {"api_name": "seriallizer.ClinicSeriallizer", "line_number": 228, "usage_type": "call"}, {"api_name": "rest_framework.decorators.api_view", "line_number": 221, "usage_type": "call"}, {"api_name": "models.Customer.objects.get", "line_number": 239, "usage_type": "call"}, {"api_name": "models.Customer.objects", "line_number": 239, "usage_type": "attribute"}, {"api_name": "models.Customer", "line_number": 239, "usage_type": "name"}, {"api_name": "models.Clinic.objects.get", "line_number": 242, "usage_type": "call"}, {"api_name": "models.Clinic.objects", "line_number": 242, "usage_type": "attribute"}, {"api_name": "models.Clinic", "line_number": 242, "usage_type": "name"}, {"api_name": "models.Clinic.DoesNotExist", "line_number": 243, "usage_type": "attribute"}, {"api_name": "models.Clinic", "line_number": 243, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 244, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_404_NOT_FOUND", "line_number": 244, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 244, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 248, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_204_NO_CONTENT", "line_number": 248, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 248, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 250, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_403_FORBIDDEN", "line_number": 250, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 250, "usage_type": "name"}, {"api_name": "rest_framework.decorators.api_view", "line_number": 235, "usage_type": "call"}, {"api_name": "rest_framework.decorators.permission_classes", "line_number": 236, "usage_type": "call"}, {"api_name": "rest_framework.permissions.IsAuthenticated", "line_number": 236, "usage_type": "name"}, {"api_name": "models.Customer.objects.get", "line_number": 258, "usage_type": "call"}, {"api_name": "models.Customer.objects", "line_number": 258, "usage_type": "attribute"}, {"api_name": "models.Customer", "line_number": 258, "usage_type": "name"}, {"api_name": "django.contrib.auth.models.User.objects.get", "line_number": 259, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.User.objects", "line_number": 259, "usage_type": "attribute"}, {"api_name": "django.contrib.auth.models.User", "line_number": 259, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 263, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_400_BAD_REQUEST", "line_number": 263, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 263, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 264, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_204_NO_CONTENT", "line_number": 264, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 264, "usage_type": "name"}, {"api_name": "rest_framework.decorators.api_view", "line_number": 253, "usage_type": "call"}, {"api_name": "rest_framework.decorators.permission_classes", "line_number": 254, "usage_type": "call"}, {"api_name": "rest_framework.permissions.IsAuthenticated", "line_number": 254, "usage_type": "name"}, {"api_name": "rest_framework.permissions.IsAdminUser", "line_number": 254, "usage_type": "name"}, {"api_name": "models.Customer.objects.get", "line_number": 271, "usage_type": "call"}, {"api_name": "models.Customer.objects", "line_number": 271, "usage_type": "attribute"}, {"api_name": "models.Customer", "line_number": 271, "usage_type": "name"}, {"api_name": "models.Customer.DoesNotExist", "line_number": 272, "usage_type": "attribute"}, {"api_name": "models.Customer", "line_number": 272, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 273, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_400_BAD_REQUEST", "line_number": 273, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 273, "usage_type": "name"}, {"api_name": "seriallizer.CustomerSerializer", "line_number": 274, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 275, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_200_OK", "line_number": 275, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 275, "usage_type": "name"}, {"api_name": "rest_framework.decorators.api_view", "line_number": 266, "usage_type": "call"}, {"api_name": "rest_framework.decorators.permission_classes", "line_number": 267, "usage_type": "call"}, {"api_name": "rest_framework.permissions.IsAuthenticated", "line_number": 267, "usage_type": "name"}, {"api_name": "models.Customer.objects.get", "line_number": 281, "usage_type": "call"}, {"api_name": "models.Customer.objects", "line_number": 281, "usage_type": "attribute"}, {"api_name": "models.Customer", "line_number": 281, "usage_type": "name"}, {"api_name": "django.contrib.auth.models.User.objects.get", "line_number": 282, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.User.objects", "line_number": 282, "usage_type": "attribute"}, {"api_name": "django.contrib.auth.models.User", "line_number": 282, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 306, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_200_OK", "line_number": 306, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 306, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 308, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_400_BAD_REQUEST", "line_number": 308, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 308, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 310, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_400_BAD_REQUEST", "line_number": 310, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 310, "usage_type": "name"}, {"api_name": "rest_framework.decorators.api_view", "line_number": 277, "usage_type": "call"}, {"api_name": "rest_framework.decorators.permission_classes", "line_number": 278, "usage_type": "call"}, {"api_name": "rest_framework.permissions.IsAuthenticated", "line_number": 278, "usage_type": "name"}, {"api_name": "models.Order.objects.filter", "line_number": 318, "usage_type": "call"}, {"api_name": "models.Order.objects", "line_number": 318, "usage_type": "attribute"}, {"api_name": "models.Order", "line_number": 318, "usage_type": "name"}, {"api_name": "seriallizer.OrderSeriallizer", "line_number": 319, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 321, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_200_OK", "line_number": 321, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 321, "usage_type": "name"}, {"api_name": "rest_framework.decorators.api_view", "line_number": 314, "usage_type": "call"}, {"api_name": "rest_framework.decorators.permission_classes", "line_number": 315, "usage_type": "call"}, {"api_name": "rest_framework.permissions.IsAuthenticated", "line_number": 315, "usage_type": "name"}, {"api_name": "models.Rent.objects.filter", "line_number": 328, "usage_type": "call"}, {"api_name": "models.Rent.objects", "line_number": 328, "usage_type": "attribute"}, {"api_name": "models.Rent", "line_number": 328, "usage_type": "name"}, {"api_name": "seriallizer.RentSeriallizer", "line_number": 329, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 331, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_200_OK", "line_number": 331, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 331, "usage_type": "name"}, {"api_name": "rest_framework.decorators.api_view", "line_number": 324, "usage_type": "call"}, {"api_name": "rest_framework.decorators.permission_classes", "line_number": 325, "usage_type": "call"}, {"api_name": "rest_framework.permissions.IsAuthenticated", "line_number": 325, "usage_type": "name"}, {"api_name": "models.Transaction.objects.filter", "line_number": 337, "usage_type": "call"}, {"api_name": "models.Transaction.objects", "line_number": 337, "usage_type": "attribute"}, {"api_name": "models.Transaction", "line_number": 337, "usage_type": "name"}, {"api_name": "seriallizer.TransactionSeriallizer", "line_number": 338, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 340, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_200_OK", "line_number": 340, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 340, "usage_type": "name"}, {"api_name": "rest_framework.decorators.api_view", "line_number": 333, "usage_type": "call"}, {"api_name": "rest_framework.decorators.permission_classes", "line_number": 334, "usage_type": "call"}, {"api_name": "rest_framework.permissions.IsAuthenticated", "line_number": 334, "usage_type": "name"}, {"api_name": "Products.api.CustomPagination", "line_number": 345, "usage_type": "call"}, {"api_name": "models.Order.objects.all", "line_number": 346, "usage_type": "call"}, {"api_name": "models.Order.objects", "line_number": 346, "usage_type": "attribute"}, {"api_name": "models.Order", "line_number": 346, "usage_type": "name"}, {"api_name": "seriallizer.OrderSeriallizer", "line_number": 349, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 352, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_200_OK", "line_number": 352, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 352, "usage_type": "name"}, {"api_name": "rest_framework.decorators.api_view", "line_number": 343, "usage_type": "call"}, {"api_name": "Products.api.CustomPagination", "line_number": 357, "usage_type": "call"}, {"api_name": "models.Rent.objects.all", "line_number": 358, "usage_type": "call"}, {"api_name": "models.Rent.objects", "line_number": 358, "usage_type": "attribute"}, {"api_name": "models.Rent", "line_number": 358, "usage_type": "name"}, {"api_name": "seriallizer.RentSeriallizer", "line_number": 361, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 364, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_200_OK", "line_number": 364, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 364, "usage_type": "name"}, {"api_name": "rest_framework.decorators.api_view", "line_number": 355, "usage_type": "call"}, {"api_name": "Products.api.CustomPagination", "line_number": 369, "usage_type": "call"}, {"api_name": "models.Transaction.objects.all", "line_number": 370, "usage_type": "call"}, {"api_name": "models.Transaction.objects", "line_number": 370, "usage_type": "attribute"}, {"api_name": "models.Transaction", "line_number": 370, "usage_type": "name"}, {"api_name": "seriallizer.TransactionSeriallizer", "line_number": 373, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 376, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_200_OK", "line_number": 376, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 376, "usage_type": "name"}, {"api_name": "rest_framework.decorators.api_view", "line_number": 367, "usage_type": "call"}, {"api_name": "models.OrderItem.objects.filter", "line_number": 380, "usage_type": "call"}, {"api_name": "models.OrderItem.objects", "line_number": 380, "usage_type": "attribute"}, {"api_name": "models.OrderItem", "line_number": 380, "usage_type": "name"}]} +{"seq_id": "34650288604", "text": "import datetime\nimport logging\nimport os\nimport uuid\n\nfrom django.conf import settings\nfrom django.core.mail import (BadHeaderError, EmailMessage,\n EmailMultiAlternatives, send_mail)\nfrom django.db import models\nfrom django.http import QueryDict\nfrom django.shortcuts import render\nfrom django.template.loader import get_template, render_to_string\nfrom django.urls import reverse\nfrom django.utils.text import slugify\nfrom django.utils.translation import gettext_lazy as _\n\nfrom .translations import filter_translations\nfrom .validators import *\n\n\"\"\"\nGet the logger\n\"\"\"\nlogger = logging.getLogger(__name__)\n\n\"\"\"\nA couple of hard coded choices for the database models.\n\"\"\"\nviews = [\n ('portfolio:detail', 'Detail View'),\n ('portfolio:collection', 'Collection View'),\n ('portfolio:page', 'Page View'),\n]\n\npage_positions = []\nfor h in range(settings.MAX_PAGES):\n page_positions.append((h, h))\n\nsection_postitions = []\nfor i in range(settings.MAX_SECTIONS):\n section_postitions.append((i, i))\n\nlink_positions = []\nfor j in range(settings.MAX_NAVLINKS):\n link_positions.append((f\"navbar-{j}\", f\"navbar {j}\"))\nfor k in range(settings.MAX_FOOTERLINKS):\n link_positions.append((f\"footer-{k}\", f\"footer {k}\"))\n\nsociallink_positions = [\n ('deg270', '12:00'),\n ('deg315', '01:30'),\n ('deg0', '03:00'),\n ('deg45', '04:30'),\n ('deg90', '06:00'),\n ('deg135', '07:30'),\n ('deg180', '09:00'),\n ('deg225', '10:30')\n]\n\nlink_types = [\n ('page', 'Page'),\n ('section', 'Section'),\n ('external', 'External')\n]\n\n\nclass Setting(models.Model):\n key = models.CharField(max_length=256)\n value = models.CharField(max_length=1024)\n\n def __str__(self):\n return f'{self.key}={self.value}'\n\n\n\"\"\"\nIcon model for external links\n\"\"\"\n\n\nclass Icon(models.Model):\n name = models.CharField(max_length=64)\n icon_class = models.CharField(max_length=64)\n\n colour = models.CharField(max_length=7, null=True,\n blank=True, validators=[validate_colour_code])\n colour_value = models.CharField(max_length=7, null=True,\n blank=True, validators=[validate_colour_code])\n\n slug = models.SlugField(null=True)\n\n def __str__(self):\n return self.name\n\n def save(self, force_insert=False, force_update=False, using=None, update_fields=None):\n super().save(force_insert, force_update, using, update_fields)\n self.slug = slugify(self.name)\n self.colour = self.colour_value\n\n logger.info('Saved icon %s in database', self.slug)\n\n\n\"\"\"\nAbstract Translatable model from which all models with translatable fields inherit\n\"\"\"\n\n\nclass AbstractTranslatable(models.Model):\n\n lang = models.CharField(\n max_length=5, choices=settings.LANGUAGES, default=settings.LANGUAGE_CODE)\n\n class Meta:\n abstract = True\n unique_together = ['lang', 'slug']\n\n def __str__(self):\n return self.lang\n\n\n\"\"\"\nModels for website pages\n########################\n\"\"\"\n\n\n\"\"\"\nPageType model for the different types of pages supported\n\"\"\"\n\n\nclass PageType(models.Model):\n name = models.CharField(max_length=24)\n template_name = models.CharField(max_length=64)\n view_name = models.CharField(max_length=64, editable=False)\n overwrite_view_name = models.CharField(\n max_length=64, null=True, blank=True)\n\n def __str__(self):\n return self.name\n\n def save(self, force_insert=False,\n force_update=False, using=None, update_fields=None):\n\n if self.overwrite_view_name != None:\n self.view_name = self.overwrite_view_name\n else:\n self.view_name = f\"portfolio:{self.name}\"\n\n logger.info('Saved page type %s in database', self.name)\n\n return super().save(force_insert=force_insert,\n force_update=force_update,\n using=using,\n update_fields=update_fields)\n\n\n\"\"\"\nPageCommon model for shared attributes between translations\n\"\"\"\n\n\nclass PageCommon(models.Model):\n friendly_name = models.CharField(max_length=64)\n\n page_type = models.ForeignKey(\n PageType, on_delete=models.SET_NULL, null=True, blank=True)\n footer_link = models.BooleanField(default=True)\n footer_position = models.IntegerField(unique=True, null=True, blank=True,\n choices=[(i, i) for i in range(10)])\n\n class Meta:\n verbose_name = _('Page')\n verbose_name_plural = _('Pages')\n\n def __str__(self):\n return self.friendly_name\n\n\n\"\"\"\nTranslatable Page model holding the page text translations\n\"\"\"\n\n\nclass Page(AbstractTranslatable):\n name = models.CharField(max_length=24)\n\n slug = models.SlugField(null=True, blank=True)\n common = models.ForeignKey(\n PageCommon, on_delete=models.CASCADE, null=True)\n\n class Meta:\n verbose_name = _('Single Page')\n verbose_name_plural = _('Single Pages')\n\n def __str__(self):\n return self.name\n\n def save(self, force_insert=False, force_update=False,\n using=None, update_fields=None):\n super().save(force_insert, force_update, using, update_fields)\n self.slug = slugify(self.name)\n\n\n\"\"\"\nModels for page sections\n########################\n\"\"\"\n\n\"\"\"\nSection Type model for defining different section types\ne.g.: Collection, Spotlight, Contact\n\"\"\"\n\n\nclass SectionType(models.Model):\n name = models.CharField(max_length=64)\n template_name = models.CharField(max_length=64)\n default_position = models.IntegerField()\n\n def __str__(self):\n return self.name\n\n\n\"\"\"\nSection Common model for shared attributes between translated sections\n\"\"\"\n\n\nclass SectionCommon(models.Model):\n friendly_name = models.CharField(max_length=64)\n section_type = models.ForeignKey(\n SectionType, on_delete=models.SET_NULL, null=True)\n position = models.IntegerField(null=True, choices=section_postitions)\n page = models.ForeignKey(\n PageCommon,\n on_delete=models.SET_NULL,\n null=True, blank=True,\n related_name='sections'\n )\n\n class Meta:\n verbose_name = _('Page Section')\n verbose_name_plural = _('Page Sections')\n unique_together = ['page', 'position']\n\n def __str__(self):\n return self.friendly_name\n\n\n\"\"\"\nTranslatable section model holding section translations\n\"\"\"\n\n\nclass Section(AbstractTranslatable):\n\n name = models.CharField(max_length=64)\n slug = models.SlugField()\n detail_slug = models.SlugField(null=True, blank=True)\n description = models.TextField(null=True, blank=True)\n common = models.ForeignKey(SectionCommon, related_name='sections',\n on_delete=models.CASCADE, null=True)\n\n class Meta:\n verbose_name = _('Section Translation')\n verbose_name_plural = _('Sections Translations')\n\n def __str__(self):\n return self.name\n\n def save(self):\n self.slug = slugify(self.name)\n return super().save()\n\n\n\"\"\"\nModels for Navigation, Contact and Footer links\n###############################################\n\"\"\"\n\n\"\"\"\nAbstract Link model from which all other link models inherit\n\"\"\"\n\n\nclass AbstractLink(models.Model):\n name = models.CharField(max_length=12)\n url = models.CharField(max_length=256, editable=False,\n blank=True, default='/')\n view = models.CharField(\n max_length=64, default='portfolio:detail', choices=views)\n position = models.CharField(\n max_length=8, null=True, choices=link_positions, unique=True)\n link_for = models.CharField(\n max_length=24, choices=link_types, null=True)\n section = models.ForeignKey(\n Section, null=True, blank=True, on_delete=models.SET_NULL)\n page = models.ForeignKey(PageCommon, null=True,\n blank=True, on_delete=models.SET_NULL)\n external = models.URLField(null=True, blank=True)\n\n def __str__(self):\n return self.url\n\n class Meta:\n abstract = True\n\n\n\"\"\"\nHelper model for editing all page links in bulk\n\"\"\"\n\n\nclass LinkEdit(models.Model):\n\n class Meta:\n verbose_name = _('Page Link')\n verbose_name_plural = _('Page Links')\n\n\n\"\"\"\nSocial Link model for the contact circle\n\"\"\"\n\n\nclass SocialLink(AbstractLink):\n icon = models.ForeignKey(Icon, on_delete=models.SET_NULL,\n null=True)\n link_edit = models.ForeignKey(\n LinkEdit, on_delete=models.SET_NULL, null=True,\n related_name='social_links')\n position = models.CharField(\n max_length=6, null=True, blank=True, unique=True,\n choices=sociallink_positions)\n\n class Meta:\n verbose_name = _('Social Link')\n verbose_name_plural = _('Social Links')\n\n\n\"\"\"\nFooter link model\n\"\"\"\n\n\nclass FooterLink(AbstractLink):\n icon = models.ForeignKey(Icon, on_delete=models.SET_NULL, null=True)\n link_edit = models.ForeignKey(\n LinkEdit, on_delete=models.SET_NULL,\n null=True, related_name='footer_links')\n\n class Meta:\n verbose_name = _('Footer Link')\n verbose_name_plural = _('Footer Links')\n\n\n\"\"\"\nNavigation Link model\n\"\"\"\n\n\nclass NavLink(AbstractLink):\n link_edit = models.ForeignKey(\n LinkEdit, on_delete=models.SET_NULL,\n null=True, related_name='navbar_links')\n\n class Meta:\n verbose_name = _('Navigation Link')\n verbose_name_plural = _('Navigation Links')\n\n\n\"\"\"\nModels for Collection Items\ne.g.: Projects, Photos\n##################\n\"\"\"\n\n\"\"\"\nCollection Item Common model for shared attributes between translated items\n\"\"\"\n\n\nclass CollectionItemCommon(models.Model):\n friendly_name = models.CharField(max_length=64)\n image = models.ImageField(upload_to='images')\n created = models.DateTimeField()\n spotlight = models.BooleanField()\n parent_section = models.ForeignKey(\n SectionCommon, on_delete=models.SET_NULL, null=True)\n detail_view = models.CharField(\n max_length=64, default='portfolio:detail', choices=views)\n\n class Meta:\n verbose_name = _('Collection Item')\n verbose_name_plural = _('Collection Items')\n\n def __str__(self):\n return self.friendly_name\n\n\n\"\"\"\nCollection Item model for translatable items\n\"\"\"\n\n\nclass CollectionItem(AbstractTranslatable):\n name = models.CharField(max_length=100)\n slug = models.SlugField(max_length=100, editable=False)\n description = models.TextField()\n common = models.ForeignKey(\n CollectionItemCommon, related_name='collection_items',\n on_delete=models.CASCADE, null=True)\n image_alttext = models.TextField(default=\"\")\n\n class Meta:\n verbose_name = _('Item Translation')\n verbose_name_plural = _('Item Translations')\n\n def save(self):\n self.slug = slugify(self.name)\n logger.info('Saved collection item %s (%s) in database',\n self.slug, self.lang)\n super().save()\n\n\n\"\"\"\nModels for the contact form\n###########################\n\"\"\"\n\n\"\"\"\nContact model to enable email address confirmation\n\"\"\"\n\n\nclass Contact(models.Model):\n id = models.UUIDField(\n primary_key=True, default=uuid.uuid4, editable=False, unique=True)\n email_address = models.EmailField()\n email_confirmed = models.BooleanField(default=False)\n name = models.CharField(max_length=64, null=True)\n\n def __str__(self):\n return self.email_address\n\n def send_confirmation_email(self, token):\n\n confirm_url = reverse('portfolio:contact', args=['confirm'])\n confirm_params = QueryDict(f'id={self.id}&token={token}').urlencode()\n url = f\"{settings.BASE_URL}{confirm_url}?{confirm_params}\"\n\n pages = Page.objects.all().select_related('common')\n pages = filter_translations(\n pages, 'en').order_by('common__footer_position')\n\n context = {\n 'pages': pages,\n 'footerlinks': FooterLink.objects.order_by('position'),\n 'user': {'confirmation_url': url}\n }\n\n html_email = render_to_string(\n 'portfolio/email_confirmation.html', context=context)\n\n send_mail(\n subject='Please Confirm your email address',\n from_email=\"Fabian Volkers \",\n recipient_list=[self.email_address],\n message=f'Use this link to confirm your email address {url}',\n html_message=html_email,\n fail_silently=(settings.ENVIRONMENT == 'production')\n )\n\n logger.info('Sent confirmation email to contact %s ', self.id)\n\n def save(self, force_insert=False, force_update=False,\n using=None, update_fields=None):\n\n logger.info('Saved contact %s in database', self.id)\n\n return super().save(force_insert, force_update,\n using, update_fields)\n\n\n\"\"\"\nMessage model for storing messages until email confirmation\n\"\"\"\n\n\nclass Message(models.Model):\n contact = models.ForeignKey(Contact, on_delete=models.CASCADE)\n subject = models.CharField(max_length=100)\n content = models.TextField()\n sent = models.BooleanField(default=False)\n date_created = models.DateTimeField(auto_now=True)\n date_sent = models.DateTimeField(blank=True, null=True, editable=False)\n\n def __str__(self):\n return f\"{self.contact.email_address} - {self.subject}\"\n\n def send(self):\n\n email_template = get_template('portfolio/email_contact.html')\n\n context = {\n 'from': self.contact.email_address,\n 'name': self.contact.name,\n 'subject': self.subject,\n 'message': self.content\n }\n\n html_message = email_template.render(context=context)\n\n headers = {\n 'Sender': 'noreply@fabianvolkers.com',\n 'From': f'{self.contact.name} via fabianvolkers.com <{self.contact.email_address}>',\n 'Reply-To': f'{self.contact.name} <{self.contact.email_address}>',\n 'To': f'Fabian Volkers <{settings.EMAIL_CONTACT_ADDRESS}>'\n }\n email = EmailMultiAlternatives(\n subject=self.subject,\n from_email=\"Fabian Volkers \",\n to=[settings.EMAIL_CONTACT_ADDRESS],\n body=self.content,\n headers=headers\n )\n email.attach_alternative(html_message, 'text/html')\n email.send(fail_silently=(settings.ENVIRONMENT == 'production'))\n\n self.date_sent = datetime.datetime.now(settings.PYTZ)\n self.sent = True\n self.save()\n\n logger.info('Sent message %s from contact %s to %s',\n self.id, self.contact.id, settings.EMAIL_CONTACT_ADDRESS)\n\n\n\"\"\"\nContact Response Action model for storing actions for response to user\ne.g.: resend confirmation email, delete personal information\n\"\"\"\n\n\nclass ContactResponseAction(models.Model):\n name = models.CharField(max_length=24)\n page = models.ForeignKey(\n PageCommon, on_delete=models.SET_NULL, null=True, blank=True)\n method = models.CharField(max_length=7, choices=[(\n 'GET', 'GET'), ('POST', 'POST'), ('DELETE', 'DELETE')])\n argument = models.CharField(max_length=32, null=True, blank=True)\n\n def __str__(self):\n return self.name\n\n\n\"\"\"\nContact response common for shared attributes between translatable contact\nresponses\n\"\"\"\n\n\nclass ContactResponseCommon(models.Model):\n friendly_name = models.CharField(max_length=32)\n action = models.ForeignKey(\n ContactResponseAction, on_delete=models.SET_NULL, null=True, blank=True)\n\n def __str__(self):\n return f\"{self.friendly_name}\"\n\n\n\"\"\"\nContact response model for translatable contact responses\n\"\"\"\n\n\nclass ContactResponse(AbstractTranslatable):\n name = models.CharField(max_length=32)\n slug = models.SlugField(blank=True, null=True)\n message = models.TextField()\n common = models.ForeignKey(\n ContactResponseCommon, on_delete=models.SET_NULL, null=True, blank=True)\n\n def __str__(self):\n return f\"{self.name} - {self.lang}\"\n", "repo_name": "FabianVolkers/homepage", "sub_path": "homepage/portfolio/models.py", "file_name": "models.py", "file_ext": "py", "file_size_in_byte": 16068, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "logging.getLogger", "line_number": 23, "usage_type": "call"}, {"api_name": "django.conf.settings.MAX_PAGES", "line_number": 35, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 35, "usage_type": "name"}, {"api_name": "django.conf.settings.MAX_SECTIONS", "line_number": 39, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 39, "usage_type": "name"}, {"api_name": "django.conf.settings.MAX_NAVLINKS", "line_number": 43, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 43, "usage_type": "name"}, {"api_name": "django.conf.settings.MAX_FOOTERLINKS", "line_number": 45, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 45, "usage_type": "name"}, {"api_name": "django.db.models.Model", "line_number": 66, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 66, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 67, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 67, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 68, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 68, "usage_type": "name"}, {"api_name": "django.db.models.Model", "line_number": 79, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 79, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 80, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 80, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 81, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 81, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 83, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 83, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 85, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 85, "usage_type": "name"}, {"api_name": "django.db.models.SlugField", "line_number": 88, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 88, "usage_type": "name"}, {"api_name": "django.utils.text.slugify", "line_number": 95, "usage_type": "call"}, {"api_name": "django.db.models.Model", "line_number": 106, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 106, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 108, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 108, "usage_type": "name"}, {"api_name": "django.conf.settings.LANGUAGES", "line_number": 109, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 109, "usage_type": "name"}, {"api_name": "django.conf.settings.LANGUAGE_CODE", "line_number": 109, "usage_type": "attribute"}, {"api_name": "django.db.models.Model", "line_number": 130, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 130, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 131, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 131, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 132, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 132, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 133, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 133, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 134, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 134, "usage_type": "name"}, {"api_name": "django.db.models.Model", "line_number": 161, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 161, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 162, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 162, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 164, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 164, "usage_type": "name"}, {"api_name": "django.db.models.SET_NULL", "line_number": 165, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 165, "usage_type": "name"}, {"api_name": "django.db.models.BooleanField", "line_number": 166, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 166, "usage_type": "name"}, {"api_name": "django.db.models.IntegerField", "line_number": 167, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 167, "usage_type": "name"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 171, "usage_type": "call"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 172, "usage_type": "call"}, {"api_name": "django.db.models.CharField", "line_number": 184, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 184, "usage_type": "name"}, {"api_name": "django.db.models.SlugField", "line_number": 186, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 186, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 187, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 187, "usage_type": "name"}, {"api_name": "django.db.models.CASCADE", "line_number": 188, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 188, "usage_type": "name"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 191, "usage_type": "call"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 192, "usage_type": "call"}, {"api_name": "django.utils.text.slugify", "line_number": 200, "usage_type": "call"}, {"api_name": "django.db.models.Model", "line_number": 214, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 214, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 215, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 215, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 216, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 216, "usage_type": "name"}, {"api_name": "django.db.models.IntegerField", "line_number": 217, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 217, "usage_type": "name"}, {"api_name": "django.db.models.Model", "line_number": 228, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 228, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 229, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 229, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 230, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 230, "usage_type": "name"}, {"api_name": "django.db.models.SET_NULL", "line_number": 231, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 231, "usage_type": "name"}, {"api_name": "django.db.models.IntegerField", "line_number": 232, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 232, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 233, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 233, "usage_type": "name"}, {"api_name": "django.db.models.SET_NULL", "line_number": 235, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 235, "usage_type": "name"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 241, "usage_type": "call"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 242, "usage_type": "call"}, {"api_name": "django.db.models.CharField", "line_number": 256, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 256, "usage_type": "name"}, {"api_name": "django.db.models.SlugField", "line_number": 257, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 257, "usage_type": "name"}, {"api_name": "django.db.models.SlugField", "line_number": 258, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 258, "usage_type": "name"}, {"api_name": "django.db.models.TextField", "line_number": 259, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 259, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 260, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 260, "usage_type": "name"}, {"api_name": "django.db.models.CASCADE", "line_number": 261, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 261, "usage_type": "name"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 264, "usage_type": "call"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 265, "usage_type": "call"}, {"api_name": "django.utils.text.slugify", "line_number": 271, "usage_type": "call"}, {"api_name": "django.db.models.Model", "line_number": 285, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 285, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 286, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 286, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 287, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 287, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 289, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 289, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 291, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 291, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 293, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 293, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 295, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 295, "usage_type": "name"}, {"api_name": "django.db.models.SET_NULL", "line_number": 296, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 296, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 297, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 297, "usage_type": "name"}, {"api_name": "django.db.models.SET_NULL", "line_number": 298, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 298, "usage_type": "name"}, {"api_name": "django.db.models.URLField", "line_number": 299, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 299, "usage_type": "name"}, {"api_name": "django.db.models.Model", "line_number": 313, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 313, "usage_type": "name"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 316, "usage_type": "call"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 317, "usage_type": "call"}, {"api_name": "django.db.models.ForeignKey", "line_number": 326, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 326, "usage_type": "name"}, {"api_name": "django.db.models.SET_NULL", "line_number": 326, "usage_type": "attribute"}, {"api_name": "django.db.models.ForeignKey", "line_number": 328, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 328, "usage_type": "name"}, {"api_name": "django.db.models.SET_NULL", "line_number": 329, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 329, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 331, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 331, "usage_type": "name"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 336, "usage_type": "call"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 337, "usage_type": "call"}, {"api_name": "django.db.models.ForeignKey", "line_number": 346, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 346, "usage_type": "name"}, {"api_name": "django.db.models.SET_NULL", "line_number": 346, "usage_type": "attribute"}, {"api_name": "django.db.models.ForeignKey", "line_number": 347, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 347, "usage_type": "name"}, {"api_name": "django.db.models.SET_NULL", "line_number": 348, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 348, "usage_type": "name"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 352, "usage_type": "call"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 353, "usage_type": "call"}, {"api_name": "django.db.models.ForeignKey", "line_number": 362, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 362, "usage_type": "name"}, {"api_name": "django.db.models.SET_NULL", "line_number": 363, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 363, "usage_type": "name"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 367, "usage_type": "call"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 368, "usage_type": "call"}, {"api_name": "django.db.models.Model", "line_number": 382, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 382, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 383, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 383, "usage_type": "name"}, {"api_name": "django.db.models.ImageField", "line_number": 384, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 384, "usage_type": "name"}, {"api_name": "django.db.models.DateTimeField", "line_number": 385, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 385, "usage_type": "name"}, {"api_name": "django.db.models.BooleanField", "line_number": 386, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 386, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 387, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 387, "usage_type": "name"}, {"api_name": "django.db.models.SET_NULL", "line_number": 388, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 388, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 389, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 389, "usage_type": "name"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 393, "usage_type": "call"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 394, "usage_type": "call"}, {"api_name": "django.db.models.CharField", "line_number": 406, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 406, "usage_type": "name"}, {"api_name": "django.db.models.SlugField", "line_number": 407, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 407, "usage_type": "name"}, {"api_name": "django.db.models.TextField", "line_number": 408, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 408, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 409, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 409, "usage_type": "name"}, {"api_name": "django.db.models.CASCADE", "line_number": 411, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 411, "usage_type": "name"}, {"api_name": "django.db.models.TextField", "line_number": 412, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 412, "usage_type": "name"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 415, "usage_type": "call"}, {"api_name": "django.utils.translation.gettext_lazy", "line_number": 416, "usage_type": "call"}, {"api_name": "django.utils.text.slugify", "line_number": 419, "usage_type": "call"}, {"api_name": "django.db.models.Model", "line_number": 435, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 435, "usage_type": "name"}, {"api_name": "django.db.models.UUIDField", "line_number": 436, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 436, "usage_type": "name"}, {"api_name": "uuid.uuid4", "line_number": 437, "usage_type": "attribute"}, {"api_name": "django.db.models.EmailField", "line_number": 438, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 438, "usage_type": "name"}, {"api_name": "django.db.models.BooleanField", "line_number": 439, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 439, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 440, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 440, "usage_type": "name"}, {"api_name": "django.urls.reverse", "line_number": 447, "usage_type": "call"}, {"api_name": "django.http.QueryDict", "line_number": 448, "usage_type": "call"}, {"api_name": "django.conf.settings.BASE_URL", "line_number": 449, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 449, "usage_type": "name"}, {"api_name": "translations.filter_translations", "line_number": 452, "usage_type": "call"}, {"api_name": "django.template.loader.render_to_string", "line_number": 461, "usage_type": "call"}, {"api_name": "django.core.mail.send_mail", "line_number": 464, "usage_type": "call"}, {"api_name": "django.conf.settings.ENVIRONMENT", "line_number": 470, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 470, "usage_type": "name"}, {"api_name": "django.db.models.Model", "line_number": 489, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 489, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 490, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 490, "usage_type": "name"}, {"api_name": "django.db.models.CASCADE", "line_number": 490, "usage_type": "attribute"}, {"api_name": "django.db.models.CharField", "line_number": 491, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 491, "usage_type": "name"}, {"api_name": "django.db.models.TextField", "line_number": 492, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 492, "usage_type": "name"}, {"api_name": "django.db.models.BooleanField", "line_number": 493, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 493, "usage_type": "name"}, {"api_name": "django.db.models.DateTimeField", "line_number": 494, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 494, "usage_type": "name"}, {"api_name": "django.db.models.DateTimeField", "line_number": 495, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 495, "usage_type": "name"}, {"api_name": "django.template.loader.get_template", "line_number": 502, "usage_type": "call"}, {"api_name": "django.conf.settings.EMAIL_CONTACT_ADDRESS", "line_number": 517, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 517, "usage_type": "name"}, {"api_name": "django.core.mail.EmailMultiAlternatives", "line_number": 519, "usage_type": "call"}, {"api_name": "django.conf.settings.EMAIL_CONTACT_ADDRESS", "line_number": 522, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 522, "usage_type": "name"}, {"api_name": "django.conf.settings.ENVIRONMENT", "line_number": 527, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 527, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 529, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 529, "usage_type": "attribute"}, {"api_name": "django.conf.settings.PYTZ", "line_number": 529, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 529, "usage_type": "name"}, {"api_name": "django.conf.settings.EMAIL_CONTACT_ADDRESS", "line_number": 534, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 534, "usage_type": "name"}, {"api_name": "django.db.models.Model", "line_number": 543, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 543, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 544, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 544, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 545, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 545, "usage_type": "name"}, {"api_name": "django.db.models.SET_NULL", "line_number": 546, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 546, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 547, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 547, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 549, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 549, "usage_type": "name"}, {"api_name": "django.db.models.Model", "line_number": 561, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 561, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 562, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 562, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 563, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 563, "usage_type": "name"}, {"api_name": "django.db.models.SET_NULL", "line_number": 564, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 564, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 576, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 576, "usage_type": "name"}, {"api_name": "django.db.models.SlugField", "line_number": 577, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 577, "usage_type": "name"}, {"api_name": "django.db.models.TextField", "line_number": 578, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 578, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 579, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 579, "usage_type": "name"}, {"api_name": "django.db.models.SET_NULL", "line_number": 580, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 580, "usage_type": "name"}]} +{"seq_id": "3490843070", "text": "import os\r\nimport torch\r\nimport torchaudio\r\nimport random\r\ndirectory = \"D:AudioMNIST/AudioMNIST_ByNumber_1s_8k/\"\r\nnew_directory_train = \"D:AudioMNIST/train/AudioMNIST_ByNumber_1s_8k/\"\r\nnew_directory_test = \"D:AudioMNIST/test/AudioMNIST_ByNumber_1s_8k/\"\r\n\r\nfor subdir, dirs, files in os.walk(directory):\r\n for file in files:\r\n filepath = subdir + os.sep + file\r\n if filepath.endswith(\".wav\"):\r\n filename = file[:-4]\r\n number = file[0]\r\n\r\n wavData, fs = torchaudio.load(filepath)\r\n\r\n #print(wavData.size())\r\n if fs != 8000:\r\n wavData = torchaudio.transforms.Resample(fs, 8000)(wavData)\r\n print(\"finished resampling \" + file)\r\n else:\r\n print(file + \" is already at appropriate fs\")\r\n\r\n length = wavData.squeeze().size()[0]\r\n n_pad = 8000 - length\r\n\r\n if n_pad > 0:\r\n pad = torch.nn.ConstantPad1d((0,n_pad),0)\r\n wavData = pad(wavData)\r\n\r\n if random.random() > .1:\r\n output_filepath = new_directory_train + number\r\n else:\r\n output_filepath = new_directory_test + number\r\n torchaudio.save(output_filepath + os.sep + file, wavData.squeeze(),8000)\r\n", "repo_name": "gavb222/AudioMnist_Classify", "sub_path": "mnist_port.py", "file_name": "mnist_port.py", "file_ext": "py", "file_size_in_byte": 1295, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "os.walk", "line_number": 9, "usage_type": "call"}, {"api_name": "os.sep", "line_number": 11, "usage_type": "attribute"}, {"api_name": "torchaudio.load", "line_number": 16, "usage_type": "call"}, {"api_name": "torchaudio.transforms.Resample", "line_number": 20, "usage_type": "call"}, {"api_name": "torchaudio.transforms", "line_number": 20, "usage_type": "attribute"}, {"api_name": "torch.nn.ConstantPad1d", "line_number": 29, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 29, "usage_type": "attribute"}, {"api_name": "random.random", "line_number": 32, "usage_type": "call"}, {"api_name": "torchaudio.save", "line_number": 36, "usage_type": "call"}, {"api_name": "os.sep", "line_number": 36, "usage_type": "attribute"}]} +{"seq_id": "3545571124", "text": "import os\nimport time\nimport pandas as pd\nfrom selenium.webdriver.common.by import By\nfrom system_upgread.check_internet_connection import CheckInternetConnection\n\n\nclass Main:\n def run_all_script(self, driver):\n time.sleep(2)\n driver.implicitly_wait(10)\n check_in_date_x_path = \"//div[@class='arrival-date dateInput']\"\n check_in_element = driver.find_element(By.XPATH, check_in_date_x_path)\n print(check_in_element)\n check_in_element.click()\n\n time.sleep(2)\n driver.implicitly_wait(10)\n two_thousand_twenty_fore_x_path = \"(//span[normalize-space()='2024'])[1]\"\n two_thousand_twenty_element = driver.find_elements(By.XPATH, two_thousand_twenty_fore_x_path)\n print(two_thousand_twenty_element)\n\n while True:\n\n if len(two_thousand_twenty_element) == 0:\n time.sleep(2)\n driver.implicitly_wait(10)\n next_x_path = \"//a[@title='Next']\"\n next_element = driver.find_element(By.XPATH, next_x_path)\n next_element.click()\n print(next_element)\n\n april_x_path = \"(//span[normalize-space()='April'])[1]\"\n if driver.find_elements(By.XPATH, april_x_path):\n april_element = driver.find_element(By.XPATH, april_x_path)\n\n print(april_element.text)\n\n time.sleep(2)\n driver.implicitly_wait(10)\n select_check_in_date_x_path = \"(//a[@href='#'][normalize-space()='21'])[1]\"\n select_check_in_element = driver.find_element(By.XPATH, select_check_in_date_x_path)\n print(select_check_in_element)\n select_check_in_element.click()\n\n time.sleep(2)\n driver.implicitly_wait(10)\n select_check_out_date_x_path = \"(//a[@href='#'][normalize-space()='28'])[1]\"\n select_check_out_element = driver.find_element(By.XPATH, select_check_out_date_x_path)\n print(select_check_out_element)\n select_check_out_element.click()\n\n time.sleep(2)\n driver.implicitly_wait(10)\n search_x_path = \"(//button[@type='submit'][normalize-space()='Search'])[2]\"\n search_element = driver.find_element(By.XPATH, search_x_path)\n print(search_element)\n search_element.click()\n\n time.sleep(2)\n driver.implicitly_wait(10)\n internal_double_room_x_path = \"//li[@data-roomcode='DBL#INT']//span[@class='price']\"\n internal_double_room_element = driver.find_elements(By.XPATH, internal_double_room_x_path)\n print(internal_double_room_element)\n print(len(internal_double_room_element))\n\n internal_double_room_prices = []\n for i in range(len(internal_double_room_element)):\n print(internal_double_room_element[i].text)\n price = internal_double_room_element[i].text\n internal_double_room_prices.append(price)\n\n data = {'Price': internal_double_room_prices}\n df = pd.DataFrame(data)\n\n # Specify the file path where you want to save the Excel file\n home_directory = os.path.expanduser(\"~\")\n file_path = os.path.join(home_directory, 'room_prices.xlsx')\n\n # Save the DataFrame to an Excel file\n df.to_excel(file_path, index=False)\n\n print(f'Prices have been saved to {file_path}')\n\n break\n\n\nif __name__ == \"__main__\":\n CheckInternetConnection().try_until_connect()\n from driver.driver import Driver\n from login.login import Login\n\n driver = Driver().driver\n driver.get(\"https://www.universalbeachhotels.com/en/hoteles/universal-hotel-marques\")\n time.sleep(4)\n Login().login(driver)\n Main().run_all_script(driver)\n", "repo_name": "sushen/UniversalBeachHotels", "sub_path": "main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 4145, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "time.sleep", "line_number": 10, "usage_type": "call"}, {"api_name": "selenium.webdriver.common.by.By.XPATH", "line_number": 13, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.by.By", "line_number": 13, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 17, "usage_type": "call"}, {"api_name": "selenium.webdriver.common.by.By.XPATH", "line_number": 20, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.by.By", "line_number": 20, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 26, "usage_type": "call"}, {"api_name": "selenium.webdriver.common.by.By.XPATH", "line_number": 29, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.by.By", "line_number": 29, "usage_type": "name"}, {"api_name": "selenium.webdriver.common.by.By.XPATH", "line_number": 34, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.by.By", "line_number": 34, "usage_type": "name"}, {"api_name": "selenium.webdriver.common.by.By.XPATH", "line_number": 35, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.by.By", "line_number": 35, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 39, "usage_type": "call"}, {"api_name": "selenium.webdriver.common.by.By.XPATH", "line_number": 42, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.by.By", "line_number": 42, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 46, "usage_type": "call"}, {"api_name": "selenium.webdriver.common.by.By.XPATH", "line_number": 49, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.by.By", "line_number": 49, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 53, "usage_type": "call"}, {"api_name": "selenium.webdriver.common.by.By.XPATH", "line_number": 56, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.by.By", "line_number": 56, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 60, "usage_type": "call"}, {"api_name": "selenium.webdriver.common.by.By.XPATH", "line_number": 63, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.by.By", "line_number": 63, "usage_type": "name"}, {"api_name": "pandas.DataFrame", "line_number": 74, "usage_type": "call"}, {"api_name": "os.path.expanduser", "line_number": 77, "usage_type": "call"}, {"api_name": "os.path", "line_number": 77, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 78, "usage_type": "call"}, {"api_name": "os.path", "line_number": 78, "usage_type": "attribute"}, {"api_name": "system_upgread.check_internet_connection.CheckInternetConnection", "line_number": 89, "usage_type": "call"}, {"api_name": "driver.driver", "line_number": 93, "usage_type": "name"}, {"api_name": "driver.driver.Driver", "line_number": 93, "usage_type": "call"}, {"api_name": "driver.driver.get", "line_number": 94, "usage_type": "call"}, {"api_name": "driver.driver", "line_number": 94, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 95, "usage_type": "call"}, {"api_name": "driver.driver", "line_number": 96, "usage_type": "argument"}, {"api_name": "login.login.Login", "line_number": 96, "usage_type": "call"}, {"api_name": "driver.driver", "line_number": 97, "usage_type": "argument"}]} +{"seq_id": "75014175091", "text": "\"\"\"LITReview URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/4.0/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf import settings\nfrom django.conf.urls.static import static\nfrom django.contrib import admin\nfrom django.contrib.auth.views import LoginView\nfrom django.urls import path\n\nimport authentication.views, review.views\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('', LoginView.as_view(\n template_name='authentication/login.html',\n redirect_authenticated_user=True),\n name='login'),\n path('signup/', authentication.views.signup_page, name='signup'),\n path('logout/', authentication.views.logout_user, name='logout'),\n path('home/', review.views.home, name='home' ),\n path('posts/', review.views.posts_user, name='posts'),\n path('posts/create-ticket/', review.views.create_ticket, name='create-ticket'),\n path('posts/edit-ticket//', review.views.EditTicket.as_view(), name='edit-ticket'),\n path('posts/delete-ticket//', review.views.DeleteTicket.as_view(), name='delete-ticket'),\n path('posts//', review.views.DetailTicket.as_view(), name='detail-ticket'),\n path('posts//add/', review.views.ReviewFormView.as_view(), name='response'),\n path('posts/new-review/', review.views.new_review, name='new-review'),\n path('posts/edit-review//', review.views.EditReview.as_view(), name='edit-review'),\n path('posts/delete-review//', review.views.DeleteReview.as_view(), name='delete-review'),\n path('follows/', review.views.FollowsList.as_view(), name='follows'),\n path('follows/search-follows/', review.views.search_follows, name='search-follows'),\n path('follows/add-follow/', review.views.add_follow, name='add-follow'),\n path('follows/unfollow/', review.views.unfollow, name='unfollow')\n]\n\nif settings.DEBUG:\n urlpatterns += static(\n settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n", "repo_name": "AlxandrV/LITReview", "sub_path": "LITReview/LITReview/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 2479, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "django.urls.path", "line_number": 25, "usage_type": "call"}, {"api_name": "django.contrib.admin.site", "line_number": 25, "usage_type": "attribute"}, {"api_name": "django.contrib.admin", "line_number": 25, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 26, "usage_type": "call"}, {"api_name": "django.contrib.auth.views.LoginView.as_view", "line_number": 26, "usage_type": "call"}, {"api_name": "django.contrib.auth.views.LoginView", "line_number": 26, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 30, "usage_type": "call"}, {"api_name": "authentication.views.views", "line_number": 30, "usage_type": "attribute"}, {"api_name": "authentication.views", "line_number": 30, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 31, "usage_type": "call"}, {"api_name": "authentication.views.views", "line_number": 31, "usage_type": "attribute"}, {"api_name": "authentication.views", "line_number": 31, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 32, "usage_type": "call"}, {"api_name": "review.views.views", "line_number": 32, "usage_type": "attribute"}, {"api_name": "review.views", "line_number": 32, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 33, "usage_type": "call"}, {"api_name": "review.views.views", "line_number": 33, "usage_type": "attribute"}, {"api_name": "review.views", "line_number": 33, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 34, "usage_type": "call"}, {"api_name": "review.views.views", "line_number": 34, "usage_type": "attribute"}, {"api_name": "review.views", "line_number": 34, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 35, "usage_type": "call"}, {"api_name": "review.views.views.EditTicket.as_view", "line_number": 35, "usage_type": "call"}, {"api_name": "review.views.views", "line_number": 35, "usage_type": "attribute"}, {"api_name": "review.views", "line_number": 35, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 36, "usage_type": "call"}, {"api_name": "review.views.views.DeleteTicket.as_view", "line_number": 36, "usage_type": "call"}, {"api_name": "review.views.views", "line_number": 36, "usage_type": "attribute"}, {"api_name": "review.views", "line_number": 36, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 37, "usage_type": "call"}, {"api_name": "review.views.views.DetailTicket.as_view", "line_number": 37, "usage_type": "call"}, {"api_name": "review.views.views", "line_number": 37, "usage_type": "attribute"}, {"api_name": "review.views", "line_number": 37, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 38, "usage_type": "call"}, {"api_name": "review.views.views.ReviewFormView.as_view", "line_number": 38, "usage_type": "call"}, {"api_name": "review.views.views", "line_number": 38, "usage_type": "attribute"}, {"api_name": "review.views", "line_number": 38, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 39, "usage_type": "call"}, {"api_name": "review.views.views", "line_number": 39, "usage_type": "attribute"}, {"api_name": "review.views", "line_number": 39, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 40, "usage_type": "call"}, {"api_name": "review.views.views.EditReview.as_view", "line_number": 40, "usage_type": "call"}, {"api_name": "review.views.views", "line_number": 40, "usage_type": "attribute"}, {"api_name": "review.views", "line_number": 40, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 41, "usage_type": "call"}, {"api_name": "review.views.views.DeleteReview.as_view", "line_number": 41, "usage_type": "call"}, {"api_name": "review.views.views", "line_number": 41, "usage_type": "attribute"}, {"api_name": "review.views", "line_number": 41, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 42, "usage_type": "call"}, {"api_name": "review.views.views.FollowsList.as_view", "line_number": 42, "usage_type": "call"}, {"api_name": "review.views.views", "line_number": 42, "usage_type": "attribute"}, {"api_name": "review.views", "line_number": 42, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 43, "usage_type": "call"}, {"api_name": "review.views.views", "line_number": 43, "usage_type": "attribute"}, {"api_name": "review.views", "line_number": 43, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 44, "usage_type": "call"}, {"api_name": "review.views.views", "line_number": 44, "usage_type": "attribute"}, {"api_name": "review.views", "line_number": 44, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 45, "usage_type": "call"}, {"api_name": "review.views.views", "line_number": 45, "usage_type": "attribute"}, {"api_name": "review.views", "line_number": 45, "usage_type": "name"}, {"api_name": "django.conf.settings.DEBUG", "line_number": 48, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 48, "usage_type": "name"}, {"api_name": "django.conf.urls.static.static", "line_number": 49, "usage_type": "call"}, {"api_name": "django.conf.settings.MEDIA_URL", "line_number": 50, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 50, "usage_type": "name"}, {"api_name": "django.conf.settings.MEDIA_ROOT", "line_number": 50, "usage_type": "attribute"}]} +{"seq_id": "74030757492", "text": "#!/usr/bin/env python3\nimport logging as log\nfrom random import choice\nfrom threading import Thread\n\nimport utils\n\n# If true, the threads will be executed in background and\n# the program will exit.\nRUN_AS_DAEMON = False\n\n# If true, the \"main\" thread will wait all other threads\n# to be finished.\nWAIT_THREADS = False\n\n\ndef main(pkg_version):\n main_thread = utils.thread_label('main', utils.RED)\n log.info(f'{main_thread} Creating threads...')\n\n sub_thread = Thread(\n target=utils.download_file,\n args=(1, pkg_version, choice(utils.COLORS)),\n daemon=RUN_AS_DAEMON\n )\n log.info(f'{main_thread} Ready? Go!')\n sub_thread.start()\n\n flag = \"yes\" if WAIT_THREADS else \"no\"\n log.info(f'{main_thread} Wait for the thread to finish? [{flag}]')\n if WAIT_THREADS:\n sub_thread.join()\n\n log.info(f'{main_thread} Done!')\n\n\nif __name__ == '__main__':\n utils.init_logs()\n main('3.0.1')\n", "repo_name": "avcaliani/python-apps", "sub_path": "py-threads/single-file.py", "file_name": "single-file.py", "file_ext": "py", "file_size_in_byte": 933, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "21", "api": [{"api_name": "utils.thread_label", "line_number": 18, "usage_type": "call"}, {"api_name": "utils.RED", "line_number": 18, "usage_type": "attribute"}, {"api_name": "logging.info", "line_number": 19, "usage_type": "call"}, {"api_name": "threading.Thread", "line_number": 21, "usage_type": "call"}, {"api_name": "utils.download_file", "line_number": 22, "usage_type": "attribute"}, {"api_name": "random.choice", "line_number": 23, "usage_type": "call"}, {"api_name": "utils.COLORS", "line_number": 23, "usage_type": "attribute"}, {"api_name": "logging.info", "line_number": 26, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 30, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 34, "usage_type": "call"}, {"api_name": "utils.init_logs", "line_number": 38, "usage_type": "call"}]} +{"seq_id": "44501415435", "text": "import os\nimport librosa.display\nimport numpy as np\nfrom parameters import *\n\ndir_str = \"./DRUM_LOOPS_DS\"\ndirectory = os.fsencode(dir_str)\n\nfor file in os.listdir(directory):\n filename = os.fsdecode(file)\n filename_wo_ext = filename[:-4]\n if filename.endswith(\".wav\"):\n y, SR = librosa.load(\"./DRUM_LOOPS_DS/\" + filename, sr=SR, duration=DURATION)\n tempo, beat_frames = librosa.beat.beat_track(y=y, sr=SR)\n print('Estimated tempo: {:.2f} beats per minute'.format(tempo))\n\n mspec = librosa.feature.melspectrogram(y=y,\n sr=SR,\n n_fft=N_FFT,\n hop_length=HOP_LENGTH,\n win_length=None,\n window='hann',\n center=True,\n pad_mode='reflect',\n power=2.0,\n n_mels=N_MELS)\n print(mspec.shape)\n np.save(\"./MEL_DRUMS_Converted/\" + filename_wo_ext, mspec)\n continue\n else:\n continue\n", "repo_name": "jboerschel/AML-Music-Gen", "sub_path": "WAV_to_MEL_conversion.py", "file_name": "WAV_to_MEL_conversion.py", "file_ext": "py", "file_size_in_byte": 1249, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "os.fsencode", "line_number": 7, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 9, "usage_type": "call"}, {"api_name": "os.fsdecode", "line_number": 10, "usage_type": "call"}, {"api_name": "librosa.display.load", "line_number": 13, "usage_type": "call"}, {"api_name": "librosa.display", "line_number": 13, "usage_type": "name"}, {"api_name": "librosa.display.beat.beat_track", "line_number": 14, "usage_type": "call"}, {"api_name": "librosa.display.beat", "line_number": 14, "usage_type": "attribute"}, {"api_name": "librosa.display", "line_number": 14, "usage_type": "name"}, {"api_name": "librosa.display.feature.melspectrogram", "line_number": 17, "usage_type": "call"}, {"api_name": "librosa.display.feature", "line_number": 17, "usage_type": "attribute"}, {"api_name": "librosa.display", "line_number": 17, "usage_type": "name"}, {"api_name": "numpy.save", "line_number": 28, "usage_type": "call"}]} +{"seq_id": "7881961416", "text": "import csv\nimport os\nimport sys\n#from sklearn.svm import SVC\n#from sklearn.preprocessing import normalize\nimport numpy as np\nfrom catboost import CatBoostClassifier, Pool\nfrom sklearn.metrics import average_precision_score\n\n#print(sys.version_info)\ntrain_data = []\ntrain_label = []\ntestPrivate_data = []\nPrivate_Y = []\ntestPublic_data = []\nPublic_Y = []\n\nwith open('Train.csv','rb') as traincsv:\n cnt = 0\n reader = csv.reader(traincsv)\n next(reader)\n for row in reader: \n tmp = row[1:23]\n train_data.append(tmp)\n train_label.append(row[24])\n\nwith open('Test_Public.csv','rb') as testcsv:\n reader = csv.reader(testcsv)\n next(reader)\n cnt = 0\n for row in reader:\n tmp = row[1:23] \n testPublic_data.append(tmp)\n\nwith open('Test_Private.csv','rb') as testcsv:\n reader = csv.reader(testcsv)\n next(reader)\n for row in reader:\n tmp = row[1:23]\n testPrivate_data.append(tmp)\n\n\n\nmodel = CatBoostClassifier()#(iterations=1000, depth=12, learning_rate=0.01, loss_function='Logloss', logging_level='Verbose')\ntrain_pool = Pool(train_data, train_label)#, cat_features=[0,2,5])\nmodel.fit(train_pool)\n\n\npredsPublic_proba = model.predict_proba(testPublic_data)\nPublic_Y = sorted(range(len(predsPublic_proba)),key=lambda i: -predsPublic_proba[i][1])\n\npredsPrivate_proba = model.predict_proba(testPrivate_data)\nPrivate_Y = sorted(range(len(predsPrivate_proba)),key=lambda i: -predsPrivate_proba[i][1])\n#print(\"proba = \", predsPrivate_proba)\n\n#print(\"sort = \", Public_Y)\n\n\nwith open('pub.csv','w') as f:\n f.write('Rank_ID')\n f.write('\\n')\n for i in range (5000):\n f.writelines(str(Public_Y[i]+1))\n f.write('\\n')\n\n\nwith open('private777.csv','w') as f:\n f.write('Rank_ID')\n f.write('\\n')\n for i in range (5000):\n f.writelines(str(Private_Y[i]+1))\n f.write('\\n') \n \n\n \n\n\n ", "repo_name": "xxxsarahfu/AIML2017", "sub_path": "data/tr+pred.py", "file_name": "tr+pred.py", "file_ext": "py", "file_size_in_byte": 1955, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "csv.reader", "line_number": 20, "usage_type": "call"}, {"api_name": "csv.reader", "line_number": 28, "usage_type": "call"}, {"api_name": "csv.reader", "line_number": 36, "usage_type": "call"}, {"api_name": "catboost.CatBoostClassifier", "line_number": 44, "usage_type": "call"}, {"api_name": "catboost.Pool", "line_number": 45, "usage_type": "call"}]} +{"seq_id": "42630727743", "text": "from glom import glom, Coalesce\n\ndata = {'a': {'b': {'c': 'd'}}}\ndata['a']['b']['c']\ndata.get('a').get('b').get('c')\ndata.get('a', {}).get('b', {}).get('c')\n\nglom(data, 'a.b.c')\n\ntarget = {'system': {'planets': [{'name': 'earth', 'moons': 1},\n {'name': 'jupiter', 'moons': 69}]}}\n\n# 自定义的格式\nspec = {'names': ('system.planets', ['name']),\n 'moons': ('system.planets', ['moons'])}\nprint(glom(target, spec))\n# {'moons': [1, 69], 'names': ['earth', 'jupiter']}\n\n\n# Coalesce 合并\nspec = {'names': (Coalesce('system.planets', 'system.dwarf_planets'), ['name']),\n 'moons': (Coalesce('system.planets', 'system.dwarf_planets'), ['moons'])}\nprint(glom(target, spec))\n\n# 求和\nprint(glom(target, {'moon_count': ('system.planets', ['moons'], sum)}))\n\n\ntarget = {\n 'data': {\n 'name': 'just_test',\n 'likes': [{'ball': 'basketball'},\n {'ball': 'football'},\n {'water': 'swim'}]\n }\n}\n\n# 希望 {'name': 'just_for_test', 'likes': ['basketball', 'football', 'water']}\n\n\nspec = {\n 'name': ('data.name'),\n 'likes': ('data.likes', [lambda x: x.values()[0] if 'ball' or 'water' in x.keys() else '']),\n}\n\nprint(glom(target, spec))", "repo_name": "SmallBlackBeans/pythonPractice", "sub_path": "hello/数据处理/嵌套数据处理.py", "file_name": "嵌套数据处理.py", "file_ext": "py", "file_size_in_byte": 1226, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "glom.glom", "line_number": 8, "usage_type": "call"}, {"api_name": "glom.glom", "line_number": 16, "usage_type": "call"}, {"api_name": "glom.Coalesce", "line_number": 21, "usage_type": "call"}, {"api_name": "glom.Coalesce", "line_number": 22, "usage_type": "call"}, {"api_name": "glom.glom", "line_number": 23, "usage_type": "call"}, {"api_name": "glom.glom", "line_number": 26, "usage_type": "call"}, {"api_name": "glom.glom", "line_number": 46, "usage_type": "call"}]} +{"seq_id": "8000603694", "text": "from django.http import HttpResponse\nfrom django.shortcuts import render\nfrom rest_framework import status\nfrom rest_framework.response import Response\nfrom rest_framework.decorators import api_view\nfrom django.views.decorators.csrf import csrf_exempt\n# Create your views here.\nfrom .models import Rooms\nfrom .serializers import RoomSerializer\n\n\n@api_view(['POST'])\ndef createrooms(request):\n data = request.data\n if not request.session.exists(request.session.session_key):\n request.session.create()\n host = request.session.session_key\n\n room = Rooms.objects.create(\n host=host, guest_can_pause=data['guest_can_pause'], votes_to_skip=data['votes_to_skip'])\n room_ser = RoomSerializer(room, many=False)\n return Response(room_ser.data)\n\n@api_view(['GET'])\ndef getinfoaboutallrooms(request):\n rooms = Rooms.objects.all()\n room_ser = RoomSerializer(rooms, many=True)\n return Response(room_ser.data)\n\n@api_view(['POST'])\ndef updateRoomSettings(request):\n data=request.data\n host=data['host']\n query = Rooms.objects.filter(host=host)\n if query.exists():\n room = query[0]\n room.guest_can_pause = data['guest_can_pause']\n room.votes_to_skip = data['votes_to_skip']\n room.save(update_fields=['guest_can_pause', 'votes_to_skip'])\n room_ser = RoomSerializer(room, many=False)\n return Response(room_ser.data,status=status.HTTP_200_OK)\n return Response({\"msg\":\"Invalid Room\"},status=status.HTTP_404_NOT_FOUND)\n\n@api_view(['GET'])\ndef getRoom(request):\n code = request.GET[\"code\"]\n data= {\"msg\":\"Room Doesnt Exist\"}\n if code!=None:\n room = Rooms.objects.filter(code=code)\n if len(room)>0:\n data=RoomSerializer(room[0],many=False).data\n return Response(data,status=status.HTTP_200_OK)\n return Response(data,status=status.HTTP_404_NOT_FOUND)\n\n@api_view(['POST'])\ndef joinRoom(request):\n data = request.data\n code = data[\"code\"]\n print(code)\n if not request.session.exists(request.session.session_key):\n request.session.create()\n if code!=None:\n room_result = Rooms.objects.filter(code=code)\n if len(room_result)>0:\n room = room_result[0]\n request.session['room_code']=code\n print(RoomSerializer(room,many=False).data)\n return Response(RoomSerializer(room,many=False).data,status=status.HTTP_200_OK)\n return Response({\"msg\": \"Invalid Room Code!!\"},status=status.HTTP_404_NOT_FOUND)\n return Response({\"msg\": \"Bad Request !!\"},status=status.HTTP_400_BAD_REQUEST)\n\n@api_view(['POST'])\ndef deleteRoom(request):\n data = request.data\n rooms = Rooms.objects.get(code=data['code'])\n rooms.delete()\n return Response(\"Deleted the Room\")\n\n", "repo_name": "Gagan666/group-music", "sub_path": "backkend/music_group/api/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 2759, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "models.Rooms.objects.create", "line_number": 19, "usage_type": "call"}, {"api_name": "models.Rooms.objects", "line_number": 19, "usage_type": "attribute"}, {"api_name": "models.Rooms", "line_number": 19, "usage_type": "name"}, {"api_name": "serializers.RoomSerializer", "line_number": 21, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 22, "usage_type": "call"}, {"api_name": "rest_framework.decorators.api_view", "line_number": 12, "usage_type": "call"}, {"api_name": "models.Rooms.objects.all", "line_number": 26, "usage_type": "call"}, {"api_name": "models.Rooms.objects", "line_number": 26, "usage_type": "attribute"}, {"api_name": "models.Rooms", "line_number": 26, "usage_type": "name"}, {"api_name": "serializers.RoomSerializer", "line_number": 27, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 28, "usage_type": "call"}, {"api_name": "rest_framework.decorators.api_view", "line_number": 24, "usage_type": "call"}, {"api_name": "models.Rooms.objects.filter", "line_number": 34, "usage_type": "call"}, {"api_name": "models.Rooms.objects", "line_number": 34, "usage_type": "attribute"}, {"api_name": "models.Rooms", "line_number": 34, "usage_type": "name"}, {"api_name": "serializers.RoomSerializer", "line_number": 40, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 41, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_200_OK", "line_number": 41, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 41, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 42, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_404_NOT_FOUND", "line_number": 42, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 42, "usage_type": "name"}, {"api_name": "rest_framework.decorators.api_view", "line_number": 30, "usage_type": "call"}, {"api_name": "models.Rooms.objects.filter", "line_number": 49, "usage_type": "call"}, {"api_name": "models.Rooms.objects", "line_number": 49, "usage_type": "attribute"}, {"api_name": "models.Rooms", "line_number": 49, "usage_type": "name"}, {"api_name": "serializers.RoomSerializer", "line_number": 51, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 52, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_200_OK", "line_number": 52, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 52, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 53, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_404_NOT_FOUND", "line_number": 53, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 53, "usage_type": "name"}, {"api_name": "rest_framework.decorators.api_view", "line_number": 44, "usage_type": "call"}, {"api_name": "models.Rooms.objects.filter", "line_number": 63, "usage_type": "call"}, {"api_name": "models.Rooms.objects", "line_number": 63, "usage_type": "attribute"}, {"api_name": "models.Rooms", "line_number": 63, "usage_type": "name"}, {"api_name": "serializers.RoomSerializer", "line_number": 67, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 68, "usage_type": "call"}, {"api_name": "serializers.RoomSerializer", "line_number": 68, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_200_OK", "line_number": 68, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 68, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 69, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_404_NOT_FOUND", "line_number": 69, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 69, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 70, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_400_BAD_REQUEST", "line_number": 70, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 70, "usage_type": "name"}, {"api_name": "rest_framework.decorators.api_view", "line_number": 55, "usage_type": "call"}, {"api_name": "models.Rooms.objects.get", "line_number": 75, "usage_type": "call"}, {"api_name": "models.Rooms.objects", "line_number": 75, "usage_type": "attribute"}, {"api_name": "models.Rooms", "line_number": 75, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 77, "usage_type": "call"}, {"api_name": "rest_framework.decorators.api_view", "line_number": 72, "usage_type": "call"}]} +{"seq_id": "22011509037", "text": "\"\"\"\nThis script tries to test for a data limit on the SEC API.\n\"\"\"\nfrom typing import List\nfrom threading import Thread\nfrom src.secapi_tl import get_registered_ciks, sec_request\n\n\nREQUIRED_CIK_LENGTH = 10\nBASE_URL_SUBMISSIONS = \"https://data.sec.gov/submissions/\"\nCIK_STRING = \"CIK\"\nJSON_FILE = \".json\"\n\nTHREAD_COUNT = 5\nciks_total = get_registered_ciks()\n\n\ndef thread_func(ciks: List[str]):\n for i, cik in enumerate(ciks):\n length_diff = REQUIRED_CIK_LENGTH - len(cik)\n cik_formatted = ('0' * length_diff) + cik\n url = BASE_URL_SUBMISSIONS + CIK_STRING + cik_formatted + JSON_FILE\n response = sec_request(url)\n print(len(response.content))\n\n\n\nif __name__ == \"__main__\":\n\n cik_buckets = [[] for _ in range(THREAD_COUNT)]\n for i, cik in enumerate(ciks_total):\n cik_buckets[i % THREAD_COUNT].append(cik)\n\n threads = []\n for t in range(THREAD_COUNT):\n bucket = cik_buckets[t]\n thread = Thread(target=thread_func, args=[bucket])\n threads.append(thread)\n thread.start()\n\n for thread in threads:\n thread.join()\n", "repo_name": "tlie03/secapi", "sub_path": "testing/request_get_submissions_test/datalimit_test.py", "file_name": "datalimit_test.py", "file_ext": "py", "file_size_in_byte": 1101, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "src.secapi_tl.get_registered_ciks", "line_number": 15, "usage_type": "call"}, {"api_name": "typing.List", "line_number": 18, "usage_type": "name"}, {"api_name": "src.secapi_tl.sec_request", "line_number": 23, "usage_type": "call"}, {"api_name": "threading.Thread", "line_number": 37, "usage_type": "call"}]} +{"seq_id": "13680740525", "text": "#file to connect stb using telnet\nimport base64\nimport telnetlib\n\nhostip = \"192.168.1.1\"\nuser = \"root\"\n\nsession = telnetlib.Telnet(hsotip)\nsession.read_until(b\"login: \")\nsession.write(user.encode('ascii')+b\"\\n\")\n\nf = open(\"test2.py\")\na=f.read()\nencodedBytes = base64.b64encode(a.encode(\"utf-8\"))\nencodedStr = str(encodedBytes, \"utf-8\")\n\nprint(encodedStr)\n", "repo_name": "divyadivakar06/newrepo", "sub_path": "TelnetSTB.py", "file_name": "TelnetSTB.py", "file_ext": "py", "file_size_in_byte": 355, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "telnetlib.Telnet", "line_number": 8, "usage_type": "call"}, {"api_name": "base64.b64encode", "line_number": 14, "usage_type": "call"}]} +{"seq_id": "34986802050", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('alumno_profesor', '0005_auto_20151217_1616'),\n ]\n\n operations = [\n migrations.RenameField(\n model_name='alumno',\n old_name='estado',\n new_name='is_active',\n ),\n ]\n", "repo_name": "danielhuamani/Proyecto-taller-base-datos", "sub_path": "src/apps/alumno_profesor/migrations/0006_auto_20151220_1948.py", "file_name": "0006_auto_20151220_1948.py", "file_ext": "py", "file_size_in_byte": 398, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "django.db.migrations.Migration", "line_number": 7, "usage_type": "attribute"}, {"api_name": "django.db.migrations", "line_number": 7, "usage_type": "name"}, {"api_name": "django.db.migrations.RenameField", "line_number": 14, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 14, "usage_type": "name"}]} +{"seq_id": "31626303410", "text": "from configparser import ConfigParser\nimport os\n\n\ndef verify_resources(resource_dir):\n output = []\n if not os.path.isdir(RESOURCE_DIR):\n raise NotADirectoryError(\n \"The resources directory is not present. Ensure the resources directory \"\n \"is created and formated properly. \"\n )\n first_dir_list = os.listdir(os.path.join(resource_dir, RESOURCE_DIRS_TO_CHECK[0]))\n for element in first_dir_list:\n present_in_all = True\n for dir in RESOURCE_DIRS_TO_CHECK:\n if not os.path.isdir(os.path.join(RESOURCE_DIR, dir, element)):\n present_in_all = False\n if present_in_all:\n output.append(element)\n return output\n\n\ndef save_resource_to_use(new_value):\n config.set(\"runtime_parameters\", \"RESOURCE_TO_USE\", str(new_value))\n with open(\"config.ini\", \"w\") as configfile:\n config.write(configfile)\n\n\nconfig = ConfigParser()\nconfig.read(\"config.ini\")\n\nCROMWELL_JAR_PATH = config.get(\"cromwell_paths\", \"CROMWELL_JAR_PATH\")\nCROMWELL_JAVA_VERSION = config.get(\"cromwell_paths\", \"CROMWELL_JAVA_VERSION\")\nCROMWELL_EXECUTION_DIRECTORY = config.get(\n \"cromwell_paths\", \"CROMWELL_EXECUTION_DIRECTORY\"\n)\nCROMWELL_CLOUD_URL = config.get(\"cromwell_paths\", \"CROMWELL_CLOUD_URL\")\nRESOURCE_ELEMENT_TO_USE = config.getint(\"runtime_parameters\", \"resource_element_to_use\")\n\nREPO_PATH = os.path.dirname(os.path.realpath(__file__))\nCONFIG_FILE = REPO_PATH + \"/config/cancer_analysis_cromwell_replacement.conf\"\nENTRY_WORKFLOW_FILE = (\n REPO_PATH + \"/workflows/somatic_cancer_genome_analysis_workflow.wdl\"\n)\nALIGN_WORFKLOW_FILE = REPO_PATH + \"/workflows/align_workflow.wdl\"\nSSM_WORKFLOW_FILE = REPO_PATH + \"/workflows/ssm_workflow.wdl\"\nSV_WORKFLOW_FILE = REPO_PATH + \"/workflows/sv_workflow.wdl\"\nCNV_WORKFLOW_FILE = REPO_PATH + \"/workflows/cnv_workflow.wdl\"\nGRIDSS_WORKFLOW_FILE = REPO_PATH + \"/workflows/gridss_workflow.wdl\"\nINPUTS_TEMPLATE_FILE_PATH = (\n REPO_PATH + \"/templates/cancer_analysis_workflow_inputs.json.template\"\n)\nEXECUTE_TEMPLATE_FILE_PATH = REPO_PATH + \"/templates/execute_analysis.sh.template\"\nEXAMPLE_FASTQ_TAB_FILE = REPO_PATH + \"/example_files/example_fastq_input.tsv\"\nEXAMPLE_BAM_TAB_FILE = REPO_PATH + \"/example_files/example_bam_input.tsv\"\nRESOURCE_DIR = REPO_PATH + \"/resources\"\n\nLOG_DIR_RELATIVE = \"/wdl_logs+run_info\"\nPROGRESS_DIR_RELATIVE = LOG_DIR_RELATIVE + \"/progress\"\nRUN_DIR_RELATIVE = LOG_DIR_RELATIVE + \"/wdl_run_info\"\nCROMWELL_LOG_DIR_NAME = \"cromwell_logs\"\nRESOURCE_DIRS_TO_CHECK = [\n \"bwa_reference\",\n \"cnv\",\n \"dummy_key\",\n \"ssm\",\n \"ssm_and_sv_reference\",\n \"sv\",\n]\nRESOURCE_ELEMENTS = verify_resources(RESOURCE_DIR)\nif len(RESOURCE_ELEMENTS) == 0:\n raise ResourceWarning(\n \"Resource directory is not implemented corrected. See README for instructions.\"\n )\n", "repo_name": "shlienlab/WGS_somatic_pipeline", "sub_path": "config.py", "file_name": "config.py", "file_ext": "py", "file_size_in_byte": 2820, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "21", "api": [{"api_name": "os.path.isdir", "line_number": 7, "usage_type": "call"}, {"api_name": "os.path", "line_number": 7, "usage_type": "attribute"}, {"api_name": "os.listdir", "line_number": 12, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 12, "usage_type": "call"}, {"api_name": "os.path", "line_number": 12, "usage_type": "attribute"}, {"api_name": "os.path.isdir", "line_number": 16, "usage_type": "call"}, {"api_name": "os.path", "line_number": 16, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 16, "usage_type": "call"}, {"api_name": "configparser.ConfigParser", "line_number": 29, "usage_type": "call"}, {"api_name": "os.path.dirname", "line_number": 40, "usage_type": "call"}, {"api_name": "os.path", "line_number": 40, "usage_type": "attribute"}, {"api_name": "os.path.realpath", "line_number": 40, "usage_type": "call"}]} +{"seq_id": "13777316824", "text": "import sqlite3\nfrom datetime import datetime\nfrom global_settings import GlobalSettings\nimport json\nimport tkinter.messagebox as messagebox\nimport timer\nimport folders\nimport os\n####################################################################################\n########################################## BDE ############################### \n####################################################################################\ndef create_operator_activity_table():\n GlobalSettings.current_operator_activities_path = f\"{GlobalSettings.current_operator_data_folder}/operator_activities.db\"\n\n # Get the current month and year\n now = datetime.now()\n month = now.strftime(\"%B\")\n year = now.year\n GlobalSettings.current_operator_activity_table_name = table_name = f\"operator_{month}_{year}\"\n\n # Connect to the database (or create it if it doesn't exist)\n conn = sqlite3.connect(GlobalSettings.current_operator_activities_path)\n c = conn.cursor()\n\n c.execute(f\"SELECT name FROM sqlite_master WHERE type='table' AND name='{table_name}'\")\n if c.fetchone() is None:\n # Create the table with the specified columns and primary key\n c.execute(\n f\"CREATE TABLE {table_name} (TS TEXT PRIMARY KEY,RFID \"\n f\"INTEGER NOT NULL,\"\n f\"Order_number INTEGER NOT NULL, Part_number INTEGER NOT NULL, Performance_ID INTEGER NOT NULL , Duration_sec INTEGER NOT \"\n f\"NULL)\")\n conn.commit()\n # Close the connection\n conn.close()\n\n\ndef insert_data_to_operator_activities():\n # Get the current month and year\n now = datetime.now()\n month = now.strftime(\"%B\")\n year = now.year\n\n # Create the table name\n table_name = GlobalSettings.current_operator_activity_table_name\n\n # Connect to the database\n conn = sqlite3.connect(GlobalSettings.current_operator_activities_path)\n c = conn.cursor()\n\n # Insert the data into the table\n c.execute(f\"INSERT INTO {table_name} (TS, RFID, Order_number, Part_number, \"\n f\"Performance_ID, Duration_sec) VALUES (?,?,?,?,?,?)\",\n (GlobalSettings.formatted_operator_activity_start_time,\n GlobalSettings.registed_MAid, GlobalSettings.registered_auftrag_nr,\n GlobalSettings.registered_bauteil_nr, GlobalSettings.registered_operator_activity_id,\n GlobalSettings.operator_activity_duration_sec))\n\n # Save changes and close the connection\n conn.commit()\n conn.close()\n\n\ndef delete_last_row_from_operator_activities():\n # Create the table name\n table_name = GlobalSettings.current_operator_activity_table_name\n\n # Connect to the database\n conn = sqlite3.connect(GlobalSettings.current_operator_activities_path)\n c = conn.cursor()\n\n # Select the last row in the table using the ROWID column\n c.execute(f'SELECT max(rowid) FROM {table_name}')\n last_rowid = c.fetchone()[0]\n\n # Select the data in the last row\n c.execute(f'SELECT * FROM {table_name} WHERE rowid=?', (last_rowid,))\n deleted_data = c.fetchone()\n\n # Delete the last row using the ROWID\n c.execute(f'DELETE FROM {table_name} WHERE rowid=?', (last_rowid,))\n print(f'DELETE FROM {table_name} WHERE rowid=?', (last_rowid,))\n # Save changes and close the connection\n conn.commit()\n conn.close()\n\n # Return the deleted data\n return deleted_data\n\n\n\ndef operator_performance_id_exists(operator_performance_id):\n with sqlite3.connect(GlobalSettings.config_db_name) as con:\n cur = con.cursor()\n cur.execute(\"SELECT 1 FROM operator_performance_type WHERE ID = ?\", (operator_performance_id,))\n result = cur.fetchone()\n return True if result else False\n\n\ndef get_leistungsart_name(ID):\n with sqlite3.connect(GlobalSettings.config_db_name) as conn:\n c = conn.cursor()\n\n # Execute a SELECT statement to retrieve the Leistungart\n c.execute(\"SELECT Performance FROM operator_performance_type WHERE ID = ?\", (ID,))\n\n # Fetch the result\n leistungsart = c.fetchone()[0]\n\n return leistungsart\n\n\n\n\n####################################################################################\n########################################## MDE ############################### \n####################################################################################\ndef create_machine_activity_table():\n GlobalSettings.current_machine_activities_path = f\"{GlobalSettings.current_machine_data_folder}\" \\\n f\"/machine_activities.db\"\n # Get the current month and year\n now = datetime.now()\n month = now.strftime(\"%B\")\n year = now.year\n GlobalSettings.current_machine_activity_table_name = table_name = f\"machine_{month}_{year}\"\n\n # Connect to the database (or create it if it doesn't exist)\n conn = sqlite3.connect(GlobalSettings.current_machine_activities_path)\n c = conn.cursor()\n\n c.execute(f\"SELECT name FROM sqlite_master WHERE type='table' AND name='{table_name}'\")\n if c.fetchone() is None:\n # Create the table with the specified columns and primary key\n c.execute(\n f\"CREATE TABLE {table_name} (TS TEXT PRIMARY KEY,\"\n f\"Order_number INTEGER NOT NULL, Part_number INTEGER NOT NULL, MaschinePerformance_ID INTEGER NOT NULL ,\"\n f\" Duration_sec INTEGER NOT NULL)\")\n conn.commit()\n # Close the connection\n conn.close()\n\n\ndef insert_data_to_machine_activities():\n # Get the current month and year\n now = datetime.now()\n month = now.strftime(\"%B\")\n year = now.year\n\n # Create the table name\n table_name = GlobalSettings.current_machine_activity_table_name\n\n # Connect to the database\n conn = sqlite3.connect(GlobalSettings.current_machine_activities_path)\n c = conn.cursor()\n\n # Insert the data into the table\n c.execute(f\"INSERT INTO {table_name} (TS, Order_number, Part_number, \"\n f\"MaschinePerformance_ID, Duration_sec) VALUES (?,?,?,?,?)\",\n (GlobalSettings.formatted_machine_activity_start_time,\n GlobalSettings.registered_auftrag_nr,\n GlobalSettings.registered_tool_nr, GlobalSettings.registered_machine_activity_name_short_form,\n GlobalSettings.machine_activity_duration_sec))\n\n # Save changes and close the connection\n conn.commit()\n conn.close()\n\n\n\ndef delete_last_row_from_machine_activities():\n # Create the table name\n table_name = GlobalSettings.current_machine_activity_table_name\n\n # Connect to the database\n conn = sqlite3.connect(GlobalSettings.current_machine_activities_path)\n c = conn.cursor()\n\n # Select the last row in the table using the ROWID column\n c.execute(f'SELECT max(rowid) FROM {table_name}')\n last_rowid = c.fetchone()[0]\n\n # Select the data in the last row\n c.execute(f'SELECT * FROM {table_name} WHERE rowid=?', (last_rowid,))\n deleted_data = c.fetchone()\n\n # Delete the last row using the ROWID\n c.execute(f'DELETE FROM {table_name} WHERE rowid=?', (last_rowid,))\n print(f'DELETE FROM {table_name} WHERE rowid=?', (last_rowid,))\n # Save changes and close the connection\n conn.commit()\n conn.close()\n\n # Return the deleted data\n return deleted_data\n\n\n####################################################################################\n################################# user data ############################### \n####################################################################################\n\ndef insert_usr_data(RFID, Avatar_id, First_name, Last_name, Role, Telephone_number_1, Telephone_number_2, Work_email,\n Is_admin):\n with sqlite3.connect(GlobalSettings.config_db_name) as conn:\n c = conn.cursor()\n c.execute(\"\"\"\n INSERT INTO PersonnelData (\n RFID, Avatar_id, First_name , Last_name , Role, Telephone_number_1, Telephone_number_2, Work_email , Is_admin\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)\n \"\"\", (\n RFID, Avatar_id, First_name, Last_name, Role, Telephone_number_1, Telephone_number_2, Work_email, Is_admin))\n conn.commit()\n\n\ndef delete_user(RFID):\n with sqlite3.connect(GlobalSettings.config_db_name) as conn:\n c = conn.cursor()\n c.execute(\"DELETE FROM PersonnelData WHERE RFID = ?\", (RFID,))\n conn.commit()\n\n\ndef rfid_exists(rfid):\n with sqlite3.connect(GlobalSettings.config_db_name) as con:\n cur = con.cursor()\n cur.execute(\"SELECT 1 FROM PersonnelData WHERE RFID = ?\", (rfid,))\n result = cur.fetchone()\n return True if result else False\n\n\ndef get_unused_avatar_names_and_ids():\n results = []\n with sqlite3.connect(GlobalSettings.config_db_name) as conn:\n c = conn.cursor()\n c.execute('''SELECT Avatars.ID, Avatars.Name\n FROM Avatars\n LEFT JOIN PersonnelData ON Avatars.ID = PersonnelData .Avatar_id\n WHERE PersonnelData .Avatar_id IS NULL''')\n tuples = c.fetchall()\n results = [list(t) for t in tuples]\n print('results', results)\n return results\n\n\n## function to return name to be displied as user name\ndef get_name(rfid, option):\n with sqlite3.connect(GlobalSettings.config_db_name) as conn:\n \n cursor = conn.cursor()\n\n cursor.execute(\"SELECT Avatar_id FROM PersonnelData WHERE RFID=?\", (rfid,))\n avatar_id = cursor.fetchone()[0]\n\n cursor.execute(\n \"SELECT Name, First_name , Last_name FROM Avatars JOIN PersonnelData ON Avatars.ID = \"\n \"PersonnelData .Avatar_id WHERE PersonnelData .RFID=?\",\n (rfid,))\n name, First_name, Last_name = cursor.fetchone()\n\n if option == 1:\n return name\n elif option == 2:\n if First_name or Last_name:\n return f\"{First_name} {Last_name}\"\n else:\n return name\n else:\n return name\n\n\ndef get_img_path(rfid):\n try:\n # Connect to the database\n con = sqlite3.connect(GlobalSettings.config_db_name)\n cur = con.cursor()\n\n # Query the 'Avatars' table for the 'img_path' where the 'RFID' in the 'PersonnelData ' table matches the provided RFID\n cur.execute(\n \"SELECT Avatars.img_path FROM Avatars JOIN PersonnelData ON Avatars.ID = PersonnelData .Avatar_id WHERE PersonnelData .RFID = ?\",\n (rfid,))\n\n # Fetch the result\n result = cur.fetchone()\n\n # Close the cursor and connection\n cur.close()\n con.close()\n\n # Return the result\n return result[0]\n except:\n return GlobalSettings.default_img_path\n\n\ndef is_RFID_in_PersonnelData(db_name, RFID):\n conn = sqlite3.connect(db_name)\n cursor = conn.cursor()\n cursor.execute(\"SELECT * FROM PersonnelData WHERE RFID=?\", (RFID,))\n result = cursor.fetchall()\n conn.close()\n\n if len(result) > 0:\n message = \"Die RFID-Karte ist im System vorhanden mit den folgenden Daten:\\n\"\n message += \"RFID: \" + str(result[0][0]) + \"\\n\"\n message += \"Avatar ID: \" + str(result[0][1]) + \"\\n\"\n message += \"First_name : \" + result[0][2] + \"\\n\"\n message += \"Last_name : \" + result[0][3] + \"\\n\"\n message += \"Role: \" + result[0][4] + \"\\n\"\n message += \"Telephone_number_1: \" + result[0][5] + \"\\n\"\n message += \"Telephone_number_2: \" + result[0][6] + \"\\n\"\n message += \"Work_email : \" + result[0][7] + \"\\n\"\n message += \"Is_admin: \" + result[0][8]\n messagebox.showinfo(\"RFID Info\", message)\n return True\n\n else:\n messagebox.showinfo(\"Ok \", \"Done!\")\n return False\n\n\n\n\n######################################################### \n########################## API ##########################\n#########################################################\ndef get_activities_from_to(activity_type, start_date, end_date):\n print('activity_type ',activity_type)\n \"\"\"\n Funktion um Aktivitätsdaten für den Zeitraum zwischen start_date und end_date für einen bestimmten Typ von Aktivität (bde oder mde) zu erhalten.\n :param activity_type: Typ der Aktivität (bde oder mde)\n :param start_date: Anfangsdatum\n :param end_date: Enddatum\n :return: Liste von Aktivitäten im JSON-Format\n \"\"\"\n # create an empty list to store the JSON objects\n json_list = []\n # Überprüfen, ob der übergebene Aktivitätstyp entweder bde oder mde ist\n if activity_type == 'bde':\n print('du willst bde daten haben')\n table_name_ = 'operator'\n source_db_path = 'DB/Erfasste_Betriebsdaten/'\n source_db_name_ ='operator_activities.db'\n elif activity_type == 'mde':\n print('du willst mde daten haben')\n table_name_ = 'machine'\n source_db_path = 'DB/Erfasste_Maschindaten/'\n source_db_name_ ='machine_activities.db'\n else:\n # Fehlermeldung ausgeben, wenn der Typ nicht bde oder mde ist\n print(f\"Eingabe muss entweder bde oder mde sein deine Eingbe war : {activity_type}\")\n return -1\n \n # Liste aller Jahre und Monate zwischen den Daten berechnen\n years_months = timer.months_between_dates(start_date, end_date)\n print(years_months)\n paths = []\n for year, month in years_months:\n source_db_name = source_db_path+ f\"{year}/{month}/\"+ source_db_name_\n table_name = table_name_ +f\"_{month}_{year}\"\n if os.path.exists(source_db_name):\n print('Quelltabelle gefunden', source_db_name)\n # Überprüfen, ob das Datenbank-Response erstellt wurde\n \n # Versuchen, eine Verbindung zur Datenbank herzustellen\n try:\n # Verbindung zur Datenbank herstellen\n conn = sqlite3.connect(source_db_name)\n # Cursor erstellen\n c = conn.cursor()\n # Daten aus der Tabelle abfragen\n c.execute(f\"SELECT * FROM {table_name} WHERE TS BETWEEN '{start_date}' AND '{end_date}'\")\n print(f\"SELECT * FROM {table_name} WHERE TS BETWEEN '{start_date}' AND '{end_date}'\")\n # Ergebnisse abrufen\n results = c.fetchall()\n # Convert the results to a JSON string\n response_json = json.dumps(results)\n json_list.append(json.loads(response_json))\n \n\n\n\n \n\n except Exception as e:\n raise HTTPException(status_code=500, detail=\"Failed to retrieve activity data\")\n\n finally:\n conn.close()\n #print('json_list>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>', json_list)\n # Write the JSON string to a file\n # with open(f\"response.json\", 'w') as f:\n # f.write(str(json_list))\n return json_list\n\n\n\n\n\n\n\n########################################################\n# ############## main ######################\n########################################################\nif __name__ == '__main__':\n \n print(get_activities_from_to('mde', '2022-05-28', '2023-03-24'))\n\n\n\n\n", "repo_name": "aaljalali/MDE_BDE_RING", "sub_path": "BDE/bde_ohen_rfid -with_API/sqlite.py", "file_name": "sqlite.py", "file_ext": "py", "file_size_in_byte": 15361, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "global_settings.GlobalSettings.current_operator_activities_path", "line_number": 13, "usage_type": "attribute"}, {"api_name": "global_settings.GlobalSettings", "line_number": 13, "usage_type": "name"}, {"api_name": "global_settings.GlobalSettings.current_operator_data_folder", "line_number": 13, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 16, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 16, "usage_type": "name"}, {"api_name": "global_settings.GlobalSettings.current_operator_activity_table_name", "line_number": 19, "usage_type": "attribute"}, {"api_name": "global_settings.GlobalSettings", "line_number": 19, "usage_type": "name"}, {"api_name": "sqlite3.connect", "line_number": 22, "usage_type": "call"}, {"api_name": "global_settings.GlobalSettings.current_operator_activities_path", "line_number": 22, "usage_type": "attribute"}, {"api_name": "global_settings.GlobalSettings", "line_number": 22, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 40, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 40, "usage_type": "name"}, {"api_name": "global_settings.GlobalSettings.current_operator_activity_table_name", "line_number": 45, "usage_type": "attribute"}, {"api_name": "global_settings.GlobalSettings", "line_number": 45, "usage_type": "name"}, {"api_name": "sqlite3.connect", "line_number": 48, "usage_type": "call"}, {"api_name": "global_settings.GlobalSettings.current_operator_activities_path", "line_number": 48, "usage_type": "attribute"}, {"api_name": "global_settings.GlobalSettings", "line_number": 48, "usage_type": "name"}, {"api_name": "global_settings.GlobalSettings.formatted_operator_activity_start_time", "line_number": 54, "usage_type": "attribute"}, {"api_name": "global_settings.GlobalSettings", "line_number": 54, "usage_type": "name"}, {"api_name": "global_settings.GlobalSettings.registed_MAid", "line_number": 55, "usage_type": "attribute"}, {"api_name": "global_settings.GlobalSettings", "line_number": 55, "usage_type": "name"}, {"api_name": "global_settings.GlobalSettings.registered_auftrag_nr", "line_number": 55, "usage_type": "attribute"}, {"api_name": "global_settings.GlobalSettings.registered_bauteil_nr", "line_number": 56, "usage_type": "attribute"}, {"api_name": "global_settings.GlobalSettings", "line_number": 56, "usage_type": "name"}, {"api_name": "global_settings.GlobalSettings.registered_operator_activity_id", "line_number": 56, "usage_type": "attribute"}, {"api_name": "global_settings.GlobalSettings.operator_activity_duration_sec", "line_number": 57, "usage_type": "attribute"}, {"api_name": "global_settings.GlobalSettings", "line_number": 57, "usage_type": "name"}, {"api_name": "global_settings.GlobalSettings.current_operator_activity_table_name", "line_number": 66, "usage_type": "attribute"}, {"api_name": "global_settings.GlobalSettings", "line_number": 66, "usage_type": "name"}, {"api_name": "sqlite3.connect", "line_number": 69, "usage_type": "call"}, {"api_name": "global_settings.GlobalSettings.current_operator_activities_path", "line_number": 69, "usage_type": "attribute"}, {"api_name": "global_settings.GlobalSettings", "line_number": 69, "usage_type": "name"}, {"api_name": "sqlite3.connect", "line_number": 93, "usage_type": "call"}, {"api_name": "global_settings.GlobalSettings.config_db_name", "line_number": 93, "usage_type": "attribute"}, {"api_name": "global_settings.GlobalSettings", "line_number": 93, "usage_type": "name"}, {"api_name": "sqlite3.connect", "line_number": 101, "usage_type": "call"}, {"api_name": "global_settings.GlobalSettings.config_db_name", "line_number": 101, "usage_type": "attribute"}, {"api_name": "global_settings.GlobalSettings", "line_number": 101, "usage_type": "name"}, {"api_name": "global_settings.GlobalSettings.current_machine_activities_path", "line_number": 119, "usage_type": "attribute"}, {"api_name": "global_settings.GlobalSettings", "line_number": 119, "usage_type": "name"}, {"api_name": "global_settings.GlobalSettings.current_machine_data_folder", "line_number": 119, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 122, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 122, "usage_type": "name"}, {"api_name": "global_settings.GlobalSettings.current_machine_activity_table_name", "line_number": 125, "usage_type": "attribute"}, {"api_name": "global_settings.GlobalSettings", "line_number": 125, "usage_type": "name"}, {"api_name": "sqlite3.connect", "line_number": 128, "usage_type": "call"}, {"api_name": "global_settings.GlobalSettings.current_machine_activities_path", "line_number": 128, "usage_type": "attribute"}, {"api_name": "global_settings.GlobalSettings", "line_number": 128, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 145, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 145, "usage_type": "name"}, {"api_name": "global_settings.GlobalSettings.current_machine_activity_table_name", "line_number": 150, "usage_type": "attribute"}, {"api_name": "global_settings.GlobalSettings", "line_number": 150, "usage_type": "name"}, {"api_name": "sqlite3.connect", "line_number": 153, "usage_type": "call"}, {"api_name": "global_settings.GlobalSettings.current_machine_activities_path", "line_number": 153, "usage_type": "attribute"}, {"api_name": "global_settings.GlobalSettings", "line_number": 153, "usage_type": "name"}, {"api_name": "global_settings.GlobalSettings.formatted_machine_activity_start_time", "line_number": 159, "usage_type": "attribute"}, {"api_name": "global_settings.GlobalSettings", "line_number": 159, "usage_type": "name"}, {"api_name": "global_settings.GlobalSettings.registered_auftrag_nr", "line_number": 160, "usage_type": "attribute"}, {"api_name": "global_settings.GlobalSettings", "line_number": 160, "usage_type": "name"}, {"api_name": "global_settings.GlobalSettings.registered_tool_nr", "line_number": 161, "usage_type": "attribute"}, {"api_name": "global_settings.GlobalSettings", "line_number": 161, "usage_type": "name"}, {"api_name": "global_settings.GlobalSettings.registered_machine_activity_name_short_form", "line_number": 161, "usage_type": "attribute"}, {"api_name": "global_settings.GlobalSettings.machine_activity_duration_sec", "line_number": 162, "usage_type": "attribute"}, {"api_name": "global_settings.GlobalSettings", "line_number": 162, "usage_type": "name"}, {"api_name": "global_settings.GlobalSettings.current_machine_activity_table_name", "line_number": 172, "usage_type": "attribute"}, {"api_name": "global_settings.GlobalSettings", "line_number": 172, "usage_type": "name"}, {"api_name": "sqlite3.connect", "line_number": 175, "usage_type": "call"}, {"api_name": "global_settings.GlobalSettings.current_machine_activities_path", "line_number": 175, "usage_type": "attribute"}, {"api_name": "global_settings.GlobalSettings", "line_number": 175, "usage_type": "name"}, {"api_name": "sqlite3.connect", "line_number": 203, "usage_type": "call"}, {"api_name": "global_settings.GlobalSettings.config_db_name", "line_number": 203, "usage_type": "attribute"}, {"api_name": "global_settings.GlobalSettings", "line_number": 203, "usage_type": "name"}, {"api_name": "sqlite3.connect", "line_number": 215, "usage_type": "call"}, {"api_name": "global_settings.GlobalSettings.config_db_name", "line_number": 215, "usage_type": "attribute"}, {"api_name": "global_settings.GlobalSettings", "line_number": 215, "usage_type": "name"}, {"api_name": "sqlite3.connect", "line_number": 222, "usage_type": "call"}, {"api_name": "global_settings.GlobalSettings.config_db_name", "line_number": 222, "usage_type": "attribute"}, {"api_name": "global_settings.GlobalSettings", "line_number": 222, "usage_type": "name"}, {"api_name": "sqlite3.connect", "line_number": 231, "usage_type": "call"}, {"api_name": "global_settings.GlobalSettings.config_db_name", "line_number": 231, "usage_type": "attribute"}, {"api_name": "global_settings.GlobalSettings", "line_number": 231, "usage_type": "name"}, {"api_name": "sqlite3.connect", "line_number": 245, "usage_type": "call"}, {"api_name": "global_settings.GlobalSettings.config_db_name", "line_number": 245, "usage_type": "attribute"}, {"api_name": "global_settings.GlobalSettings", "line_number": 245, "usage_type": "name"}, {"api_name": "sqlite3.connect", "line_number": 272, "usage_type": "call"}, {"api_name": "global_settings.GlobalSettings.config_db_name", "line_number": 272, "usage_type": "attribute"}, {"api_name": "global_settings.GlobalSettings", "line_number": 272, "usage_type": "name"}, {"api_name": "global_settings.GlobalSettings.default_img_path", "line_number": 290, "usage_type": "attribute"}, {"api_name": "global_settings.GlobalSettings", "line_number": 290, "usage_type": "name"}, {"api_name": "sqlite3.connect", "line_number": 294, "usage_type": "call"}, {"api_name": "tkinter.messagebox.showinfo", "line_number": 311, "usage_type": "call"}, {"api_name": "tkinter.messagebox", "line_number": 311, "usage_type": "name"}, {"api_name": "tkinter.messagebox.showinfo", "line_number": 315, "usage_type": "call"}, {"api_name": "tkinter.messagebox", "line_number": 315, "usage_type": "name"}, {"api_name": "timer.months_between_dates", "line_number": 352, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 358, "usage_type": "call"}, {"api_name": "os.path", "line_number": 358, "usage_type": "attribute"}, {"api_name": "sqlite3.connect", "line_number": 365, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 374, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 375, "usage_type": "call"}]} +{"seq_id": "42041294858", "text": "from __future__ import annotations\n\nfrom typing import Optional\n\nfrom src.cats import Wolf, Vampire\nfrom src.events import Event, event_listener\nfrom src.functions import get_all_players\nfrom src.gamestate import GameState\nfrom src.messages import messages\nfrom src.status import add_protection\nfrom src.users import User\n\n\n@event_listener(\"team_win\")\ndef on_team_win(evt: Event, var: GameState, player: User, main_role: str, all_roles: set[str], winner: str):\n if winner == \"monsters\" and main_role == \"monster\":\n evt.data[\"team_win\"] = True\n\n@event_listener(\"chk_win\", priority=4)\ndef on_chk_win(evt: Event, var: GameState, rolemap: dict[str, set[User]], mainroles: dict[User, str], lpl: int, lwolves: int, lrealwolves: int, lvampires: int):\n monsters = rolemap.get(\"monster\", ())\n lm = len(monsters)\n\n if not monsters:\n return\n\n if not lrealwolves:\n evt.data[\"message\"] = messages[\"monster_win\"].format(lm)\n evt.data[\"winner\"] = \"monsters\"\n elif lwolves >= lpl / 2 and not lvampires:\n evt.data[\"message\"] = messages[\"monster_wolf_win\"].format(lm)\n evt.data[\"winner\"] = \"monsters\"\n elif lvampires >= lpl / 2 and not lwolves:\n evt.data[\"message\"] = messages[\"monster_vampire_win\"].format(lm)\n evt.data[\"winner\"] = \"monsters\"\n\n@event_listener(\"send_role\")\ndef on_send_role(evt: Event, var: GameState):\n for monster in get_all_players(var, (\"monster\",)):\n add_protection(var, monster, protector=None, protector_role=\"monster\", scope=Wolf | Vampire, priority=10)\n monster.send(messages[\"monster_notify\"])\n\n@event_listener(\"remove_protection\")\ndef on_remove_protection(evt: Event, var: GameState, target: User, attacker: User, attacker_role: str, protector: User, protector_role: str, reason: str):\n if attacker_role == \"fallen angel\" and protector_role == \"monster\":\n evt.data[\"remove\"] = True\n\n@event_listener(\"get_role_metadata\")\ndef on_get_role_metadata(evt: Event, var: Optional[GameState], kind: str):\n if kind == \"role_categories\":\n evt.data[\"monster\"] = {\"Neutral\", \"Win Stealer\", \"Cursed\"}\n", "repo_name": "lykoss/lykos", "sub_path": "src/roles/monster.py", "file_name": "monster.py", "file_ext": "py", "file_size_in_byte": 2110, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 123, "dataset": "github-code", "pt": "21", "api": [{"api_name": "src.events.Event", "line_number": 15, "usage_type": "name"}, {"api_name": "src.gamestate.GameState", "line_number": 15, "usage_type": "name"}, {"api_name": "src.users.User", "line_number": 15, "usage_type": "name"}, {"api_name": "src.events.event_listener", "line_number": 14, "usage_type": "call"}, {"api_name": "src.events.Event", "line_number": 20, "usage_type": "name"}, {"api_name": "src.gamestate.GameState", "line_number": 20, "usage_type": "name"}, {"api_name": "src.users.User", "line_number": 20, "usage_type": "name"}, {"api_name": "src.messages.messages", "line_number": 28, "usage_type": "name"}, {"api_name": "src.messages.messages", "line_number": 31, "usage_type": "name"}, {"api_name": "src.messages.messages", "line_number": 34, "usage_type": "name"}, {"api_name": "src.events.event_listener", "line_number": 19, "usage_type": "call"}, {"api_name": "src.events.Event", "line_number": 38, "usage_type": "name"}, {"api_name": "src.gamestate.GameState", "line_number": 38, "usage_type": "name"}, {"api_name": "src.functions.get_all_players", "line_number": 39, "usage_type": "call"}, {"api_name": "src.status.add_protection", "line_number": 40, "usage_type": "call"}, {"api_name": "src.cats.Wolf", "line_number": 40, "usage_type": "name"}, {"api_name": "src.cats.Vampire", "line_number": 40, "usage_type": "name"}, {"api_name": "src.messages.messages", "line_number": 41, "usage_type": "name"}, {"api_name": "src.events.event_listener", "line_number": 37, "usage_type": "call"}, {"api_name": "src.events.Event", "line_number": 44, "usage_type": "name"}, {"api_name": "src.gamestate.GameState", "line_number": 44, "usage_type": "name"}, {"api_name": "src.users.User", "line_number": 44, "usage_type": "name"}, {"api_name": "src.events.event_listener", "line_number": 43, "usage_type": "call"}, {"api_name": "src.events.Event", "line_number": 49, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 49, "usage_type": "name"}, {"api_name": "src.gamestate.GameState", "line_number": 49, "usage_type": "name"}, {"api_name": "src.events.event_listener", "line_number": 48, "usage_type": "call"}]} +{"seq_id": "15425477125", "text": "import os\nimport openai\n\nimport tiktoken\n\n# Load your API key from an environment variable or secret management service\n# openai.api_key = os.getenv(\"OPENAI_API_KEY\")\nopenai.api_key = \"sk-\"\ngpt_model = \"text-davinci-003\"\n\n\"\"\"\nGenerate samples with GPT-2 and filter out those that are likely to be\nmemorized samples from the training set.\n\"\"\"\n\nimport logging\nlogging.basicConfig(level='ERROR')\n\nimport argparse\nimport numpy as np\nfrom pprint import pprint\nimport sys\nimport torch\nimport zlib\nfrom tqdm import tqdm\nimport os\nimport math\nos.environ['TRANSFORMERS_CACHE'] = '/scratch/gpfs/blou/.cache/'\nos.environ['TIKTOKEN_CACHE_DIR'] = \"/scratch/gpfs/blou/tmp/\"\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\ndef calculate_perplexity(token_logprobs):\n num_tokens = len(token_logprobs)\n log_prob_sum = sum(token_logprobs)\n avg_log_prob = log_prob_sum / num_tokens\n return np.exp(-avg_log_prob)\n\n\n\ndef print_best(metric, samples, name1, scores1, name2=None, scores2=None, n=10):\n \"\"\"\n print the `n` best samples according to the given `metric`\n \"\"\"\n idxs = np.argsort(metric)[::-1][:n]\n\n for i, idx in enumerate(idxs):\n if scores2 is not None:\n print(f\"{i+1}: {name1}={scores1[idx]:.3f}, {name2}={scores2[idx]:.3f}, score={metric[idx]:.3f}\")\n else:\n print(f\"{i+1}: {name1}={scores1[idx]:.3f}, , score={metric[idx]:.3f}\")\n\n print()\n #for line in samples[idx].split(\"\\n\"):\n # print(f\"\\t {line.rstrip()}\")\n pprint(samples[idx])\n print()\n print()\n \n\ndef parse_commoncrawl(wet_file):\n \"\"\"\n Quick and ugly parsing of a WET file.\n Tested for the May 2021 crawl.\n \"\"\"\n with open(wet_file) as f:\n lines = f.readlines() \n \n start_idxs = [i for i in range(len(lines)) if \"WARC/1.0\" in lines[i]]\n \n all_eng = \"\"\n\n count_eng = 0\n for i in range(len(start_idxs)-1):\n start = start_idxs[i]\n end = start_idxs[i+1]\n if \"WARC-Identified-Content-Language: eng\" in lines[start+7]:\n count_eng += 1\n for j in range(start+10, end):\n all_eng += lines[j]\n\n return all_eng\n\n\ndef main():\n print(f\"using device: {device}\")\n\n if args.internet_sampling:\n print(\"Loading common crawl...\")\n cc = parse_commoncrawl(args.wet_file)\n\n # number of tokens to generate\n seq_len = 256\n\n # sample from the top_k tokens output by the model\n top_k = 40\n\n # print(\"Loading GPT2...\")\n \n # tokenizer = GPT2Tokenizer.from_pretrained('gpt2', cache_dir=\"/scratch/gpfs/blou/.cache/\")\n # tokenizer.padding_side = \"left\" \n # tokenizer.pad_token = tokenizer.eos_token\n tokenizer = tiktoken.encoding_for_model(gpt_model)\n\n # model1 = GPT2LMHeadModel.from_pretrained('gpt2-xl', return_dict=True, cache_dir=\"/scratch/gpfs/blou/.cache/\").to(device)\n # model1.config.pad_token_id = model1.config.eos_token_id\n # model2 = GPT2LMHeadModel.from_pretrained('gpt2', return_dict=True, cache_dir=\"/scratch/gpfs/blou/.cache/\").to(device)\n # model1.eval()\n # model2.eval()\n \n samples = []\n scores = {\"GPT3\": [], \"zlib\": []}\n\n num_batches = int(np.ceil(args.N / args.batch_size))\n with tqdm(total=args.N) as pbar:\n for i in range(num_batches):\n # encode the prompts\n if args.internet_sampling:\n # pick a random 10-token prompt in common crawl \n\n input_len = 10\n input_ids = []\n attention_mask = []\n prompts = []\n while len(input_ids) < args.batch_size:\n # take some random words in common crawl\n r = np.random.randint(0, len(cc))\n prompt = \" \".join(cc[r:r+100].split(\" \")[1:-1])\n\n # make sure we get the same number of tokens for each prompt to enable batching\n # inputs = tokenizer(prompt, return_tensors=\"pt\", max_length=input_len, truncation=True)\n inputs = tokenizer.encode(prompt)[:input_len]\n if len(inputs) == input_len:\n input_ids.append(inputs)\n # attention_mask.append(inputs['attention_mask'][0])\n prompts.append(inputs)\n\n # inputs = {'input_ids': torch.stack(input_ids), \n # 'attention_mask': torch.stack(attention_mask)}\n\n # the actual truncated prompts\n # prompts = tokenizer.batch_decode(inputs['input_ids'], skip_special_tokens=True)\n \n else:\n # prompts = [\"<|endoftext|>\"] * args.batch_size\n input_len = 1\n # inputs = tokenizer(prompts, return_tensors=\"pt\", padding=True)\n prompts = [tokenizer.encode(\"<|endoftext|>\", allowed_special={'<|endoftext|>'}) for i in range(args.batch_size)]\n\n # batch generation\n # output_sequences = model1.generate(\n # input_ids=inputs['input_ids'].to(device),\n # attention_mask=inputs['attention_mask'].to(device),\n # max_length=input_len + seq_len,\n # do_sample=True, \n # top_k=top_k, \n # top_p=1.0\n # )\n # texts = tokenizer.batch_decode(output_sequences, skip_special_tokens=True)\n texts = openai.Completion.create(model=gpt_model, \n prompt=prompts, \n max_tokens=input_len + seq_len,\n top_p=1.0,\n logprobs=1,\n )\n\n\n for choice in texts.choices:\n text = choice.text\n \n p1 = calculate_perplexity(choice['logprobs']['token_logprobs'])\n\n # perplexity on lower-case sample\n # p_lower = calculate_perplexity(text.lower(), choice, tokenizer)\n\n # Zlib \"entropy\" of sample\n zlib_entropy = len(zlib.compress(bytes(text, 'utf-8')))\n\n samples.append(text)\n scores[\"GPT3\"].append(p1)\n # scores[\"Lower\"].append(p_lower.cpu())\n scores[\"zlib\"].append(zlib_entropy)\n\n pbar.update(args.batch_size)\n\n scores[\"GPT3\"] = np.asarray(scores[\"GPT3\"])\n # scores[\"S\"] = np.asarray(scores[\"S\"])\n # scores[\"Lower\"] = np.asarray(scores[\"Lower\"])\n scores[\"zlib\"] = np.asarray(scores[\"zlib\"])\n\n # Sort by perplexity\n metric = -np.log(scores[\"GPT3\"])\n print(f\"======== top sample by GPT3 perplexity: ========\")\n print_best(metric, samples, \"PPL\", scores[\"GPT3\"])\n print()\n print()\n\n # Sort by ratio of log perplexities of S and GPT3 models\n # metric = np.log(scores[\"S\"]) / np.log(scores[\"GPT3\"])\n # print(f\"======== top sample by ratio of S and GPT3 perplexities: ========\")\n # print_best(metric, samples, \"PPL-GPT3\", scores[\"GPT3\"], \"PPL-S\", scores[\"S\"])\n # print()\n # print()\n\n # Sort by ratio of log perplexities of lower-case and normal-case perplexities \n # metric = np.log(scores[\"Lower\"]) / np.log(scores[\"GPT3\"])\n # print(f\"======== top sample by ratio of lower-case and normal-case perplexities: ========\")\n # print_best(metric, samples, \"PPL-GPT3\", scores[\"GPT3\"], \"PPL-GPT3-Lower\", scores[\"Lower\"])\n # print()\n # print()\n\n # Sort by ratio of Zlib entropy and GPT3 perplexity\n metric = scores[\"zlib\"] / np.log(scores[\"GPT3\"])\n print(f\"======== top sample by ratio of Zlib entropy and GPT3 perplexity: ========\")\n print_best(metric, samples, \"PPL-GPT3\", scores[\"GPT3\"], \"Zlib\", scores[\"zlib\"])\n\ndef parse_arguments(argv):\n parser = argparse.ArgumentParser()\n parser.add_argument('--N', type=int, default=1000, help=\"Number of samples to generate\")\n parser.add_argument('--batch-size', type=int, default=10, help=\"Batch size for generation\")\n parser.add_argument('--internet-sampling', action='store_true', help=\"condition the generation using commoncrawl\")\n parser.add_argument('--wet-file', type=str, default=None, help=\"path to a commoncrawl WET file\")\n return parser.parse_args(argv)\n\nif __name__ == '__main__':\n args = parse_arguments(sys.argv[1:])\n main()\n", "repo_name": "brianlou2024/Training-Data-Extraction-Attack-on-LLMs", "sub_path": "gpt-3_extraction.py", "file_name": "gpt-3_extraction.py", "file_ext": "py", "file_size_in_byte": 8366, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "21", "api": [{"api_name": "openai.api_key", "line_number": 8, "usage_type": "attribute"}, {"api_name": "logging.basicConfig", "line_number": 17, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 28, "usage_type": "attribute"}, {"api_name": "os.environ", "line_number": 29, "usage_type": "attribute"}, {"api_name": "torch.device", "line_number": 30, "usage_type": "call"}, {"api_name": "torch.cuda.is_available", "line_number": 30, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 30, "usage_type": "attribute"}, {"api_name": "numpy.exp", "line_number": 36, "usage_type": "call"}, {"api_name": "numpy.argsort", "line_number": 44, "usage_type": "call"}, {"api_name": "pprint.pprint", "line_number": 55, "usage_type": "call"}, {"api_name": "tiktoken.encoding_for_model", "line_number": 102, "usage_type": "call"}, {"api_name": "numpy.ceil", "line_number": 113, "usage_type": "call"}, {"api_name": "tqdm.tqdm", "line_number": 114, "usage_type": "call"}, {"api_name": "numpy.random.randint", "line_number": 126, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 126, "usage_type": "attribute"}, {"api_name": "openai.Completion.create", "line_number": 159, "usage_type": "call"}, {"api_name": "openai.Completion", "line_number": 159, "usage_type": "attribute"}, {"api_name": "zlib.compress", "line_number": 176, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 185, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 188, "usage_type": "call"}, {"api_name": "numpy.log", "line_number": 191, "usage_type": "call"}, {"api_name": "numpy.log", "line_number": 212, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 217, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 225, "usage_type": "attribute"}]} +{"seq_id": "38609790977", "text": "#main\r\nimport pygame as pg\r\nimport random\r\nfrom settings import *\r\nfrom sprites import *\r\n\r\nclass Game:\r\n\tdef __init__(self): #initialize game window\r\n\t\tpg.init() #initialize pygame\r\n\t\tpg.mixer.init() #initialize pygame sounds\r\n\t\tself.screen = pg.display.set_mode((WIDTH,HEIGHT)) #create screen\r\n\t\tpg.display.set_caption(TITLE) #set window title\r\n\t\tself.clock = pg.time.Clock() #create clock\r\n\t\tself.running = True #set run loop to true\r\n\t\t\r\n\tdef new(self): #resets the game\r\n\t\tself.all_sprites = pg.sprite.Group()\r\n\t\tself.player = Player()\r\n\t\tself.all_sprites.add(self.player)\r\n\t\tself.run()\r\n\t\t\r\n\tdef run(self): #game loop\r\n\t\tself.playing = True\r\n\t\twhile self.playing:\r\n\t\t\tself.clock.tick(FPS)\r\n\t\t\tself.events()\r\n\t\t\tself.update()\r\n\t\t\tself.draw()\r\n\t\t\r\n\tdef events(self): #game loop - events\r\n\t\tfor event in pg.event.get():\r\n\t\t\tif event.type == pg.QUIT: #check for QUIT\r\n\t\t\t\tself.playing = False\r\n\t\t\t\tself.running = False\r\n\t\r\n\tdef update(self): #game loop - update\r\n\t\tself.all_sprites.update()\r\n\t\t\r\n\tdef draw(self): #game loop - draw\r\n\t\tself.screen.fill(BLACK)\r\n\t\tself.all_sprites.draw(self.screen)\r\n\t\tpg.display.flip() #*after* drawing everything, flip the display\r\n\t\t\r\n\tdef show_start_screen(self): #show start screen\r\n\t\tpass\r\n\t\t\r\n\tdef show_go_screen(self): #show game over screen\r\n\t\tpass\r\n\t\t\r\ng = Game()\r\ng.show_start_screen()\r\nwhile g.running:\r\n\tg.new()\r\n\tg.show_go_screen()\r\n\t\r\npg.quit()", "repo_name": "wheresthelasagna/lasagna", "sub_path": "main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 1391, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "pygame.init", "line_number": 9, "usage_type": "call"}, {"api_name": "pygame.mixer.init", "line_number": 10, "usage_type": "call"}, {"api_name": "pygame.mixer", "line_number": 10, "usage_type": "attribute"}, {"api_name": "pygame.display.set_mode", "line_number": 11, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 11, "usage_type": "attribute"}, {"api_name": "pygame.display.set_caption", "line_number": 12, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 12, "usage_type": "attribute"}, {"api_name": "pygame.time.Clock", "line_number": 13, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 13, "usage_type": "attribute"}, {"api_name": "pygame.sprite.Group", "line_number": 17, "usage_type": "call"}, {"api_name": "pygame.sprite", "line_number": 17, "usage_type": "attribute"}, {"api_name": "pygame.event.get", "line_number": 31, "usage_type": "call"}, {"api_name": "pygame.event", "line_number": 31, "usage_type": "attribute"}, {"api_name": "pygame.QUIT", "line_number": 32, "usage_type": "attribute"}, {"api_name": "pygame.display.flip", "line_number": 42, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 42, "usage_type": "attribute"}, {"api_name": "pygame.quit", "line_number": 56, "usage_type": "call"}]} +{"seq_id": "13484268305", "text": "import torch\nimport torch.autograd as autograd\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\n\ntorch.manual_seed(1)\nEMBDDING_DIM = 10\nCONTEXT_SIZE = 2 # 2 words to the left, 2 to the right\nraw_text = \"\"\"We are about to study the idea of a computational process.\nComputational processes are abstract beings that inhabit computers.\nAs they evolve, processes manipulate other abstract things called data.\nThe evolution of a process is directed by a pattern of rules\ncalled a program. People create programs to direct processes. In effect,\nwe conjure the spirits of the computer with our spells.\"\"\".split()\n\n# By deriving a set from `raw_text`, we deduplicate the array\nvocab = set(raw_text)\nvocab_size = len(vocab)\n\nword_to_ix = {word: i for i, word in enumerate(vocab)}\ndata = []\nfor i in range(2, len(raw_text) - 2):\n context = [raw_text[i - 2], raw_text[i - 1],\n raw_text[i + 1], raw_text[i + 2]]\n target = raw_text[i]\n data.append((context, target))\nprint(data[:5])\n\n\nclass CBOW(nn.Module):\n\n def __init__(self, vocab_size, embedding_dim, context_size):\n super(CBOW, self).__init__()\n self.embeddings = nn.Embedding(vocab_size, embedding_dim)\n self.linear1 = nn.Linear(embedding_dim, vocab_size)\n\n def forward(self, inputs):\n embeds = self.embeddings(inputs)\n embeds = torch.sum(embeds, 0)\n out = self.linear1(embeds).view((1, -1))\n log_probs = F.log_softmax(out)\n return log_probs\n\n# create your model and train. here are some functions to help you make\n# the data ready for use by your module\nlosses = []\ncritical = nn.NLLLoss()\nmodel = CBOW(vocab_size, EMBDDING_DIM, CONTEXT_SIZE)\noptimizier = optim.SGD(model.parameters(), lr=0.001)\n\nfor epoch in range(10):\n total_loss = torch.Tensor([0])\n for context, label in data:\n context_idxs = [word_to_ix[w] for w in context]\n context_var = autograd.Variable(torch.LongTensor(context_idxs))\n\n model.zero_grad()\n log_probs = model(context_var)\n loss = critical(log_probs, autograd.Variable(torch.LongTensor([word_to_ix[label]])))\n\n loss.backward()\n optimizier.step()\n\n total_loss += loss.data\n losses.append(total_loss)\nprint(losses)\n\ndef make_context_vector(context, word_to_ix):\n idxs = [word_to_ix[w] for w in context]\n tensor = torch.LongTensor(idxs)\n return autograd.Variable(tensor)\n\n\nprint(make_context_vector(data[0][0], word_to_ix)) # example", "repo_name": "JimLee4530/pytorch-tutorials", "sub_path": "Exercise_Continuis_Bag_of_Words.py", "file_name": "Exercise_Continuis_Bag_of_Words.py", "file_ext": "py", "file_size_in_byte": 2494, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "torch.manual_seed", "line_number": 7, "usage_type": "call"}, {"api_name": "torch.nn.Module", "line_number": 31, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 31, "usage_type": "name"}, {"api_name": "torch.nn.Embedding", "line_number": 35, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 35, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 36, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 36, "usage_type": "name"}, {"api_name": "torch.sum", "line_number": 40, "usage_type": "call"}, {"api_name": "torch.nn.functional.log_softmax", "line_number": 42, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 42, "usage_type": "name"}, {"api_name": "torch.nn.NLLLoss", "line_number": 48, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 48, "usage_type": "name"}, {"api_name": "torch.optim.SGD", "line_number": 50, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 50, "usage_type": "name"}, {"api_name": "torch.Tensor", "line_number": 53, "usage_type": "call"}, {"api_name": "torch.autograd.Variable", "line_number": 56, "usage_type": "call"}, {"api_name": "torch.autograd", "line_number": 56, "usage_type": "name"}, {"api_name": "torch.LongTensor", "line_number": 56, "usage_type": "call"}, {"api_name": "torch.autograd.Variable", "line_number": 60, "usage_type": "call"}, {"api_name": "torch.autograd", "line_number": 60, "usage_type": "name"}, {"api_name": "torch.LongTensor", "line_number": 60, "usage_type": "call"}, {"api_name": "torch.LongTensor", "line_number": 71, "usage_type": "call"}, {"api_name": "torch.autograd.Variable", "line_number": 72, "usage_type": "call"}, {"api_name": "torch.autograd", "line_number": 72, "usage_type": "name"}]} +{"seq_id": "70528978292", "text": "#!/usr/bin/env python3\nimport os\nimport mdtraj as md\nimport numpy as np\nimport glob\nimport pickle\nimport pathlib\nimport re\nimport shutil\nimport time\nimport heapq\nimport argparse\nimport MDAnalysis as mda\n\n\n\"\"\"\nThis file can make rid dir for given molecular.\nPlease modify 'pdbname'.\nLast update date: 2021/2/24\nAuthor: Dongdong Wang, Yanze Wang.\n\"\"\"\nnum_sol = None\nbox_size = []\nnum_Na, num_Cl = None, None\n\ndef replace(file_name, pattern, subst):\n \"\"\"\n Replace string in file_name. from pattern to subst. pattern is written by Regular Expression.\n \"\"\"\n file_handel = open(file_name, 'r')\n file_string = file_handel.read()\n file_handel.close()\n file_string = (re.sub(pattern, subst, file_string))\n file_handel = open(file_name, 'w')\n file_handel.write(file_string)\n file_handel.close()\n\n\ndef get_all_dihedral_index(file_path):\n u = mda.Universe(file_path)\n all_res_list = []\n for seg in u.segments:\n chain_res_list = seg.residues.resindices\n if len(chain_res_list) <= 2:\n continue\n else:\n all_res_list += chain_res_list[1:-1].tolist()\n print(\"The dihedral angle indexes selected are:\", all_res_list)\n return all_res_list\n\n\ndef change_his(pdbname):\n \"\"\"\n This function can change all the HIS residues to HSD residues in pdbfile(pdbname). \n it's used to meet the need of force field file. Some pdbs have different H+ sites on HIS residues, varying from HSD to HSP.\n \"\"\"\n with open(pdbname, 'r') as pdb:\n ret = pdb.read()\n ret = ret.replace('HIS', 'HSD')\n with open(pdbname, 'w') as pdb:\n pdb.write(ret)\n\n\ndef run_md(pdbname, loop=0):\n \"\"\"\n Let molecule in pdb files go into the equilibrium state through em, nvt and npt simulations. The boxes information, solvent, ions are added too.\n All initial structures and walkers have the exact same solvent number, ion number, ion type and box size. Concentration of saline is set as 0.15M.\n For this purpose, we record the information of the first structure as the tamplate.\n \"\"\"\n global num_sol, box_size, num_Na, num_Cl\n initial_file = pdbname\n \n # if not os.path.exists(\"topol.top\"):\n print(\"topol.top not found, generate one.\")\n # os.system('echo -e \"1\\n1\\n\" | gmx pdb2gmx -f %s.pdb -o processed.gro -ignh -heavyh > grompp.log 2>&1' % pdbname)\n os.system('echo -e \"1\\n1\\n\" | gmx pdb2gmx -f %s.pdb -o processed.gro -ignh > grompp.log 2>&1' % pdbname)\n initial_file = \"processed.gro\"\n \n if loop == 0:\n print('gmx editconf -f {} -o newbox.gro -d 0.9 -c -bt triclinic'.format(initial_file))\n os.system(\n 'gmx editconf -f {} -o newbox.gro -d 0.9 -c -bt triclinic'.format(initial_file))\n print('gmx solvate -cp newbox.gro -cs spc216.gro -o solv.gro -p topol.top > sol.log 2>&1')\n os.system(\n 'gmx solvate -cp newbox.gro -cs spc216.gro -o solv.gro -p topol.top > sol.log 2>&1')\n with open('solv.gro', 'r') as sol_gro:\n for line in sol_gro.readlines():\n info = line.split()\n # print(info)\n if len(info) == 3:\n if all([all([j.isdigit() for j in i.split('.')]) for i in info]):\n box_size = [float(k)+0.10000 for k in info]\n\n with open('topol.top', 'r') as top:\n for line in top.readlines():\n line_sp = line.split()\n if line_sp == []:\n continue\n if line.split()[0] == 'SOL' and line_sp[1].isdigit():\n num_sol = line_sp[1]\n print('Max number of solvents is:', num_sol)\n os.system(\n 'gmx grompp -f ions.mdp -c solv.gro -p topol.top -o ions.tpr -maxwarn 2 > grompp_ion.log 2>&1')\n os.system(\n 'echo -e \"13\\n\" | gmx genion -s ions.tpr -o solv_ions.gro -p topol.top -pname NA -nname CL -neutral -conc 0.15')\n with open('topol.top', 'r') as top:\n for line in top.readlines():\n line_sp = line.split()\n if line_sp == []:\n continue\n if line.split()[0] == 'NA':\n num_Na = line_sp[1]\n if line.split()[0] == 'CL':\n num_Cl = line_sp[1]\n with open('../box_information.txt', 'w') as box_info:\n box_info.write('num_sol={}\\nbox_size={},{},{}\\nnum_Na={}\\nnum_Cl={}'.format(\n num_sol, box_size[0], box_size[1], box_size[2], num_Na, num_Cl))\n else:\n print('gmx editconf -f {} -o newbox.gro -box {} {} {} -c -bt triclinic'.format(\n initial_file, box_size[0], box_size[1], box_size[2]))\n os.system('gmx editconf -f {} -o newbox.gro -box {} {} {} -c -bt triclinic'.format(\n initial_file, box_size[0], box_size[1], box_size[2]))\n print('gmx solvate -cp newbox.gro -cs spc216.gro -o solv.gro -p topol.top > sol.log 2>&1')\n os.system(\n 'gmx solvate -cp newbox.gro -cs spc216.gro -maxsol {} -o solv.gro -p topol.top > sol.log 2>&1'.format(int(num_sol)))\n\n with open('topol.top', 'r') as top:\n for line in top.readlines():\n line_sp = line.split()\n if line_sp == []:\n continue\n if line.split()[0] == 'SOL' and line_sp[1].isdigit():\n print('Max number of solvents is:', line_sp[1])\n\n os.system(\n 'gmx grompp -f ions.mdp -c solv.gro -p topol.top -o ions.tpr -maxwarn 2 > grompp_ion.log 2>&1')\n os.system('echo -e \"13\\n\" | gmx genion -s ions.tpr -o solv_ions.gro -p topol.top -pname NA -nname CL -neutral -np {} -nn {}'.format(num_Na, num_Cl))\n\n os.system('gmx grompp -f minim.mdp -c solv_ions.gro -p topol.top -o em.tpr -maxwarn 1 > grompp_em.log 2>&1')\n # os.system('gmx mdrun -deffnm em -v -nt 4')\n os.system('gmx mdrun -deffnm em -v -ntmpi 1 -nt 4')\n os.system('gmx grompp -f nvt.mdp -c em.gro -p topol.top -o nvt.tpr -r em.gro -maxwarn 1 > grompp_nvt.log 2>&1')\n command = 'gmx mdrun -deffnm nvt -ntmpi 1 -v -nt 4'\n os.system(command)\n os.system('gmx grompp -f npt.mdp -c nvt.gro -t nvt.cpt -p topol.top -o npt.tpr -r nvt.gro -maxwarn 1 > grompp_npt.log 2>&1')\n command = 'gmx mdrun -deffnm npt -ntmpi 1 -v -nt 4'\n os.system(command)\n # os.system('gmx mdrun -deffnm npt -v -nt 4')\n os.system('cp topol.top topol.top.bak')\n\n\ndef mk_posre(dirname, dih_list, bottom_width=0.4):\n # 1~119 122~228\n # print(list_biased_ang)\n os.system('cp %s/source/jsons/phipsi_selected.json ./' % dirname)\n replace('phipsi_selected.json', '.*selected_index.*',\n ' \"selected_index\": %s,' % dih_list)\n structure = 'nvt.gro'\n # kappa=0.025 #kcal/mol/A2 *4.184*100\n # kappa=15 #kj/mol/nm2\n t_ref = md.load(structure, top=structure)\n topology = t_ref.topology\n ca_atoms = topology.select('name CA')+1\n wf = open('posre.itp.templ', 'w')\n wf.write('[ position_restraints ]\\n; i funct g r(nm) k\\n')\n for i in range(len(ca_atoms)):\n wf.write('%d 2 1 %f TEMP\\n' %\n (ca_atoms[i], bottom_width))\n wf.close()\n\n\ndef mk_rid(dirname, pdbname):\n mol_dir = os.path.join(dirname, 'source/mol/', pdbname)\n print('mol_dir', mol_dir)\n print('pdbname', pdbname)\n print('dirname', dirname)\n pathlib.Path(mol_dir).mkdir(parents=True, exist_ok=True)\n case_path_list = [x for x in glob.glob(\"./*\") if os.path.isdir(x)]\n assert len(case_path_list) > 0\n os.system('cp %s/topol.top %s' % (case_path_list[0], mol_dir))\n os.system('cp %s/*.itp %s' % (case_path_list[0], mol_dir))\n \n for i in range(len(case_path_list)):\n os.system('cp %s/npt.gro %s/conf00%d.gro' % (case_path_list[i], mol_dir, i))\n if len(case_path_list) < 8:\n for j in range(len(case_path_list), 8):\n os.system('cp %s/npt.gro %s/conf00%d.gro' % (case_path_list[0], mol_dir, j))\n os.system('cp %s/npt.gro %s/conf.gro' % (case_path_list[0], mol_dir))\n os.system('cp %s/posre.itp.templ %s/posre.itp' % (case_path_list[0], mol_dir))\n os.system('cp %s/source/mol/*.mdp %s' % (dirname, mol_dir))\n os.chdir('%s/source/' % dirname)#ooi\n os.system('python gen.py rid ./jsons/default_gen.json %s/%s/%s/phipsi_selected.json ./mol/%s/ -o %s/%s.run06' %\n (dirname, pdbname, os.path.basename(case_path_list[0]), pdbname, dirname, pdbname))\n all_itp = glob.glob(os.path.join(dirname, \"source\", \"mol\", pdbname, \"*.itp\"))\n for itp in all_itp:\n shutil.copy(itp, \"{}/{}.run06/template/mol\".format(dirname, pdbname))\n os.chdir('%s/%s' % (dirname, pdbname))\n\n\ndef mk_score(where_rw_dir, where_evo_path, target):\n '''\n generate rwplus dir in *.run dir. 3 files (calRWplus, rw.dat, scb,dat) should be in where_rw_dir.\n Args:\n where_sco_dir: containing rwplus files.\n target: name of protein.\n '''\n score_dir = './{}.run06/score'.format(target) # where they will be copied to.\n if os.path.exists(score_dir):\n shutil.rmtree(score_dir)\n os.mkdir(score_dir)\n os.system('cp -r {}/calRWplus {}'.format(where_rw_dir, score_dir))\n os.system('cp -r {}/rw.dat {}'.format(where_rw_dir, score_dir))\n os.system('cp -r {}/scb.dat {}'.format(where_rw_dir, score_dir))\n os.system('cp -r {}/TMscore {}'.format(os.path.join(where_rw_dir, '..'), score_dir))\n return\n\n\ndef main(target_name, file_path, dih_list, bottom_width):\n pdb_path_list = glob.glob(os.path.join(file_path,\"*.pdb\"))\n pp = target_name.strip()\n pathlib.Path(pp).mkdir(parents=True, exist_ok=True)\n os.chdir(pp) # at R0949/\n for num, rr in enumerate(pdb_path_list):\n pdb_name = os.path.basename(rr).split(\".pdb\")[0]\n if os.path.exists(pdb_name):\n shutil.rmtree(pdb_name)\n pathlib.Path(pdb_name).mkdir(parents=True, exist_ok=True)\n os.chdir(pdb_name)\n os.system('cp %s ./' % (rr))\n os.system('cp %s/topol.top ./' % (file_path))\n os.system('cp %s/*.itp ./' % (file_path))\n os.system('cp %s/mdp/* ./' % dirname)\n os.system('cp -r %s/charmm36-mar2019.ff ./' % dirname)\n change_his('./%s.pdb' % pdb_name)\n run_md(pdb_name, loop=num) \n replace('topol.top', '.*charmm36-mar2019.ff',\n '#include \"{}/charmm36-mar2019.ff'.format(dirname))\n \n mk_posre(dirname, dih_list, bottom_width=bottom_width)\n os.chdir('..')\n \n mk_rid(dirname, target_name)\n os.chdir('..')\n mk_score(where_rw_dir='/home/dongdong/wyz/rwplus/RWplus', where_evo_path=\"/home/dongdong/wyz/EvoEF2-master/EvoEF2\", target=pp)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Make Refinement Directory')\n parser.add_argument('TASK', type=str, help=\"the task name\")\n # parser.add_argument('--mol', type=str)\n parser.add_argument('--mol', type=str)\n parser.add_argument('--all-dihedral', action=\"store_true\")\n parser.add_argument('-c', '--dihedral-index', nargs='+', type=int, default=None, help=\"the indexes of selected dihedral angles.\")\n parser.add_argument('-d', '--bottom-width', type=float, default=0.4, help=\"the width of the bottom of the flat bottom harmonic potential(nm)\")\n parser.add_argument('-r', '--config', type=str, default=None, help='config file')\n args = parser.parse_args()\n dirname = os.getcwd()\n if args.all_dihedral:\n _pdb_list = glob.glob(os.path.join(args.mol, \"*.pdb\"))\n if len(_pdb_list) == 0:\n raise RuntimeError(\"No pdb exists within {}.\".format(args.mol))\n else:\n _pdb = _pdb_list[0]\n dih_list = get_all_dihedral_index(_pdb)\n else:\n if args.dihedral_index is None:\n raise RuntimeError(\"Please set dihedral angle indexes for CVs.\")\n dih_list = args.dihedral_index\n\n\n main(target_name = args.TASK, file_path=args.mol, dih_list=dih_list, bottom_width=args.bottom_width)\n # python mk_rid_refinement.py --mol /home/dongdong/wyz/refinement3_2chain/PDB/test_2chain\n\n\n", "repo_name": "Dead-fisher/Protein-Structure-Refinement", "sub_path": "mk_rid_refinement.py", "file_name": "mk_rid_refinement.py", "file_ext": "py", "file_size_in_byte": 12074, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "re.sub", "line_number": 33, "usage_type": "call"}, {"api_name": "MDAnalysis.Universe", "line_number": 40, "usage_type": "call"}, {"api_name": "os.system", "line_number": 76, "usage_type": "call"}, {"api_name": "os.system", "line_number": 81, "usage_type": "call"}, {"api_name": "os.system", "line_number": 84, "usage_type": "call"}, {"api_name": "os.system", "line_number": 102, "usage_type": "call"}, {"api_name": "os.system", "line_number": 104, "usage_type": "call"}, {"api_name": "os.system", "line_number": 121, "usage_type": "call"}, {"api_name": "os.system", "line_number": 124, "usage_type": "call"}, {"api_name": "os.system", "line_number": 135, "usage_type": "call"}, {"api_name": "os.system", "line_number": 137, "usage_type": "call"}, {"api_name": "os.system", "line_number": 139, "usage_type": "call"}, {"api_name": "os.system", "line_number": 141, "usage_type": "call"}, {"api_name": "os.system", "line_number": 142, "usage_type": "call"}, {"api_name": "os.system", "line_number": 144, "usage_type": "call"}, {"api_name": "os.system", "line_number": 145, "usage_type": "call"}, {"api_name": "os.system", "line_number": 147, "usage_type": "call"}, {"api_name": "os.system", "line_number": 149, "usage_type": "call"}, {"api_name": "os.system", "line_number": 155, "usage_type": "call"}, {"api_name": "mdtraj.load", "line_number": 161, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 173, "usage_type": "call"}, {"api_name": "os.path", "line_number": 173, "usage_type": "attribute"}, {"api_name": "pathlib.Path", "line_number": 177, "usage_type": "call"}, {"api_name": "glob.glob", "line_number": 178, "usage_type": "call"}, {"api_name": "os.path.isdir", "line_number": 178, "usage_type": "call"}, {"api_name": "os.path", "line_number": 178, "usage_type": "attribute"}, {"api_name": "os.system", "line_number": 180, "usage_type": "call"}, {"api_name": "os.system", "line_number": 181, "usage_type": "call"}, {"api_name": "os.system", "line_number": 184, "usage_type": "call"}, {"api_name": "os.system", "line_number": 187, "usage_type": "call"}, {"api_name": "os.system", "line_number": 188, "usage_type": "call"}, {"api_name": "os.system", "line_number": 189, "usage_type": "call"}, {"api_name": "os.system", "line_number": 190, "usage_type": "call"}, {"api_name": "os.chdir", "line_number": 191, "usage_type": "call"}, {"api_name": "os.system", "line_number": 192, "usage_type": "call"}, {"api_name": "os.path.basename", "line_number": 193, "usage_type": "call"}, {"api_name": "os.path", "line_number": 193, "usage_type": "attribute"}, {"api_name": "glob.glob", "line_number": 194, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 194, "usage_type": "call"}, {"api_name": "os.path", "line_number": 194, "usage_type": "attribute"}, {"api_name": "shutil.copy", "line_number": 196, "usage_type": "call"}, {"api_name": "os.chdir", "line_number": 197, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 208, "usage_type": "call"}, {"api_name": "os.path", "line_number": 208, "usage_type": "attribute"}, {"api_name": "shutil.rmtree", "line_number": 209, "usage_type": "call"}, {"api_name": "os.mkdir", "line_number": 210, "usage_type": "call"}, {"api_name": "os.system", "line_number": 211, "usage_type": "call"}, {"api_name": "os.system", "line_number": 212, "usage_type": "call"}, {"api_name": "os.system", "line_number": 213, "usage_type": "call"}, {"api_name": "os.system", "line_number": 214, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 214, "usage_type": "call"}, {"api_name": "os.path", "line_number": 214, "usage_type": "attribute"}, {"api_name": "glob.glob", "line_number": 219, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 219, "usage_type": "call"}, {"api_name": "os.path", "line_number": 219, "usage_type": "attribute"}, {"api_name": "pathlib.Path", "line_number": 221, "usage_type": "call"}, {"api_name": "os.chdir", "line_number": 222, "usage_type": "call"}, {"api_name": "os.path.basename", "line_number": 224, "usage_type": "call"}, {"api_name": "os.path", "line_number": 224, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 225, "usage_type": "call"}, {"api_name": "os.path", "line_number": 225, "usage_type": "attribute"}, {"api_name": "shutil.rmtree", "line_number": 226, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 227, "usage_type": "call"}, {"api_name": "os.chdir", "line_number": 228, "usage_type": "call"}, {"api_name": "os.system", "line_number": 229, "usage_type": "call"}, {"api_name": "os.system", "line_number": 230, "usage_type": "call"}, {"api_name": "os.system", "line_number": 231, "usage_type": "call"}, {"api_name": "os.system", "line_number": 232, "usage_type": "call"}, {"api_name": "os.system", "line_number": 233, "usage_type": "call"}, {"api_name": "os.chdir", "line_number": 240, "usage_type": "call"}, {"api_name": "os.chdir", "line_number": 243, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 248, "usage_type": "call"}, {"api_name": "os.getcwd", "line_number": 257, "usage_type": "call"}, {"api_name": "glob.glob", "line_number": 259, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 259, "usage_type": "call"}, {"api_name": "os.path", "line_number": 259, "usage_type": "attribute"}]} +{"seq_id": "20971364137", "text": "# select for double coding\n\n# python prepare_for_doublecoding.py --session 983f28e8-40ac-4226-9968-47562ab5c8de --data_basepath /Users/stephan/dropbox/Documents/MIT/research/PLEARN\n\nimport pandas as pd\nimport glob\nimport argparse\nimport os\n\ndef main(args):\n \n NUM_TRIALS_TO_SAMPLE = 4\n\n if args.session is not None:\n # process a single specified session\n prepare_session_for_doublecoding(args.data_basepath, args.session, NUM_TRIALS_TO_SAMPLE)\n else: \n # list all sessions in lookit_data and process them\n data_root = os.path.join(args.data_basepath, 'lookit_data') \n sessions = os.listdir(data_root)\n\n # process each session\n for session in sessions:\n prepare_session_for_doublecoding(args.data_basepath, session, NUM_TRIALS_TO_SAMPLE)\n\ndef prepare_session_for_doublecoding(data_basepath, session, NUM_TRIALS_TO_SAMPLE): \n trials_file = os.path.join(data_basepath, 'lookit_data', session, 'processed', session+'.csv')\n try:\n trials_df = pd.read_csv(trials_file)\n except:\n print('No trials file found for '+session)\n return\n\n test_trials_df = trials_df.loc[trials_df.file.str.contains('test-normal')]\n selected_trials = test_trials_df.sample(NUM_TRIALS_TO_SAMPLE)\n\n selected_trials_file = trials_file.replace('.csv','_doublecode_list.csv')\n if not os.path.exists(selected_trials_file):\n selected_trials.to_csv(selected_trials_file, index=False)\n print('Selected '+str(NUM_TRIALS_TO_SAMPLE)+' files and output them at '+selected_trials_file)\n print('Processing complete!')\n else:\n print('Selected trials file already exists at '+selected_trials_file+'. Delete it first and run again.')\n\n \n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Select test trials for double coding')\n parser.add_argument('--data_basepath',\n type=str,\n action='store',\n help='The data root for the project (should include lookit_data as a directory, containing folders corresponding to sessions) ')\n parser.add_argument('--session', \n action='store',\n type=str,\n help='The session identifier under lookit-data to process. If unspecified, then all sessions in `lookit_data` will be processed.')\n \n args = parser.parse_args()\n\n main(args)", "repo_name": "smeylan/PLEARN_lookit", "sub_path": "prepare_for_doublecoding.py", "file_name": "prepare_for_doublecoding.py", "file_ext": "py", "file_size_in_byte": 2495, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "os.path.join", "line_number": 19, "usage_type": "call"}, {"api_name": "os.path", "line_number": 19, "usage_type": "attribute"}, {"api_name": "os.listdir", "line_number": 20, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 27, "usage_type": "call"}, {"api_name": "os.path", "line_number": 27, "usage_type": "attribute"}, {"api_name": "pandas.read_csv", "line_number": 29, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 38, "usage_type": "call"}, {"api_name": "os.path", "line_number": 38, "usage_type": "attribute"}, {"api_name": "argparse.ArgumentParser", "line_number": 48, "usage_type": "call"}]} +{"seq_id": "13263817429", "text": "from selenium import webdriver\nfrom webdriver_manager.chrome import ChromeDriverManager\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.support.ui import WebDriverWait \nfrom selenium.webdriver.support import expected_conditions, expected_conditions\nfrom selenium.webdriver.common.by import By \nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.common.exceptions import NoSuchElementException,TimeoutException,ElementNotInteractableException\nfrom bs4 import BeautifulSoup\nimport time\nimport requests\nimport re\n\n\n# specifies the path to the chromedriver.exe\ndriver = webdriver.Chrome(ChromeDriverManager().install())\n\n# Two urls one with opening the linkedIn second with flter (India)\n\nurls = ['https://www.linkedin.com',\"https://www.linkedin.com/uas/login?session_redirect=https%3A%2F%2Fwww%2Elinkedin%2Ecom%2Fsearch%2Fresults%2Fpeople%2F%3FgeoUrn%3D%255B%2522102713980%2522%255D%26keywords%3Dsolutions%2520engineer%26origin%3DFACETED_SEARCH&fromSignIn=true&trk=cold_join_sign_in\"]\npeople = []\nfile_list = open('C:\\\\Users\\\\samee\\\\Desktop\\\\Stevens\\\\Third_Sem\\\\BIA 660 A\\\\Extra Credit\\\\filelist.txt','w',encoding='utf8')\n#driver.get method() will navigate to a page given by the URL address\nfor i in range(len(urls)):\n try:\n driver.get(urls[i])\n except TimeoutException:\n print(\"Either Linkedin is not responding or Askijng for captcha Try after some time\")\n \n if i == 0:\n username = driver.find_element_by_id('session_key')\n password = driver.find_element_by_id('session_password')\n username.send_keys('') #username\n\n if i == 1:\n password = driver.find_element_by_id('password')\n \n password.send_keys('') #password\n if i == 0:\n button = driver.find_element_by_class_name('sign-in-form__submit-button')\n else:\n button = driver.find_element_by_xpath('//*[@id=\"app__container\"]/main/div[2]/form/div[3]/button')\n\n button.click()\n \n if i == 0:\n search = WebDriverWait(driver, 10).until(\n expected_conditions.presence_of_element_located((By.XPATH, \"//input[@placeholder='Search']\"))).click()\n WebDriverWait(driver, 10).until(\n expected_conditions.element_to_be_clickable((By.XPATH, \"//input[@placeholder='Search']\"))).send_keys('solutions engineer')\n\n\n driver.find_element_by_xpath(\"//*[@id='ember16']/input\").send_keys(Keys.RETURN)\n\n people_page = WebDriverWait(driver, 10).until(\n expected_conditions.presence_of_element_located((By.CSS_SELECTOR, \"[aria-label=People]\"))).click()\n\n time.sleep(3)\n \n no_of_people = 0\n\n i=0\n while i < 100:\n try:\n time.sleep(10)\n j = 0\n soup = BeautifulSoup(driver.page_source,'html.parser')\n links = soup.find_all('a', {'class':'app-aware-link ember-view search-result__result-link'})\n # for i in soup.find_all('h3', {'class':'actor-name-with-distance search-result__title single-line-truncate ember-view'}):\n for j in range(0,10):\n people.append(links[j]['href'])\n file_list.write('%s\\n' %links[j]['href'])\n driver.execute_script(\"window.scrollTo(0, document.body.scrollHeight);\")\n people_page = WebDriverWait(driver, 10).until(\n expected_conditions.presence_of_element_located((By.CSS_SELECTOR, \"[aria-label=Next]\"))).click()\n i = i+1\n except (TimeoutException,IndexError):\n retry_page = WebDriverWait(driver, 3).until(\n expected_conditions.presence_of_element_located((By.CSS_SELECTOR, \"[data-test=no-results-cta]\"))).click()\n continue\nfile_list.close()\ndriver.close()", "repo_name": "Sameerb95/LinkedIn_Scrapper", "sub_path": "Scrapping_profile_links.py", "file_name": "Scrapping_profile_links.py", "file_ext": "py", "file_size_in_byte": 3717, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "selenium.webdriver.Chrome", "line_number": 16, "usage_type": "call"}, {"api_name": "selenium.webdriver", "line_number": 16, "usage_type": "name"}, {"api_name": "webdriver_manager.chrome.ChromeDriverManager", "line_number": 16, "usage_type": "call"}, {"api_name": "selenium.common.exceptions.TimeoutException", "line_number": 27, "usage_type": "name"}, {"api_name": "selenium.webdriver.support.ui.WebDriverWait", "line_number": 47, "usage_type": "call"}, {"api_name": "selenium.webdriver.support.expected_conditions.presence_of_element_located", "line_number": 48, "usage_type": "call"}, {"api_name": "selenium.webdriver.support.expected_conditions", "line_number": 48, "usage_type": "name"}, {"api_name": "selenium.webdriver.common.by.By.XPATH", "line_number": 48, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.by.By", "line_number": 48, "usage_type": "name"}, {"api_name": "selenium.webdriver.support.ui.WebDriverWait", "line_number": 49, "usage_type": "call"}, {"api_name": "selenium.webdriver.support.expected_conditions.element_to_be_clickable", "line_number": 50, "usage_type": "call"}, {"api_name": "selenium.webdriver.support.expected_conditions", "line_number": 50, "usage_type": "name"}, {"api_name": "selenium.webdriver.common.by.By.XPATH", "line_number": 50, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.by.By", "line_number": 50, "usage_type": "name"}, {"api_name": "selenium.webdriver.common.keys.Keys.RETURN", "line_number": 53, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.keys.Keys", "line_number": 53, "usage_type": "name"}, {"api_name": "selenium.webdriver.support.ui.WebDriverWait", "line_number": 55, "usage_type": "call"}, {"api_name": "selenium.webdriver.support.expected_conditions.presence_of_element_located", "line_number": 56, "usage_type": "call"}, {"api_name": "selenium.webdriver.support.expected_conditions", "line_number": 56, "usage_type": "name"}, {"api_name": "selenium.webdriver.common.by.By.CSS_SELECTOR", "line_number": 56, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.by.By", "line_number": 56, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 58, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 65, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 67, "usage_type": "call"}, {"api_name": "selenium.webdriver.support.ui.WebDriverWait", "line_number": 74, "usage_type": "call"}, {"api_name": "selenium.webdriver.support.expected_conditions.presence_of_element_located", "line_number": 75, "usage_type": "call"}, {"api_name": "selenium.webdriver.support.expected_conditions", "line_number": 75, "usage_type": "name"}, {"api_name": "selenium.webdriver.common.by.By.CSS_SELECTOR", "line_number": 75, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.by.By", "line_number": 75, "usage_type": "name"}, {"api_name": "selenium.common.exceptions.TimeoutException", "line_number": 77, "usage_type": "name"}, {"api_name": "selenium.webdriver.support.ui.WebDriverWait", "line_number": 78, "usage_type": "call"}, {"api_name": "selenium.webdriver.support.expected_conditions.presence_of_element_located", "line_number": 79, "usage_type": "call"}, {"api_name": "selenium.webdriver.support.expected_conditions", "line_number": 79, "usage_type": "name"}, {"api_name": "selenium.webdriver.common.by.By.CSS_SELECTOR", "line_number": 79, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.by.By", "line_number": 79, "usage_type": "name"}]} +{"seq_id": "1882478452", "text": "import abc\nimport collections\nimport os\nimport pelops.utils as utils\n\n# ================================================================================\n# Chip Factory\n# ================================================================================\n\n\nclass DatasetFactory(object):\n @staticmethod\n def create_dataset(dataset_type, dataset_path, set_type=None):\n for cls in ChipDataset.__subclasses__():\n if cls.check_dataset_type(dataset_type):\n return cls(dataset_path, set_type)\n\n# ================================================================================\n# Chip Dataset\n# ================================================================================\n\n\nclass ChipDataset(metaclass = abc.ABCMeta):\n def __init__(self, dataset_path, set_type=None):\n self.dataset_path = dataset_path\n self.__set_set_type(set_type)\n self.chips = dict()\n self.chips_by_cam_id = None\n self.chips_by_car_id = None\n\n def __set_set_type(self, set_type):\n self.set_type = None\n\n # The Default ALL\n if set_type is None:\n self.set_type = utils.SetType.ALL\n\n # If passed a SetType\n if isinstance(set_type, utils.SetType):\n self.set_type = set_type\n\n # If passed a string\n if isinstance(set_type, str):\n set_type = set_type.lower()\n for st in utils.SetType:\n if set_type == st.value:\n self.set_type = st\n\n if self.set_type is None:\n raise ValueError(\"set_type is not a valid string or SetType enum\")\n\n\n @classmethod\n def check_dataset_type(self, dataset_type):\n return dataset_type == self.__name__\n\n def get_all_chips_by_car_id(self, car_id):\n if self.chips_by_car_id is None:\n self.chips_by_car_id = collections.defaultdict(list)\n for chip_key, chip in self.chips.items():\n self.chips_by_car_id[chip.car_id].append(chip_key)\n return [self.chips[chip_key] for chip_key in self.chips_by_car_id[car_id]]\n\n def get_all_chips_by_car_id_camera_id(self, car_id, cam_id):\n output = []\n for chip in self.get_all_chips_by_car_id(car_id):\n if chip.cam_id == cam_id:\n output.append(chip)\n return output\n\n def get_all_chips_by_cam_id(self, cam_id):\n if self.chips_by_cam_id is None:\n self.chips_by_cam_id = collections.defaultdict(list)\n for chip_key, chip in self.chips.items():\n self.chips_by_cam_id[chip.cam_id].append(chip_key)\n\n return [self.chips[chip_key] for chip_key in self.chips_by_cam_id[cam_id]]\n\n def get_distinct_cams_by_car_id(self, car_id):\n # TODO: Look at performance\n return self.get_distinct_cams_per_car()[car_id]\n\n def get_distinct_cams_per_car(self):\n # TODO: Look at performance\n list_of_cameras_per_car = collections.defaultdict(set)\n for chip in self.chips.values():\n list_of_cameras_per_car[chip.car_id].add(chip.cam_id)\n return list_of_cameras_per_car\n\n def get_all_cam_ids(self):\n return list(set(chip.cam_id for chip in self.chips.values()))\n\n def get_all_car_ids(self):\n return list(set(chip.car_id for chip in self.chips.values()))\n\n def __iter__(self):\n for chip in self.chips.values():\n yield chip\n raise StopIteration()\n\n def __len__(self):\n return len(self.chips)\n\n# ================================================================================\n# Chip Base\n# ================================================================================\n\n\n# chip_id is the filepath\nChip = collections.namedtuple(\"Chip\",\n [\"filepath\",\n \"car_id\",\n \"cam_id\",\n \"time\",\n \"misc\"])\n", "repo_name": "Lab41/pelops", "sub_path": "pelops/datasets/chip.py", "file_name": "chip.py", "file_ext": "py", "file_size_in_byte": 3808, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 44, "dataset": "github-code", "pt": "21", "api": [{"api_name": "abc.ABCMeta", "line_number": 23, "usage_type": "attribute"}, {"api_name": "pelops.utils.SetType", "line_number": 36, "usage_type": "attribute"}, {"api_name": "pelops.utils", "line_number": 36, "usage_type": "name"}, {"api_name": "pelops.utils.SetType", "line_number": 39, "usage_type": "attribute"}, {"api_name": "pelops.utils", "line_number": 39, "usage_type": "name"}, {"api_name": "pelops.utils.SetType", "line_number": 45, "usage_type": "attribute"}, {"api_name": "pelops.utils", "line_number": 45, "usage_type": "name"}, {"api_name": "collections.defaultdict", "line_number": 59, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 73, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 85, "usage_type": "call"}, {"api_name": "collections.namedtuple", "line_number": 110, "usage_type": "call"}]} +{"seq_id": "43677113535", "text": "import numpy as np\nimport random\nimport pandas as pd\nfrom sklearn.preprocessing import MinMaxScaler\nimport os\nimport datetime\nprint(\"import successfully\")\nprint()\nprint()\n\npath=os.path.dirname(__file__)\ndata=pd.read_csv(path+\"\\\\bdata.csv\",index_col=0)\nlabels=pd.read_csv(path+\"\\\\blabel.csv\",index_col=0)\ndata=data.values\nlabels=labels.values\nsample_num=data.shape[0]\n#shuffle\nindices=np.arange(sample_num)\nnp.random.shuffle(indices)\ndata=data[indices]\nlabels=labels[indices]\n\n#把二维矩阵化成三维,适用训练的函数\nti=[]\nfor i in range(sample_num):\n temp=[]\n for j in range(20):\n temp.append([data[i][j]])\n ti.append(np.array(temp))\ntrain_input=ti\ntrain_output=labels\n#把label归一化0~20 -> 0~1\nscaler=MinMaxScaler()\ntrain_output=scaler.fit_transform(train_output)\n\n\nnum_test=int(0.01*sample_num)\n\ntest_input = train_input[:num_test]\ntest_output = train_output[:num_test]\ntrain_input = train_input[num_test:]\ntrain_output = train_output[num_test:]\n\n \n\nprint()\nprint()\nprint(\"preprocess successfully\")\nprint()\nprint()\n#############################################\n\nimport tensorflow as tf\ndata=tf.placeholder(tf.float32,[None,20,1])\ntarget=tf.placeholder(tf.float32,[None,1])\n\nnum_hidden_unit=24\ncell=tf.nn.rnn_cell.LSTMCell(\n num_hidden_unit,state_is_tuple=True)\nval,_=tf.nn.dynamic_rnn(cell,data,dtype=tf.float32)\n\nval=tf.transpose(val,[1,0,2])\nlast=tf.gather(val, int(val.get_shape()[0]) - 1)\n\nweight=tf.Variable(tf.truncated_normal(\n [num_hidden_unit , int(target.get_shape()[1])]\n ))\nbias=tf.Variable(\n tf.constant(0.1,shape=[\n target.get_shape()[1]\n ])\n)\nprediction=tf.matmul(last,weight)+bias\ncross_entropy=tf.reduce_sum(\n tf.abs(target-tf.clip_by_value(prediction,1e-10,1.0)))\noptimizer=tf.train.AdamOptimizer()\nminimize=optimizer.minimize(cross_entropy)\n\npred=tf.round(prediction*20)/20.0\nmistakes=tf.not_equal(\n target,pred\n)\nerror=tf.reduce_mean(tf.cast(mistakes,tf.float32))\n#summary\ntf.summary.scalar('error',error)\ninit_opr=tf.initialize_all_variables()\n\nprint()\nprint()\nprint(\"start training\")\nprint()\nprint()\n\nsess=tf.Session()\nsess.run(init_opr)\nmerged=tf.summary.merge_all()\ntrain_writer=tf.summary.FileWriter(\n os.path.dirname(__file__)+\"\\\\summary\\\\train\",sess.graph)\ntest_writer=tf.summary.FileWriter(\n os.path.dirname(__file__)+\"\\\\summary\\\\test\")\n\n############## \ns=tf.train.Saver()\nsave_num=1\nsave_dir=os.path.dirname(__file__)+\"\\\\save\"+str(save_num)+\"\\\\\"\nif os.path.exists(save_dir):\n s.restore(sess,tf.train.latest_checkpoint(save_dir))\n\n\nbatch_size=10\n#num_of_batches=int(len(train_input)/batch_size)\nnum_of_batches=10\nepoch_to_train=100\nfor epoch in range(epoch_to_train):\n ptr=0\n for j in range(num_of_batches):\n inp=train_input[ptr:ptr+batch_size]\n out=train_output[ptr:ptr+batch_size]\n ptr+=batch_size\n sess.run(minimize,feed_dict={\n data:inp,target:out\n })\n #if epoch%10==0:\n if True:\n summary,error_train=sess.run([merged,error],\n feed_dict={data:train_input,\n target:train_output})\n train_writer.add_summary(summary,epoch)\n \n summary,error_test=sess.run([merged,error],\n feed_dict={data:test_input,\n target:test_output})\n test_writer.add_summary(summary,epoch)\n \n print(\"{0} {1:.4f} {2:.4f}\".format(epoch,error_train,error_test))\n\ns.save(sess,save_dir+\"+\"+str(epoch_to_train)+\"@\"\n +datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S')\n )\n\n\nincorrect=sess.run(error,feed_dict={\n data:test_input,target:test_output\n})\n\nincorrect = sess.run(error,{data: test_input, target: test_output})\nprint( sess.run(prediction,{data: [[[1],[0],[0],[1],[1],[0],[1],[1],[1],[0],[1],[0],[0],[1],[1],[0],[1],[1],[1],[0]]]}) )\nprint('Epoch {:2d} error {:3.1f}%'.format(i + 1, 100 * incorrect))\n\nsess.close()\n\n#lstm层数还要增加\n#tensorboard --logdir=train:\"./summary/train\",test:\"./summary/test\"\n\n\n\n\n", "repo_name": "luoye2333/ann", "sub_path": "rbinary/LSTM_naive.py", "file_name": "LSTM_naive.py", "file_ext": "py", "file_size_in_byte": 3956, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "os.path.dirname", "line_number": 11, "usage_type": "call"}, {"api_name": "os.path", "line_number": 11, "usage_type": "attribute"}, {"api_name": "pandas.read_csv", "line_number": 12, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 13, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 18, "usage_type": "call"}, {"api_name": "numpy.random.shuffle", "line_number": 19, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 19, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 29, "usage_type": "call"}, {"api_name": "sklearn.preprocessing.MinMaxScaler", "line_number": 33, "usage_type": "call"}, {"api_name": "tensorflow.placeholder", "line_number": 54, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 54, "usage_type": "attribute"}, {"api_name": "tensorflow.placeholder", "line_number": 55, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 55, "usage_type": "attribute"}, {"api_name": "tensorflow.nn.rnn_cell.LSTMCell", "line_number": 58, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 58, "usage_type": "attribute"}, {"api_name": "tensorflow.nn.dynamic_rnn", "line_number": 60, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 60, "usage_type": "attribute"}, {"api_name": "tensorflow.float32", "line_number": 60, "usage_type": "attribute"}, {"api_name": "tensorflow.transpose", "line_number": 62, "usage_type": "call"}, {"api_name": "tensorflow.gather", "line_number": 63, "usage_type": "call"}, {"api_name": "tensorflow.Variable", "line_number": 65, "usage_type": "call"}, {"api_name": "tensorflow.truncated_normal", "line_number": 65, "usage_type": "call"}, {"api_name": "tensorflow.Variable", "line_number": 68, "usage_type": "call"}, {"api_name": "tensorflow.constant", "line_number": 69, "usage_type": "call"}, {"api_name": "tensorflow.matmul", "line_number": 73, "usage_type": "call"}, {"api_name": "tensorflow.reduce_sum", "line_number": 74, "usage_type": "call"}, {"api_name": "tensorflow.abs", "line_number": 75, "usage_type": "call"}, {"api_name": "tensorflow.clip_by_value", "line_number": 75, "usage_type": "call"}, {"api_name": "tensorflow.train.AdamOptimizer", "line_number": 76, "usage_type": "call"}, {"api_name": "tensorflow.train", "line_number": 76, "usage_type": "attribute"}, {"api_name": "tensorflow.round", "line_number": 79, "usage_type": "call"}, {"api_name": "tensorflow.not_equal", "line_number": 80, "usage_type": "call"}, {"api_name": "tensorflow.reduce_mean", "line_number": 83, "usage_type": "call"}, {"api_name": "tensorflow.cast", "line_number": 83, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 83, "usage_type": "attribute"}, {"api_name": "tensorflow.summary.scalar", "line_number": 85, "usage_type": "call"}, {"api_name": "tensorflow.summary", "line_number": 85, "usage_type": "attribute"}, {"api_name": "tensorflow.initialize_all_variables", "line_number": 86, "usage_type": "call"}, {"api_name": "tensorflow.Session", "line_number": 94, "usage_type": "call"}, {"api_name": "tensorflow.summary.merge_all", "line_number": 96, "usage_type": "call"}, {"api_name": "tensorflow.summary", "line_number": 96, "usage_type": "attribute"}, {"api_name": "tensorflow.summary.FileWriter", "line_number": 97, "usage_type": "call"}, {"api_name": "tensorflow.summary", "line_number": 97, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 98, "usage_type": "call"}, {"api_name": "os.path", "line_number": 98, "usage_type": "attribute"}, {"api_name": "tensorflow.summary.FileWriter", "line_number": 99, "usage_type": "call"}, {"api_name": "tensorflow.summary", "line_number": 99, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 100, "usage_type": "call"}, {"api_name": "os.path", "line_number": 100, "usage_type": "attribute"}, {"api_name": "tensorflow.train.Saver", "line_number": 103, "usage_type": "call"}, {"api_name": "tensorflow.train", "line_number": 103, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 105, "usage_type": "call"}, {"api_name": "os.path", "line_number": 105, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 106, "usage_type": "call"}, {"api_name": "os.path", "line_number": 106, "usage_type": "attribute"}, {"api_name": "tensorflow.train.latest_checkpoint", "line_number": 107, "usage_type": "call"}, {"api_name": "tensorflow.train", "line_number": 107, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 138, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 138, "usage_type": "attribute"}]} +{"seq_id": "25956759966", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Aug 10 17:33:01 2018\r\n\r\n@author: admin\r\n\"\"\"\r\n\r\nimport cv2\r\nimport numpy as np\r\n \r\n# read image into matrix.\r\nm = cv2.imread(\"b1.jpg\")\r\n \r\n# get image properties.\r\nh,w,bpp = np.shape(m)\r\n \r\n# iterate over the entire image.\r\nfor py in range(0,h):\r\n print(py,\"next row started\")\r\n for px in range(0,w):\r\n print (m[py][px])\r\n \r\n \r\n \r\nwhile True:\r\n if cv2.waitKey(25) & 0xFF == ord('q'):\r\n cv2.destroyAllWindows()\r\n break\r\n", "repo_name": "ANDROID564/pc_cyber_lab", "sub_path": "pixel_iterate.py", "file_name": "pixel_iterate.py", "file_ext": "py", "file_size_in_byte": 511, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "cv2.imread", "line_number": 12, "usage_type": "call"}, {"api_name": "numpy.shape", "line_number": 15, "usage_type": "call"}, {"api_name": "cv2.waitKey", "line_number": 26, "usage_type": "call"}, {"api_name": "cv2.destroyAllWindows", "line_number": 27, "usage_type": "call"}]} +{"seq_id": "29822410928", "text": "import matplotlib.pyplot as plt\nimport numpy as np\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.layers import Dropout\nfrom keras.layers import Flatten, BatchNormalization\nfrom keras.layers.convolutional import Conv2D\nfrom keras.layers.convolutional import MaxPooling2D\nfrom keras.optimizers import RMSprop\nfrom keras.callbacks import ReduceLROnPlateau\nfrom keras.utils import np_utils\nimport pandas as pd\nfrom keras import regularizers\nimport os\nfrom keras.models import model_from_json\n\n\ndef plot_figure(X_train):\n plt.subplot(221)\n plt.imshow(X_train[0], cmap=plt.get_cmap('gray'))\n plt.subplot(222)\n plt.imshow(X_train[1], cmap=plt.get_cmap('gray'))\n plt.subplot(223)\n plt.imshow(X_train[2], cmap=plt.get_cmap('gray'))\n plt.subplot(224)\n plt.imshow(X_train[3], cmap=plt.get_cmap('gray'))\n plt.show()\n\n\nnp.random.seed(7)\n\n\ndef plot1(history):\n # list all data in history\n print(history.history.keys())\n # summarize history for accuracy\n plt.plot(history.history['acc'])\n plt.plot(history.history['val_acc'])\n plt.title('model accuracy')\n plt.ylabel('accuracy')\n plt.xlabel('epoch')\n plt.legend(['train', 'test'], loc='upper right')\n plt.savefig('Accuracy-Model14.jpg')\n\n\ndef plot2(history):\n plt.plot(history.history['loss'])\n plt.plot(history.history['val_loss'])\n plt.title('model loss')\n plt.ylabel('loss')\n plt.xlabel('epoch')\n plt.legend(['train', 'test'], loc='upper right')\n plt.savefig('Loss-Model14.jpg')\n\n\ndef get_data():\n # ToDo : Change all paths to '.'\n # training data\n x_train = pd.read_csv('.')\n x_train = x_train.iloc[:, :]\n\n y_train = pd.read_csv('.')\n y_train = y_train.iloc[:, :]\n\n # validation data\n x_val = pd.read_csv('.')\n x_val = x_val.iloc[:, :]\n\n y_val = pd.read_csv('.')\n y_val = y_val.iloc[:, :]\n\n return x_train.values, y_train.values, x_val.values, y_val.values\n\n\ndef baseline_model():\n model = Sequential()\n model.add(Conv2D(32, (5, 5), activation='relu', input_shape=(1, 28, 28), padding='Same'))\n model.add(Conv2D(32, (5, 5), activation='relu', padding='Same'))\n model.add(BatchNormalization(axis=-1))\n model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))\n model.add(Dropout(0.25))\n\n model.add(Conv2D(64, (3, 3), activation='relu', input_shape=(1, 28, 28), padding='Same'))\n model.add(Conv2D(64, (3, 3), activation='relu', padding='Same'))\n model.add(BatchNormalization(axis=-1))\n model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))\n model.add(Dropout(0.25))\n\n model.add(Flatten())\n model.add(Dense(128, activation='relu'))\n model.add(Dropout(0.5))\n model.add(Dense(10, activation='softmax'))\n\n # optimizer = RMSprop(lr=0.001, rho=0.9, epsilon=1e-08, decay=0.0)\n model.compile(loss='categorical_crossentropy',\n optimizer='adam',\n metrics=['accuracy'])\n return model\n\n\ndef save_model(model):\n model_json = model.to_json()\n with open(\"model.json\", \"w\") as json_file:\n json_file.write(model_json)\n\n # serialize weights to HDF5\n model.save_weights(\"model.h5\")\n print(\"Saved model to disk\")\n\n # # load json and create model\n # json_file = open('model.json', 'r')\n # loaded_model_json = json_file.read()\n # json_file.close()\n # loaded_model = model_from_json(loaded_model_json)\n # # load weights into new model\n # loaded_model.load_weights(\"model.h5\")\n # print(\"Loaded model from disk\")\n\n\ndef main():\n x_train, y_train, x_val, y_val = get_data()\n\n # reshape to be [samples][pixels][width][height]\n x_train = x_train.reshape(x_train.shape[0], 1, 28, 28).astype('float32')\n x_val = x_val.reshape(x_val.shape[0], 1, 28, 28).astype('float32')\n\n # normalize\n x_train /= 255\n x_val /= 255\n y_train = np_utils.to_categorical(y_train)\n y_val = np_utils.to_categorical(y_val)\n # num_classes = y_train.shape[1]\n\n # learning rate reduction\n learning_rate_reduction = ReduceLROnPlateau(monitor='val_acc',\n patience=3,\n verbose=1,\n factor=0.5,\n min_lr=0.00001)\n\n model = baseline_model()\n batch_size = 86\n history = model.fit(x_train, y_train, batch_size=batch_size, epochs=25, verbose=2,\n validation_data=(x_val, y_val),\n callbacks=[learning_rate_reduction])\n plot1(history)\n plot2(history)\n scores = model.evaluate(x_val, y_val, verbose=0)\n save_model(model)\n print(\"CNN Error: %.2f%%\" % (100 - scores[1] * 100))\n\n\nif __name__ == '__main__':\n main()\n", "repo_name": "KaranKaur/mnist", "sub_path": "cnn.py", "file_name": "cnn.py", "file_ext": "py", "file_size_in_byte": 4758, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "matplotlib.pyplot.subplot", "line_number": 19, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 19, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 20, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 20, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.get_cmap", "line_number": 20, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 21, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 21, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 22, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 22, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.get_cmap", "line_number": 22, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 23, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 23, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 24, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 24, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.get_cmap", "line_number": 24, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 25, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 25, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 26, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 26, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.get_cmap", "line_number": 26, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.show", "line_number": 27, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 27, "usage_type": "name"}, {"api_name": "numpy.random.seed", "line_number": 30, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 30, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 37, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 37, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 38, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 38, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 39, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 39, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 40, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 40, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 41, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 41, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 42, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 42, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 43, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 43, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 47, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 47, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 48, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 48, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 49, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 49, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 50, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 50, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 51, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 51, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 52, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 52, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 53, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 53, "usage_type": "name"}, {"api_name": "pandas.read_csv", "line_number": 59, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 62, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 66, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 69, "usage_type": "call"}, {"api_name": "keras.models.Sequential", "line_number": 76, "usage_type": "call"}, {"api_name": "keras.layers.convolutional.Conv2D", "line_number": 77, "usage_type": "call"}, {"api_name": "keras.layers.convolutional.Conv2D", "line_number": 78, "usage_type": "call"}, {"api_name": "keras.layers.BatchNormalization", "line_number": 79, "usage_type": "call"}, {"api_name": "keras.layers.convolutional.MaxPooling2D", "line_number": 80, "usage_type": "call"}, {"api_name": "keras.layers.Dropout", "line_number": 81, "usage_type": "call"}, {"api_name": "keras.layers.convolutional.Conv2D", "line_number": 83, "usage_type": "call"}, {"api_name": "keras.layers.convolutional.Conv2D", "line_number": 84, "usage_type": "call"}, {"api_name": "keras.layers.BatchNormalization", "line_number": 85, "usage_type": "call"}, {"api_name": "keras.layers.convolutional.MaxPooling2D", "line_number": 86, "usage_type": "call"}, {"api_name": "keras.layers.Dropout", "line_number": 87, "usage_type": "call"}, {"api_name": "keras.layers.Flatten", "line_number": 89, "usage_type": "call"}, {"api_name": "keras.layers.Dense", "line_number": 90, "usage_type": "call"}, {"api_name": "keras.layers.Dropout", "line_number": 91, "usage_type": "call"}, {"api_name": "keras.layers.Dense", "line_number": 92, "usage_type": "call"}, {"api_name": "keras.utils.np_utils.to_categorical", "line_number": 130, "usage_type": "call"}, {"api_name": "keras.utils.np_utils", "line_number": 130, "usage_type": "name"}, {"api_name": "keras.utils.np_utils.to_categorical", "line_number": 131, "usage_type": "call"}, {"api_name": "keras.utils.np_utils", "line_number": 131, "usage_type": "name"}, {"api_name": "keras.callbacks.ReduceLROnPlateau", "line_number": 135, "usage_type": "call"}]} +{"seq_id": "40314968442", "text": "import logging\nfrom pathlib import Path\nfrom rich.logging import RichHandler\n\nlog_file = f\"netts_log.log\"\n\nlogger = logging.getLogger('netts')\n\nfile_handler = logging.FileHandler(log_file)\nconsole_handler = RichHandler(markup=True, show_path=False)\n\nlogger.setLevel(logging.INFO)\nfile_handler.setLevel(logging.INFO)\nconsole_handler.setLevel(logging.INFO)\n\nfmt_file = '%(levelname)s %(asctime)s [%(filename)s:%(funcName)s:%(lineno)d] %(message)s'\nfmt_console = '%(message)s'\n\nfile_formatter = logging.Formatter(fmt_file)\nconsole_formatter = logging.Formatter(fmt_console)\n\nfile_handler.setFormatter(file_formatter)\nconsole_handler.setFormatter(console_formatter)\n\nlogger.addHandler(file_handler)\nlogger.addHandler(console_handler)\n\nstanza_logger = logging.getLogger(\"stanza\")\nstanza_logger.addHandler(file_handler)\nstanza_logger.addHandler(console_handler)", "repo_name": "alan-turing-institute/netts", "sub_path": "netts/logger.py", "file_name": "logger.py", "file_ext": "py", "file_size_in_byte": 855, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 8, "dataset": "github-code", "pt": "21", "api": [{"api_name": "logging.getLogger", "line_number": 7, "usage_type": "call"}, {"api_name": "logging.FileHandler", "line_number": 9, "usage_type": "call"}, {"api_name": "rich.logging.RichHandler", "line_number": 10, "usage_type": "call"}, {"api_name": "logging.INFO", "line_number": 12, "usage_type": "attribute"}, {"api_name": "logging.INFO", "line_number": 13, "usage_type": "attribute"}, {"api_name": "logging.INFO", "line_number": 14, "usage_type": "attribute"}, {"api_name": "logging.Formatter", "line_number": 19, "usage_type": "call"}, {"api_name": "logging.Formatter", "line_number": 20, "usage_type": "call"}, {"api_name": "logging.getLogger", "line_number": 28, "usage_type": "call"}]} +{"seq_id": "74991311731", "text": "import threading\n\nfrom gi.repository import GLib\n\nfrom ._base import MMKeysBackend, MMKeysAction, MMKeysImportError\n\ntry:\n from AppKit import NSKeyUp, NSSystemDefined, NSEvent\n import Quartz\nexcept ImportError as e:\n raise MMKeysImportError from e\n\n\nclass OSXBackend(MMKeysBackend):\n\n def __init__(self, name, callback):\n self.__eventsapp = MacKeyEventsTap(callback)\n self.__eventsapp.start()\n\n def cancel(self):\n if self.__eventsapp is not None:\n self.__eventsapp.stop()\n self.__eventsapp = None\n\n\nclass MacKeyEventsTap(threading.Thread):\n # Quartz event tap, listens for media key events and translates these to\n # control messages for quodlibet.\n\n _EVENTS = {\n 16: MMKeysAction.PLAYPAUSE,\n 19: MMKeysAction.NEXT,\n 20: MMKeysAction.PREV,\n }\n\n def __init__(self, callback):\n super().__init__()\n self._callback = callback\n self._tap = None\n self._runLoopSource = None\n self._event = threading.Event()\n\n def _push_callback(self, action):\n # push to the main thread, ignore if we have been stopped by now\n def idle_call(action):\n if self._tap:\n self._callback(action)\n return False\n\n GLib.idle_add(idle_call, action)\n\n def _event_tap(self, proxy, type_, event, refcon):\n # evenTrap disabled by timeout or user input, re-enable\n if type_ == Quartz.kCGEventTapDisabledByUserInput or \\\n type_ == Quartz.kCGEventTapDisabledByTimeout:\n assert self._tap is not None\n Quartz.CGEventTapEnable(self._tap, True)\n return event\n\n # Convert the Quartz CGEvent into something more useful\n keyEvent = NSEvent.eventWithCGEvent_(event)\n if keyEvent.subtype() == 8: # subtype 8 is media keys\n data = keyEvent.data1()\n keyCode = (data & 0xFFFF0000) >> 16\n keyState = (data & 0xFF00) >> 8\n if keyCode in self._EVENTS:\n if keyState == NSKeyUp:\n self._push_callback(self._EVENTS[keyCode])\n return None # swallow the event, so iTunes doesn't launch\n return event\n\n def _loop_start(self, observer, activiti, info):\n self._event.set()\n\n def run(self):\n self._tap = Quartz.CGEventTapCreate(\n Quartz.kCGSessionEventTap, # Session level is enough for our needs\n Quartz.kCGHeadInsertEventTap, # Insert wherever, we do not filter\n # Active, to swallow the play/pause event is enough\n Quartz.kCGEventTapOptionDefault,\n # NSSystemDefined for media keys\n Quartz.CGEventMaskBit(NSSystemDefined),\n self._event_tap,\n None\n )\n\n # the above can fail\n if self._tap is None:\n self._event.set()\n return\n\n self._loop = Quartz.CFRunLoopGetCurrent()\n\n # add an observer so we know when we can stop it\n # without a race condition\n self._observ = Quartz.CFRunLoopObserverCreate(\n None, Quartz.kCFRunLoopEntry, False, 0, self._loop_start, None)\n Quartz.CFRunLoopAddObserver(\n self._loop, self._observ, Quartz.kCFRunLoopCommonModes)\n\n # Create a runloop source and add it to the current loop\n self._runLoopSource = Quartz.CFMachPortCreateRunLoopSource(\n None, self._tap, 0)\n\n Quartz.CFRunLoopAddSource(\n self._loop,\n self._runLoopSource,\n Quartz.kCFRunLoopDefaultMode\n )\n\n # Enable the tap\n Quartz.CGEventTapEnable(self._tap, True)\n\n # runrunrun\n Quartz.CFRunLoopRun()\n\n def stop(self):\n \"\"\"Call once from the main thread to stop the thread.\n After this returns no callback will be called anymore.\n \"\"\"\n\n # wait until we fail or the observer tells us that the loop has started\n self._event.wait()\n\n # failed to create a tap, nothing to stop\n if self._tap is None:\n return\n\n # remove the runloop source\n Quartz.CFRunLoopRemoveSource(\n self._loop,\n self._runLoopSource,\n Quartz.kCFRunLoopDefaultMode\n )\n self._runLoopSource = None\n\n # remove observer\n Quartz.CFRunLoopRemoveObserver(\n self._loop, self._observ, Quartz.kCFRunLoopCommonModes)\n self._observ = None\n\n # stop the loop\n Quartz.CFRunLoopStop(self._loop)\n self._loop = None\n\n # Disable the tap\n Quartz.CGEventTapEnable(self._tap, False)\n self._tap = None\n", "repo_name": "quodlibet/quodlibet", "sub_path": "quodlibet/mmkeys/osx.py", "file_name": "osx.py", "file_ext": "py", "file_size_in_byte": 4644, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1306, "dataset": "github-code", "pt": "21", "api": [{"api_name": "_base.MMKeysImportError", "line_number": 11, "usage_type": "name"}, {"api_name": "_base.MMKeysBackend", "line_number": 14, "usage_type": "name"}, {"api_name": "threading.Thread", "line_number": 26, "usage_type": "attribute"}, {"api_name": "_base.MMKeysAction.PLAYPAUSE", "line_number": 31, "usage_type": "attribute"}, {"api_name": "_base.MMKeysAction", "line_number": 31, "usage_type": "name"}, {"api_name": "_base.MMKeysAction.NEXT", "line_number": 32, "usage_type": "attribute"}, {"api_name": "_base.MMKeysAction", "line_number": 32, "usage_type": "name"}, {"api_name": "_base.MMKeysAction.PREV", "line_number": 33, "usage_type": "attribute"}, {"api_name": "_base.MMKeysAction", "line_number": 33, "usage_type": "name"}, {"api_name": "threading.Event", "line_number": 41, "usage_type": "call"}, {"api_name": "gi.repository.GLib.idle_add", "line_number": 50, "usage_type": "call"}, {"api_name": "gi.repository.GLib", "line_number": 50, "usage_type": "name"}, {"api_name": "Quartz.kCGEventTapDisabledByUserInput", "line_number": 54, "usage_type": "attribute"}, {"api_name": "Quartz.kCGEventTapDisabledByTimeout", "line_number": 55, "usage_type": "attribute"}, {"api_name": "Quartz.CGEventTapEnable", "line_number": 57, "usage_type": "call"}, {"api_name": "AppKit.NSEvent.eventWithCGEvent_", "line_number": 61, "usage_type": "call"}, {"api_name": "AppKit.NSEvent", "line_number": 61, "usage_type": "name"}, {"api_name": "AppKit.NSKeyUp", "line_number": 67, "usage_type": "name"}, {"api_name": "Quartz.CGEventTapCreate", "line_number": 76, "usage_type": "call"}, {"api_name": "Quartz.kCGSessionEventTap", "line_number": 77, "usage_type": "attribute"}, {"api_name": "Quartz.kCGHeadInsertEventTap", "line_number": 78, "usage_type": "attribute"}, {"api_name": "Quartz.kCGEventTapOptionDefault", "line_number": 80, "usage_type": "attribute"}, {"api_name": "Quartz.CGEventMaskBit", "line_number": 82, "usage_type": "call"}, {"api_name": "AppKit.NSSystemDefined", "line_number": 82, "usage_type": "argument"}, {"api_name": "Quartz.CFRunLoopGetCurrent", "line_number": 92, "usage_type": "call"}, {"api_name": "Quartz.CFRunLoopObserverCreate", "line_number": 96, "usage_type": "call"}, {"api_name": "Quartz.kCFRunLoopEntry", "line_number": 97, "usage_type": "attribute"}, {"api_name": "Quartz.CFRunLoopAddObserver", "line_number": 98, "usage_type": "call"}, {"api_name": "Quartz.kCFRunLoopCommonModes", "line_number": 99, "usage_type": "attribute"}, {"api_name": "Quartz.CFMachPortCreateRunLoopSource", "line_number": 102, "usage_type": "call"}, {"api_name": "Quartz.CFRunLoopAddSource", "line_number": 105, "usage_type": "call"}, {"api_name": "Quartz.kCFRunLoopDefaultMode", "line_number": 108, "usage_type": "attribute"}, {"api_name": "Quartz.CGEventTapEnable", "line_number": 112, "usage_type": "call"}, {"api_name": "Quartz.CFRunLoopRun", "line_number": 115, "usage_type": "call"}, {"api_name": "Quartz.CFRunLoopRemoveSource", "line_number": 130, "usage_type": "call"}, {"api_name": "Quartz.kCFRunLoopDefaultMode", "line_number": 133, "usage_type": "attribute"}, {"api_name": "Quartz.CFRunLoopRemoveObserver", "line_number": 138, "usage_type": "call"}, {"api_name": "Quartz.kCFRunLoopCommonModes", "line_number": 139, "usage_type": "attribute"}, {"api_name": "Quartz.CFRunLoopStop", "line_number": 143, "usage_type": "call"}, {"api_name": "Quartz.CGEventTapEnable", "line_number": 147, "usage_type": "call"}]} +{"seq_id": "27872292822", "text": "\n#IGNORE THIS FILE IT DOESN'T WORK AND I AM GOING TO DO THIS A DIFFERENT WAY\n\n\n\n\n\nimport flask\nfrom quart import Quart\nfrom twisted.internet.defer import inlineCallbacks, returnValue\nimport asyncio\n\nimport inviteManager\nimport guildManager\n\napp = Quart(__name__)\n#app.config['DEBUG'] = True\n\nclient = None\n\n#Link the path '/' to the function home() and let it be accessible through GET requests\n@app.route('/api/v1/resources/createinvite', methods=['GET'])\nasync def api_createinvite():\n # Check if an ID was provided as part of the URL.\n # If ID is provided, assign it to a variable.\n # If no ID is provided, display an error in the browser.\n if 'id' in request.args:\n studentID = request.args['id']\n else:\n return (\"Error: No id field provided. Please specify an id.\")\n if 'channel' in request.args:\n channelID = request.args['channel']\n else:\n return (\"Error. No channel field provided. Please specify a channel id.\")\n \n channel = guildManager.get_channel_from_id(client, channelID)\n return await inviteManager.create_tracked_invite(channel, studentID).link\n\nasync def main(discordClient, loop):\n client = discordClient\n print(\"running api\")\n print(client)\n await app.run()", "repo_name": "dinocoder/PilotCity-Discord-Integration-Module", "sub_path": "discord/api.py", "file_name": "api.py", "file_ext": "py", "file_size_in_byte": 1246, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "quart.Quart", "line_number": 16, "usage_type": "call"}, {"api_name": "guildManager.get_channel_from_id", "line_number": 36, "usage_type": "call"}, {"api_name": "inviteManager.create_tracked_invite", "line_number": 37, "usage_type": "call"}]} +{"seq_id": "40754336897", "text": "\"\"\"Plotting methods for skeleton lines.\n\nA \"skeleton line\" is a polyline description of a polygon. For more details, see\nskeleton_lines.py.\n\"\"\"\n\nimport numpy\nimport matplotlib\nmatplotlib.use('agg')\nfrom generalexam.ge_utils import skeleton_lines\nfrom gewittergefahr.gg_utils import error_checking\n\nDEFAULT_POLYGON_COLOUR = numpy.array([0., 0., 0.]) / 255\nDEFAULT_SKELETON_LINE_COLOUR = numpy.array([252., 141., 98.]) / 255\nDEFAULT_END_NODE_COLOUR = numpy.array([252., 141., 98.]) / 255\nDEFAULT_NEW_EDGE_COLOUR = numpy.array([102., 194., 165.]) / 255\nDEFAULT_BRANCH_NODE_COLOUR = numpy.array([102., 194., 165.]) / 255\nDEFAULT_JUMPER_NODE_COLOUR = numpy.array([141., 160., 203.]) / 255\n\nDEFAULT_LINE_WIDTH = 2.\nDEFAULT_MARKER_SIZE = 8\n\nMARKER_TYPE = 'o'\nFONT_SIZE = 16\nHORIZONTAL_ALIGNMENT_FOR_NODES = 'left'\nVERTICAL_ALIGNMENT_FOR_NODES = 'bottom'\nHORIZONTAL_ALIGNMENT_FOR_POLYGON_VERTICES = 'right'\nVERTICAL_ALIGNMENT_FOR_POLYGON_VERTICES = 'top'\n\n\ndef plot_polygon(\n polygon_object_xy, axes_object, line_colour=DEFAULT_POLYGON_COLOUR,\n line_width=DEFAULT_LINE_WIDTH):\n \"\"\"Plots original polygon (without skeleton line or Delaunay triangulation).\n\n :param polygon_object_xy: Instance of `shapely.geometry.Polygon` with\n vertices in x-y (Cartesian) coordinates.\n :param axes_object: Instance of `matplotlib.axes._subplots.AxesSubplot`.\n :param line_colour: Colour of polygon edges (in any format accepted by\n `matplotlib.colors`).\n :param line_width: Width of polygon edges (real positive number).\n \"\"\"\n\n vertex_x_coords = numpy.array(polygon_object_xy.exterior.xy[0])\n vertex_y_coords = numpy.array(polygon_object_xy.exterior.xy[1])\n\n axes_object.plot(\n vertex_x_coords, vertex_y_coords, color=line_colour, linestyle='solid',\n linewidth=line_width)\n\n num_vertices = len(vertex_x_coords)\n for i in range(num_vertices - 1):\n axes_object.text(\n vertex_x_coords[i], vertex_y_coords[i], str(i), fontsize=FONT_SIZE,\n color=line_colour,\n horizontalalignment=HORIZONTAL_ALIGNMENT_FOR_POLYGON_VERTICES,\n verticalalignment=VERTICAL_ALIGNMENT_FOR_POLYGON_VERTICES)\n\n\ndef plot_delaunay_triangulation(\n polygon_object_xy, node_table, new_edge_table, axes_object,\n new_edge_colour=DEFAULT_NEW_EDGE_COLOUR,\n new_edge_width=DEFAULT_LINE_WIDTH,\n end_node_colour=DEFAULT_END_NODE_COLOUR,\n end_node_marker_size=DEFAULT_MARKER_SIZE,\n branch_node_colour=DEFAULT_BRANCH_NODE_COLOUR,\n branch_node_marker_size=DEFAULT_MARKER_SIZE,\n jumper_node_colour=DEFAULT_JUMPER_NODE_COLOUR,\n jumper_node_marker_size=DEFAULT_MARKER_SIZE):\n \"\"\"Plots Delaunay triangulation of polygon.\n\n :param polygon_object_xy: Instance of `shapely.geometry.Polygon` with\n vertices in x-y (Cartesian) coordinates.\n :param node_table: pandas DataFrame created by\n `skeleton_lines._find_and_classify_nodes` or\n `skeleton_lines._find_and_classify_node_children`.\n :param new_edge_table: pandas DataFrame created by\n `skeleton_lines._find_new_edges_from_triangulation`.\n :param axes_object: Instance of `matplotlib.axes._subplots.AxesSubplot`.\n :param new_edge_colour: Colour of new edges (those in triangulation and not\n in original polygon) (in any format accepted by `matplotlib.colors`).\n :param new_edge_width: Width of new edges.\n :param end_node_colour: Colour of end nodes.\n :param end_node_marker_size: Marker size for end nodes.\n :param branch_node_colour: Colour of branch nodes.\n :param branch_node_marker_size: Marker size for branch nodes.\n :param jumper_node_colour: Colour of jumper nodes.\n :param jumper_node_marker_size: Marker size for jumper nodes.\n \"\"\"\n\n polygon_vertex_x_coords = numpy.array(polygon_object_xy.exterior.xy[0])\n polygon_vertex_y_coords = numpy.array(polygon_object_xy.exterior.xy[1])\n\n num_new_edges = len(new_edge_table.index)\n for i in range(num_new_edges):\n these_vertex_indices = new_edge_table[\n skeleton_lines.VERTEX_INDICES_KEY].values[i]\n\n axes_object.plot(\n polygon_vertex_x_coords[these_vertex_indices],\n polygon_vertex_y_coords[these_vertex_indices],\n color=new_edge_colour, linestyle='solid', linewidth=new_edge_width)\n\n num_nodes = len(node_table.index)\n for i in range(num_nodes):\n this_node_type = node_table[skeleton_lines.NODE_TYPE_KEY].values[i]\n\n if this_node_type == skeleton_lines.END_NODE_TYPE:\n this_colour = end_node_colour\n this_marker_size = end_node_marker_size\n elif this_node_type == skeleton_lines.BRANCH_NODE_TYPE:\n this_colour = branch_node_colour\n this_marker_size = branch_node_marker_size\n elif this_node_type == skeleton_lines.JUMPER_NODE_TYPE:\n this_colour = jumper_node_colour\n this_marker_size = jumper_node_marker_size\n\n axes_object.plot(\n node_table[skeleton_lines.NODE_X_COORDS_KEY].values[i],\n node_table[skeleton_lines.NODE_Y_COORDS_KEY].values[i],\n linestyle='None', marker=MARKER_TYPE, markerfacecolor=this_colour,\n markeredgecolor=this_colour, markersize=this_marker_size,\n markeredgewidth=1)\n axes_object.text(\n node_table[skeleton_lines.NODE_X_COORDS_KEY].values[i],\n node_table[skeleton_lines.NODE_Y_COORDS_KEY].values[i], str(i),\n fontsize=FONT_SIZE, color=this_colour,\n horizontalalignment=HORIZONTAL_ALIGNMENT_FOR_NODES,\n verticalalignment=VERTICAL_ALIGNMENT_FOR_NODES)\n\n\ndef plot_skeleton_line(\n skeleton_line_x_coords, skeleton_line_y_coords, axes_object,\n line_colour=DEFAULT_SKELETON_LINE_COLOUR,\n line_width=DEFAULT_LINE_WIDTH):\n \"\"\"Plots skeleton line through polygon.\n\n P = number of points in skeleton line\n\n :param skeleton_line_x_coords: length-P numpy array with x-coordinates on\n skeleton line.\n :param skeleton_line_y_coords: length-P numpy array with y-coordinates on\n skeleton line.\n :param axes_object: Instance of `matplotlib.axes._subplots.AxesSubplot`.\n :param line_colour: Colour of skeleton line (in any format accepted by\n `matplotlib.colors`).\n :param line_width: Width of skeleton line (real positive number).\n \"\"\"\n\n error_checking.assert_is_numpy_array_without_nan(skeleton_line_x_coords)\n error_checking.assert_is_numpy_array(\n skeleton_line_x_coords, num_dimensions=1)\n num_points = len(skeleton_line_x_coords)\n\n error_checking.assert_is_numpy_array_without_nan(skeleton_line_y_coords)\n error_checking.assert_is_numpy_array(\n skeleton_line_y_coords, exact_dimensions=numpy.array([num_points]))\n\n axes_object.plot(\n skeleton_line_x_coords, skeleton_line_y_coords, color=line_colour,\n linestyle='solid', linewidth=line_width)\n", "repo_name": "thunderhoser/GeneralExam", "sub_path": "generalexam/plotting/skeleton_line_plotting.py", "file_name": "skeleton_line_plotting.py", "file_ext": "py", "file_size_in_byte": 6957, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "21", "api": [{"api_name": "matplotlib.use", "line_number": 9, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 13, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 14, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 15, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 16, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 17, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 18, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 44, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 45, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 91, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 92, "usage_type": "call"}, {"api_name": "generalexam.ge_utils.skeleton_lines.VERTEX_INDICES_KEY", "line_number": 97, "usage_type": "attribute"}, {"api_name": "generalexam.ge_utils.skeleton_lines", "line_number": 97, "usage_type": "name"}, {"api_name": "generalexam.ge_utils.skeleton_lines.NODE_TYPE_KEY", "line_number": 106, "usage_type": "attribute"}, {"api_name": "generalexam.ge_utils.skeleton_lines", "line_number": 106, "usage_type": "name"}, {"api_name": "generalexam.ge_utils.skeleton_lines.END_NODE_TYPE", "line_number": 108, "usage_type": "attribute"}, {"api_name": "generalexam.ge_utils.skeleton_lines", "line_number": 108, "usage_type": "name"}, {"api_name": "generalexam.ge_utils.skeleton_lines.BRANCH_NODE_TYPE", "line_number": 111, "usage_type": "attribute"}, {"api_name": "generalexam.ge_utils.skeleton_lines", "line_number": 111, "usage_type": "name"}, {"api_name": "generalexam.ge_utils.skeleton_lines.JUMPER_NODE_TYPE", "line_number": 114, "usage_type": "attribute"}, {"api_name": "generalexam.ge_utils.skeleton_lines", "line_number": 114, "usage_type": "name"}, {"api_name": "generalexam.ge_utils.skeleton_lines.NODE_X_COORDS_KEY", "line_number": 119, "usage_type": "attribute"}, {"api_name": "generalexam.ge_utils.skeleton_lines", "line_number": 119, "usage_type": "name"}, {"api_name": "generalexam.ge_utils.skeleton_lines.NODE_Y_COORDS_KEY", "line_number": 120, "usage_type": "attribute"}, {"api_name": "generalexam.ge_utils.skeleton_lines", "line_number": 120, "usage_type": "name"}, {"api_name": "generalexam.ge_utils.skeleton_lines.NODE_X_COORDS_KEY", "line_number": 125, "usage_type": "attribute"}, {"api_name": "generalexam.ge_utils.skeleton_lines", "line_number": 125, "usage_type": "name"}, {"api_name": "generalexam.ge_utils.skeleton_lines.NODE_Y_COORDS_KEY", "line_number": 126, "usage_type": "attribute"}, {"api_name": "generalexam.ge_utils.skeleton_lines", "line_number": 126, "usage_type": "name"}, {"api_name": "gewittergefahr.gg_utils.error_checking.assert_is_numpy_array_without_nan", "line_number": 150, "usage_type": "call"}, {"api_name": "gewittergefahr.gg_utils.error_checking", "line_number": 150, "usage_type": "name"}, {"api_name": "gewittergefahr.gg_utils.error_checking.assert_is_numpy_array", "line_number": 151, "usage_type": "call"}, {"api_name": "gewittergefahr.gg_utils.error_checking", "line_number": 151, "usage_type": "name"}, {"api_name": "gewittergefahr.gg_utils.error_checking.assert_is_numpy_array_without_nan", "line_number": 155, "usage_type": "call"}, {"api_name": "gewittergefahr.gg_utils.error_checking", "line_number": 155, "usage_type": "name"}, {"api_name": "gewittergefahr.gg_utils.error_checking.assert_is_numpy_array", "line_number": 156, "usage_type": "call"}, {"api_name": "gewittergefahr.gg_utils.error_checking", "line_number": 156, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 157, "usage_type": "call"}]} +{"seq_id": "33249215378", "text": "import aid_gym\nimport numpy as np\nimport ipdb\nimport cv2\nimport time\n\ndef display_map(start_state,goal_state):\n start = start_state/5\n start = start.astype(int)\n goal = goal_state/5\n goal = goal.astype(int)\n image_location = \"assets/island.png\"\n img = cv2.imread(image_location)\n cv2.circle(img,(start[1], start[0]), 1, (255,0,0), -1)\n cv2.circle(img,(goal[1], goal[0]), 1, (0,255,0), -1)\n cv2.imshow(\"Final_Map\", img)\n cv2.waitKey(0)\n\ndef update_V_table(V_table,rollout,GAMMA,ERROR_THRESHOLD):\n has_converged = True\n while(len(rollout)!=0):\n curr_state,next_state,reward,success_prob,best_action = rollout.pop()\n old_Q = V_table[curr_state[0]][curr_state[1]]\n V_table[curr_state[0]][curr_state[1]] = reward + GAMMA*(success_prob*V_table[next_state[0]][next_state[1]] + (1-success_prob)*V_table[curr_state[0]][curr_state[1]])\n if(has_converged and abs(V_table[curr_state[0]][curr_state[1]]-old_Q)>ERROR_THRESHOLD):\n has_converged = False\n # print(\"Updated value function in reverse order!\")\n return has_converged\n\ndef is_arr_in_list(array, list_of_arrays):\n for a in list_of_arrays:\n if np.array_equal(array, a):\n return True\n return False\n\nenv = aid_gym.IslandEnv()\nenv.reset()\n\nstart_state = env.s\ngoal_state = env.s_goal\n\n# display_map(start_state,goal_state)\n\nprint(env.MAP_SIZE)\nprint(\"Start_state is: \",start_state,\"\\t\",\"Goal State: \",goal_state)\n# ipdb.set_trace()\n# V_table = np.zeros((env.MAP_SIZE, env.MAP_SIZE))\n# obstacle_table = np.full((env.MAP_SIZE,env.MAP_SIZE), False, dtype=bool)\n\n# # valid_states = np.zeros((1,2))\n# valid_state_list = []\n\n##Modifying the Value function table for obstacles and goal states\n\"\"\"Uncomment this section to recompute V_table and obstacle_table initialization\"\"\"\n\n# for i in range(env.MAP_SIZE):\n# for j in range(env.MAP_SIZE):\n# pos = np.array([i,j]) \n# if(not env._isValidPosition(pos)):\n# V_table[i][j] = -float('Inf')\n# obstacle_table[i][j] = True\n\n# print(\"Modified V_table\")\n# np.save(\"initially_modified_v_table\", V_table)\n# np.save(\"obstacle_table\", obstacle_table)\n# print(\"Saved v_table and obstacle _table\")\n# obstacle_table = np.load('obstacle_table.npy')\nV_table = np.load('initially_modified_v_table.npy')\n\nV_table[goal_state[0]][goal_state[1]] = 100000\n\nMAXIMUM_EPISODE_LENGTH = 7*int(np.linalg.norm(start_state-goal_state))\nprint(\"MAXIMUM_EPISODE_LENGTH: \",MAXIMUM_EPISODE_LENGTH)\nMAX_EPISODES = 25000\nHAS_CONVERGED = False\nGAMMA = 1\nERROR_THRESHOLD = 0.80\n\ndirX = [-1,-1,-1,0,0,1,1,1]\ndirY = [-1,0,1,-1,1,-1,0,1]\n\ncurr_state = start_state\ndone = False\n\nif(np.array_equal(start_state, goal_state)):\n print(\"Goal already reached\")\n exit()\n\nt0 = time.time()\n\nnum_episodes=0\nlast_feasible_rollout = []\nREACHED_GOAL_ATLEAST_ONCE = False\npotential_reward = -float('Inf')\nwhile(num_episodesmax_Q and not is_arr_in_list(next_state, visited)):\n if(Q>max_Q):\n max_Q = Q\n best_next_state = next_state\n best_state_success_prob = success_prob\n best_state_reward = reward\n best_action = action\n\n # rollout.append([curr_state,best_next_state,best_state_reward,best_state_success_prob,best_action]) #Use for reverse back-up\n\n tot_reward+=best_state_reward\n\n if(not max_Q>-float('Inf')):\n print(\"Going back to previous state\")\n break\n\n \"\"\"Un-comment the 4 lines below for a forward backup instead of a reverse one\"\"\"\n old_Q = V_table[curr_state[0]][curr_state[1]]\n V_table[curr_state[0]][curr_state[1]] = max_Q\n\n if(HAS_CONVERGED and abs(V_table[curr_state[0]][curr_state[1]]-old_Q)>ERROR_THRESHOLD):\n HAS_CONVERGED = False\n\n if np.random.rand() <= best_state_success_prob:\n potential_feasible_rollout.append([curr_state,best_next_state,best_action])\n # previous_state = curr_state\n # visited.append(best_next_state)\n curr_state = best_next_state\n\n if(np.array_equal(curr_state, goal_state)):\n print(\"Goal reached!!!!!\")\n done = True\n tot_reward+=1000\n if(potential_rewardbest_V_val and not is_arr_in_list(s_, visited)):\n best_action = action\n best_V_val = V_table[s_[0]][s_[1]]\n\n if(not best_V_val>-float('Inf')):\n print(\"Going back to previous state\")\n env.s = previous_state \n else:\n next_state, reward, done, info = env.step(best_action) \n total_reward+=reward\n if(not is_arr_in_list(next_state[:2], visited)):\n visited.append(next_state[:2])\n if(not np.array_equal(next_state[:2], curr_state)):\n previous_state = curr_state\n print(\"Next state is: \",next_state[:2],\"\\t\",\"Present_state is: \",curr_state,\"\\t Action is: \",best_action)\n\n if(done and np.array_equal(next_state[:2], goal_state)):\n print(\"Path to goal found. Goal reached successfully. Total reward is: \",total_reward)\n elif(done):\n print(\"Robot fell into water\")\n exit()", "repo_name": "harshsha5/Maze_Solver_RL", "sub_path": "rtdp.py", "file_name": "rtdp.py", "file_ext": "py", "file_size_in_byte": 8405, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "cv2.imread", "line_number": 13, "usage_type": "call"}, {"api_name": "cv2.circle", "line_number": 14, "usage_type": "call"}, {"api_name": "cv2.circle", "line_number": 15, "usage_type": "call"}, {"api_name": "cv2.imshow", "line_number": 16, "usage_type": "call"}, {"api_name": "cv2.waitKey", "line_number": 17, "usage_type": "call"}, {"api_name": "numpy.array_equal", "line_number": 32, "usage_type": "call"}, {"api_name": "aid_gym.IslandEnv", "line_number": 36, "usage_type": "call"}, {"api_name": "numpy.load", "line_number": 68, "usage_type": "call"}, {"api_name": "numpy.linalg.norm", "line_number": 72, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 72, "usage_type": "attribute"}, {"api_name": "numpy.array_equal", "line_number": 85, "usage_type": "call"}, {"api_name": "time.time", "line_number": 89, "usage_type": "call"}, {"api_name": "numpy.clip", "line_number": 110, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 110, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 111, "usage_type": "call"}, {"api_name": "numpy.square", "line_number": 111, "usage_type": "call"}, {"api_name": "numpy.random.rand", "line_number": 139, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 139, "usage_type": "attribute"}, {"api_name": "numpy.array_equal", "line_number": 145, "usage_type": "call"}, {"api_name": "time.time", "line_number": 165, "usage_type": "call"}, {"api_name": "numpy.array_equal", "line_number": 185, "usage_type": "call"}, {"api_name": "numpy.clip", "line_number": 200, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 200, "usage_type": "call"}, {"api_name": "numpy.array_equal", "line_number": 213, "usage_type": "call"}, {"api_name": "numpy.array_equal", "line_number": 217, "usage_type": "call"}]} +{"seq_id": "5644680258", "text": "from .. import models, schemas, oauth2\nfrom fastapi import Response, status, HTTPException, Depends, APIRouter\nfrom .. database import get_db\nfrom sqlalchemy.orm import Session\nfrom sqlalchemy import func\nfrom typing import List, Optional\n\nrouter = APIRouter(\n prefix = \"/posts\",\n tags = ['Posts'] # affects the docs\n)\n\n@router.get(\"/\",response_model = List[schemas.PostOut])\ndef get_posts(db: Session = Depends(get_db),\n limit: int = 10, skip: int = 0, search: Optional[str] = \"\"):\n #skip+offset is how we'll implement pagination\n posts = db.query(models.Post).filter(models.Post.title.contains(search)).limit(limit).offset(skip).all()\n #Get the votes data. Going to do some left joins\n results = db.query(models.Post, func.count(models.Vote.post_id).label(\"votes\")\n ).join(\n models.Vote, models.Vote.post_id == models.Post.id, isouter=True\n ).group_by(\n models.Post.id\n ).all()\n\n return results\n\n@router.post(\"/\", status_code=status.HTTP_201_CREATED,response_model = schemas.Post)\ndef create_posts(post: schemas.PostCreate, response: Response,db: Session = Depends(get_db),\n current_user: int = Depends(oauth2.get_current_user)):\n\n #print(current_user.email) #don't really need this, just showing how we have the user object from the oauth stuff.\n new_post = models.Post(owner_id=current_user.id, **post.dict())\n db.add(new_post)\n db.commit()\n db.refresh(new_post)\n return new_post\n\n@router.get(\"/{id}\",response_model = schemas.Post)\ndef get_post(id: int, db: Session = Depends(get_db)):\n\n post = db.query(models.Post).filter(models.Post.id == id).first()\n\n if not post:\n raise HTTPException(status_code = status.HTTP_404_NOT_FOUND, detail = f\"There is no post number {id}\")\n \n return post\n\n@router.delete(\"/{id}\",status_code = status.HTTP_204_NO_CONTENT)\ndef delete_post(id: int, response: Response,db: Session = Depends(get_db),\n current_user: int = Depends(oauth2.get_current_user)):\n\n query_post = db.query(models.Post).filter(models.Post.id == id)\n\n post = query_post.first()\n\n if post == None:\n raise HTTPException(status_code = status.HTTP_404_NOT_FOUND, detail = f\"Post with id {id} was not found\")\n \n if post.owner_id != current_user.id:\n raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=\"You can only delete your own posts\")\n\n query_post.delete(synchronize_session=False)\n db.commit()\n\n return Response(status_code=status.HTTP_204_NO_CONTENT)\n\n@router.put(\"/{id}\",status_code=status.HTTP_200_OK,response_model = schemas.Post)\ndef update_post(id: int, post: schemas.PostCreate, response: Response,db: Session = Depends(get_db),\n current_user: int = Depends(oauth2.get_current_user)):\n \n query_post = db.query(models.Post).filter(models.Post.id == id)\n updated_post = query_post.first()\n\n if updated_post == None:\n raise HTTPException(status_code = status.HTTP_404_NOT_FOUND, \n detail = f\"Post with id {id} was not found\")\n \n if updated_post.owner_id != current_user.id:\n raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=\"You can only update your own posts\")\n \n query_post.update(post.dict(), synchronize_session=False)\n db.commit()\n\n return query_post.first()", "repo_name": "Purpello/example-fastapi", "sub_path": "app/routers/post.py", "file_name": "post.py", "file_ext": "py", "file_size_in_byte": 3373, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "fastapi.APIRouter", "line_number": 8, "usage_type": "call"}, {"api_name": "sqlalchemy.orm.Session", "line_number": 14, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 15, "usage_type": "name"}, {"api_name": "fastapi.Depends", "line_number": 14, "usage_type": "call"}, {"api_name": "database.get_db", "line_number": 14, "usage_type": "argument"}, {"api_name": "sqlalchemy.func.count", "line_number": 19, "usage_type": "call"}, {"api_name": "sqlalchemy.func", "line_number": 19, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 13, "usage_type": "name"}, {"api_name": "fastapi.Response", "line_number": 29, "usage_type": "name"}, {"api_name": "sqlalchemy.orm.Session", "line_number": 29, "usage_type": "name"}, {"api_name": "fastapi.Depends", "line_number": 29, "usage_type": "call"}, {"api_name": "database.get_db", "line_number": 29, "usage_type": "argument"}, {"api_name": "fastapi.Depends", "line_number": 30, "usage_type": "call"}, {"api_name": "fastapi.status.HTTP_201_CREATED", "line_number": 28, "usage_type": "attribute"}, {"api_name": "fastapi.status", "line_number": 28, "usage_type": "name"}, {"api_name": "sqlalchemy.orm.Session", "line_number": 40, "usage_type": "name"}, {"api_name": "fastapi.Depends", "line_number": 40, "usage_type": "call"}, {"api_name": "database.get_db", "line_number": 40, "usage_type": "argument"}, {"api_name": "fastapi.HTTPException", "line_number": 45, "usage_type": "call"}, {"api_name": "fastapi.status.HTTP_404_NOT_FOUND", "line_number": 45, "usage_type": "attribute"}, {"api_name": "fastapi.status", "line_number": 45, "usage_type": "name"}, {"api_name": "fastapi.Response", "line_number": 50, "usage_type": "name"}, {"api_name": "sqlalchemy.orm.Session", "line_number": 50, "usage_type": "name"}, {"api_name": "fastapi.Depends", "line_number": 50, "usage_type": "call"}, {"api_name": "database.get_db", "line_number": 50, "usage_type": "argument"}, {"api_name": "fastapi.Depends", "line_number": 51, "usage_type": "call"}, {"api_name": "fastapi.HTTPException", "line_number": 58, "usage_type": "call"}, {"api_name": "fastapi.status.HTTP_404_NOT_FOUND", "line_number": 58, "usage_type": "attribute"}, {"api_name": "fastapi.status", "line_number": 58, "usage_type": "name"}, {"api_name": "fastapi.HTTPException", "line_number": 61, "usage_type": "call"}, {"api_name": "fastapi.status.HTTP_403_FORBIDDEN", "line_number": 61, "usage_type": "attribute"}, {"api_name": "fastapi.status", "line_number": 61, "usage_type": "name"}, {"api_name": "fastapi.Response", "line_number": 66, "usage_type": "call"}, {"api_name": "fastapi.status.HTTP_204_NO_CONTENT", "line_number": 66, "usage_type": "attribute"}, {"api_name": "fastapi.status", "line_number": 66, "usage_type": "name"}, {"api_name": "fastapi.status.HTTP_204_NO_CONTENT", "line_number": 49, "usage_type": "attribute"}, {"api_name": "fastapi.status", "line_number": 49, "usage_type": "name"}, {"api_name": "fastapi.Response", "line_number": 69, "usage_type": "name"}, {"api_name": "sqlalchemy.orm.Session", "line_number": 69, "usage_type": "name"}, {"api_name": "fastapi.Depends", "line_number": 69, "usage_type": "call"}, {"api_name": "database.get_db", "line_number": 69, "usage_type": "argument"}, {"api_name": "fastapi.Depends", "line_number": 70, "usage_type": "call"}, {"api_name": "fastapi.HTTPException", "line_number": 76, "usage_type": "call"}, {"api_name": "fastapi.status.HTTP_404_NOT_FOUND", "line_number": 76, "usage_type": "attribute"}, {"api_name": "fastapi.status", "line_number": 76, "usage_type": "name"}, {"api_name": "fastapi.HTTPException", "line_number": 80, "usage_type": "call"}, {"api_name": "fastapi.status.HTTP_403_FORBIDDEN", "line_number": 80, "usage_type": "attribute"}, {"api_name": "fastapi.status", "line_number": 80, "usage_type": "name"}, {"api_name": "fastapi.status.HTTP_200_OK", "line_number": 68, "usage_type": "attribute"}, {"api_name": "fastapi.status", "line_number": 68, "usage_type": "name"}]} +{"seq_id": "71237302774", "text": "import json\nimport datetime\nimport operator\nfrom datetime import timedelta\nfrom dateutil import parser\n\ndef diferenca_entre_datas(data1, data2):\n d1 = datetime.datetime.strptime(data1, \"%d-%m-%Y\")\n d2 = datetime.datetime.strptime(data2, \"%d-%m-%Y\")\n return abs((d1 - d2).days)\n\ndef ler_arquivo_json_tipo_1(nome_arquivo):\n with open(nome_arquivo, 'r', encoding='utf8') as f:\n return json.load(f)\n\n# Leitura de arquivo json linha a linha\ndef ler_arquivo_json_tipo_2(nome_arquivo):\n lista_json = []\n for line in open(nome_arquivo, 'r', encoding='utf8'):\n lista_json.append(json.loads(line))\n \n return lista_json\n\n# Gerar lista de repositorios desde sua data de criacao até uma data limite com estrelas zeradas\ndef gerar_datas_repositorios_criacao_ate_fim(arquivo_json):\n arquivo_saida = []\n\n for i in range(len(arquivo_json)):\n \n # Formata a data de criação do repositório\n data_criacao_utc = arquivo_json[i]['created_at']\n data_criacao = parser.parse(data_criacao_utc)\n data_criacao = datetime.datetime.strftime(data_criacao, \"%d-%m-%Y\")\n \n # Calcula a diferença entre a data de criação e a data limite\n qtd_dias = diferenca_entre_datas(data_criacao,'01-06-2019')\n \n data_hora = parser.parse(data_criacao)\n \n # Cria registro para todas as datas entre a data de criação\n # e a data limite informando número de estrelas zerado\n for x in range(qtd_dias):\n data_hora = data_hora + timedelta(days=1)\n data = datetime.datetime.strftime(data_hora, \"%d-%m-%Y\")\n registro = {}\n registro['id'] = arquivo_json[i]['id']\n registro['data'] = data\n registro['estrelas'] = 0\n arquivo_saida.append(registro)\n \n return arquivo_saida\n\ndef calcular_estrelas_cada_dia(arquivo,arquivo_estrelas):\n repo_ant_id = 0\n estrelas_ant = 0\n\n for i in range(len(arquivo)):\n\n # Quando chega repositório novo zera o repositório anterior\n if arquivo[i]['id'] != repo_ant_id:\n print(arquivo[i]['id'])\n estrelas_ant = 0\n repo_ant_id = arquivo[i]['id']\n\n # Filtra as estrelas do repositorio naquele dia\n # Forma uma lista e conta quantos registros tem na lista \n registro = list(filter(lambda x:x[\"repo_id\"] == arquivo[i]['id'] and \n x[\"data\"] == arquivo[i]['data'],\n arquivo_estrelas))\n \n if len(registro) == 1:\n estrelas_ant = estrelas_ant + int(registro[0]['quantidade_estrelas'])\n arquivo[i]['estrelas'] = estrelas_ant\n\n if len(registro) > 1:\n print(\"ERRO\")\n print(registro)\n break\n \n return arquivo\n\ndef gravar_arquivo_json(nome_arquivo, dados):\n with open(nome_arquivo, 'w', encoding='utf-8') as f:\n json.dump(dados, f, ensure_ascii=False, indent=2, sort_keys=False, separators=(',' , ':'))\n\n#================================================================================#\n# MAIN #\n#================================================================================#\n\nprint(\"Informe o arquivo.json dos repositórios: \")\nnome_arquivo_repositorios = input()\n\nprint(\"Informe o nome do arquivo.json das estrelas: \")\nnome_arquivo_estrelas = input()\n\narquivo_json_repositorios = ler_arquivo_json_tipo_1(nome_arquivo_repositorios)\n\narquivo_json_saida_repo = gerar_datas_repositorios_criacao_ate_fim(arquivo_json_repositorios)\n\narquivo_json_estrelas = ler_arquivo_json_tipo_1(nome_arquivo_estrelas)\n\narquivo_json_estrelas.sort(key=operator.itemgetter('repo_id'), reverse=True)\n\narquivo_saida = calcular_estrelas_cada_dia(arquivo_json_saida_repo,arquivo_json_estrelas)\n\ngravar_arquivo_json(\"saida4.json\",arquivo_saida)", "repo_name": "carlosdenner/github", "sub_path": "levantamento_dados/estrelas/gerar_arquivo_dia_estrelas_repo.py", "file_name": "gerar_arquivo_dia_estrelas_repo.py", "file_ext": "py", "file_size_in_byte": 3954, "program_lang": "python", "lang": "pt", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "21", "api": [{"api_name": "datetime.datetime.strptime", "line_number": 8, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 8, "usage_type": "attribute"}, {"api_name": "datetime.datetime.strptime", "line_number": 9, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 9, "usage_type": "attribute"}, {"api_name": "json.load", "line_number": 14, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 20, "usage_type": "call"}, {"api_name": "dateutil.parser.parse", "line_number": 32, "usage_type": "call"}, {"api_name": "dateutil.parser", "line_number": 32, "usage_type": "name"}, {"api_name": "datetime.datetime.strftime", "line_number": 33, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 33, "usage_type": "attribute"}, {"api_name": "dateutil.parser.parse", "line_number": 38, "usage_type": "call"}, {"api_name": "dateutil.parser", "line_number": 38, "usage_type": "name"}, {"api_name": "datetime.timedelta", "line_number": 43, "usage_type": "call"}, {"api_name": "datetime.datetime.strftime", "line_number": 44, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 44, "usage_type": "attribute"}, {"api_name": "json.dump", "line_number": 84, "usage_type": "call"}, {"api_name": "operator.itemgetter", "line_number": 102, "usage_type": "call"}]} +{"seq_id": "17093325553", "text": "import sqlite3\n\nimport flask\nfrom flask import cli\n\nfrom golinx.models import link_model\nfrom golinx.models import user_model\n\ndef get_db():\n if 'db' not in flask.g:\n flask.g.db = sqlite3.connect(\n flask.current_app.config['DATABASE'],\n detect_types=sqlite3.PARSE_DECLTYPES\n )\n flask.g.db.row_factory = sqlite3.Row\n\n return flask.g.db\n\n\ndef close_db(e=None):\n db = flask.g.pop('db', None)\n\n if db is not None:\n db.close()\n\n\ndef init_db():\n db = get_db()\n\n with flask.current_app.open_resource('models/schema.sql') as f:\n db.executescript(f.read().decode('utf8'))\n\n with flask.current_app.open_resource(\n 'models/data/seed_users.csv', mode='r') as f:\n for seed_user in user_model.UserModel.from_csv(f, db=db):\n seed_user.save()\n\n with flask.current_app.open_resource(\n 'models/data/seed_links.csv', mode='r') as f:\n for seed_link in link_model.LinkModel.from_csv(f, db=db):\n seed_link.save()\n\n\ndef init_app(app):\n app.teardown_appcontext(close_db)\n", "repo_name": "johnjameswhitman/golinx", "sub_path": "golinx/models/db.py", "file_name": "db.py", "file_ext": "py", "file_size_in_byte": 1089, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "flask.g", "line_number": 10, "usage_type": "attribute"}, {"api_name": "flask.g", "line_number": 11, "usage_type": "attribute"}, {"api_name": "sqlite3.connect", "line_number": 11, "usage_type": "call"}, {"api_name": "flask.current_app", "line_number": 12, "usage_type": "attribute"}, {"api_name": "sqlite3.PARSE_DECLTYPES", "line_number": 13, "usage_type": "attribute"}, {"api_name": "flask.g", "line_number": 15, "usage_type": "attribute"}, {"api_name": "sqlite3.Row", "line_number": 15, "usage_type": "attribute"}, {"api_name": "flask.g", "line_number": 17, "usage_type": "attribute"}, {"api_name": "flask.g.pop", "line_number": 21, "usage_type": "call"}, {"api_name": "flask.g", "line_number": 21, "usage_type": "attribute"}, {"api_name": "flask.current_app.open_resource", "line_number": 30, "usage_type": "call"}, {"api_name": "flask.current_app", "line_number": 30, "usage_type": "attribute"}, {"api_name": "flask.current_app.open_resource", "line_number": 33, "usage_type": "call"}, {"api_name": "flask.current_app", "line_number": 33, "usage_type": "attribute"}, {"api_name": "golinx.models.user_model.UserModel.from_csv", "line_number": 35, "usage_type": "call"}, {"api_name": "golinx.models.user_model.UserModel", "line_number": 35, "usage_type": "attribute"}, {"api_name": "golinx.models.user_model", "line_number": 35, "usage_type": "name"}, {"api_name": "flask.current_app.open_resource", "line_number": 38, "usage_type": "call"}, {"api_name": "flask.current_app", "line_number": 38, "usage_type": "attribute"}, {"api_name": "golinx.models.link_model.LinkModel.from_csv", "line_number": 40, "usage_type": "call"}, {"api_name": "golinx.models.link_model.LinkModel", "line_number": 40, "usage_type": "attribute"}, {"api_name": "golinx.models.link_model", "line_number": 40, "usage_type": "name"}]} +{"seq_id": "25743962226", "text": "# 03\n# Medium\n\n# BFS: Given a graph and a target number T, find if T exists in the graph.\n\n\n# -----------------------------------------------------\n\n# Time Complexity: O(V + E)\n# Space Complexity: O(V)\n# We can store at most V nodes on the Queue, and we also use V space to store the state\n# of each node.\n\n# 3:43\n\nfrom collections import deque\n\nclass Node(object):\n def __init__(self, data: int):\n self.data = data\n self.relations = []\n self.visited = False\n\n def __repr__(self) -> str:\n return str(self.data)\n\nclass Graph(object):\n def __init__(self):\n self.nodes = []\n\n def reset(self) -> None:\n for n in self.nodes:\n n.visited = False\n\n def contains(self, v: int) -> bool:\n for node in self.nodes:\n if node.visited:\n continue\n q = deque()\n q.appendleft(node)\n while q:\n n = q.pop()\n if n.data == v:\n return True\n n.visited = True\n for r in node.relations:\n if not r.visited:\n q.appendleft(r)\n return False\n\n# -----------------------------------------------------\n\nn1 = Node(5)\nn2 = Node(10)\nn3 = Node(15)\nn4 = Node(20)\nn5 = Node(25)\nn6 = Node(30)\n\nn1.relations = [n2,n3]\nn2.relations = [n4]\nn3.relations = [n4,n5]\nn4.relations = [n6]\nn5.relations = [n6]\n \ng = Graph()\ng.nodes = [n1,n2,n3,n4,n5,n6]\n\nimport pytest\n\ndef test_graph_contains():\n assert(g.contains(25))\n g.reset()\n assert(not g.contains(31))\n g.reset()\n assert(not g.contains(1))\n g.reset()\n assert(g.contains(5))\n\npytest.main()\n", "repo_name": "dannynoonan/interview-prep", "sub_path": "ic/15_graphs/03_bfs_search.py", "file_name": "03_bfs_search.py", "file_ext": "py", "file_size_in_byte": 1685, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "collections.deque", "line_number": 39, "usage_type": "call"}, {"api_name": "pytest.main", "line_number": 80, "usage_type": "call"}]} +{"seq_id": "12568646194", "text": "import socket, select \nimport config\n\nconnlist = []\nrecv_buffer = 4096\n\ndef broadcast(sock , msg):\n for socket in connlist :\n if not socket == ss and not socket == sock :\n try:\n socket.send(msg)\n except:\n socket.close()\n connlist.remove(socket)\n\nif __name__ == \"__main__\":\n ## TCP Server udp use socket.SOCK_DGRAM\n ss = socket.socket(socket.AF_INET , socket.SOCK_STREAM)\n \n ss.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)\n ss.bind((config.ip,config.port))\n \n ## conn value\n ss.listen(10) \n connlist.append(ss)\n print('server run on ' + str(config.ip))\n\n while 1:\n rdsocket,wrsocket,errsocket = select.select(connlist,[],[])\n for s in rdsocket :\n if s == ss:\n sockfd , addr = ss.accept()\n connlist.append(sockfd)\n print('conn client' + str(addr)) \n broadcast(sockfd,\"[%s:%s] enter \\n\" % addr)\n else:\n try :\n data = s.recv(recv_buffer)\n if data :\n broadcast(s,\"\\r\" + '<' + str(s.getpeername()) + '> ' + data)\n except:\n broadcast(s, \"(%s, %s) go dead\" % addr)\n s.close()\n connlist.remove(s)\n continue\n ss.close()\n\n\n", "repo_name": "m85091081/Socket_Chat-", "sub_path": "server.py", "file_name": "server.py", "file_ext": "py", "file_size_in_byte": 1395, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "socket.send", "line_number": 11, "usage_type": "call"}, {"api_name": "socket.close", "line_number": 13, "usage_type": "call"}, {"api_name": "socket.socket", "line_number": 18, "usage_type": "call"}, {"api_name": "socket.AF_INET", "line_number": 18, "usage_type": "attribute"}, {"api_name": "socket.SOCK_STREAM", "line_number": 18, "usage_type": "attribute"}, {"api_name": "socket.SOL_SOCKET", "line_number": 20, "usage_type": "attribute"}, {"api_name": "socket.SO_REUSEADDR", "line_number": 20, "usage_type": "attribute"}, {"api_name": "config.ip", "line_number": 21, "usage_type": "attribute"}, {"api_name": "config.port", "line_number": 21, "usage_type": "attribute"}, {"api_name": "config.ip", "line_number": 26, "usage_type": "attribute"}, {"api_name": "select.select", "line_number": 29, "usage_type": "call"}]} +{"seq_id": "23128612240", "text": "import pandas as pd\nimport numpy as np\nimport re\nfrom dataclasses import dataclass\nfrom scipy.interpolate import CubicSpline\n\n\n@dataclass\nclass FeaturesExtractor:\n # name of Interpolator from scipy.interpolate\n interpolator: str = \"CubicSpline\"\n # path to csv file with data\n path_to_file: str = \"\"\n # number of grid points\n n_grid: int = 10\n\n def convert_row_to_array_to_float(self, item, column_name, verbose=0):\n \"\"\"Convert string to float ndarray\"\"\"\n try:\n x = np.array([float(z) for z in re.split(\"\\n | \", item[column_name][1:-1]) if z != \"\"])\n except ValueError:\n if verbose == 1:\n print(\n f\"Error convert {column_name}\"\n f'data for TIC={item[\"TIC\"]} object'\n f'cadence_id={item[\"cadence_id\"]}'\n )\n x = np.array([])\n return x\n\n def fit_interpolator(self, x, y):\n \"\"\"Fit interpolator for initial data\"\"\"\n interpolator_object = None\n if self.interpolator == \"CubicSpline\":\n interpolator_object = CubicSpline(x, y)\n else:\n raise ValueError(\"Undefined interpolator name\")\n return interpolator_object\n\n def get_data(self, feature_label, verbose=0) -> pd.DataFrame:\n \"\"\"Return dataframe with interpolated by interpolator object\n (cubic spline by default) n_grid points.\"\"\"\n features_columns = [f\"{feature_label}_{i}\" for i in range(self.n_grid)]\n data = pd.DataFrame(columns=[\"TIC\", \"cadence_id\"] + features_columns)\n initial_data = pd.read_csv(self.path_to_file)\n\n for index, item in initial_data.iterrows():\n x = self.convert_row_to_array_to_float(item, column_name=\"mjd\")\n y = self.convert_row_to_array_to_float(item, column_name=feature_label)\n # check input data\n if len(x) == 0 or len(y) == 0 or len(x) != len(y):\n if verbose == 1 and len(x) != len(y):\n print(\n f\"len time points={len(x)} not equl len mag points={len(y)}\"\n f' in data for TIC={item[\"TIC\"]} object'\n f' cadence_id={item[\"cadence_id\"]}'\n )\n continue\n interpolator = self.fit_interpolator(x, y)\n xnew = np.linspace(x.min(), x.max(), self.n_grid)\n # add features to output datafrzme\n data.loc[index, :] = [item[\"TIC\"], item[\"cadence_id\"]] + list(interpolator(xnew))\n\n return data\n\n\nif __name__ == \"__main__\":\n import time\n\n start_time = time.time()\n print(\"Start feature extract\")\n FE = FeaturesExtractor(path_to_file=\"generated_250k.csv\", n_grid=20)\n data = FE.get_data(feature_label=\"mag\")\n print(data.head())\n print(f\"End features extract time execution = {(time.time() - start_time):.2f} seconds\")\n", "repo_name": "snad-space/flare-classifier", "sub_path": "nb/features_extract.py", "file_name": "features_extract.py", "file_ext": "py", "file_size_in_byte": 2902, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "numpy.array", "line_number": 20, "usage_type": "call"}, {"api_name": "re.split", "line_number": 20, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 28, "usage_type": "call"}, {"api_name": "scipy.interpolate.CubicSpline", "line_number": 35, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 44, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 45, "usage_type": "call"}, {"api_name": "numpy.linspace", "line_number": 60, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 40, "usage_type": "attribute"}, {"api_name": "dataclasses.dataclass", "line_number": 8, "usage_type": "name"}, {"api_name": "time.time", "line_number": 70, "usage_type": "call"}, {"api_name": "time.time", "line_number": 75, "usage_type": "call"}]} +{"seq_id": "8377203777", "text": "# 1. GENEL RESIM\n\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nfrom matplotlib import pyplot as plt\n\npd.pandas.set_option('display.max_columns', None)\ndf = pd.read_csv(\"/Users/mvahit/Documents/GitHub/dsmlbc/datasets/train.csv\")\n\ndf.head()\ndf.tail()\ndf.shape\ndf.info()\ndf.columns\ndf.index\ndf.describe().T\ndf.isnull().values.any()\ndf.isnull().sum()\n\n\n# 2. KATEGORIK DEGISKEN ANALIZI\ndf.Survived.unique()\ndf.Survived.value_counts()\n\n# Kac kategorik değişken var ve isimleri neler?\ncat_cols = [col for col in df.columns if df[col].dtypes == 'O']\nprint('Kategorik Değişken Sayısı: ', len(cat_cols))\nprint(cat_cols)\n\n\nmore_cat_cols = [col for col in df.columns if len(df[col].unique()) < 10]\nprint('Kategorik Değişken Sayısı: ', len(more_cat_cols))\nprint(more_cat_cols)\n\n\n# Hangi kategorik değişkenin kaç sınıfı var?\ndf[cat_cols].nunique()\n\n# Kategorik Değişkenlerin Sütun Grafik İle Gösterilmesi\nsns.countplot(x=\"Sex\", data=df)\nplt.show()\n\n\ndef cats_summary(data):\n cats_names = [col for col in data.columns if len(data[col].unique()) < 10 and data[col].dtypes == 'O']\n for var in cats_names:\n print(pd.DataFrame({var: data[var].value_counts(),\n \"Ratio\": 100 * data[var].value_counts() / len(data)}), end=\"\\n\\n\\n\")\n sns.countplot(x=var, data=data)\n plt.show()\n\n\ncats_summary(df)\n\n\ndef cats_summary(data, categorical_cols, number_of_classes=10):\n var_count = 0 # Kaç kategorik değişken olduğu raporlanacak\n vars_more_classes = [] # Belirli bir sayıdan daha fazla sayıda sınıfı olan değişkenler saklanacak.\n for var in data:\n if var in categorical_cols:\n if len(list(data[var].unique())) <= number_of_classes: # sınıf sayısına göre seç\n print(pd.DataFrame({var: data[var].value_counts(),\n \"Ratio\": 100 * data[var].value_counts() / len(data)}),\n end=\"\\n\\n\\n\")\n var_count += 1\n else:\n vars_more_classes.append(data[var].name)\n print('%d categorical variables have been described' % var_count, end=\"\\n\\n\")\n print('There are', len(vars_more_classes), \"variables have more than\", number_of_classes, \"classes\", end=\"\\n\\n\")\n print('Variable names have more than %d classes:' % number_of_classes, end=\"\\n\\n\")\n print(vars_more_classes)\n\n\ncats_summary(df, cat_cols)\n\n\n# 3. SAYISAL DEGISKEN ANALIZI\n\n# Sayısal değişkenlere genel bakış:\ndf.describe().T\ndf.describe([0.05, 0.10, 0.25, 0.50, 0.75, 0.80, 0.90, 0.95, 0.99]).T\n\nsns.boxplot(x=df[\"Age\"])\n\n# Veri setinde kaç sayısal değişken var?\nnum_cols = [col for col in df.columns if df[col].dtypes != 'O']\nprint('Sayısal değişken sayısı: ', len(num_cols))\n\n# Sayısal değişkenlerin isimleri neler?\nnum_cols\n\n# Veri setindeki id değişkeninden ve survived değişkeninden yukarıdaki kod ile nasıl kurtulabiliriz?\n# Normal olarak nasıl kurtuluyorduk ki?\n\ndf.drop(\"PassengerId\", axis=1).columns\n\n# Önceki kod ile:\nnum_cols = [col for col in df.columns if df[col].dtypes != 'O' and\n col not in \"PassengerId\" and\n col not in \"Survived\"]\nnum_cols\n\n# Bir sayısal değişkenin dağılımını inceleyelim:\ndf[\"Age\"].hist(bins=30)\nplt.show()\n\nsns.boxplot(x=df[\"Age\"])\nplt.show()\n\n\n# Sayısal değişkenlerin hepsini otomatik olarak nasıl analiz ederiz?\ndef hist_for_nums(data, numeric_cols):\n col_counter = 0\n data = data.copy()\n for col in numeric_cols:\n data[col].hist(bins=20)\n plt.xlabel(col)\n plt.title(col)\n plt.show()\n col_counter += 1\n print(col_counter, \"variables have been plotted\")\n\n\nhist_for_nums(df, num_cols)\n\n# Baska bir veri seti ile deneyelim:\ndf = pd.read_csv(\"eda/application_train.csv\")\ndf.head()\n\nnum_cols = [col for col in df.columns if df[col].dtypes != 'O' and\n col not in \"SK_ID_CURR \" and\n col not in \"TARGET\"]\n\nhist_for_nums(df, num_cols)\n\n# İki sınıflı olanlar da geldi. Bunlardan pratik olarak nasıl kurtuluruz?\nnum_cols = [col for col in df.columns if df[col].dtypes != 'O' and\n len(df[col].unique()) > 20 and\n col not in \"SK_ID_CURR \" and\n col not in \"TARGET\"]\n\nhist_for_nums(df, num_cols)\n\n# Bu değişkenlerin dağılımları çok da normal değil gibi.\n# Eğer doğrusal bir model kullanacak olsaydık bu durumda bu değişkenlere logaritmik bir dönüşüm uygulamak gerekirdi.\n\n\n# 4. TARGET ANALIZI\ndf = pd.read_csv(\"eda/titanic.csv\")\n\n# Survived değişkeninin dağılımını inceleyelim\ndf[\"Survived\"].value_counts()\n\n# KATEGORIK DEGISKENLERE GORE TARGET ANALIZI\n# Nasıl yani? Kategorik değişkenlere göre grup by yapıp survived'ın ortalamasını alarak.\ndf.groupby(\"Sex\")[\"Survived\"].mean()\n\nmore_cat_cols = [col for col in df.columns if len(df[col].unique()) < 10]\nprint('Kategorik Değişken Sayısı: ', len(more_cat_cols))\nprint(more_cat_cols)\n\n\n# Peki bunu tüm değişkenlere otomatik olarak nasıl yapabiliriz?\ndef target_summary_with_cat(data, target):\n cats_names = [col for col in data.columns if len(data[col].unique()) < 10 and col not in target]\n for var in cats_names:\n print(pd.DataFrame({\"TARGET_MEAN\": data.groupby(var)[target].mean()}), end=\"\\n\\n\\n\")\n\n\ntarget_summary_with_cat(df, \"Survived\")\n\n# SAYISAL DEGISKENLERE GORE TARGET ANALIZI\ndf.groupby(\"Survived\").agg({\"Age\": np.mean})\n\n\ndef target_summary_with_nums(data, target):\n num_names = [col for col in data.columns if len(data[col].unique()) > 5\n and df[col].dtypes != 'O'\n and col not in target\n and col not in \"PassengerId\"]\n\n for var in num_names:\n print(df.groupby(target).agg({var: np.mean}), end=\"\\n\\n\\n\")\n\n\ntarget_summary_with_nums(df, \"Survived\")\n\nfrom functools import reduce\n\nA = [\"Veri\", \"Bilimi\", \"Okulu\"]\n\nprint(reduce(lambda a, b: a + b, list(map(lambda x: x[0], A))))\n\n# 5.SAYISAL DEGISKENLERIN BIRBIRLERINE GORE INCELENMESI\n\ndf = sns.load_dataset(\"tips\")\ndf.head()\n\nsns.scatterplot(x=\"total_bill\", y=\"tip\", data=df)\nplt.show()\n\nsns.lmplot(x=\"total_bill\", y=\"tip\", data=df)\nplt.show()\n\n\ndf.corr()\n\n\n", "repo_name": "Tayfuncanikli/Data-Analysis-projects", "sub_path": "eda.py", "file_name": "eda.py", "file_ext": "py", "file_size_in_byte": 6142, "program_lang": "python", "lang": "tr", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "pandas.pandas.set_option", "line_number": 8, "usage_type": "call"}, {"api_name": "pandas.pandas", "line_number": 8, "usage_type": "attribute"}, {"api_name": "pandas.read_csv", "line_number": 9, "usage_type": "call"}, {"api_name": "seaborn.countplot", "line_number": 41, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.show", "line_number": 42, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 42, "usage_type": "name"}, {"api_name": "pandas.DataFrame", "line_number": 48, "usage_type": "call"}, {"api_name": "seaborn.countplot", "line_number": 50, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.show", "line_number": 51, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 51, "usage_type": "name"}, {"api_name": "pandas.DataFrame", "line_number": 63, "usage_type": "call"}, {"api_name": "seaborn.boxplot", "line_number": 84, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.show", "line_number": 106, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 106, "usage_type": "name"}, {"api_name": "seaborn.boxplot", "line_number": 108, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.show", "line_number": 109, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 109, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 118, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 118, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 119, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 119, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 120, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 120, "usage_type": "name"}, {"api_name": "pandas.read_csv", "line_number": 128, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 150, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 168, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 174, "usage_type": "attribute"}, {"api_name": "numpy.mean", "line_number": 184, "usage_type": "attribute"}, {"api_name": "functools.reduce", "line_number": 193, "usage_type": "call"}, {"api_name": "seaborn.load_dataset", "line_number": 197, "usage_type": "call"}, {"api_name": "seaborn.scatterplot", "line_number": 200, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.show", "line_number": 201, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 201, "usage_type": "name"}, {"api_name": "seaborn.lmplot", "line_number": 203, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.show", "line_number": 204, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 204, "usage_type": "name"}]} +{"seq_id": "8673345876", "text": "from numpy.core.fromnumeric import argsort\r\nimport tensorflow as tf\r\nfrom tensorflow import keras\r\nfrom tensorflow.keras.datasets import mnist\r\nfrom tensorflow.keras import backend as K\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib.lines import Line2D\r\nfrom sklearn . preprocessing import QuantileTransformer\r\nfrom tensorflow.python.keras.activations import linear\r\nfrom sklearn.metrics import roc_auc_score, roc_curve\r\n\r\n\r\npath = 'D:/strojno_ucenje/7Avtoenkoderji/blackbox_jetobs.npy'\r\n\r\nx_train = np.load(path)\r\nlabels = np.load('D:/strojno_ucenje/7Avtoenkoderji/lhco_01_labels.npy')\r\nx_train = x_train.astype('float32')\r\nf_scaler = QuantileTransformer( output_distribution ='uniform',random_state=100)\r\nx_train_transformed = f_scaler.fit_transform(x_train)\r\ninv_mass = np.load('D:/strojno_ucenje/7Avtoenkoderji/blackbox_invmass.npy')\r\n\r\nprint(x_train_transformed.shape)\r\nprint(x_train_transformed.shape[1:])\r\n\r\noriginal_dim = np.prod( x_train_transformed.shape[1:]) # dimenzija vhodnih podatkov\r\nhidden_dim = 64 # skriti sloj z 64 node -i\r\nlatent_dim = 1 # 2D latentni prostor\r\ninputs = keras.Input(shape=(original_dim,))\r\nx = keras.layers.Dense (hidden_dim, activation='selu')(inputs)\r\nx = keras.layers.Dense (hidden_dim, activation='selu')(x)\r\nx = keras.layers.Dense (hidden_dim, activation='selu')(x)\r\nz_mean = keras.layers.Dense (latent_dim, name='z_mean')(x)\r\nz_log_var = keras.layers.Dense(latent_dim, name='z_log_var')(x)\r\n\r\ndef sampling(args):\r\n z_mean , z_log_var = args\r\n epsilon = K.random_normal(shape=(K.shape(z_mean)[0], latent_dim) , mean=0.0 , stddev=1.0)\r\n return z_mean + K.exp( 0.5 * z_log_var ) * epsilon\r\n\r\nz = keras.layers.Lambda(sampling)([z_mean, z_log_var])\r\n\r\nencoder = keras.Model(inputs, [z_mean ,z_log_var, z],name ='encoder')\r\n\r\nlatent_inputs = keras.Input(shape=(latent_dim, ) , name='z_sampling')\r\nx = keras.layers.Dense(hidden_dim , activation ='selu') (latent_inputs)\r\nx = keras.layers.Dense(hidden_dim , activation ='selu') (x)\r\nx = keras.layers.Dense(hidden_dim , activation ='selu') (x)\r\noutputs = keras.layers.Dense(original_dim)(x)\r\ndecoder = keras.Model(latent_inputs, outputs, name='decoder')\r\n\r\noutputs = decoder(encoder(inputs)[2])\r\nvae = keras.Model(inputs ,outputs ,name ='vae')\r\n\r\n\r\nrec_loss =keras.losses.mean_squared_error(inputs, outputs)\r\nrec_loss *= 5000\r\nkl_loss = -0.5*K.sum( 1 + z_log_var - K.square(z_mean) - K.exp(z_log_var) ,axis=-1)\r\nvae_loss = K.mean(rec_loss + kl_loss)\r\nvae.add_loss(vae_loss)\r\nvae.compile (optimizer ='adadelta')\r\n\r\nbatch_size = 1000\r\n\r\n#history = vae.fit(x_train_transformed ,x_train_transformed ,epochs=100,batch_size=batch_size ,validation_data=None)\r\n\r\n\"\"\"\r\nx_encoded = np.load(f'D:/strojno_ucenje/7Avtoenkoderji/blackbox_1.npy')\r\n\r\nmean, z_var, napovedan_z = x_encoded \r\n\r\nocenjevalec = z_var\r\n\r\n\r\nplt.hist(ocenjevalec,100)\r\nplt.show()\r\n\"\"\"\r\n\r\nx_encoded = np.load(f'D:/strojno_ucenje/7Avtoenkoderji/blackbox_1.npy', allow_pickle=True)\r\n\r\nmean, z_var, napovedan_z = x_encoded \r\nmean2 = mean **2 \r\nindex = np.flip(mean2[:,0].argsort())\r\nprint(index)\r\nx_train = x_train[index]\r\na = 800\r\ninv_mass = inv_mass[index]\r\n\r\nplt.hist(inv_mass[:a],40,histtype=u'step')\r\nplt.xlabel('inv mass')\r\nplt.ylabel('N')\r\nplt.show()\r\n\r\n\r\nfor i in range(4):\r\n\r\n plt.hist(x_train[:,i][:a],bins=40,histtype=u'step',label='curek 1')\r\n plt.hist(x_train[:,i + 4][:a],bins=40,histtype=u'step',label='curek 2')\r\n\r\n plt.ylabel(\"N\")\r\n if i == 0:\r\n plt.xlabel(r\"$m$\")\r\n elif i == 1:\r\n plt.xlabel(r'$(\\tau_2 / \\tau_1)$') \r\n elif i == 2:\r\n plt.xlabel(r'$(\\tau_3 / \\tau_2)$') \r\n elif i == 3:\r\n plt.xlabel(r'$m_{d}$') \r\n \r\n plt.legend()\r\n plt.show()\r\n\r\n", "repo_name": "maticdeb/Machine-learning", "sub_path": "Variational_autoencoder/napoved.py", "file_name": "napoved.py", "file_ext": "py", "file_size_in_byte": 3698, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "numpy.load", "line_number": 16, "usage_type": "call"}, {"api_name": "numpy.load", "line_number": 17, "usage_type": "call"}, {"api_name": "sklearn.preprocessing.QuantileTransformer", "line_number": 19, "usage_type": "call"}, {"api_name": "numpy.load", "line_number": 21, "usage_type": "call"}, {"api_name": "numpy.prod", "line_number": 26, "usage_type": "call"}, {"api_name": "tensorflow.keras.Input", "line_number": 29, "usage_type": "call"}, {"api_name": "tensorflow.keras", "line_number": 29, "usage_type": "name"}, {"api_name": "tensorflow.keras.layers.Dense", "line_number": 30, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers", "line_number": 30, "usage_type": "attribute"}, {"api_name": "tensorflow.keras", "line_number": 30, "usage_type": "name"}, {"api_name": "tensorflow.keras.layers.Dense", "line_number": 31, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers", "line_number": 31, "usage_type": "attribute"}, {"api_name": "tensorflow.keras", "line_number": 31, "usage_type": "name"}, {"api_name": "tensorflow.keras.layers.Dense", "line_number": 32, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers", "line_number": 32, "usage_type": "attribute"}, {"api_name": "tensorflow.keras", "line_number": 32, "usage_type": "name"}, {"api_name": "tensorflow.keras.layers.Dense", "line_number": 33, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers", "line_number": 33, "usage_type": "attribute"}, {"api_name": "tensorflow.keras", "line_number": 33, "usage_type": "name"}, {"api_name": "tensorflow.keras.layers.Dense", "line_number": 34, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers", "line_number": 34, "usage_type": "attribute"}, {"api_name": "tensorflow.keras", "line_number": 34, "usage_type": "name"}, {"api_name": "tensorflow.keras.backend.random_normal", "line_number": 38, "usage_type": "call"}, {"api_name": "tensorflow.keras.backend", "line_number": 38, "usage_type": "name"}, {"api_name": "tensorflow.keras.backend.shape", "line_number": 38, "usage_type": "call"}, {"api_name": "tensorflow.keras.backend.exp", "line_number": 39, "usage_type": "call"}, {"api_name": "tensorflow.keras.backend", "line_number": 39, "usage_type": "name"}, {"api_name": "tensorflow.keras.layers.Lambda", "line_number": 41, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers", "line_number": 41, "usage_type": "attribute"}, {"api_name": "tensorflow.keras", "line_number": 41, "usage_type": "name"}, {"api_name": "tensorflow.keras.Model", "line_number": 43, "usage_type": "call"}, {"api_name": "tensorflow.keras", "line_number": 43, "usage_type": "name"}, {"api_name": "tensorflow.keras.Input", "line_number": 45, "usage_type": "call"}, {"api_name": "tensorflow.keras", "line_number": 45, "usage_type": "name"}, {"api_name": "tensorflow.keras.layers.Dense", "line_number": 46, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers", "line_number": 46, "usage_type": "attribute"}, {"api_name": "tensorflow.keras", "line_number": 46, "usage_type": "name"}, {"api_name": "tensorflow.keras.layers.Dense", "line_number": 47, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers", "line_number": 47, "usage_type": "attribute"}, {"api_name": "tensorflow.keras", "line_number": 47, "usage_type": "name"}, {"api_name": "tensorflow.keras.layers.Dense", "line_number": 48, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers", "line_number": 48, "usage_type": "attribute"}, {"api_name": "tensorflow.keras", "line_number": 48, "usage_type": "name"}, {"api_name": "tensorflow.keras.layers.Dense", "line_number": 49, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers", "line_number": 49, "usage_type": "attribute"}, {"api_name": "tensorflow.keras", "line_number": 49, "usage_type": "name"}, {"api_name": "tensorflow.keras.Model", "line_number": 50, "usage_type": "call"}, {"api_name": "tensorflow.keras", "line_number": 50, "usage_type": "name"}, {"api_name": "tensorflow.keras.Model", "line_number": 53, "usage_type": "call"}, {"api_name": "tensorflow.keras", "line_number": 53, "usage_type": "name"}, {"api_name": "tensorflow.keras.losses.mean_squared_error", "line_number": 56, "usage_type": "call"}, {"api_name": "tensorflow.keras.losses", "line_number": 56, "usage_type": "attribute"}, {"api_name": "tensorflow.keras", "line_number": 56, "usage_type": "name"}, {"api_name": "tensorflow.keras.backend.sum", "line_number": 58, "usage_type": "call"}, {"api_name": "tensorflow.keras.backend", "line_number": 58, "usage_type": "name"}, {"api_name": "tensorflow.keras.backend.square", "line_number": 58, "usage_type": "call"}, {"api_name": "tensorflow.keras.backend.exp", "line_number": 58, "usage_type": "call"}, {"api_name": "tensorflow.keras.backend.mean", "line_number": 59, "usage_type": "call"}, {"api_name": "tensorflow.keras.backend", "line_number": 59, "usage_type": "name"}, {"api_name": "numpy.load", "line_number": 79, "usage_type": "call"}, {"api_name": "numpy.flip", "line_number": 83, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.hist", "line_number": 89, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 89, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 90, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 90, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 91, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 91, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 92, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 92, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.hist", "line_number": 97, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 97, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.hist", "line_number": 98, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 98, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 100, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 100, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 102, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 102, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 104, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 104, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 106, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 106, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 108, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 108, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 110, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 110, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 111, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 111, "usage_type": "name"}]} +{"seq_id": "8127499230", "text": "# coding=utf-8\nfrom bs4 import BeautifulSoup\n\nfrom django.contrib import admin\nfrom django.core.exceptions import ValidationError\nfrom django.core.urlresolvers import reverse\n\n# Register your models here.\nfrom django.contrib.admin import register\nfrom django.utils import timezone\nfrom django.forms.models import BaseInlineFormSet\n\nfrom .models import Sportscar, SportCarIdentificationRequestRecord, SportCarOwnership, Manufacturer, CarMediaItem\nfrom .models import MAX_AUDIO_PER_CAR, MAX_IMAGE_PER_CAR, MAX_VIDEO_PER_CAR\nfrom Notification.signal import send_notification\n\nclass SportscarInlineAdmin(admin.StackedInline):\n\n model = Sportscar\n exclude = (\"remote_id\", 'price_number', 'remote_image', 'remote_thumbnail', 'data_fetched')\n extra = 1\n show_change_link = True\n\n\nclass CarMediaItemFormset(BaseInlineFormSet):\n\n def clean(self):\n super(CarMediaItemFormset, self).clean()\n image_num = 0\n video_num = 0\n audio_num = 0\n for form in self.forms:\n if not form.is_valid():\n continue\n if form.cleaned_data[\"DELETE\"]:\n continue\n item_type = form.cleaned_data.get(\"item_type\", None)\n if item_type == \"image\":\n image_num += 1\n elif item_type == \"video\":\n video_num += 1\n elif item_type == \"audio\":\n audio_num += 1\n else:\n raise ValidationError(message=u\"没有定义的附件类型\")\n\n if image_num > MAX_IMAGE_PER_CAR:\n raise ValidationError(message=u\"最多只允许%s张图片\" % MAX_IMAGE_PER_CAR)\n if video_num > MAX_VIDEO_PER_CAR:\n raise ValidationError(message=u\"最多只允许%s个视频\" % MAX_VIDEO_PER_CAR)\n if audio_num > MAX_AUDIO_PER_CAR:\n raise ValidationError(message=u'最多只允许%s个音频' % MAX_AUDIO_PER_CAR)\n\n def save(self, commit=True):\n items = super(CarMediaItemFormset, self).save(commit=False)\n for item in items:\n if item.item_type == \"video\":\n link = item.link\n try:\n src = BeautifulSoup(link).find(\"iframe\")[\"src\"]\n item.link = src\n except TypeError:\n pass\n if commit:\n item.save()\n if commit:\n for delete_obj in self.deleted_objects:\n delete_obj.delete()\n return items\n\n\nclass CarMediaItemAdmin(admin.TabularInline):\n\n model = CarMediaItem\n formset = CarMediaItemFormset\n extra = 0\n readonly_fields = (\"created_at\", )\n\n\n@register(Sportscar)\nclass SportscarAdmin(admin.ModelAdmin):\n exclude = (\"remote_id\", 'price_number', 'remote_image', 'remote_thumbnail', 'data_fetched', \"image\", \"thumbnail\")\n list_display = ('name', 'price', 'fuel_consumption', 'engine', 'transmission', 'max_speed', 'torque')\n search_fields = (\"name\", )\n\n inlines = (CarMediaItemAdmin, )\n\n\nclass SportCarOwnershipInlineAdmin(admin.StackedInline):\n\n model = SportCarOwnership\n\n\n@register(SportCarIdentificationRequestRecord)\nclass SportCarIdentificationRequestRecordAdmin(admin.ModelAdmin):\n search_fields = (\"license_num\", )\n\n # def link_to_user(self, obj):\n # return u'%s(%s)' % (obj.ownership.user.id, obj.ownership.user.nick_name,\n # obj.ownership.user.username)\n # link_to_user.short_description = u'申请人'\n # link_to_user.allow_tags = True\n\n # fields = (\"ownership\", \"created_at\", \"approved\",\n # \"drive_license_admin\", \"id_card_admin\", \"photo_admin\", \"license_num\",\n # \"link_to_user\", )\n\n def has_add_permission(self, request):\n return False\n\n def has_delete_permission(self, request, obj=None):\n return False\n\n fields = (\"link_to_user\", \"link_to_car\", \"license_num\", \"approved\", \"checked\", \"drive_license_admin\",\n \"photo_admin\", \"created_at\", )\n exclude = None\n readonly_fields = (\"link_to_user\", \"drive_license_admin\", \"id_card_admin\", \"photo_admin\", \"created_at\",\n \"link_to_car\", \"license_num\")\n list_display = (\"created_at\", \"link_to_user\", \"link_to_car\", \"checked\", \"approved\")\n list_filter = (\"checked\", \"approved\")\n\n def save_model(self, request, obj, form, change):\n old_obj = SportCarIdentificationRequestRecord.objects.get(id=obj.id)\n if not old_obj.checked and obj.checked:\n own = obj.ownership\n own.identified = obj.approved\n own.identified_at = timezone.now()\n user = own.user\n if own.identified and user.avatar_car is None:\n user.avatar_car = own\n user.save()\n own.save()\n send_notification.send(\n sender=SportCarIdentificationRequestRecord,\n target=user,\n display_mode=\"minimal\",\n extra_info=\"agree\" if obj.approved else \"deny\",\n related_user=user,\n related_own=own\n )\n\n super(SportCarIdentificationRequestRecordAdmin, self)\\\n .save_model(request, obj, form, change)\n\n\n@register(Manufacturer)\nclass ManufacturerAdmin(admin.ModelAdmin):\n exclude = ('remote_id', 'detail_url', 'logo_remote', )\n list_display = ('name', 'index', )\n search_fields = ('name', 'index', )\n\n inlines = [SportscarInlineAdmin, ]\n\n", "repo_name": "huangy10/SportscarStyle", "sub_path": "Sportscar/admin.py", "file_name": "admin.py", "file_ext": "py", "file_size_in_byte": 5495, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "django.contrib.admin.StackedInline", "line_number": 17, "usage_type": "attribute"}, {"api_name": "django.contrib.admin", "line_number": 17, "usage_type": "name"}, {"api_name": "models.Sportscar", "line_number": 19, "usage_type": "name"}, {"api_name": "django.forms.models.BaseInlineFormSet", "line_number": 25, "usage_type": "name"}, {"api_name": "django.core.exceptions.ValidationError", "line_number": 45, "usage_type": "call"}, {"api_name": "models.MAX_IMAGE_PER_CAR", "line_number": 47, "usage_type": "name"}, {"api_name": "django.core.exceptions.ValidationError", "line_number": 48, "usage_type": "call"}, {"api_name": "models.MAX_IMAGE_PER_CAR", "line_number": 48, "usage_type": "name"}, {"api_name": "models.MAX_VIDEO_PER_CAR", "line_number": 49, "usage_type": "name"}, {"api_name": "django.core.exceptions.ValidationError", "line_number": 50, "usage_type": "call"}, {"api_name": "models.MAX_VIDEO_PER_CAR", "line_number": 50, "usage_type": "name"}, {"api_name": "models.MAX_AUDIO_PER_CAR", "line_number": 51, "usage_type": "name"}, {"api_name": "django.core.exceptions.ValidationError", "line_number": 52, "usage_type": "call"}, {"api_name": "models.MAX_AUDIO_PER_CAR", "line_number": 52, "usage_type": "name"}, {"api_name": "bs4.BeautifulSoup", "line_number": 60, "usage_type": "call"}, {"api_name": "django.contrib.admin.TabularInline", "line_number": 72, "usage_type": "attribute"}, {"api_name": "django.contrib.admin", "line_number": 72, "usage_type": "name"}, {"api_name": "models.CarMediaItem", "line_number": 74, "usage_type": "name"}, {"api_name": "django.contrib.admin.ModelAdmin", "line_number": 81, "usage_type": "attribute"}, {"api_name": "django.contrib.admin", "line_number": 81, "usage_type": "name"}, {"api_name": "django.contrib.admin.register", "line_number": 80, "usage_type": "call"}, {"api_name": "models.Sportscar", "line_number": 80, "usage_type": "argument"}, {"api_name": "django.contrib.admin.StackedInline", "line_number": 89, "usage_type": "attribute"}, {"api_name": "django.contrib.admin", "line_number": 89, "usage_type": "name"}, {"api_name": "models.SportCarOwnership", "line_number": 91, "usage_type": "name"}, {"api_name": "django.contrib.admin.ModelAdmin", "line_number": 95, "usage_type": "attribute"}, {"api_name": "django.contrib.admin", "line_number": 95, "usage_type": "name"}, {"api_name": "models.SportCarIdentificationRequestRecord.objects.get", "line_number": 123, "usage_type": "call"}, {"api_name": "models.SportCarIdentificationRequestRecord.objects", "line_number": 123, "usage_type": "attribute"}, {"api_name": "models.SportCarIdentificationRequestRecord", "line_number": 123, "usage_type": "name"}, {"api_name": "django.utils.timezone.now", "line_number": 127, "usage_type": "call"}, {"api_name": "django.utils.timezone", "line_number": 127, "usage_type": "name"}, {"api_name": "Notification.signal.send_notification.send", "line_number": 133, "usage_type": "call"}, {"api_name": "Notification.signal.send_notification", "line_number": 133, "usage_type": "name"}, {"api_name": "models.SportCarIdentificationRequestRecord", "line_number": 134, "usage_type": "name"}, {"api_name": "django.contrib.admin.register", "line_number": 94, "usage_type": "call"}, {"api_name": "models.SportCarIdentificationRequestRecord", "line_number": 94, "usage_type": "argument"}, {"api_name": "django.contrib.admin.ModelAdmin", "line_number": 147, "usage_type": "attribute"}, {"api_name": "django.contrib.admin", "line_number": 147, "usage_type": "name"}, {"api_name": "django.contrib.admin.register", "line_number": 146, "usage_type": "call"}, {"api_name": "models.Manufacturer", "line_number": 146, "usage_type": "argument"}]} +{"seq_id": "6742256658", "text": "from logging import fatal\nfrom os import name\nfrom django.shortcuts import render\nfrom django.http import JsonResponse, response\nfrom InkItUp.models import *\nfrom django.views.decorators.csrf import csrf_exempt\nimport json\n\n# Create your views here.\n\n\n#____________Get appointments____________\n\ndef getAllappointments(request):\n if request.method == 'GET':\n try:\n appointments = Appointment.nodes.all()\n response = []\n for appointment in appointments :\n obj = {\n \"idappointment\": appointment.idappointment,\n \"date\": appointment.date,\n \"time\": appointment.time,\n \"sessionlenght\": appointment.sessionlenght,\n }\n response.append(obj)\n return JsonResponse(response, safe=False)\n except:\n response = {\"error\": \"Error Occurred\"}\n return JsonResponse(response, safe=False)\n\n#____CRUD appointment____\n@csrf_exempt\ndef appointmentDetails(request, appointmentid):\n#____Get appointment by ID____\n if request.method == 'GET':\n #name = request.GET.get('name', ' ')\n try:\n appointment = Appointment.nodes.get(appointmentid=appointmentid)\n response = {\n \"idappointment\": appointment.idappointment,\n \"date\": appointment.date,\n \"time\": appointment.time,\n \"sessionlenght\": appointment.sessionlenght,\n }\n return JsonResponse(response, safe=False)\n except :\n response = {\"error\": \"Error Occurred\"}\n return JsonResponse(response, safe=False)\n\n#____ Create one appointment ____\n if request.method == 'POST':\n json_data = json.loads(request.body)\n idappointment = json_data ['idappointment']\n date = json_data['date']\n time = json_data['time']\n sessionlenght = int(json_data['sessionlenght'])\n try:\n appointment = Appointment(idappointment=idappointment, date=date, time=time, sessionlenght=sessionlenght)\n appointment.save()\n response = {\n \"cpr\": appointment.cpr,\n }\n return JsonResponse(response)\n except :\n response = {\"error\": \"Error Occurred\"}\n return JsonResponse(response, safe=False)\n#____Update one appointment_____\n if request.method == 'PUT':\n json_data = json.loads(request.body)\n idappointment = json_data ['idappointment']\n date = json_data['date']\n time = json_data['time']\n sessionlenght = int(json_data['sessionlenght'])\n \n #TVIVL HER\n #uid = json_data['uid']\n try:\n appointment = Appointment.nodes.get(idappointment=idappointment)\n appointment.date\n appointment.time\n appointment.sessionlenght\n appointment.save()\n response = {\n \"idappointment\": appointment.idappointment,\n \"date\": appointment.date,\n \"time\": appointment.time,\n \"sessionlenght\": appointment.sessionlenght,\n }\n return JsonResponse(response, safe=False)\n except:\n response = {\"error\": \"Error occurred\"}\n return JsonResponse(response, safe=False)\n\n#____Delete appointment_____\n if request.method == 'DELETE':\n json_data = json.loads(request.body)\n idappointment = json_data['idappointment']\n try: \n appointment = Appointment.nodes.get(idappointment=idappointment)\n appointment.delete()\n response = {\"success\": \"appointment Deleted\"}\n return JsonResponse(response, safe=False)\n except:\n response = {\"error\": \"Error occurred\"}\n return JsonResponse(response, safe=False)", "repo_name": "Holmern/Django_Neo4j", "sub_path": "Django_Neo4j/InkItUp/views/appointment.py", "file_name": "appointment.py", "file_ext": "py", "file_size_in_byte": 3879, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "django.http.response", "line_number": 18, "usage_type": "name"}, {"api_name": "django.http.response.append", "line_number": 26, "usage_type": "call"}, {"api_name": "django.http.response", "line_number": 26, "usage_type": "name"}, {"api_name": "django.http.JsonResponse", "line_number": 27, "usage_type": "call"}, {"api_name": "django.http.response", "line_number": 27, "usage_type": "argument"}, {"api_name": "django.http.response", "line_number": 29, "usage_type": "name"}, {"api_name": "django.http.JsonResponse", "line_number": 30, "usage_type": "call"}, {"api_name": "django.http.response", "line_number": 30, "usage_type": "argument"}, {"api_name": "django.http.response", "line_number": 40, "usage_type": "name"}, {"api_name": "django.http.JsonResponse", "line_number": 46, "usage_type": "call"}, {"api_name": "django.http.response", "line_number": 46, "usage_type": "argument"}, {"api_name": "django.http.response", "line_number": 48, "usage_type": "name"}, {"api_name": "django.http.JsonResponse", "line_number": 49, "usage_type": "call"}, {"api_name": "django.http.response", "line_number": 49, "usage_type": "argument"}, {"api_name": "json.loads", "line_number": 53, "usage_type": "call"}, {"api_name": "django.http.response", "line_number": 61, "usage_type": "name"}, {"api_name": "django.http.JsonResponse", "line_number": 64, "usage_type": "call"}, {"api_name": "django.http.response", "line_number": 64, "usage_type": "argument"}, {"api_name": "django.http.response", "line_number": 66, "usage_type": "name"}, {"api_name": "django.http.JsonResponse", "line_number": 67, "usage_type": "call"}, {"api_name": "django.http.response", "line_number": 67, "usage_type": "argument"}, {"api_name": "json.loads", "line_number": 70, "usage_type": "call"}, {"api_name": "django.http.response", "line_number": 84, "usage_type": "name"}, {"api_name": "django.http.JsonResponse", "line_number": 90, "usage_type": "call"}, {"api_name": "django.http.response", "line_number": 90, "usage_type": "argument"}, {"api_name": "django.http.response", "line_number": 92, "usage_type": "name"}, {"api_name": "django.http.JsonResponse", "line_number": 93, "usage_type": "call"}, {"api_name": "django.http.response", "line_number": 93, "usage_type": "argument"}, {"api_name": "json.loads", "line_number": 97, "usage_type": "call"}, {"api_name": "django.http.response", "line_number": 102, "usage_type": "name"}, {"api_name": "django.http.JsonResponse", "line_number": 103, "usage_type": "call"}, {"api_name": "django.http.response", "line_number": 103, "usage_type": "argument"}, {"api_name": "django.http.response", "line_number": 105, "usage_type": "name"}, {"api_name": "django.http.JsonResponse", "line_number": 106, "usage_type": "call"}, {"api_name": "django.http.response", "line_number": 106, "usage_type": "argument"}, {"api_name": "django.views.decorators.csrf.csrf_exempt", "line_number": 33, "usage_type": "name"}]} +{"seq_id": "12699331770", "text": "import pandas as pd\nimport numpy as np\nimport glob\nfrom utils import read_chirps, StatisticalTest\nimport os\n\ndef formatdf(df):\n\n dfa = df.loc[df.iloc[:, 0] == \"From Date\"]\n df = df.iloc[dfa.index[0] :, :]\n df, df.columns = df[1:], df.iloc[0]\n df = df.drop(\"To Date\", axis=1)\n dfc = df.loc[dfa.index[1] :].copy()\n dfc, dfc.columns = dfc[1:], dfc.iloc[0]\n dfc = dfc.dropna(axis=1, how=\"all\")\n dfd = df.loc[df.iloc[:, 0].isnull() == True].index[0]\n dfe = df.loc[: dfd - 1]\n dff = dfe.merge(dfc, on=\"From Date\", how=\"outer\")\n dff[\"_index\"] = pd.to_datetime(dff[\"From Date\"], format=\"%d-%m-%Y %H:%M\")\n dff = dff.replace({\"None\": np.nan})\n dff = dff.dropna(axis =1, how=\"all\")\n dff = dff.drop(\"From Date\", axis=1)\n return dff\n\n\natm = {\n \"PM2.5\": [30, 60, 90, 120, 250],\n \"PM10\": [50, 100, 250, 350, 430],\n \"NO2\": [40, 80, 180, 280, 400],\n \"NH3\": [200, 400, 800, 1200, 1800],\n \"NOx\": [40, 80, 180, 280, 400],\n \"Ozone\": [50, 100, 168, 208, 748],\n \"CO\": [1, 2, 10, 17, 34],\n \"SO2\": [40, 80, 380, 800, 1600],\n}\n\n\ndef roundoff(func):\n def wrapper(*args, **kwargs):\n return np.rint(func(*args, **kwargs))\n\n return wrapper\n\n\n@roundoff\ndef sub_index(a, b):\n if a <= b[0]:\n return a * 50 / b[0]\n elif a > b[0] and a <= b[1]:\n return 50 + (a - b[0]) * 50 / (b[1] - b[0])\n elif a > b[1] and a <= b[2]:\n return 100 + (a - b[1]) * 100 / (b[2] - b[1])\n elif a > b[2] and a <= b[3]:\n return 200 + (a - b[2]) * 100 / (b[3] - b[2])\n elif a > b[3] and a <= b[4]:\n return 300 + (a - b[3]) * 100 / (b[4] - b[3])\n elif a > b[4]:\n return 400 + (a - b[4]) * 100 / (b[4] - b[3])\n else:\n return np.nan\n\n\ndef aqi(row, column_list):\n mylist = [sub_index(row[i], atm[i]) for i in column_list if i != \"NO\"]\n return max(mylist)\n\n\nif __name__=='__main__':\n\n dirname = os.path.dirname(os.path.abspath(__file__))\n os.chdir(dirname)\n \n # read ground aqi data\n path_assets = os.path.join(os.pardir, 'assets', 'grd_aqi')\n sigLevel = 0.01\n # air quality ground station\n c_df = [formatdf(pd.read_excel(i)) for i in glob.glob(os.path.join(path_assets, \"*.xlsx\"))]\n df_aqi = pd.concat(c_df).set_index(\"_index\")\n column_list = df_aqi.columns\n df_aqi[\"AQI\"] = df_aqi.apply(lambda row: aqi(row, column_list), axis=1)\n df_aqi.index.name = None\n df_aqi[\"mm-dd\"] = df_aqi.index.strftime(\"%m-%d\")\n\n # read rainfall\n df_rainfall = read_chirps()\n\n # Join rainfall and ground station air quality data\n df_anlys = df_rainfall.join(df_aqi, how=\"inner\")\n df_anlys.loc[:,\"precip_past\"] = df_anlys[\"precip\"].shift(1)\n df_anlys = df_anlys.loc[(df_anlys.precip < 5) & (df_anlys.precip_past < 5)]\n\n # add unique id for statistical analysis\n for year in [2019, 2020, 2021]:\n df_anlys.loc[f\"{year}-03-24\":f\"{year}-05-30\", \"year_class\"] = str(year)\n\n\n for param in [\"AQI\"]:\n print(f\"statistical analyis for param: {param}\")\n myobj = StatisticalTest(param, sigLevel)\n myobj.tukey_test(df_anlys)\n ", "repo_name": "amanbagrecha/covid-19-analysis", "sub_path": "src/sts_grd_aqi.py", "file_name": "sts_grd_aqi.py", "file_ext": "py", "file_size_in_byte": 3087, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "pandas.to_datetime", "line_number": 19, "usage_type": "call"}, {"api_name": "numpy.nan", "line_number": 20, "usage_type": "attribute"}, {"api_name": "numpy.rint", "line_number": 40, "usage_type": "call"}, {"api_name": "numpy.nan", "line_number": 60, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 70, "usage_type": "call"}, {"api_name": "os.path", "line_number": 70, "usage_type": "attribute"}, {"api_name": "os.path.abspath", "line_number": 70, "usage_type": "call"}, {"api_name": "os.chdir", "line_number": 71, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 74, "usage_type": "call"}, {"api_name": "os.path", "line_number": 74, "usage_type": "attribute"}, {"api_name": "os.pardir", "line_number": 74, "usage_type": "attribute"}, {"api_name": "pandas.read_excel", "line_number": 77, "usage_type": "call"}, {"api_name": "glob.glob", "line_number": 77, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 77, "usage_type": "call"}, {"api_name": "os.path", "line_number": 77, "usage_type": "attribute"}, {"api_name": "pandas.concat", "line_number": 78, "usage_type": "call"}, {"api_name": "utils.read_chirps", "line_number": 85, "usage_type": "call"}, {"api_name": "utils.StatisticalTest", "line_number": 99, "usage_type": "call"}]} +{"seq_id": "6159444038", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('curriculum', '0003_auto_20151002_1013'),\n ('documents', '0005_auto_20151013_1550'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='document',\n name='lessons',\n field=models.ManyToManyField(blank=True, to='curriculum.Lesson', verbose_name='Lesson PDFs (new tab)'),\n ),\n migrations.AlterField(\n model_name='document',\n name='initial_x',\n field=models.IntegerField(blank=True, null=True, verbose_name='Default (blank) is 0 (centered)'),\n ),\n migrations.AlterField(\n model_name='document',\n name='initial_y',\n field=models.IntegerField(blank=True, null=True, verbose_name='Default (blank) is 0 (centered)'),\n ),\n migrations.AlterField(\n model_name='document',\n name='initial_zoom',\n field=models.IntegerField(blank=True, null=True, verbose_name='Default (blank) is 50 (%)'),\n ),\n migrations.AlterField(\n model_name='document',\n name='narrative',\n field=models.TextField(blank=True, verbose_name='About this...', default=''),\n ),\n ]\n", "repo_name": "DigitalGizmo/mse21", "sub_path": "mse/documents/migrations/0006_auto_20151023_0931.py", "file_name": "0006_auto_20151023_0931.py", "file_ext": "py", "file_size_in_byte": 1366, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "django.db.migrations.Migration", "line_number": 7, "usage_type": "attribute"}, {"api_name": "django.db.migrations", "line_number": 7, "usage_type": "name"}, {"api_name": "django.db.migrations.AddField", "line_number": 15, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 15, "usage_type": "name"}, {"api_name": "django.db.models.ManyToManyField", "line_number": 18, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 18, "usage_type": "name"}, {"api_name": "django.db.migrations.AlterField", "line_number": 20, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 20, "usage_type": "name"}, {"api_name": "django.db.models.IntegerField", "line_number": 23, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 23, "usage_type": "name"}, {"api_name": "django.db.migrations.AlterField", "line_number": 25, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 25, "usage_type": "name"}, {"api_name": "django.db.models.IntegerField", "line_number": 28, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 28, "usage_type": "name"}, {"api_name": "django.db.migrations.AlterField", "line_number": 30, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 30, "usage_type": "name"}, {"api_name": "django.db.models.IntegerField", "line_number": 33, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 33, "usage_type": "name"}, {"api_name": "django.db.migrations.AlterField", "line_number": 35, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 35, "usage_type": "name"}, {"api_name": "django.db.models.TextField", "line_number": 38, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 38, "usage_type": "name"}]} +{"seq_id": "13353779011", "text": "from TTS.api import TTS\nfrom core.temp_manager import TempFileManager\nfrom core.mapper import map\nimport torch\n\n\nclass VoiceCloner:\n def __init__(self, lang):\n self.lang_code = map(lang)\n self.tts = TTS(\"tts_models/multilingual/multi-dataset/xtts_v2\", gpu=torch.cuda.is_available())\n\n def process(self, speaker_wav_filename, text, speed=1.0, out_filename=None):\n temp_manager = TempFileManager()\n if not out_filename:\n out_filename = temp_manager.create_temp_file(suffix='.wav').name\n self.tts.tts_to_file(\n text=text, \n speaker_wav=speaker_wav_filename, \n language=self.lang_code, \n file_path=out_filename,\n speed=speed\n )\n return out_filename\n", "repo_name": "BrasD99/HeyGenClone", "sub_path": "core/voice_cloner.py", "file_name": "voice_cloner.py", "file_ext": "py", "file_size_in_byte": 766, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 371, "dataset": "github-code", "pt": "21", "api": [{"api_name": "core.mapper.map", "line_number": 9, "usage_type": "call"}, {"api_name": "TTS.api.TTS", "line_number": 10, "usage_type": "call"}, {"api_name": "torch.cuda.is_available", "line_number": 10, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 10, "usage_type": "attribute"}, {"api_name": "core.temp_manager.TempFileManager", "line_number": 13, "usage_type": "call"}]} +{"seq_id": "16021140142", "text": "from datetime import datetime, timedelta\nfrom airflow import DAG\nfrom airflow.operators.dummy_operator import DummyOperator\nfrom airflow.operators.postgres_operator import PostgresOperator\nfrom airflow.operators import StageToRedshiftOperator\nfrom airflow.operators import LoadFactOperator\nfrom airflow.operators import LoadDimensionOperator\nfrom airflow.operators import DataQualityOperator \nfrom helpers import SqlQueries\nfrom airflow.operators.bash_operator import BashOperator\n\n\ndefault_args = {\n 'owner': 'ronnald',\n 'start_date': datetime.utcnow(),\n 'depends_on_past': False,\n 'email_on_retry': False,\n 'retries': 3,\n 'retry_delay': timedelta(minutes=5),\n 'catchup' : False\n}\n\ndag = DAG('capstone',\n default_args=default_args,\n description='Load and transform data in Redshift with Airflow',\n schedule_interval='@monthly')\n\nstart_operator = DummyOperator(task_id='Begin_execution', dag=dag)\n\nstage_capstone_events = StageToRedshiftOperator(\n task_id='staging_capstone_events',\n dag=dag,\n redshift_conn_id='redshift',\n aws_credentials_id=\"aws_credentials\",\n table=\"staging_capstone_events\",\n s3_source=\"s3://rrm86capstone/input/events/\",\n json_paths=\"auto\",\n file_type=\"CSV\"\n)\n\nstage_capstone_states = StageToRedshiftOperator(\n task_id='staging_capstone_states',\n dag=dag,\n redshift_conn_id=\"redshift\",\n aws_credentials_id=\"aws_credentials\",\n table=\"staging_capstone_states\",\n s3_source=\"s3://rrm86capstone/input/states/states2.json\",\n json_paths=\"auto\",\n file_type=\"JSON\"\n)\n\nstage_capstone_region = StageToRedshiftOperator(\n task_id='staging_capstone_region',\n dag=dag,\n redshift_conn_id=\"redshift\",\n aws_credentials_id=\"aws_credentials\",\n table=\"staging_capstone_region\",\n s3_source=\"s3://rrm86capstone/input/region/region.json\",\n json_paths=\"auto\",\n file_type=\"JSON\"\n)\n\nload_event_table = LoadFactOperator(\n task_id='load_event_table',\n dag=dag,\n redshift_conn_id=\"redshift\",\n table=\"capstone_events\",\n query=SqlQueries.event_table_insert\n)\n\nload_states_table = LoadDimensionOperator(\n task_id='load_states_table',\n dag=dag,\n redshift_conn_id='redshift',\n table='capstone_states',\n query=SqlQueries.states_table_insert,\n mode='delete-load'\n)\n\nload_region_table = LoadDimensionOperator(\n task_id='load_region_table',\n dag=dag,\n redshift_conn_id='redshift',\n table='capstone_region',\n query=SqlQueries.region_table_insert,\n mode='delete-load'\n)\n\nload_time_table = LoadDimensionOperator(\n task_id='load_time_table',\n dag=dag,\n redshift_conn_id='redshift',\n table='capstone_time',\n query=SqlQueries.time_table_insert,\n mode='delete-load'\n)\n\n\nrun_quality_checks = DataQualityOperator(\n task_id='Run_data_quality_checks',\n dag=dag,\n redshift_conn_id=\"redshift\",\n data_quality = [{\"table\":\"capstone_events\", \"field\":None,\"result\":0, \"type\":\"count\"},\n {\"table\":\"capstone_region\", \"field\":\"region\",\"result\":0, \"type\":\"count-where\"},\n {\"table\":\"capstone_states\", \"field\":\"state\",\"result\":0, \"type\":\"count-where\"}]\n)\n\n\nend_operator = DummyOperator(task_id='Stop_execution', dag=dag)\n\n\nstart_operator >> stage_capstone_events \nstart_operator >> stage_capstone_states\nstart_operator >> stage_capstone_region\nstage_capstone_events >> load_event_table\nstage_capstone_states >> load_event_table\nstage_capstone_region >> load_event_table\nload_event_table >> load_states_table\nload_event_table >> load_region_table\nload_event_table >> load_time_table\nload_states_table >> run_quality_checks\nload_region_table >> run_quality_checks\nload_time_table >> run_quality_checks\nrun_quality_checks >> end_operator\n", "repo_name": "rrm86/capstone_DENG", "sub_path": "airflow/dags/udac_capstone.py", "file_name": "udac_capstone.py", "file_ext": "py", "file_size_in_byte": 3734, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "datetime.datetime.utcnow", "line_number": 15, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 15, "usage_type": "name"}, {"api_name": "datetime.timedelta", "line_number": 19, "usage_type": "call"}, {"api_name": "airflow.DAG", "line_number": 23, "usage_type": "call"}, {"api_name": "airflow.operators.dummy_operator.DummyOperator", "line_number": 28, "usage_type": "call"}, {"api_name": "airflow.operators.StageToRedshiftOperator", "line_number": 30, "usage_type": "call"}, {"api_name": "airflow.operators.StageToRedshiftOperator", "line_number": 41, "usage_type": "call"}, {"api_name": "airflow.operators.StageToRedshiftOperator", "line_number": 52, "usage_type": "call"}, {"api_name": "airflow.operators.LoadFactOperator", "line_number": 63, "usage_type": "call"}, {"api_name": "helpers.SqlQueries.event_table_insert", "line_number": 68, "usage_type": "attribute"}, {"api_name": "helpers.SqlQueries", "line_number": 68, "usage_type": "name"}, {"api_name": "airflow.operators.LoadDimensionOperator", "line_number": 71, "usage_type": "call"}, {"api_name": "helpers.SqlQueries.states_table_insert", "line_number": 76, "usage_type": "attribute"}, {"api_name": "helpers.SqlQueries", "line_number": 76, "usage_type": "name"}, {"api_name": "airflow.operators.LoadDimensionOperator", "line_number": 80, "usage_type": "call"}, {"api_name": "helpers.SqlQueries.region_table_insert", "line_number": 85, "usage_type": "attribute"}, {"api_name": "helpers.SqlQueries", "line_number": 85, "usage_type": "name"}, {"api_name": "airflow.operators.LoadDimensionOperator", "line_number": 89, "usage_type": "call"}, {"api_name": "helpers.SqlQueries.time_table_insert", "line_number": 94, "usage_type": "attribute"}, {"api_name": "helpers.SqlQueries", "line_number": 94, "usage_type": "name"}, {"api_name": "airflow.operators.DataQualityOperator", "line_number": 99, "usage_type": "call"}, {"api_name": "airflow.operators.dummy_operator.DummyOperator", "line_number": 109, "usage_type": "call"}]} +{"seq_id": "22981337600", "text": "'''A collection of functions to plot the data'''\n\nimport matplotlib.pyplot as plt\n\nfrom tools import m2nm, nm2m, ms2kts, rad2deg\n\ndef plot_histogram(data,title,xlabel,nbins,ylim=10,range=None):\n\n if not range:\n range = (data.min(),data.max())\n\n plt.figure()\n (n,bins,patches) = plt.hist(data,\n bins=nbins,\n range=range,\n rwidth=0.7)\n\n plt.ylim([0,ylim])\n plt.xticks(bins)\n plt.grid()\n plt.title(title)\n plt.xlabel(xlabel)\n\ndef plot_path_deviation(path_deviation):\n\n max_path_deviation = [ m2nm(deviation.max()) for deviation in path_deviation]\n\n max_path_deviation = [ deviation for deviation in max_path_deviation if deviation>0.01]\n\n if max_path_deviation:\n plot_histogram(max_path_deviation,\n title = 'Path deviation',\n xlabel = 'Path deviation [NM]',\n nbins = 20,\n range = (0,20.0))\n\ndef plot_largest_cmd_change(cmd_change):\n \n spd_changes = [ms2kts(spd) for (spd,hdg) in cmd_change if spd>0.01]\n hdg_changes = [rad2deg(hdg) for (spd,hdg) in cmd_change if hdg>0.01]\n\n if spd_changes:\n plot_histogram(spd_changes,\n title = 'Largest speed change commands',\n xlabel = 'Speed change command [kts]',\n nbins = 10,\n range = (0,100.0) )\n\n if hdg_changes:\n plot_histogram(hdg_changes,\n title = 'Largest heading change commands',\n xlabel = 'Heading change command [deg]',\n nbins = 18,\n range = (0,180.0) )\n\ndef plot_largest_cmd_state_change(state_change):\n\n state_change = [ms2kts(state) for state in state_change if state>0.01]\n\n if state_change:\n plot_histogram(state_change,\n title = 'Largest state change commands',\n xlabel = 'State change command [kts]',\n nbins = 15,\n range = (0,300.0) )\n \n\ndef plot_los(los_data):\n '''Make a histogram of the LOS data'''\n \n los_cpas = [ m2nm(pair['cpa']) for pair in los_data ]\n\n if los_cpas:\n plot_histogram(los_cpas,\n title = 'Number of LOS',\n xlabel = 'CPA Distance [NM]',\n nbins = 5,\n range=(0.0,5.0))\n\n \n\ndef plot_los_time(los_data):\n '''Make a histogram of the LOS times'''\n\n los_time = [ pair['time'][-1] - pair['time'][0] for pair in los_data ]\n\n if los_time:\n plot_histogram(los_time,\n title = 'Time in LOS',\n xlabel = 'Time [s]',\n nbins = 10,\n range=(0.0, 200.0))\n\n\ndef plot_conflicts(conflict_data):\n '''Make a histogram of the conflict data'''\n \n conflict_cpas = [ m2nm(pair['cpa']) for pair in conflict_data ]\n\n if conflict_cpas:\n plot_histogram(conflict_cpas,\n title = 'Number of conflicts',\n xlabel = 'CPA Distance [NM]',\n nbins = 5,\n range=(0.0,5.0))\n \n\ndef plot_conflicts_time(conflict_data):\n '''Make a histogram of the LOS times'''\n\n conflicts_time = [ pair['time'][-1] - pair['time'][0] for pair in conflict_data ]\n\n if conflicts_time:\n plot_histogram(conflicts_time,\n title = 'Time in conflict',\n xlabel = 'Time [s]',\n nbins = 15,\n range = (0.0,300.0))\n\n \ndef show():\n '''Show all plots'''\n plt.show()\n", "repo_name": "tegginamaniss/BSpostprocessing", "sub_path": "plot_functions.py", "file_name": "plot_functions.py", "file_ext": "py", "file_size_in_byte": 3761, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "matplotlib.pyplot.figure", "line_number": 12, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 12, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.hist", "line_number": 13, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 13, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylim", "line_number": 18, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 18, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xticks", "line_number": 19, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 19, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.grid", "line_number": 20, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 20, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 21, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 21, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 22, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 22, "usage_type": "name"}, {"api_name": "tools.m2nm", "line_number": 26, "usage_type": "call"}, {"api_name": "tools.ms2kts", "line_number": 39, "usage_type": "call"}, {"api_name": "tools.rad2deg", "line_number": 40, "usage_type": "call"}, {"api_name": "tools.ms2kts", "line_number": 58, "usage_type": "call"}, {"api_name": "tools.m2nm", "line_number": 71, "usage_type": "call"}, {"api_name": "tools.m2nm", "line_number": 98, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.show", "line_number": 123, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 123, "usage_type": "name"}]} +{"seq_id": "1325613479", "text": "import os\nimport uuid\nimport torch\nimport librosa\nimport subprocess\nimport soundfile as sf\nfrom openunmix import predict\n\n\nclass AudioSeparator:\n @staticmethod\n def _convert_to_wav(audio_path, output_path):\n wav_audio_path = os.path.join(output_path, str(uuid.uuid4()) + \".wav\")\n cmd = f\"ffmpeg -i {audio_path} {wav_audio_path}\"\n if os.environ.get('DEBUG', 'False') == 'True':\n # not silence run\n os.system(cmd)\n else:\n # silence run\n subprocess.run(cmd, shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)\n return wav_audio_path\n\n def separate_audio(self, wav_audio_path, output_path, converted_wav=False, target_wav=\"vocals\", device=\"cpu\",\n resample=True, compare_result=True):\n # target_wav is \"vocals\" or \"residual\"\n # Convert to WAV\n wav_audio_path = self._convert_to_wav(wav_audio_path, output_path) if converted_wav else wav_audio_path\n\n # Load the converted WAV file\n audio, rate = sf.read(wav_audio_path)\n audio_tensor = torch.tensor(audio).float()\n\n # Separate sources using Open-Unmix\n estimates = predict.separate(\n audio_tensor,\n rate=rate,\n targets=[target_wav if target_wav != \"residual\" else \"vocals\"], # I set this condition if I will add radios for target_wav as bass or dump\n residual=True,\n device=device,\n )\n\n wav_name = str(uuid.uuid4())\n\n # Save separated sources\n for target, estimate in estimates.items():\n output_audio = estimate.detach().cpu().numpy().squeeze().T\n output_filename = os.path.join(output_path, f\"{wav_name}_{target}.wav\")\n if target_wav == target:\n if resample:\n # Resample to 16 kHz\n output_audio = librosa.resample(output_audio.T, orig_sr=rate, target_sr=16000)\n # Save file\n sf.write(output_filename, output_audio.T, 16000)\n else:\n sf.write(output_filename, output_audio, rate)\n print(f\"Saved: {output_filename}\")\n break\n\n if compare_result:\n duration_more = self.compare_audio_duration(wav_audio_path, os.path.join(output_path, f\"{wav_name}_{target_wav}.wav\"))\n if duration_more:\n return wav_audio_path\n else:\n return os.path.join(output_path, f\"{wav_name}_{target_wav}.wav\")\n\n return os.path.join(output_path, f\"{wav_name}_{target_wav}.wav\")\n\n @staticmethod\n def compare_audio_duration(original_audio_path, separated_audio_path):\n # Load the audios and get their durations\n y_original, sr_original = librosa.load(original_audio_path, sr=None)\n y_separated, sr_separated = librosa.load(separated_audio_path, sr=None)\n\n duration_original = librosa.get_duration(y=y_original, sr=sr_original)\n duration_separated = librosa.get_duration(y=y_separated, sr=sr_separated)\n\n # Compare durations\n if duration_separated > duration_original * 1.05: # more than 5% from original\n print(\n f\"Separated audio ({duration_separated:.2f} seconds) is longer than the original ({duration_original:.2f} seconds).\")\n return True\n else:\n print(\n f\"Separated audio ({duration_separated:.2f} seconds) is shorter or equal to the original ({duration_original:.2f} seconds).\")\n return False\n\n @staticmethod\n def trim_silence(audio_path, output_path):\n y, sr = librosa.load(audio_path, sr=None)\n\n # Trim the silence from the start and end\n # `top_db` is the threshold in dB below which audio is considered silent\n y_trimmed, index = librosa.effects.trim(y, top_db=60)\n\n # Save the trimmed audio\n output_file = os.path.join(output_path, str(uuid.uuid4()) + \".wav\")\n sf.write(output_file, y_trimmed, sr)\n return output_file", "repo_name": "wladradchenko/wunjo.wladradchenko.ru", "sub_path": "portable/src/speech/unmix/utils/model.py", "file_name": "model.py", "file_ext": "py", "file_size_in_byte": 4066, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 404, "dataset": "github-code", "pt": "21", "api": [{"api_name": "os.path.join", "line_number": 13, "usage_type": "call"}, {"api_name": "os.path", "line_number": 13, "usage_type": "attribute"}, {"api_name": "uuid.uuid4", "line_number": 13, "usage_type": "call"}, {"api_name": "os.environ.get", "line_number": 15, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 15, "usage_type": "attribute"}, {"api_name": "os.system", "line_number": 17, "usage_type": "call"}, {"api_name": "subprocess.run", "line_number": 20, "usage_type": "call"}, {"api_name": "subprocess.DEVNULL", "line_number": 20, "usage_type": "attribute"}, {"api_name": "soundfile.read", "line_number": 30, "usage_type": "call"}, {"api_name": "torch.tensor", "line_number": 31, "usage_type": "call"}, {"api_name": "openunmix.predict.separate", "line_number": 34, "usage_type": "call"}, {"api_name": "openunmix.predict", "line_number": 34, "usage_type": "name"}, {"api_name": "uuid.uuid4", "line_number": 42, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 47, "usage_type": "call"}, {"api_name": "os.path", "line_number": 47, "usage_type": "attribute"}, {"api_name": "librosa.resample", "line_number": 51, "usage_type": "call"}, {"api_name": "soundfile.write", "line_number": 53, "usage_type": "call"}, {"api_name": "soundfile.write", "line_number": 55, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 60, "usage_type": "call"}, {"api_name": "os.path", "line_number": 60, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 64, "usage_type": "call"}, {"api_name": "os.path", "line_number": 64, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 66, "usage_type": "call"}, {"api_name": "os.path", "line_number": 66, "usage_type": "attribute"}, {"api_name": "librosa.load", "line_number": 71, "usage_type": "call"}, {"api_name": "librosa.load", "line_number": 72, "usage_type": "call"}, {"api_name": "librosa.get_duration", "line_number": 74, "usage_type": "call"}, {"api_name": "librosa.get_duration", "line_number": 75, "usage_type": "call"}, {"api_name": "librosa.load", "line_number": 89, "usage_type": "call"}, {"api_name": "librosa.effects.trim", "line_number": 93, "usage_type": "call"}, {"api_name": "librosa.effects", "line_number": 93, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 96, "usage_type": "call"}, {"api_name": "os.path", "line_number": 96, "usage_type": "attribute"}, {"api_name": "uuid.uuid4", "line_number": 96, "usage_type": "call"}, {"api_name": "soundfile.write", "line_number": 97, "usage_type": "call"}]} +{"seq_id": "27948043317", "text": "import tensorflow.keras as k\nfrom tensorflow.keras import metrics\nimport numpy as np\nimport datetime\nimport random\nimport os\nimport pandas as pd\nimport json\n\nfrom NeuralNet.default_params import params\nfrom system.system import System\nfrom gcloud.gcloud import GCloud\nfrom sklearn.model_selection import train_test_split\n\nclass NeuralNet:\n def __init__(self, csv, out_dir, param_file = None):\n self.out_dir = out_dir\n self.csv = csv\n self.params = self.read_params(param_file)\n\n def read_params(self, param_file):\n if param_file is None:\n p = params\n else:\n with open(param_file) as f:\n p = json.load(f)\n return p\n\n def train(self):\n df = pd.read_csv(self.csv, skiprows=1)\n train, test = train_test_split(df, test_size=0.2)\n train_x = train.iloc[:, 0:-1]\n train_y = train.iloc[:, -1:]\n test_x = test.iloc[:, 0:-1]\n test_y = test.iloc[:, -1:]\n self.train_model(np.array(train_x), np.array(train_y), np.array(test_x), np.array(test_y))\n\n def train_model(self, train_x, train_y, test_x, test_y):\n # Create neural network architecture\n model = k.Sequential()\n\n input_layer = k.layers.Dense(len(train_x), input_dim=len(train_x[0]),\n activation=self.params['INPUT_LAYER']['ACTIVATION'])\n model.add(input_layer)\n\n for hidden_layer_data in self.params['HIDDEN_LAYERS']:\n hidden_layer = k.layers.Dense(hidden_layer_data['NUM_NODES'],\n activation=hidden_layer_data['ACTIVATION'])\n model.add(hidden_layer)\n\n output_layer = k.layers.Dense(self.params['OUTPUT_LAYER']['NUM_NODES'],\n activation=self.params['OUTPUT_LAYER']['ACTIVATION'])\n model.add(output_layer)\n\n # optimizer - sgd, rmsprop\n model.compile(loss=self.params['LOSS_FUNCTION'], optimizer=self.params['OPTIMIZER'], metrics=[metrics.binary_accuracy])\n model.fit(np.array(train_x), np.array(train_y), validation_split=self.params['VALIDATION_SPLIT'],\n epochs=self.params['EPOCHS'], batch_size=self.params['BATCH_SIZE'])\n\n test_loss_test, test_acc_test = model.evaluate(test_x, test_y)\n\n print('Results: loss {}, accuracy {}, :'.format(test_loss_test, test_acc_test))\n self.test_acc = test_acc_test\n self.model = model\n self.save()\n \n def save(self):\n out_dir = self.out_dir\n date_str = str(datetime.datetime.now().strftime(\"%d-%B-%Y-%I-%M%p\")) + \"-\" + str(self.test_acc)\n package_dir = os.path.join(out_dir, date_str)\n os.makedirs(package_dir)\n \n self.model.save(os.path.join(package_dir, 'model.h5'))\n System.copy_file_to(self.csv, os.path.join(package_dir, 'data.csv'))\n System.write_json_to_file({\n 'test_accuracy': str(self.test_acc),\n }, os.path.join(package_dir, 'accuracy.json'))\n GCloud.upload_directory_to_bucket(package_dir, 'test_bucket_12349876')\n # write_to_json(os.path.join(out_dir, date_str, 'data.csv'), Match.get_features_list())\n # write_to_json(os.path.join(keras_models_directory, date_str, 'params.json'), params)\n # write_to_json(os.path.join(keras_models_directory, date_str, 'accuracy.json'), { 'loss': str(test_loss_test), 'accuracy': str(test_acc_test) })", "repo_name": "augerm/machine-learning-on-cloud-vm", "sub_path": "NeuralNet/NeuralNet.py", "file_name": "NeuralNet.py", "file_ext": "py", "file_size_in_byte": 3503, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "NeuralNet.default_params.params", "line_number": 23, "usage_type": "name"}, {"api_name": "json.load", "line_number": 26, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 30, "usage_type": "call"}, {"api_name": "sklearn.model_selection.train_test_split", "line_number": 31, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 36, "usage_type": "call"}, {"api_name": "tensorflow.keras.Sequential", "line_number": 40, "usage_type": "call"}, {"api_name": "tensorflow.keras", "line_number": 40, "usage_type": "name"}, {"api_name": "tensorflow.keras.layers.Dense", "line_number": 42, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers", "line_number": 42, "usage_type": "attribute"}, {"api_name": "tensorflow.keras", "line_number": 42, "usage_type": "name"}, {"api_name": "tensorflow.keras.layers.Dense", "line_number": 47, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers", "line_number": 47, "usage_type": "attribute"}, {"api_name": "tensorflow.keras", "line_number": 47, "usage_type": "name"}, {"api_name": "tensorflow.keras.layers.Dense", "line_number": 51, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers", "line_number": 51, "usage_type": "attribute"}, {"api_name": "tensorflow.keras", "line_number": 51, "usage_type": "name"}, {"api_name": "tensorflow.keras.metrics.binary_accuracy", "line_number": 56, "usage_type": "attribute"}, {"api_name": "tensorflow.keras.metrics", "line_number": 56, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 57, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 69, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 69, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 70, "usage_type": "call"}, {"api_name": "os.path", "line_number": 70, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 71, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 73, "usage_type": "call"}, {"api_name": "os.path", "line_number": 73, "usage_type": "attribute"}, {"api_name": "system.system.System.copy_file_to", "line_number": 74, "usage_type": "call"}, {"api_name": "system.system.System", "line_number": 74, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 74, "usage_type": "call"}, {"api_name": "os.path", "line_number": 74, "usage_type": "attribute"}, {"api_name": "system.system.System.write_json_to_file", "line_number": 75, "usage_type": "call"}, {"api_name": "system.system.System", "line_number": 75, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 77, "usage_type": "call"}, {"api_name": "os.path", "line_number": 77, "usage_type": "attribute"}, {"api_name": "gcloud.gcloud.GCloud.upload_directory_to_bucket", "line_number": 78, "usage_type": "call"}, {"api_name": "gcloud.gcloud.GCloud", "line_number": 78, "usage_type": "name"}]} +{"seq_id": "4627884553", "text": "import math\nimport tempfile\nimport unittest\nfrom unittest import mock\n\nfrom chainer import testing\n\nimport chainerrl\n\n\n@testing.parameterize(*testing.product({\n 'num_envs': [1, 2],\n 'max_episode_len': [None, 2],\n 'steps': [5, 6],\n}))\nclass TestTrainAgentBatch(unittest.TestCase):\n\n def test(self):\n\n steps = self.steps\n\n outdir = tempfile.mkdtemp()\n\n agent = mock.Mock()\n agent.batch_act_and_train.side_effect = [[1] * self.num_envs] * 1000\n\n def make_env():\n env = mock.Mock()\n env.reset.side_effect = [('state', 0)] * 1000\n if self.max_episode_len is None:\n # Episodic env that terminates after 5 actions\n env.step.side_effect = [\n (('state', 1), 0, False, {}),\n (('state', 2), 0, False, {}),\n (('state', 3), -0.5, False, {}),\n (('state', 4), 0, False, {}),\n (('state', 5), 1, True, {}),\n ] * 1000\n else:\n # Continuing env\n env.step.side_effect = [\n (('state', 1), 0, False, {}),\n ] * 1000\n return env\n\n vec_env = chainerrl.envs.SerialVectorEnv(\n [make_env() for _ in range(self.num_envs)])\n\n hook = mock.Mock()\n\n chainerrl.experiments.train_agent_batch(\n agent=agent,\n env=vec_env,\n steps=steps,\n outdir=outdir,\n max_episode_len=self.max_episode_len,\n step_hooks=[hook],\n )\n\n iters = math.ceil(steps / self.num_envs)\n self.assertEqual(agent.batch_act_and_train.call_count, iters)\n self.assertEqual(agent.batch_observe_and_train.call_count, iters)\n\n for env in vec_env.envs:\n if self.max_episode_len is None:\n if self.num_envs == 1:\n if self.steps == 6:\n # In the beginning and after 5 iterations\n self.assertEqual(env.reset.call_count, 2)\n else:\n assert steps == 5\n # Only in the beginning. While the last state is\n # terminal, env.reset should not be called because\n # training is complete.\n self.assertEqual(env.reset.call_count, 1)\n elif self.num_envs == 2:\n # Only in the beginning\n self.assertEqual(env.reset.call_count, 1)\n else:\n assert False\n elif self.max_episode_len == 2:\n if self.num_envs == 1:\n # In the beginning, after 2 and 4 iterations\n self.assertEqual(env.reset.call_count, 3)\n elif self.num_envs == 2:\n # In the beginning, after 2 iterations\n self.assertEqual(env.reset.call_count, 2)\n else:\n assert False\n self.assertEqual(env.step.call_count, iters)\n\n if steps % self.num_envs == 0:\n self.assertEqual(hook.call_count, steps)\n else:\n self.assertEqual(hook.call_count, self.num_envs * iters)\n\n # A hook receives (env, agent, step)\n for i, call in enumerate(hook.call_args_list):\n args, kwargs = call\n self.assertEqual(args[0], vec_env)\n self.assertEqual(args[1], agent)\n # step starts with 1\n self.assertEqual(args[2], i + 1)\n\n\nclass TestTrainAgentBatchNeedsReset(unittest.TestCase):\n\n def test_needs_reset(self):\n steps = 10\n\n outdir = tempfile.mkdtemp()\n\n agent = mock.Mock()\n agent.batch_act_and_train.side_effect = [[1, 1]] * 5\n\n def make_env(idx):\n env = mock.Mock()\n if idx == 0:\n # First episode: 0 -> 1 -> 2 -> 3 (reset)\n # Second episode: 4 -> 5 -> 6 -> 7 (done)\n env.reset.side_effect = [('state', 0), ('state', 4)]\n env.step.side_effect = [\n (('state', 1), 0, False, {}),\n (('state', 2), 0, False, {}),\n (('state', 3), 0, False, {'needs_reset': True}),\n (('state', 5), -0.5, False, {}),\n (('state', 6), 0, False, {}),\n (('state', 7), 1, True, {}),\n ]\n else:\n # First episode: 0 -> 1 (reset)\n # Second episode: 2 -> 3 (reset)\n # Third episode: 4 -> 5 -> 6 -> 7 (done)\n env.reset.side_effect = [\n ('state', 0), ('state', 2), ('state', 4)]\n env.step.side_effect = [\n (('state', 1), 0, False, {'needs_reset': True}),\n (('state', 3), 0, False, {'needs_reset': True}),\n (('state', 5), -0.5, False, {}),\n (('state', 6), 0, False, {}),\n (('state', 7), 1, True, {}),\n ]\n return env\n\n vec_env = chainerrl.envs.SerialVectorEnv(\n [make_env(i) for i in range(2)])\n\n chainerrl.experiments.train_agent_batch(\n agent=agent,\n env=vec_env,\n steps=steps,\n outdir=outdir,\n )\n\n self.assertEqual(vec_env.envs[0].reset.call_count, 2)\n self.assertEqual(vec_env.envs[0].step.call_count, 5)\n self.assertEqual(vec_env.envs[1].reset.call_count, 3)\n self.assertEqual(vec_env.envs[1].step.call_count, 5)\n", "repo_name": "chainer/chainerrl", "sub_path": "tests/experiments_tests/test_train_agent_batch.py", "file_name": "test_train_agent_batch.py", "file_ext": "py", "file_size_in_byte": 5605, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1134, "dataset": "github-code", "pt": "21", "api": [{"api_name": "unittest.TestCase", "line_number": 16, "usage_type": "attribute"}, {"api_name": "tempfile.mkdtemp", "line_number": 22, "usage_type": "call"}, {"api_name": "unittest.mock.Mock", "line_number": 24, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 24, "usage_type": "name"}, {"api_name": "unittest.mock.Mock", "line_number": 28, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 28, "usage_type": "name"}, {"api_name": "chainerrl.envs.SerialVectorEnv", "line_number": 46, "usage_type": "call"}, {"api_name": "chainerrl.envs", "line_number": 46, "usage_type": "attribute"}, {"api_name": "unittest.mock.Mock", "line_number": 49, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 49, "usage_type": "name"}, {"api_name": "chainerrl.experiments.train_agent_batch", "line_number": 51, "usage_type": "call"}, {"api_name": "chainerrl.experiments", "line_number": 51, "usage_type": "attribute"}, {"api_name": "math.ceil", "line_number": 60, "usage_type": "call"}, {"api_name": "chainer.testing.parameterize", "line_number": 11, "usage_type": "call"}, {"api_name": "chainer.testing", "line_number": 11, "usage_type": "name"}, {"api_name": "chainer.testing.product", "line_number": 11, "usage_type": "call"}, {"api_name": "unittest.TestCase", "line_number": 106, "usage_type": "attribute"}, {"api_name": "tempfile.mkdtemp", "line_number": 111, "usage_type": "call"}, {"api_name": "unittest.mock.Mock", "line_number": 113, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 113, "usage_type": "name"}, {"api_name": "unittest.mock.Mock", "line_number": 117, "usage_type": "call"}, {"api_name": "unittest.mock", "line_number": 117, "usage_type": "name"}, {"api_name": "chainerrl.envs.SerialVectorEnv", "line_number": 145, "usage_type": "call"}, {"api_name": "chainerrl.envs", "line_number": 145, "usage_type": "attribute"}, {"api_name": "chainerrl.experiments.train_agent_batch", "line_number": 148, "usage_type": "call"}, {"api_name": "chainerrl.experiments", "line_number": 148, "usage_type": "attribute"}]} +{"seq_id": "28949075613", "text": "import numpy as np\nimport cv2 as cv\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\ndef bilinear_interpolate(source, input_pos, scale=2, pad=1):\n \"\"\"\n :param source:\n :param input_pos: 维度: 2 x 30w (点的个数) 第一个维度中0:x坐标,(h),1:y坐标 (w)\n :param scale:\n :param pad:\n :return:\n \"\"\"\n\n sour_shape = source.shape\n (sh, sw) = (sour_shape[-2], sour_shape[-1])\n padding = pad * np.ones((sour_shape[0], sour_shape[1], sh + 1, sw + 1))\n padding[:, :, :-1, :-1] = source\n # 目标图像h,w\n (th, tw) = (round(scale * sh), round(scale * sw))\n # 生成grid,新图,存放 新图在老图上对应的坐标\n grid = np.array(np.meshgrid(np.arange(th), np.arange(tw)), dtype=np.float32) # 2,59,47\n xy = np.copy(grid)\n # 计算新图到老图上的坐标。\n xy[0] = sh / th * (xy[0] + 0.5) - 0.5\n xy[1] = sw / tw * (xy[1] + 0.5) - 0.5\n\n x = input_pos[0]\n y = input_pos[1]\n\n # 拉平,这里和我的数据十分相似了。里面是对应的坐标\n x = xy[0].flatten()\n y = xy[1].flatten()\n\n # 计算取整的坐标,并拉平\n clip = np.floor(xy).astype(np.int)\n cx = clip[0].flatten()\n cy = clip[1].flatten()\n\n f1 = padding[:, :, cx, cy]\n f2 = padding[:, :, cx + 1, cy]\n f3 = padding[:, :, cx, cy + 1]\n f4 = padding[:, :, cx + 1, cy + 1]\n\n a = cx + 1 - x\n b = x - cx\n c = cy + 1 - y\n d = y - cy\n\n fx1 = a * f1 + b * f2\n fx2 = a * f3 + b * f4\n fy = c * fx1 + d * fx2\n fy = fy.reshape(fy.shape[0], fy.shape[1], tw, th).transpose((0, 1, 3, 2))\n return fy\n\n\nif __name__ == '__main__':\n path_list = ['inter/dog.jpg']\n imgs = []\n for path in path_list:\n im = cv.cvtColor(cv.imread(path), cv.COLOR_BGR2RGB) / 255\n imgs.append(im)\n imgs = np.array(imgs).transpose((0, 3, 1, 2))\n interps_0d1 = bilinear_interpolate(imgs, scale=0.1)\n interps_2d2 = bilinear_interpolate(imgs, scale=2.2)\n for im, interp0, interp1 in zip(imgs, interps_0d1, interps_2d2):\n plt.figure()\n plt.subplot(131)\n plt.imshow(im.transpose(1, 2, 0))\n plt.subplot(132)\n plt.imshow(interp0.transpose(1, 2, 0))\n plt.title('scale to 0.1 times of the original image')\n plt.subplot(133)\n plt.imshow(interp1.transpose(1, 2, 0))\n plt.title('scale to 2.2 times of the original image')\n plt.show()", "repo_name": "pksolar/sailus", "sub_path": "bleeding/inter_test4.py", "file_name": "inter_test4.py", "file_ext": "py", "file_size_in_byte": 2410, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "numpy.ones", "line_number": 18, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 23, "usage_type": "call"}, {"api_name": "numpy.meshgrid", "line_number": 23, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 23, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 23, "usage_type": "attribute"}, {"api_name": "numpy.copy", "line_number": 24, "usage_type": "call"}, {"api_name": "numpy.floor", "line_number": 37, "usage_type": "call"}, {"api_name": "numpy.int", "line_number": 37, "usage_type": "attribute"}, {"api_name": "cv2.cvtColor", "line_number": 62, "usage_type": "call"}, {"api_name": "cv2.imread", "line_number": 62, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2RGB", "line_number": 62, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 64, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 68, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 68, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 69, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 69, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 70, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 70, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 71, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 71, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 72, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 72, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 73, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 73, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 74, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 74, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 75, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 75, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 76, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 76, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 77, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 77, "usage_type": "name"}]} +{"seq_id": "31825306921", "text": "#!/usr/bin/env python\n\nimport individual\nimport box\nimport random\n\n'''\nCreated on May 24, 2011\n\n@author: baro\n'''\n\nclass Population:\n def __init__(self, \n population_size, \n elitism=True, \n elitismFraction=0.10,\n deathFraction=0.10,\n mutationProb=0.001):\n \n self.population_size = population_size\n self.elitism = elitism\n self.mutationProb = mutationProb\n self.elistismFraction = elitismFraction\n self.infantMortality = deathFraction\n \n file = open(\"boxes.txt\")\n fileinput = file.readlines()\n file.close()\n \n rawboxes = []\n for index in range(len(fileinput)):\n rawboxes.append(fileinput[index].replace(\"\\n\", \"\").split(\"\\t\")) \n for index2 in range(len(rawboxes[index])):\n rawboxes[index][index2] = int(rawboxes[index][index2])\n \n objectBoxes = []\n for item in rawboxes:\n placing_box = box.Box(item[0],item[1],item[2],item[3],item[4])\n objectBoxes.append(placing_box)\n \n self.population = []\n for iteration in range(self.population_size):\n self.population.append(individual.Individual(\"random\", objectBoxes))\n \n def evolve(self):\n populationToMate = len(self.population)\n workingPopulation = self.population[:]\n workingPopulation.sort(key=lambda obj: obj.fitness, reverse=True)\n \n newPopulation = []\n if self.elitism == True:\n numberOfElites = int(round(len(workingPopulation) * \n self.elistismFraction))\n populationToMate -= numberOfElites\n for ind in range(numberOfElites):\n newPopulation.append(workingPopulation[ind])\n \n numberOfDeadInfants = int(round(len(workingPopulation) * \n self.infantMortality))\n del workingPopulation[-numberOfDeadInfants:-1]\n\n total = int(round(sum([ind.fitness for ind in workingPopulation])))\n \n for ind in range(populationToMate):\n sel1 = random.randint(1, total-2)\n sel2 = random.randint(sel1, total-1)\n \n count = 0\n firstParentPlaced = False\n for individual in workingPopulation:\n count += individual.fitness\n if count > sel1 and not firstParentPlaced:\n firstParent = individual\n firstParentPlaced = True\n if count > sel2:\n secondParent = individual\n count = 0\n firstParentPlaced = False\n break\n offspring = firstParent + secondParent \n self.mutate(offspring)\n newPopulation.append(offspring) \n \n self.population = newPopulation\n \n #TODO: reporting of results to txtfile with actual rotations/boxorders\n #TODO: mutation\n \n def mutate(self, ind):\n chance = random.random()\n if chance < self.mutationProb * ind.alleleLength:\n pick = random.randint(1,3)\n al1 = random.randint(1,ind.alleleLength)\n al2 = random.randint(1,ind.alleleLength)\n \n if pick == 1:\n (ind.boxOrder[al1], ind.boxOrder[al2]) = (ind.boxOrder[al2], \n ind.boxOrder[al1])\n if pick == 2:\n ind.boxRotation[al1] = random.randint(0,5)\n ind.boxRotation[al2] = random.randint(0,5)\n else:\n (ind.boxOrder[al1], ind.boxOrder[al2]) = (ind.boxOrder[al2], \n ind.boxOrder[al1])\n (ind.boxRotation[al1], \n ind.boxRotation[al2]) = (ind.boxRotation[al2], \n ind.boxRotation[al1])\n\n def getReport(self):\n total = sum([individual.fitness for individual in self.population])\n average = total/len(self.population)\n best = max([individual.fitness for individual in self.population])\n \n bOrd = [ind.boxOrder for ind in self.population if ind.fitness == best][0]\n bRot = [ind.boxRotation for ind in self.population if ind.fitness == best ][0]\n \n return {\"average\": average, \"best\": best, \"bestBoxRotation\": bRot, \"bestBoxOrder\": bOrd}\n \n\n", "repo_name": "janvandenbroeck/rackfiller", "sub_path": "population.py", "file_name": "population.py", "file_ext": "py", "file_size_in_byte": 4551, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "box.Box", "line_number": 39, "usage_type": "call"}, {"api_name": "individual.Individual", "line_number": 44, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 66, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 67, "usage_type": "call"}, {"api_name": "individual.fitness", "line_number": 72, "usage_type": "attribute"}, {"api_name": "random.random", "line_number": 91, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 93, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 94, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 95, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 101, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 102, "usage_type": "call"}, {"api_name": "individual.fitness", "line_number": 111, "usage_type": "attribute"}, {"api_name": "individual.fitness", "line_number": 113, "usage_type": "attribute"}]} +{"seq_id": "13884768874", "text": "# -*- coding:utf-8 -*-\n\n__author__ = 'matt'\n__email__ = 'mattemail@foxmail.com'\n__copyright__ = 'Copyright @ 2019/8/11 0011, matt '\n\n\nimport torch\nimport torch.nn as nn\nfrom model.utils import *\n\n\nclass DNCNN(nn.Module):\n def __init__(self, verbose=False):\n super(DNCNN, self).__init__()\n self.verbose = verbose\n\n self.layer1 = nn.Sequential(\n nn.Conv2d(3, 32, kernel_size=3, stride=1, padding=1),\n nn.ReLU(True)\n )\n self.layer2 = nn.Sequential(\n nn.Conv2d(32, 32, kernel_size=3, stride=1, padding=1),\n nn.ReLU(True)\n )\n self.layer3 = nn.Sequential(\n nn.Conv2d(32, 64, kernel_size=3, stride=1, padding=1),\n nn.ReLU(True)\n )\n self.pool1 = nn.MaxPool2d(kernel_size=2, stride=2)\n self.layer4 = nn.Sequential(\n nn.Conv2d(64, 64, kernel_size=3, stride=1, padding=1),\n nn.ReLU(True)\n )\n self.layer5 = nn.Sequential(\n nn.Conv2d(64, 64, kernel_size=3, stride=1, padding=1),\n nn.ReLU(True)\n )\n self.pool2 = nn.MaxPool2d(kernel_size=2, stride=2)\n self.layer6 = nn.Sequential(\n nn.Conv2d(64, 384, kernel_size=3, stride=1, padding=1),\n nn.ReLU(True)\n )\n self.layer7 = nn.Sequential(\n nn.Conv2d(384, 384, kernel_size=3, stride=1, padding=1),\n nn.ReLU(True)\n )\n self.layer8 = nn.Sequential(\n nn.Conv2d(384, 256, kernel_size=3, stride=2, padding=1),\n nn.ReLU(True)\n )\n self.pool3 = nn.MaxPool2d(kernel_size=2, stride=2)\n self.classify = nn.Sequential(\n nn.Linear(9216, 2048),\n nn.Dropout(0.5),\n nn.ReLU(True),\n nn.Linear(2048, 2048),\n nn.Dropout(0.5),\n nn.ReLU(True),\n nn.Linear(2048, 2)\n )\n weights_init_kaiming(self)\n\n def forward(self, x):\n x = self.layer1(x)\n if self.verbose:\n print(\"layer1 size: \", x.size())\n x = self.layer2(x)\n if self.verbose:\n print(\"layer1 size: \", x.size())\n x = self.layer3(x)\n if self.verbose:\n print(\"layer3 size: \", x.size())\n x = self.pool1(x)\n if self.verbose:\n print(\"pool1 size: \", x.size())\n x = self.layer4(x)\n if self.verbose:\n print(\"layer4 size: \", x.size())\n x = self.layer5(x)\n if self.verbose:\n print(\"layer5 size: \", x.size())\n x = self.pool2(x)\n if self.verbose:\n print(\"pool2 size: \", x.size())\n x = self.layer6(x)\n if self.verbose:\n print(\"layer6 size: \", x.size())\n x = self.layer7(x)\n if self.verbose:\n print(\"layer7 size: \", x.size())\n x = self.layer8(x)\n if self.verbose:\n print(\"layer8 size: \", x.size())\n\n x = x.view(x.size(0), -1)\n if self.verbose:\n print(\"view size: \", x.size())\n x = self.classify(x)\n if self.verbose:\n print(\"classify size: \", x.size())\n return x\n\n\nif __name__ == \"__main__\":\n net = DNCNN(verbose=True)\n x = torch.randn((1, 3, 48, 48))\n y = net(x)\n\n", "repo_name": "yuanluw/smog-detection", "sub_path": "model/dncnn.py", "file_name": "dncnn.py", "file_ext": "py", "file_size_in_byte": 3253, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "21", "api": [{"api_name": "torch.nn.Module", "line_number": 13, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 13, "usage_type": "name"}, {"api_name": "torch.nn.Sequential", "line_number": 18, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 18, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 19, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 19, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 20, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 20, "usage_type": "name"}, {"api_name": "torch.nn.Sequential", "line_number": 22, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 22, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 23, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 23, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 24, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 24, "usage_type": "name"}, {"api_name": "torch.nn.Sequential", "line_number": 26, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 26, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 27, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 27, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 28, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 28, "usage_type": "name"}, {"api_name": "torch.nn.MaxPool2d", "line_number": 30, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 30, "usage_type": "name"}, {"api_name": "torch.nn.Sequential", "line_number": 31, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 31, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 32, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 32, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 33, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 33, "usage_type": "name"}, {"api_name": "torch.nn.Sequential", "line_number": 35, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 35, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 36, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 36, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 37, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 37, "usage_type": "name"}, {"api_name": "torch.nn.MaxPool2d", "line_number": 39, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 39, "usage_type": "name"}, {"api_name": "torch.nn.Sequential", "line_number": 40, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 40, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 41, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 41, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 42, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 42, "usage_type": "name"}, {"api_name": "torch.nn.Sequential", "line_number": 44, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 44, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 45, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 45, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 46, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 46, "usage_type": "name"}, {"api_name": "torch.nn.Sequential", "line_number": 48, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 48, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 49, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 49, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 50, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 50, "usage_type": "name"}, {"api_name": "torch.nn.MaxPool2d", "line_number": 52, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 52, "usage_type": "name"}, {"api_name": "torch.nn.Sequential", "line_number": 53, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 53, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 54, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 54, "usage_type": "name"}, {"api_name": "torch.nn.Dropout", "line_number": 55, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 55, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 56, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 56, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 57, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 57, "usage_type": "name"}, {"api_name": "torch.nn.Dropout", "line_number": 58, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 58, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 59, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 59, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 60, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 60, "usage_type": "name"}, {"api_name": "torch.randn", "line_number": 107, "usage_type": "call"}]} +{"seq_id": "42467665324", "text": "import numpy as np\nfrom prize_method import reward_function\nfrom enum import Enum\nfrom numpy import pi, sign\n\n\nclass sd:\n class SystemDynamics_Reply(Enum):\n favourable = +1\n unfavourable = -1\n\n class Realm(Enum):\n reject = -1\n optimistic = +1\n\n def __init__(self, amount_stairs, high_necessary_stair, shield_area):\n self._shield_area = self._check_shield_area(shield_area)\n self._highest_punishment_modulus_index = self.calc_strongest_punishment_absIdx(amount_stairs)\n self._punishment_functions_array = self._define_prize_method_functions(amount_stairs, high_necessary_stair)\n\n def _check_shield_area(self, shield_area):\n if (shield_area < 0):\n raise ValueError('shield_area has to be neutral.')\n return shield_area\n\n def start_over(self):\n return self.Realm.optimistic, 0, self.SystemDynamics_Reply.favourable\n\n def prize_method(self, miscal_phi_index, location):\n return self.get_punishment_method(miscal_phi_index).prize_method(location)\n\n def condition_change(self, realm, miscal_phi_index, systemDynamics_reply, location):\n\n old_realm = realm\n\n realm = self._calc_realm(old_realm, location)\n\n\n if realm != old_realm:\n systemDynamics_reply = self.SystemDynamics_Reply.favourable\n\n\n miscal_phi_index += self._calc_angular_step(realm, miscal_phi_index, systemDynamics_reply, location)\n\n\n systemDynamics_reply = self._changed_systemDynamics_reply(miscal_phi_index, systemDynamics_reply)\n\n\n miscal_phi_index = self._apply_uniformity(miscal_phi_index)\n\n if (miscal_phi_index == 0) and (abs(location) <= self._shield_area):\n realm, miscal_phi_index, systemDynamics_reply = self.start_over()\n\n return realm, miscal_phi_index, systemDynamics_reply\n\n def _calc_realm(self, realm, location):\n if abs(location) <= self._shield_area:\n return realm\n else:\n return self.Realm(sign(location))\n\n def _calc_angular_step(self, realm, miscal_phi_index, systemDynamics_reply, location):\n if abs(location) <= self._shield_area:\n return -sign(miscal_phi_index)\n\n if miscal_phi_index == -realm.value * self._highest_punishment_modulus_index:\n return 0\n else:\n return systemDynamics_reply.value * sign(location)\n\n def _changed_systemDynamics_reply(self, miscal_phi_index, systemDynamics_reply):\n if abs(miscal_phi_index) >= self._highest_punishment_modulus_index:\n return self.SystemDynamics_Reply.unfavourable\n return systemDynamics_reply\n\n def _apply_uniformity(self, miscal_phi_index):\n punishment_range = 4 * self._highest_punishment_modulus_index\n if abs(miscal_phi_index) < self._highest_punishment_modulus_index:\n return miscal_phi_index\n miscal_phi_index = (miscal_phi_index + punishment_range) % punishment_range\n miscal_phi_index = 2 * self._highest_punishment_modulus_index - miscal_phi_index\n return miscal_phi_index\n\n def get_punishment_method(self, miscal_phi_index):\n # Compute the index of the punishment function to use\n idx_offset = int(self._highest_punishment_modulus_index + miscal_phi_index)\n idx = idx_offset % len(self._punishment_functions_array)\n\n # Return the selected punishment function\n return self._punishment_functions_array[idx]\n\n def _define_prize_method_functions(self, amount_stairs, high_necessary_stair):\n angles = np.arange(-self._highest_punishment_modulus_index,\n self._highest_punishment_modulus_index + 1) * 2 * np.pi / amount_stairs\n reward_funcs = [reward_function.reward_function(angle, high_necessary_stair) for angle in angles]\n return np.array(reward_funcs)\n\n def calc_strongest_punishment_absIdx(self, amount_stairs):\n if (amount_stairs < 1) or (amount_stairs % 4 != 0):\n raise ValueError('Number of steps must be a positive integer and multiple of four.')\n return amount_stairs // 4\n\n try:\n amount_stairs = int(input(\"Enter the number of stairs: \"))\n print(f\"The highest punishment modulus index is {highest_punishment_modulus_index(amount_stairs)}\")\n except ValueError as e:\n print(e)", "repo_name": "gauravkumar313/model_policy_training_stochastic", "sub_path": "src/components/systemdyn.py", "file_name": "systemdyn.py", "file_ext": "py", "file_size_in_byte": 4340, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "enum.Enum", "line_number": 8, "usage_type": "name"}, {"api_name": "enum.Enum", "line_number": 12, "usage_type": "name"}, {"api_name": "numpy.sign", "line_number": 60, "usage_type": "call"}, {"api_name": "numpy.sign", "line_number": 64, "usage_type": "call"}, {"api_name": "numpy.sign", "line_number": 69, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 93, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 94, "usage_type": "attribute"}, {"api_name": "prize_method.reward_function.reward_function", "line_number": 95, "usage_type": "call"}, {"api_name": "prize_method.reward_function", "line_number": 95, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 96, "usage_type": "call"}]} +{"seq_id": "19373444870", "text": "from __future__ import annotations\nfrom collections.abc import Sequence\nfrom typing import overload, Union\nimport logging\nimport tempfile\nimport threading\n\nimport numpy\nimport numpy.typing\n\nfrom ...api.data import (DiffractionDataset, DiffractionMetadata, DiffractionPatternArray,\n DiffractionPatternArrayType, DiffractionPatternIndexes,\n DiffractionPatternState, SimpleDiffractionPatternArray)\nfrom ...api.image import ImageExtent\nfrom ...api.tree import SimpleTreeNode\nfrom .settings import DiffractionDatasetSettings, DiffractionPatternSettings\nfrom .sizer import DiffractionPatternSizer\n\n__all__ = [\n 'ActiveDiffractionDataset',\n]\n\nlogger = logging.getLogger(__name__)\n\n\nclass ActiveDiffractionDataset(DiffractionDataset):\n\n def __init__(self, datasetSettings: DiffractionDatasetSettings,\n patternSettings: DiffractionPatternSettings,\n diffractionPatternSizer: DiffractionPatternSizer) -> None:\n super().__init__()\n self._datasetSettings = datasetSettings\n self._patternSettings = patternSettings\n self._diffractionPatternSizer = diffractionPatternSizer\n\n self._metadata = DiffractionMetadata.createNullInstance()\n self._contentsTree = SimpleTreeNode.createRoot(list())\n self._arrayListLock = threading.RLock()\n self._arrayList: list[DiffractionPatternArray] = list()\n self._arrayData: DiffractionPatternArrayType = numpy.zeros((0, 0, 0), dtype=numpy.uint16)\n self._changedEvent = threading.Event()\n\n def getMetadata(self) -> DiffractionMetadata:\n return self._metadata\n\n def getContentsTree(self) -> SimpleTreeNode:\n return self._contentsTree\n\n def getInfoText(self) -> str:\n number, height, width = self._arrayData.shape\n dtype = str(self._arrayData.dtype)\n sizeInMB = self._arrayData.nbytes / (1024 * 1024)\n return f'Total: {number} {dtype}({width}W x {height}H) frames [{sizeInMB:.2f}MB]'\n\n @overload\n def __getitem__(self, index: int) -> DiffractionPatternArray:\n ...\n\n @overload\n def __getitem__(self, index: slice) -> Sequence[DiffractionPatternArray]:\n ...\n\n def __getitem__(self, index: Union[int, slice]) -> \\\n Union[DiffractionPatternArray, Sequence[DiffractionPatternArray]]:\n with self._arrayListLock:\n return self._arrayList[index]\n\n def __len__(self) -> int:\n with self._arrayListLock:\n return len(self._arrayList)\n\n def reset(self, metadata: DiffractionMetadata, contentsTree: SimpleTreeNode) -> None:\n with self._arrayListLock:\n self._metadata = metadata\n self._contentsTree = contentsTree\n self._arrayList.clear()\n\n self._changedEvent.set()\n\n def realloc(self) -> None:\n shape = (\n self._metadata.numberOfPatternsTotal,\n self._diffractionPatternSizer.getExtentYInPixels(),\n self._diffractionPatternSizer.getExtentXInPixels(),\n )\n\n with self._arrayListLock:\n self._arrayList.clear()\n\n if self._datasetSettings.memmapEnabled.value:\n scratchDirectory = self._datasetSettings.scratchDirectory.value\n scratchDirectory.mkdir(mode=0o755, parents=True, exist_ok=True)\n npyTempFile = tempfile.NamedTemporaryFile(dir=scratchDirectory, suffix='.npy')\n logger.debug(f'Scratch data file {npyTempFile.name} is {shape}')\n self._arrayData = numpy.memmap(npyTempFile,\n dtype=self._metadata.patternDataType,\n shape=shape)\n self._arrayData[:] = 0\n else:\n logger.debug(f'Scratch memory is {shape}')\n self._arrayData = numpy.zeros(shape, dtype=self._metadata.patternDataType)\n\n self._changedEvent.set()\n\n def insertArray(self, array: DiffractionPatternArray) -> None:\n if array.getState() == DiffractionPatternState.LOADED:\n data = self._diffractionPatternSizer(array.getData())\n\n if self._patternSettings.valueUpperBoundEnabled.value:\n valueLowerBound = self._patternSettings.valueLowerBound.value\n valueUpperBound = self._patternSettings.valueUpperBound.value\n data[data >= valueUpperBound] = valueLowerBound\n\n if self._patternSettings.valueLowerBoundEnabled.value:\n valueLowerBound = self._patternSettings.valueLowerBound.value\n data[data < valueLowerBound] = valueLowerBound\n\n if self._patternSettings.flipXEnabled.value:\n data = numpy.flip(data, axis=-1)\n\n if self._patternSettings.flipYEnabled.value:\n data = numpy.flip(data, axis=-2)\n\n offset = self._metadata.numberOfPatternsPerArray * array.getIndex()\n sliceZ = slice(offset, offset + data.shape[0])\n dataView = self._arrayData[sliceZ, :, :]\n dataView[:] = data\n dataView.flags.writeable = False\n\n array = SimpleDiffractionPatternArray(array.getLabel(), array.getIndex(), dataView,\n array.getState())\n\n with self._arrayListLock:\n self._arrayList.append(array)\n self._arrayList.sort(key=lambda arr: arr.getIndex())\n\n self._changedEvent.set()\n\n def getAssembledIndexes(self) -> Sequence[int]:\n indexes: list[int] = list()\n\n with self._arrayListLock:\n for array in self._arrayList:\n if array.getState() == DiffractionPatternState.LOADED:\n offset = self._metadata.numberOfPatternsPerArray * array.getIndex()\n size = array.getNumberOfPatterns()\n indexes.extend(range(offset, offset + size))\n\n return indexes\n\n def getAssembledData(self) -> DiffractionPatternArrayType:\n indexes = self.getAssembledIndexes()\n return self._arrayData[indexes]\n\n def setAssembledData(self, arrayData: DiffractionPatternArrayType,\n arrayIndexes: DiffractionPatternIndexes) -> None:\n with self._arrayListLock:\n numberOfPatterns, detectorHeight, detectorWidth = arrayData.shape\n\n self._metadata = DiffractionMetadata(\n numberOfPatternsPerArray=numberOfPatterns,\n numberOfPatternsTotal=numberOfPatterns,\n patternDataType=arrayData.dtype,\n detectorExtentInPixels=ImageExtent(detectorWidth, detectorHeight),\n )\n\n self._contentsTree = SimpleTreeNode.createRoot(['Name', 'Type', 'Details'])\n\n # TODO use arrayIndexes\n self._arrayList = [\n SimpleDiffractionPatternArray(\n label='Restart',\n index=0,\n data=arrayData[...],\n state=DiffractionPatternState.LOADED,\n ),\n ]\n self._arrayData = arrayData\n\n self.notifyObservers()\n\n def notifyObserversIfDatasetChanged(self) -> None:\n if self._changedEvent.is_set():\n self._changedEvent.clear()\n self.notifyObservers()\n", "repo_name": "AdvancedPhotonSource/ptychodus", "sub_path": "ptychodus/model/data/active.py", "file_name": "active.py", "file_ext": "py", "file_size_in_byte": 7301, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 7, "dataset": "github-code", "pt": "21", "api": [{"api_name": "logging.getLogger", "line_number": 23, "usage_type": "call"}, {"api_name": "api.data.DiffractionDataset", "line_number": 26, "usage_type": "name"}, {"api_name": "settings.DiffractionDatasetSettings", "line_number": 28, "usage_type": "name"}, {"api_name": "settings.DiffractionPatternSettings", "line_number": 29, "usage_type": "name"}, {"api_name": "sizer.DiffractionPatternSizer", "line_number": 30, "usage_type": "name"}, {"api_name": "api.data.DiffractionMetadata.createNullInstance", "line_number": 36, "usage_type": "call"}, {"api_name": "api.data.DiffractionMetadata", "line_number": 36, "usage_type": "name"}, {"api_name": "api.tree.SimpleTreeNode.createRoot", "line_number": 37, "usage_type": "call"}, {"api_name": "api.tree.SimpleTreeNode", "line_number": 37, "usage_type": "name"}, {"api_name": "threading.RLock", "line_number": 38, "usage_type": "call"}, {"api_name": "api.data.DiffractionPatternArray", "line_number": 39, "usage_type": "name"}, {"api_name": "api.data.DiffractionPatternArrayType", "line_number": 40, "usage_type": "name"}, {"api_name": "numpy.zeros", "line_number": 40, "usage_type": "call"}, {"api_name": "numpy.uint16", "line_number": 40, "usage_type": "attribute"}, {"api_name": "threading.Event", "line_number": 41, "usage_type": "call"}, {"api_name": "api.data.DiffractionMetadata", "line_number": 43, "usage_type": "name"}, {"api_name": "api.tree.SimpleTreeNode", "line_number": 46, "usage_type": "name"}, {"api_name": "typing.overload", "line_number": 55, "usage_type": "name"}, {"api_name": "api.data.DiffractionPatternArray", "line_number": 56, "usage_type": "name"}, {"api_name": "typing.overload", "line_number": 59, "usage_type": "name"}, {"api_name": "collections.abc.Sequence", "line_number": 60, "usage_type": "name"}, {"api_name": "api.data.DiffractionPatternArray", "line_number": 60, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 63, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 64, "usage_type": "name"}, {"api_name": "api.data.DiffractionPatternArray", "line_number": 64, "usage_type": "name"}, {"api_name": "collections.abc.Sequence", "line_number": 64, "usage_type": "name"}, {"api_name": "api.data.DiffractionMetadata", "line_number": 72, "usage_type": "name"}, {"api_name": "api.tree.SimpleTreeNode", "line_number": 72, "usage_type": "name"}, {"api_name": "tempfile.NamedTemporaryFile", "line_number": 93, "usage_type": "call"}, {"api_name": "numpy.memmap", "line_number": 95, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 101, "usage_type": "call"}, {"api_name": "api.data.DiffractionPatternArray", "line_number": 105, "usage_type": "name"}, {"api_name": "api.data.DiffractionPatternState.LOADED", "line_number": 106, "usage_type": "attribute"}, {"api_name": "api.data.DiffractionPatternState", "line_number": 106, "usage_type": "name"}, {"api_name": "numpy.flip", "line_number": 119, "usage_type": "call"}, {"api_name": "numpy.flip", "line_number": 122, "usage_type": "call"}, {"api_name": "api.data.SimpleDiffractionPatternArray", "line_number": 130, "usage_type": "call"}, {"api_name": "api.data.DiffractionPatternState.LOADED", "line_number": 144, "usage_type": "attribute"}, {"api_name": "api.data.DiffractionPatternState", "line_number": 144, "usage_type": "name"}, {"api_name": "collections.abc.Sequence", "line_number": 139, "usage_type": "name"}, {"api_name": "api.data.DiffractionPatternArrayType", "line_number": 151, "usage_type": "name"}, {"api_name": "api.data.DiffractionPatternArrayType", "line_number": 155, "usage_type": "name"}, {"api_name": "api.data.DiffractionPatternIndexes", "line_number": 156, "usage_type": "name"}, {"api_name": "api.data.DiffractionMetadata", "line_number": 160, "usage_type": "call"}, {"api_name": "api.image.ImageExtent", "line_number": 164, "usage_type": "call"}, {"api_name": "api.tree.SimpleTreeNode.createRoot", "line_number": 167, "usage_type": "call"}, {"api_name": "api.tree.SimpleTreeNode", "line_number": 167, "usage_type": "name"}, {"api_name": "api.data.SimpleDiffractionPatternArray", "line_number": 171, "usage_type": "call"}, {"api_name": "api.data.DiffractionPatternState.LOADED", "line_number": 175, "usage_type": "attribute"}, {"api_name": "api.data.DiffractionPatternState", "line_number": 175, "usage_type": "name"}]} +{"seq_id": "34149644541", "text": "# Created by Aleksei Wan on 26.03.2020\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.utils.data as utils\nfrom torchvision import transforms\nfrom torchvision import datasets\nimport json\n\ntorch.manual_seed(1) # set the random seed\n\nTRAINING_RESULTS = True\nUSE_TRANSFER_LEARNING = True\n\n\nclass EmotionNet(nn.Module):\n def __init__(self):\n super(EmotionNet, self).__init__()\n self.name = \"EmotionNet\"\n self.conv1 = nn.Conv2d(3, 5, 5)\n self.pool1 = nn.MaxPool2d(2, 2)\n self.conv2 = nn.Conv2d(5, 10, 3)\n self.pool2 = nn.MaxPool2d(2, 2)\n\n self.fc1 = nn.Linear(10 * 18 * 18, 18 * 18)\n self.fc2 = nn.Linear(18 * 18, 32)\n self.fc3 = nn.Linear(32, 8)\n\n def forward(self, img):\n x = self.pool1(F.relu(self.conv1(img)))\n x = self.pool2(F.relu(self.conv2(x)))\n # print(\"shape\", x.shape)\n x = x.view(-1, 10 * 18 * 18)\n x = F.relu(self.fc1(x))\n x = F.relu(self.fc2(x))\n x = self.fc3(x)\n return x\n\n\n# class AlexASLNet(nn.Module):\n# def __init__(self):\n# super(AlexASLNet, self).__init__()\n# self.name = \"AlexEmotionNet-3layer-640-final\"\n# self.fc1 = nn.Linear(256 * 10 * 10, 192)\n# self.fc2 = nn.Linear(192, 128)\n# self.fc3 = nn.Linear(128, 8)\n#\n# def forward(self, img):\n# x = img.view(-1, 256 * 10 * 10)\n# x = F.relu(self.fc1(x))\n# x = F.relu(self.fc2(x))\n# x = self.fc3(x)\n# return x\n\nclass AlexASLNet(nn.Module):\n def __init__(self):\n super(AlexASLNet, self).__init__()\n self.name = \"AlexEmotionNet-5class-3layer-640\"\n self.fc1 = nn.Linear(256*10*10, 192)\n self.fc2 = nn.Linear(192, 128)\n self.fc3 = nn.Linear(128, 5)\n\n def forward(self, img):\n x = img.view(-1, 256*10*10)\n x = F.relu(self.fc1(x))\n x = F.relu(self.fc2(x))\n x = self.fc3(x)\n return x\n\ndef load_from_checkpoint(net, path):\n # load the model state from a final\n checkpoint = torch.load(path)\n net.load_state_dict(checkpoint)\n net.eval()\n return\n\ndef do_processing(dl, name):\n preds = []\n it = 0\n for imgs, labels in dl:\n it += 1\n print('Iteration', it)\n if torch.cuda.is_available():\n imgs = imgs.cuda()\n labels = labels.cuda()\n output = net(imgs)\n preds.append(\n (output.data.cpu().numpy().tolist()[0], labels.data.cpu().numpy().tolist()[0]) if TRAINING_RESULTS\n else output.data.cpu().numpy().tolist()[0])\n with open('lightgbm/' + name + 'results.json', 'w+') as f:\n json.dump(preds, f)\n return\n\n\nif __name__ == \"__main__\":\n transform = transforms.Compose([transforms.Resize((90, 160)), # (1080,1920) (hight, width)\n transforms.CenterCrop(80),\n transforms.ToTensor()])\n net = AlexASLNet()\n load_from_checkpoint(net, 'cp1')\n test_set = datasets.DatasetFolder('./data/alex-full-features/test', loader=torch.load, extensions=('.tensor'))\n test_loader = torch.utils.data.DataLoader(test_set, batch_size=1)\n val_set = datasets.DatasetFolder('./data/alex-full-features/val', loader=torch.load, extensions=('.tensor'))\n val_loader = torch.utils.data.DataLoader(val_set, batch_size=1)\n train_set = datasets.DatasetFolder('./data/alex-full-features/train', loader=torch.load, extensions=('.tensor'))\n train_loader = torch.utils.data.DataLoader(train_set, batch_size=1)\n\n # net = EmotionNet()\n # load_from_checkpoint(net, 'cp_ournn')\n # trainFolder = datasets.ImageFolder('./lightgbm/train', transform=transform)\n # train_loader = torch.utils.data.DataLoader(trainFolder, batch_size=1)\n # valFolder = datasets.ImageFolder('./lightgbm/val', transform=transform)\n # val_loader = torch.utils.data.DataLoader(valFolder, batch_size=1)\n # testFolder = datasets.ImageFolder('./data/test', transform=transform)\n # test_loader = torch.utils.data.DataLoader(testFolder, batch_size=1)\n\n if torch.cuda.is_available():\n net.cuda()\n\n print('Total Iterations:', len(test_loader) + len(train_loader) + len(val_loader))\n\n do_processing(train_loader, 'train')\n do_processing(val_loader, 'val')\n do_processing(test_loader, 'test')\n", "repo_name": "alewan/aps360project", "sub_path": "calculate_results.py", "file_name": "calculate_results.py", "file_ext": "py", "file_size_in_byte": 4348, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "torch.manual_seed", "line_number": 11, "usage_type": "call"}, {"api_name": "torch.nn.Module", "line_number": 17, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 17, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 21, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 21, "usage_type": "name"}, {"api_name": "torch.nn.MaxPool2d", "line_number": 22, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 22, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 23, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 23, "usage_type": "name"}, {"api_name": "torch.nn.MaxPool2d", "line_number": 24, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 24, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 26, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 26, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 27, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 27, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 28, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 28, "usage_type": "name"}, {"api_name": "torch.nn.functional.relu", "line_number": 31, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 31, "usage_type": "name"}, {"api_name": "torch.nn.functional.relu", "line_number": 32, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 32, "usage_type": "name"}, {"api_name": "torch.nn.functional.relu", "line_number": 35, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 35, "usage_type": "name"}, {"api_name": "torch.nn.functional.relu", "line_number": 36, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 36, "usage_type": "name"}, {"api_name": "torch.nn.Module", "line_number": 56, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 56, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 60, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 60, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 61, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 61, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 62, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 62, "usage_type": "name"}, {"api_name": "torch.nn.functional.relu", "line_number": 66, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 66, "usage_type": "name"}, {"api_name": "torch.nn.functional.relu", "line_number": 67, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 67, "usage_type": "name"}, {"api_name": "torch.load", "line_number": 73, "usage_type": "call"}, {"api_name": "torch.cuda.is_available", "line_number": 84, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 84, "usage_type": "attribute"}, {"api_name": "json.dump", "line_number": 92, "usage_type": "call"}, {"api_name": "torchvision.transforms.Compose", "line_number": 97, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 97, "usage_type": "name"}, {"api_name": "torchvision.transforms.Resize", "line_number": 97, "usage_type": "call"}, {"api_name": "torchvision.transforms.CenterCrop", "line_number": 98, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 98, "usage_type": "name"}, {"api_name": "torchvision.transforms.ToTensor", "line_number": 99, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 99, "usage_type": "name"}, {"api_name": "torchvision.datasets.DatasetFolder", "line_number": 102, "usage_type": "call"}, {"api_name": "torchvision.datasets", "line_number": 102, "usage_type": "name"}, {"api_name": "torch.load", "line_number": 102, "usage_type": "attribute"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 103, "usage_type": "call"}, {"api_name": "torch.utils", "line_number": 103, "usage_type": "attribute"}, {"api_name": "torchvision.datasets.DatasetFolder", "line_number": 104, "usage_type": "call"}, {"api_name": "torchvision.datasets", "line_number": 104, "usage_type": "name"}, {"api_name": "torch.load", "line_number": 104, "usage_type": "attribute"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 105, "usage_type": "call"}, {"api_name": "torch.utils", "line_number": 105, "usage_type": "attribute"}, {"api_name": "torchvision.datasets.DatasetFolder", "line_number": 106, "usage_type": "call"}, {"api_name": "torchvision.datasets", "line_number": 106, "usage_type": "name"}, {"api_name": "torch.load", "line_number": 106, "usage_type": "attribute"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 107, "usage_type": "call"}, {"api_name": "torch.utils", "line_number": 107, "usage_type": "attribute"}, {"api_name": "torch.cuda.is_available", "line_number": 118, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 118, "usage_type": "attribute"}]} +{"seq_id": "32314846566", "text": "import matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport time, os\r\nimport path\r\nfrom acados_settings import *\r\nimport bicycle_model\r\nimport mpc_plot\r\nimport obstacle\r\n\r\n# os.chdir(\"/home/marunyu/study/planning/Planning_project\")\r\n\r\ntest_path = path.test_path\r\nspeed_profile = path.get_velprofile(test_path,3.,0.1)\r\ntest_param = path.test_param\r\n\r\nTf = test_param[\"Tf\"] # prediction horizon\r\nN = test_param[\"N\"] # number of discretization steps\r\ndisc_offset = test_param[\"disc_offset\"]\r\nradius = test_param[\"radius\"]\r\nT = 80.00\r\nstate = bicycle_model.ROBOT_STATE(x=10.0, y=7.0, yaw=2.09, v=0.0)\r\ninit_state = np.array([state.x,state.y,state.v,state.yaw,state.delta])\r\n\r\n\r\nconstraint, model, acados_solver = acados_settings(Tf, N, init_state,3)\r\nobstacles = []\r\nobstacles.append(obstacle.box(45, 14.5,0, 10, 2))\r\nobstacles.append(obstacle.box(45, 21,0, 10, 2))\r\n# obstacles.append(obstacle.box(4.5, 21,0,1,1))\r\nobstacles.append(obstacle.circle(4.5, 21,1))\r\n\r\n# dimensions\r\nnx = model.x.size()[0]\r\nnu = model.u.size()[0]\r\nny = nx + nu\r\nNsim = int(T * N / Tf)\r\n\r\n\r\nx_rec = []\r\ny_rec = []\r\nyaw_rec = []\r\nv_rec = []\r\nt_rec = []\r\ndelta_rec = []\r\nderdelta_rec = []\r\na_rec = []\r\n\r\nstate = bicycle_model.ROBOT_STATE(x=10.0, y=7.0, yaw=2.09, v=0.0)\r\nfor i in range(Nsim):\r\n # update reference\r\n ref,ind,dir = path.get_reftraj(state,test_path,speed_profile,test_param)\r\n plt.cla()\r\n\r\n\r\n x0 = np.array([state.x,state.y,state.v,state.yaw,state.delta])\r\n # print(\"x0\",x0)\r\n acados_solver.set(0, \"lbx\", x0)\r\n acados_solver.set(0, \"ubx\", x0)\r\n for j in range(N+1):\r\n hyperplanes = []\r\n for obs in obstacles:\r\n obs.plot()\r\n h = obs.find_hyperplane(state, ref[:,j], 1.25)\r\n if h is not None:\r\n obs.draw_hyperplane(h)\r\n hyperplanes.append(h)\r\n print(\"h:\",h)\r\n constraint_num = len(hyperplanes)\r\n C = np.zeros((constraint_num*2, nx))\r\n D = np.zeros((constraint_num*2, nu))\r\n g_l = -1000*np.ones(constraint_num*2)\r\n g_u = 1000*np.ones(constraint_num*2)\r\n for i in range(constraint_num):\r\n if hyperplanes[i] is not None:\r\n h = hyperplanes[i]\r\n T = np.array([[1, 0, 0, -np.sin(state.yaw) * disc_offset, 0],\r\n [0, 1, 0, np.cos(state.yaw) * disc_offset, 0],\r\n [1, 0, 0, np.sin(state.yaw) * disc_offset, 0],\r\n [0, 1, 0, -np.cos(state.yaw) * disc_offset, 0]])\r\n t = np.array([disc_offset * np.cos(state.yaw) + state.yaw * np.sin(state.yaw) * disc_offset,\r\n disc_offset * np.sin(state.yaw) - state.yaw * np.cos(state.yaw) * disc_offset,\r\n -disc_offset * np.cos(state.yaw) - state.yaw * np.sin(state.yaw) * disc_offset,\r\n -disc_offset * np.sin(state.yaw) + state.yaw * np.cos(state.yaw) * disc_offset])\r\n L = np.array([[h[0],h[1],0,0],\r\n [0,0,h[0],h[1]]])\r\n C[i*2:(i+1)*2,:] = L @ T\r\n g_u[i*2:(i+1)*2] = np.array([-h[2], -h[2]]) -L @ t\r\n g_l[i*2:(i+1)*2] = np.array([-np.inf, -np.inf])\r\n\r\n acados_solver.constraints_set(j, \"C\", C, api='new')\r\n if j < N:\r\n acados_solver.constraints_set(j, \"D\", D, api='new')\r\n acados_solver.constraints_set(j, \"lg\", g_l)\r\n acados_solver.constraints_set(j, \"ug\", g_u)\r\n for j in range(N):\r\n yref = np.zeros(7)\r\n yref[:5] = np.array(ref[:,j])\r\n acados_solver.set(j, \"yref\", yref)\r\n\r\n acados_solver.set(N, \"yref\", np.array(ref[:,N]))\r\n status = acados_solver.solve()\r\n if status != 0:\r\n print(\"acados returned status {} in closed loop iteration {}.\".format(status, i))\r\n print(C@x0-g_u)\r\n x_pred = [acados_solver.get(j, \"x\") for j in range(N+1)]\r\n u = [acados_solver.get(j, \"u\") for j in range(N)]\r\n\r\n print(\"x_pred\",x_pred)\r\n state.state_update(u[0][0],u[0][1],test_param)\r\n\r\n mpc_plot.plot_mpc(test_path.cx, test_path.cy, test_path.cyaw, ref, x_pred, speed_profile)\r\n\r\n mpc_plot.draw_car(state.x, state.y, state.yaw, state.delta)\r\n plt.xlim(0, 50)\r\n plt.ylim(-15, 35)\r\n plt.title(\"Linear MPC, \" + \"v = \" + str(state.v) + \"\\n delta = \" + str(state.delta))\r\n # if status != 0:\r\n # plt.pause(10)\r\n plt.pause(0.001)\r\n x_rec.append([state.x, ref[0][0]])\r\n y_rec.append([state.y, ref[1][0]])\r\n v_rec.append([state.v, ref[2][0]])\r\n delta_rec.append([state.delta, ref[4][0]])\r\n yaw_rec.append([state.yaw, ref[3][0]])\r\n derdelta_rec.append([u[0][1]])\r\n # plt.show()\r\n\r\n# plt.cla()\r\n# plt.subplot(2,2,1)\r\n# plt.plot(np.array(x_rec)[:,0])\r\n# plt.plot(np.array(x_rec)[:,1])\r\n# plt.subplot(2,2,2)\r\n# plt.plot(np.array(delta_rec)[:,0])\r\n# plt.plot(np.array(delta_rec)[:,1])\r\n# plt.subplot(2,2,3)\r\n# plt.plot(np.array(yaw_rec)[:,0])\r\n# plt.plot(np.array(yaw_rec)[:,1])\r\n# plt.subplot(2,2,4)\r\n# plt.plot(np.array(derdelta_rec)[:,0])\r\nplt.show()\r\n", "repo_name": "runyuma/Planning_project", "sub_path": "nonlinear_mpc/test.py", "file_name": "test.py", "file_ext": "py", "file_size_in_byte": 5053, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "21", "api": [{"api_name": "path.test_path", "line_number": 12, "usage_type": "attribute"}, {"api_name": "path.get_velprofile", "line_number": 13, "usage_type": "call"}, {"api_name": "path.test_param", "line_number": 14, "usage_type": "attribute"}, {"api_name": "bicycle_model.ROBOT_STATE", "line_number": 21, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 22, "usage_type": "call"}, {"api_name": "obstacle.box", "line_number": 27, "usage_type": "call"}, {"api_name": "obstacle.box", "line_number": 28, "usage_type": "call"}, {"api_name": "obstacle.circle", "line_number": 30, "usage_type": "call"}, {"api_name": "bicycle_model.ROBOT_STATE", "line_number": 48, "usage_type": "call"}, {"api_name": "path.get_reftraj", "line_number": 51, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.cla", "line_number": 52, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 52, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 55, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 69, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 70, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 71, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 72, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 76, "usage_type": "call"}, {"api_name": "numpy.sin", "line_number": 76, "usage_type": "call"}, {"api_name": "numpy.cos", "line_number": 77, "usage_type": "call"}, {"api_name": "numpy.sin", "line_number": 78, "usage_type": "call"}, {"api_name": "numpy.cos", "line_number": 79, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 80, "usage_type": "call"}, {"api_name": "numpy.cos", "line_number": 80, "usage_type": "call"}, {"api_name": "numpy.sin", "line_number": 80, "usage_type": "call"}, {"api_name": "numpy.sin", "line_number": 81, "usage_type": "call"}, {"api_name": "numpy.cos", "line_number": 81, "usage_type": "call"}, {"api_name": "numpy.cos", "line_number": 82, "usage_type": "call"}, {"api_name": "numpy.sin", "line_number": 82, "usage_type": "call"}, {"api_name": "numpy.sin", "line_number": 83, "usage_type": "call"}, {"api_name": "numpy.cos", "line_number": 83, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 84, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 87, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 88, "usage_type": "call"}, {"api_name": "numpy.inf", "line_number": 88, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 96, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 97, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 100, "usage_type": "call"}, {"api_name": "mpc_plot.plot_mpc", "line_number": 111, "usage_type": "call"}, {"api_name": "mpc_plot.draw_car", "line_number": 113, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.xlim", "line_number": 114, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 114, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylim", "line_number": 115, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 115, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 116, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 116, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.pause", "line_number": 119, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 119, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 140, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 140, "usage_type": "name"}]} +{"seq_id": "17546197982", "text": "import numpy as np\nimport pandas as pd\nimport timeit as tm\nimport matplotlib.pyplot as plt\n\n\ndef main(nlist, iterations, repeats):\n global j\n numpy_dict = {}\n cramer_dict = {}\n for n in nlist:\n j = n\n numpy_times = []\n cramer_times = []\n for i in range (0, repeats):\n cra_time = tm.timeit(cramer, number=iterations)\n num_time = tm.timeit(numpy, number=iterations)\n print(\"\\nNumpy Linear Algorithm Method - \" + str(n) + \"x\" +str(n) +\" matrix run \" + str(i + 1) +\n \" with \" + str(iterations) +\n \" iterations completed in a time of \" + str(num_time))\n print(\"\\nCramer's Recursive Method - \" + str(n) + \"x\" +str(n) +\" matrix run \" + str(i + 1) +\n \" with \" + str(iterations) +\n \" iterations completed in a time of \" + str(cra_time))\n numpy_times.append(num_time)\n cramer_times.append(cra_time)\n\n\n numpy_sum = 0\n for t in numpy_times:\n numpy_sum = numpy_sum + t\n\n cramer_sum = 0\n for u in cramer_times:\n cramer_sum = cramer_sum + u\n\n num_avg = numpy_sum / len(numpy_times)\n cra_avg = cramer_sum / len(cramer_times)\n print(\"\\n\\nNumpy Linear Algorithm Method - Average time to complete one run of \" +\n str(iterations) + \" iterations for a random \" + str(n) +\n \"x\" + str(n) + \" matrix = \" + str(num_avg))\n print(\"\\nCramer's Recursive Method - Average time to complete one run of \" +\n str(iterations) + \" iterations for a random \" + str(n) +\n \"x\" + str(n) + \" matrix = \" + str(cra_avg) + \"\\n\\n\")\n numpy_dict.update({n: [n, num_avg]})\n cramer_dict.update({n: [n, cra_avg]})\n print(\"not quite finished - please wait\")\n print(numpy_dict)\n print(cramer_dict)\n dataFrame(numpy_dict, cramer_dict, nlist[0], nlist[-1])\n\n\ndef numpy():\n global j\n nmatrix = np.random.rand(j, j)\n imatrix = np.linalg.inv(nmatrix)\n return imatrix\n\ndef cramer():\n global j\n rmatrix = np.random.rand(j, j)\n cmatrix = inverse(rmatrix)\n return cmatrix\n\n\ndef getMinor(A, i, j):\n return np.delete(np.delete(A, i, 0), j, 1)\n\n\ndef determinant(A):\n if A.size is 4:\n result = A[0, 0] * A[1, 1] - A[1, 0] * A[0, 1]\n else:\n result = 0\n for k in range(A.shape[1]):\n result += ((-1) ** k) * A[0, k] * determinant(getMinor(A, 0, k))\n\n return result\n\ndef inverse(A):\n C = np.zeros(A.shape)\n for i in range(A.shape[0]):\n for j in range(A.shape[1]):\n C[i, j] = ((-1) ** (i + j)) * determinant(getMinor(A, i, j))\n\n detA = 0\n for j in range(A.shape[1]):\n detA += C[0, j] * A[0, j]\n\n if abs(detA) == 0:\n raise Exception('This matrix is singular!')\n else:\n imatrix = C.transpose() / detA\n return imatrix\n\n\ndef dataFrame(numpy_dict, cramer_dict, nmin, nmax):\n numpy_df = pd.DataFrame.from_dict(numpy_dict, orient='index', columns=['Size', 'Average Time'])\n print(numpy_df)\n cramer_df = pd.DataFrame.from_dict(cramer_dict, orient='index', columns=['Size', 'Average Time'])\n print(cramer_df)\n print(\"finished\")\n plt.plot('Size', 'Average Time', data=numpy_df, marker='D', markerfacecolor='skyblue', markersize=5, color='skyblue',\n linewidth=2, label='Numpy Linear Algorithm Method')\n plt.plot('Size', 'Average Time', data=cramer_df, marker='o', markerfacecolor='pink', markersize=5, color='pink',\n linewidth=2, label=\"Cramer's Recursive Method\")\n plt.legend()\n plt.xlabel(\"Size 'n' of square matrix\")\n plt.ylabel(\"Average Time (seconds)\")\n plt.xticks(np.arange(nmin, nmax+1, step=1.0))\n plt.show()\n\ndef setup():\n nvalues = []\n not_complete = True\n while len(nvalues) == 0:\n nval = input(\"Input the values of n that you wish to measure: \")\n try:\n nval = int(nval)\n nvalues.append(nval)\n except:\n print(\"\\nPlease only enter integer numbers.\")\n continue\n while len(nvalues) > 0:\n nvalues.sort()\n print(nvalues)\n nval = input(\"Continue to add values or enter 'start' begin measurements: \")\n try:\n nval = int(nval)\n try:\n nvalues.index(nval)\n continue\n except ValueError:\n nvalues.append(nval)\n except ValueError:\n if nval == 'start':\n break\n while not_complete:\n iterations = input(\"\\nInput the number of iterations that you wish to measure: \")\n repeats = input(\"\\nInput the number of repeats that you wish to measure: \")\n try:\n iterations = int(iterations)\n repeats = int(repeats)\n not_complete = False\n except ValueError:\n continue\n return nvalues, iterations, repeats\n\n\nif __name__ == '__main__':\n j = 0\n setup = setup()\n main(setup[0], setup[1], setup[2])\n", "repo_name": "Will-Harris00/computational-limits", "sub_path": "Matrix Inverse Computational Limits.py", "file_name": "Matrix Inverse Computational Limits.py", "file_ext": "py", "file_size_in_byte": 5022, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "timeit.timeit", "line_number": 16, "usage_type": "call"}, {"api_name": "timeit.timeit", "line_number": 17, "usage_type": "call"}, {"api_name": "numpy.random.rand", "line_number": 54, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 54, "usage_type": "attribute"}, {"api_name": "numpy.linalg.inv", "line_number": 55, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 55, "usage_type": "attribute"}, {"api_name": "numpy.random.rand", "line_number": 60, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 60, "usage_type": "attribute"}, {"api_name": "numpy.delete", "line_number": 66, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 80, "usage_type": "call"}, {"api_name": "pandas.DataFrame.from_dict", "line_number": 97, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 97, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame.from_dict", "line_number": 99, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 99, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 102, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 102, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 104, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 104, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 106, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 106, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 107, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 107, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 108, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 108, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xticks", "line_number": 109, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 109, "usage_type": "name"}, {"api_name": "numpy.arange", "line_number": 109, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.show", "line_number": 110, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 110, "usage_type": "name"}]} +{"seq_id": "5460054885", "text": "from selenium import webdriver\nfrom selenium.webdriver.common.proxy import Proxy, ProxyType\nimport time\nfrom selenium.webdriver.common.keys import Keys\n\nfrom selenium.webdriver.common.action_chains import ActionChains \nfrom selenium.webdriver.common.keys import Keys \n\ndriver = webdriver.Chrome('C:\\chromedriver.exe')\ndriver.get('https://www.redbubble.com/people/ilustrata/explore?page=1&sortOrder=recent')\nx=101\ny=1\n\nwhile(x<172):\t\n\ttry:\t\t\n\t\ta = driver.find_element_by_css_selector('#app > div > div.ds-theme-find-your-thing.App__dsWrapper--RyVET > main > div > div:nth-child(4) > div > div > div > div > a:nth-child('+str(y)+')')\n\t\tprint(a.get_attribute('href'))\n\t\ty=y+1\n\texcept:\n\t\ty=1\n\t\tx=x+1\n\t\tdriver.get('https://www.redbubble.com/people/ilustrata/explore?page=1&sortOrder=recent')\n\t\ttime.sleep(4)\n\t\tdriver.find_element_by_css_selector('#app > div > div.ds-theme-find-your-thing.App__dsWrapper--RyVET > main > div > div.styles__box--206r9.ExploreDesignsGrid__masonryGridContainer--ncG3n > div:nth-child(2) > div > div > div:nth-child('+str(x)+')').click()\n\n", "repo_name": "samsauhard/rb-link-collector", "sub_path": "rblink.py", "file_name": "rblink.py", "file_ext": "py", "file_size_in_byte": 1062, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "21", "api": [{"api_name": "selenium.webdriver.Chrome", "line_number": 9, "usage_type": "call"}, {"api_name": "selenium.webdriver", "line_number": 9, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 23, "usage_type": "call"}]} +{"seq_id": "29156692417", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nMódulo de condomínio\n\"\"\"\n\nimport ModSCC as cond\nimport ModCombine_csv\nimport ModEDA,ModDG\n\nfrom tqdm import tqdm\n\n\nclass ManageSCC():\n \n def __init__(self,dias=365,casas=100,graf_agend=0,lang=0,atualizar=False):\n self.dias = dias\n self.casas = casas\n self.graf_agend = graf_agend\n self.lang = lang\n \n if atualizar == True: # Gerar e combinar novas arquivos no SHC\n self.sim() # Gera arquivos do condomínio\n self.comb() # Concatena os dados em único arquivo csv \n self.EDA() # Analise os dados\n self.DG()\n \n def sim(self): \n for i in tqdm(range(self.dias)):\n cond.SCC(graf=self.graf_agend,lang=self.lang,dias=i,casas=self.casas) \n print('\\nSimulação terminada!')\n \n def comb(self):\n try:\n ModCombine_csv.combine_csv()\n print('\\nArquivos csv combinados!')\n except: \n print('\\nFalha na execução do módulo ModCombine_csv')\n \n def EDA(self):\n a=ModEDA.EDA()\n a.graf_eda()\n \n def DG(self):\n ModDG.Forecast_DG().Previsao_DG(1)\n \n#******************************************************************************\n# AREA DE TESTES\n#******************************************************************************\n# Extração de gráficos específicos\na=ManageSCC(atualizar=1)\n# a.sim()\n# a.comb()\n\n# a.sim()\n# a=ManageSCC()\n# a.comb()\n# a.EDA() \n# # a.DG()\n\n# Simulação geral\n# ManageSCC(atualizar=1)\n \n \n\n\n\n\n ", "repo_name": "jonathacosta/SmartGrid", "sub_path": "SCC-SHC/Codes/SCC/main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 1677, "program_lang": "python", "lang": "pt", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "21", "api": [{"api_name": "tqdm.tqdm", "line_number": 29, "usage_type": "call"}, {"api_name": "ModSCC.SCC", "line_number": 30, "usage_type": "call"}, {"api_name": "ModCombine_csv.combine_csv", "line_number": 35, "usage_type": "call"}, {"api_name": "ModEDA.EDA", "line_number": 41, "usage_type": "call"}, {"api_name": "ModDG.Forecast_DG", "line_number": 45, "usage_type": "call"}]} +{"seq_id": "24611708773", "text": "from ast import keyword\nimport base64\nfrom datetime import datetime\nimport io\nfrom pickle import GET\nfrom random import random\nfrom string import whitespace\nfrom flask import Flask, render_template, request, jsonify, session, url_for\nfrom flask_cors import CORS, cross_origin\nfrom firebase import firebase\nfrom werkzeug.utils import redirect\nimport requests\nimport matplotlib\nmatplotlib.use('Agg')\nfrom matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas\nfrom matplotlib.figure import Figure\nimport matplotlib.pyplot as plt\nfrom wordcloud import WordCloud\nimport pandas as pd\nimport urllib\nimport numpy as np\nimport babel\nimport time\n\napp = Flask(__name__)\napp.secret_key = 'secret'\nfb_app = firebase.FirebaseApplication('https://hotel-review-f7091-default-rtdb.asia-southeast1.firebasedatabase.app/', authentication=None)\ndisplaymessage =''\nhotels = ['Campbell Inn', 'Grand Hyatt Singapore', 'Hotel 81 Bugis', 'Ibis Styles Singapore on Macpherson', 'JEN Singapore Orchardgateway by Shangri-La', 'K Hotel 14', 'Lion Peak Hotel Raffles', 'Shangri-La Singapore', 'Studio M Hotel', 'Vintage Inn']\nhotelswebsite = {'Campbell Inn': 'https://nomadrest.com/campbell-inn-singapore/', 'K Hotel 14':'https://khotel.co/k-hotel-14/', 'Grand Hyatt Singapore':'https://www.hyatt.com/en-US/hotel/singapore/grand-hyatt-singapore/sinrs', 'Hotel 81 Bugis':'https://www.hotel81.com.sg/hotel81-bugis.shtml', 'Ibis Styles Singapore on Macpherson':'https://all.accor.com/hotel/9411/index.en.shtml?utm_campaign=seo+maps&utm_medium=seo+maps&utm_source=google+Maps&y_source=1_MTUzNjI0MDYtNzE1LWxvY2F0aW9uLndlYnNpdGU%3D', 'JEN Singapore Orchardgateway by Shangri-La':'https://www.shangri-la.com/hotels/jen/','Lion Peak Hotel Raffles':'https://populoushotel.zoombookdirect.com/?utm_source=googlemybusiness&utm_medium=organic&utm_campaign=google_my_business', 'Shangri-La Singapore':'https://www.shangri-la.com/en/singapore/shangrila/', 'Studio M Hotel':'https://www.millenniumhotels.com/en/singapore/studio-m-hotel/', 'Vintage Inn':'http://www.vintageinn.sg'}\n\n\n\"\"\" def plot_wordcloud(data):\n uniquewords = set(data)\n uniquedict={}\n freqlist = []\n for words in uniquewords:\n freqlist.append(data.count(words))\n uniquedict['words'] = list(uniquewords)\n uniquedict['freq'] = freqlist\n dfm = pd.DataFrame(uniquedict)\n d = {a: x for a, x in dfm.values}\n wc = WordCloud(background_color='white', width=1000,height=600)\n wc.fit_words(d)\n return wc.to_image() \"\"\"\n\ndef green_color_func(word, font_size, position,orientation,random_state=None, **kwargs):\n return(\"hsl(155,67%%, %d%%)\" % np.random.randint(45,51))\n\ndef red_color_func(word, font_size, position,orientation,random_state=None, **kwargs):\n return(\"hsl(2,80%%, %d%%)\" % np.random.randint(45,51))\n\n@app.template_filter()\ndef format_datetime(value):\n \n return (datetime.strptime(value,'%B %Y')).strftime('%B %Y')\n\n@app.route('/', methods=('GET','POST'))\ndef main(): \n if request.method == 'POST':\n if request.form['btn_identifier'] == 'view_button':\n messages = []\n hotel = request.form['reviews']\n messages.append({'hotel':hotel})\n session['hotel'] = messages\n #return render_template(\"reviews.html\", hotels = messages)\n return redirect(url_for('reviewsPage'))\n\n #elif request.method == 'GET':\n #displaymessage = session['message']\n\n return render_template(\"home.html\", hotels = hotels)\n\n@app.route('/reviews', methods=('GET','POST'))\ndef reviewsPage():\n if request.method == \"POST\":\n return redirect(url_for('reviewsPage'))\n\n elif request.method =='GET':\n headings = (\"Title\", \"Score\", \"Date\", \"Review\")\n hotel = session['hotel'][0]['hotel']\n reviewdata = fb_app.get('/'+hotel,None)\n total = 0\n for rating in reviewdata:\n total += int(reviewdata[rating]['reviewRating'])/10\n average = \"{:.2f}\".format(total/len(reviewdata))\n return render_template('reviews.html', hotels = hotel, reviewdata = reviewdata, headings = headings, hotelwebsite = hotelswebsite[hotel], average = average)\n\n\n@app.route('/refresh', methods=('GET','POST'))\ndef refreshData():\n displaymessage = ''\n if request.method == \"POST\":\n hotel = request.form['reviewstorefresh']\n messages = []\n messages.append(hotel)\n api_url = 'http://127.0.0.1:5000/scrapeone'\n data = {\"query_string\" : hotel}\n response = requests.post(api_url,json=data)\n displaymessage = hotel + ' data has been refreshed.'\n #return redirect(url_for('refreshData'))\n\n #elif request.method =='GET':\n return render_template('refreshdata.html', hotels = hotels, displaymessage = displaymessage)\n\n\n\n@app.route('/makecloud', methods=('GET','POST'))\ndef cloudpage():\n if request.method == \"POST\":\n session['keyword'] = ''\n messages = []\n hotel = request.form['hotelname']\n messages.append({'hotel':hotel})\n session['hotel'] = messages\n '''api_url = 'http://127.0.0.1:5002/api/keywords'\n data = {\"query_string\" : hotel}\n response = requests.post(api_url,json=data)\n session['keyword'] = (response.json())['keyword']\n print(session['keyword'])'''\n return redirect(url_for('hotelcloud'))\n\n return render_template('viewcloud.html', hotels = hotels)\n\n\n@app.route('/hotelcloud', methods=('GET','POST'))\ndef hotelcloud():\n if request.method == \"POST\":\n \n return redirect(url_for('reviewsPage'))\n\n elif request.method =='GET':\n hotel = session['hotel'][0]['hotel']\n api_url = 'http://127.0.0.1:5002/api/keywords'\n data = {\"query_string\" : hotel}\n response = requests.post(api_url,json=data)\n keyword = (response.json())['keyword']\n \n\n\n reviewdata = fb_app.get('/'+hotel,None)\n total = 0\n for rating in reviewdata:\n total += int(reviewdata[rating]['reviewRating'])/10\n average = \"{:.2f}\".format(total/len(reviewdata))\n img = io.BytesIO()\n #plot_wordcloud(data=keyword).save(img, format='PNG')\n #fig = WordCloud(collocations = False, background_color = 'white').generate(keyword)\n #plt.imshow(fig, interpolation='bilinear')\n #plt.axis('off')\n #output = io.BytesIO()\n #plt.savefig(output, format='png')\n #data = base64.b64encode(output.getbuffer()).decode(\"ascii\")= base64.b64encode(img.getvalue()).decode(\n #data = base64.b64encode(img.read())\n #data = data.replace(\"b'\", \"\") \n #data = data.replace(\"'\", \"\")\n #basedata = 'data:image/png;base64,'+ data\n try:\n stop_words = [\"hostel\",\"hotel\",\"thing\"]\n wordcloud = WordCloud(\n background_color=\"white\",max_words=1000,stopwords=stop_words)\n wordcloud.generate(keyword)\n if float(average) > 3.5:\n wordcloud.recolor(color_func=green_color_func)\n else:\n wordcloud.recolor(color_func=red_color_func)\n plt.imshow(wordcloud, interpolation=\"bilinear\")\n plt.axis(\"off\")\n image = io.BytesIO()\n plt.savefig(image, format=\"png\")\n image.seek(0)\n string = base64.b64encode(image.read())\n image_64 = \"data:image/png;base64,\" + urllib.parse.quote_plus(string)\n session['keyword'] = ''\n return render_template('cloud.html',img_data = image_64, average = average)\n except ValueError:\n return None\n #return render_template('cloud.html',keyword = data,img_data = data)\n\n return render_template('cloud.html', hotels = hotel,keyword = keyword,average = average)\n\n\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n\n\n#export FLASK_APP=main\n#flask run --port 5001", "repo_name": "Jemerylim/HotelReviewApp", "sub_path": "main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 7809, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "matplotlib.use", "line_number": 14, "usage_type": "call"}, {"api_name": "flask.Flask", "line_number": 25, "usage_type": "call"}, {"api_name": "firebase.firebase.FirebaseApplication", "line_number": 27, "usage_type": "call"}, {"api_name": "firebase.firebase", "line_number": 27, "usage_type": "name"}, {"api_name": "numpy.random.randint", "line_number": 48, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 48, "usage_type": "attribute"}, {"api_name": "numpy.random.randint", "line_number": 51, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 51, "usage_type": "attribute"}, {"api_name": "datetime.datetime.strptime", "line_number": 56, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 56, "usage_type": "name"}, {"api_name": "flask.request.method", "line_number": 60, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 60, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 61, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 61, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 63, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 63, "usage_type": "name"}, {"api_name": "flask.session", "line_number": 65, "usage_type": "name"}, {"api_name": "werkzeug.utils.redirect", "line_number": 67, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 67, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 72, "usage_type": "call"}, {"api_name": "flask.request.method", "line_number": 76, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 76, "usage_type": "name"}, {"api_name": "werkzeug.utils.redirect", "line_number": 77, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 77, "usage_type": "call"}, {"api_name": "flask.request.method", "line_number": 79, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 79, "usage_type": "name"}, {"api_name": "flask.session", "line_number": 81, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 87, "usage_type": "call"}, {"api_name": "flask.request.method", "line_number": 93, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 93, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 94, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 94, "usage_type": "name"}, {"api_name": "requests.post", "line_number": 99, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 104, "usage_type": "call"}, {"api_name": "flask.request.method", "line_number": 110, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 110, "usage_type": "name"}, {"api_name": "flask.session", "line_number": 111, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 113, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 113, "usage_type": "name"}, {"api_name": "flask.session", "line_number": 115, "usage_type": "name"}, {"api_name": "werkzeug.utils.redirect", "line_number": 121, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 121, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 123, "usage_type": "call"}, {"api_name": "flask.request.method", "line_number": 128, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 128, "usage_type": "name"}, {"api_name": "werkzeug.utils.redirect", "line_number": 130, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 130, "usage_type": "call"}, {"api_name": "flask.request.method", "line_number": 132, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 132, "usage_type": "name"}, {"api_name": "flask.session", "line_number": 133, "usage_type": "name"}, {"api_name": "requests.post", "line_number": 136, "usage_type": "call"}, {"api_name": "ast.keyword", "line_number": 137, "usage_type": "name"}, {"api_name": "io.BytesIO", "line_number": 146, "usage_type": "call"}, {"api_name": "wordcloud.WordCloud", "line_number": 160, "usage_type": "call"}, {"api_name": "wordcloud.generate", "line_number": 162, "usage_type": "call"}, {"api_name": "ast.keyword", "line_number": 162, "usage_type": "argument"}, {"api_name": "wordcloud.recolor", "line_number": 164, "usage_type": "call"}, {"api_name": "wordcloud.recolor", "line_number": 166, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 167, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 167, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.axis", "line_number": 168, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 168, "usage_type": "name"}, {"api_name": "io.BytesIO", "line_number": 169, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 170, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 170, "usage_type": "name"}, {"api_name": "base64.b64encode", "line_number": 172, "usage_type": "call"}, {"api_name": "urllib.parse.quote_plus", "line_number": 173, "usage_type": "call"}, {"api_name": "urllib.parse", "line_number": 173, "usage_type": "attribute"}, {"api_name": "flask.session", "line_number": 174, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 175, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 180, "usage_type": "call"}, {"api_name": "ast.keyword", "line_number": 180, "usage_type": "name"}]} +{"seq_id": "14279585639", "text": "_author__ = 'bdm4'\r\n\r\nimport requests, json\r\n\r\n\r\nauthorize_url = \"https://account.ezeep.com/oauth/authorize\"\r\ntoken_url = \"https://account.ezeep.com/oauth/access_token/\"\r\n\r\n#callback url specified when the application was defined\r\ncallback_uri = \"https://www.ezeep.com\"\r\n\r\n\r\n#client (application) credentials\r\nclient_id = 'put your client id'\r\nclient_secret = \"put your client secret\"\r\n#step A - simulate a request from a browser on the authorize_url - will return an authorization code after the user is\r\n# prompted for credentials.\r\n\r\nauthorization_redirect_url = authorize_url + '?response_type=code&client_id=' + client_id + '&redirect_uri=' + callback_uri\r\n\r\n\r\nprint(\"go to the following url on the browser and enter the code from the returned url: \")\r\nprint(\"--- \" + authorization_redirect_url + \" ---\")\r\nauthorization_code = input('code: ')\r\n\r\n# step -turn the authorization code into a access token, etc\r\ndata = {'grant_type': 'authorization_code', 'code': authorization_code}\r\nprint(\"requesting access token\")\r\naccess_token_response = requests.post(token_url, data=data, verify=False, allow_redirects=False, auth=(client_id, client_secret))\r\n\r\nprint(\"response\")\r\nprint(access_token_response.headers)\r\nprint('body: ' + access_token_response.text)\r\n\r\n# we can now use the access_token as much as we want to access protected resources.\r\ntokens = json.loads(access_token_response.text)\r\naccess_token = tokens['access_token']\r\nprint(\"access token: \" + access_token)\r\n\r\n\r\n", "repo_name": "wickywaa/ezeep", "sub_path": "oauth.py", "file_name": "oauth.py", "file_ext": "py", "file_size_in_byte": 1477, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "21", "api": [{"api_name": "requests.post", "line_number": 29, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 36, "usage_type": "call"}]} +{"seq_id": "33801948597", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport matplotlib.pyplot as plt\nimport numpy as np\n\ns_open, s_close = np.loadtxt('./data/1.csv', skiprows=1, usecols=(1, 4), delimiter=',', unpack=True)\nchange = s_close - s_open\nyesterday = change[:-1]\ntoday = change[1:]\n\nfig = plt.figure()\nax = fig.add_subplot(111)\nax.scatter(yesterday, today, s=10, marker='s', c='g')\nplt.show()", "repo_name": "Lovecanon/ProfessionalPython", "sub_path": "Matplotlib/Lesson1.py", "file_name": "Lesson1.py", "file_ext": "py", "file_size_in_byte": 378, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "numpy.loadtxt", "line_number": 6, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 11, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 11, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 14, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 14, "usage_type": "name"}]} +{"seq_id": "2161200280", "text": "import sqlite3\n\n# Create sqlite database connection\nconn = sqlite3.connect('details.db')\ncur = conn.cursor()\n\n# Create database to store customer details\n\n# cur.execute(\"\"\"\n# CREATE TABLE customer_details(\n# email text,\n# clientId text,\n# secret text,\n# ref text\n# )\"\"\")\n\n# Delete all customer entries from database\n# cur.execute(\"DELETE from customer_details\")\n\n# Delete entire table\n# cur.execute(\"DROP TABLE customer_details\")\n\n\nconn.commit()\nconn.close()\n\n# Create a customer record in database\n\n\ndef create_record(email, clientId, secret_number, ref):\n\n conn = sqlite3.connect('details.db')\n cur = conn.cursor()\n\n cur.execute('INSERT INTO customer_details VALUES(:email,:clientId,:secret_number,:ref)',\n {\n 'email': email,\n 'clientId': clientId,\n 'secret_number': secret_number,\n 'ref': ref\n })\n\n conn.commit()\n conn.close()\n\n# Fetch image refernces from database\n\n\ndef fetch_references():\n refernces = []\n conn = sqlite3.connect('details.db')\n cur = conn.cursor()\n\n cur.execute(\"SELECT ref FROM customer_details\")\n rows = cur.fetchall()\n\n for row in rows:\n print(row[0])\n refernces.append(row[0])\n print()\n\n conn.commit()\n conn.close()\n\n return refernces\n\n# Fetch customer details for a match\n\n\ndef fetch_payment_details(img_ref):\n conn = sqlite3.connect('details.db')\n cur = conn.cursor()\n\n cur.execute(\"SELECT * FROM customer_details WHERE ref=?\", (img_ref,))\n row = cur.fetchall()\n print('Customer details are --------')\n print(row)\n\n conn.commit()\n conn.close()\n return row", "repo_name": "MeetJainAi/PAYMENT-USING-FACIAL-RECOGNITION", "sub_path": "details_db.py", "file_name": "details_db.py", "file_ext": "py", "file_size_in_byte": 1696, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "21", "api": [{"api_name": "sqlite3.connect", "line_number": 4, "usage_type": "call"}, {"api_name": "sqlite3.connect", "line_number": 32, "usage_type": "call"}, {"api_name": "sqlite3.connect", "line_number": 51, "usage_type": "call"}, {"api_name": "sqlite3.connect", "line_number": 71, "usage_type": "call"}]} +{"seq_id": "9097179495", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport sys\nimport os\nimport yaml\nfrom PyQt5 import QtCore, QtWidgets, QtGui\nfrom source.gui.ui_main_window import MainWindow\nimport atexit\nfrom signal import signal, SIGINT, SIG_DFL\nfrom os import kill\nfrom multiprocessing import Process\ntry:\n from server.EliteQuant import tradingengine_ # windows\nexcept ImportError:\n from server.libelitequant import tradingengine_ # linux\n\n# https://stackoverflow.com/questions/4938723/what-is-the-correct-way-to-make-my-pyqt-application-quit-when-killed-from-the-co\nsignal(SIGINT, SIG_DFL)\n\ndef main():\n config_server = None\n try:\n path = os.path.abspath(os.path.dirname(__file__))\n config_file = os.path.join(path, 'config_server.yaml')\n with open(os.path.expanduser(config_file), encoding='utf8') as fd:\n config_server = yaml.load(fd)\n except IOError:\n print(\"config_server.yaml is missing\")\n\n config_client = None\n try:\n path = os.path.abspath(os.path.dirname(__file__))\n config_file = os.path.join(path, 'config_client.yaml')\n with open(os.path.expanduser(config_file), encoding='utf8') as fd:\n config_client = yaml.load(fd)\n except IOError:\n print(\"config_client.yaml is missing\")\n\n lang_dict = None\n font = None\n try:\n path = os.path.abspath(os.path.dirname(__file__))\n config_file = os.path.join(path, 'language/en/live_text.yaml')\n font = QtGui.QFont('Microsoft Sans Serif', 10)\n if config_client['language'] == 'cn':\n config_file = os.path.join(path, 'language/cn/live_text.yaml')\n font = QtGui.QFont(u'微软雅黑', 10)\n with open(os.path.expanduser(config_file), encoding='utf8') as fd:\n lang_dict = yaml.load(fd)\n lang_dict['font'] = font\n except IOError:\n print(\"live_text.yaml is missing\")\n\n app = QtWidgets.QApplication(sys.argv)\n mainWindow = MainWindow(config_server, config_client, lang_dict)\n\n if config_client['theme'] == 'dark':\n import qdarkstyle\n app.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5())\n\n mainWindow.showMaximized()\n\n sys.exit(app.exec_())\n\ndef start_server():\n print('Running python server.')\n server = tradingengine_()\n server.run()\n\ndef stop_server():\n global server_process\n kill(server_process.pid, SIGINT)\n\nserver_process = None\n\nif __name__ == \"__main__\":\n server_process = Process(target=start_server)\n server_process.start()\n atexit.register(stop_server)\n\n main()", "repo_name": "timothyyu/ml_monorepo", "sub_path": "EliteQuant_Python/source/live_engine.py", "file_name": "live_engine.py", "file_ext": "py", "file_size_in_byte": 2551, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 59, "dataset": "github-code", "pt": "21", "api": [{"api_name": "signal.signal", "line_number": 18, "usage_type": "call"}, {"api_name": "signal.SIGINT", "line_number": 18, "usage_type": "argument"}, {"api_name": "signal.SIG_DFL", "line_number": 18, "usage_type": "argument"}, {"api_name": "os.path.abspath", "line_number": 23, "usage_type": "call"}, {"api_name": "os.path", "line_number": 23, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 23, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 24, "usage_type": "call"}, {"api_name": "os.path", "line_number": 24, "usage_type": "attribute"}, {"api_name": "os.path.expanduser", "line_number": 25, "usage_type": "call"}, {"api_name": "os.path", "line_number": 25, "usage_type": "attribute"}, {"api_name": "yaml.load", "line_number": 26, "usage_type": "call"}, {"api_name": "os.path.abspath", "line_number": 32, "usage_type": "call"}, {"api_name": "os.path", "line_number": 32, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 32, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 33, "usage_type": "call"}, {"api_name": "os.path", "line_number": 33, "usage_type": "attribute"}, {"api_name": "os.path.expanduser", "line_number": 34, "usage_type": "call"}, {"api_name": "os.path", "line_number": 34, "usage_type": "attribute"}, {"api_name": "yaml.load", "line_number": 35, "usage_type": "call"}, {"api_name": "os.path.abspath", "line_number": 42, "usage_type": "call"}, {"api_name": "os.path", "line_number": 42, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 42, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 43, "usage_type": "call"}, {"api_name": "os.path", "line_number": 43, "usage_type": "attribute"}, {"api_name": "PyQt5.QtGui.QFont", "line_number": 44, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 44, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 46, "usage_type": "call"}, {"api_name": "os.path", "line_number": 46, "usage_type": "attribute"}, {"api_name": "PyQt5.QtGui.QFont", "line_number": 47, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 47, "usage_type": "name"}, {"api_name": "os.path.expanduser", "line_number": 48, "usage_type": "call"}, {"api_name": "os.path", "line_number": 48, "usage_type": "attribute"}, {"api_name": "yaml.load", "line_number": 49, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QApplication", "line_number": 54, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets", "line_number": 54, "usage_type": "name"}, {"api_name": "sys.argv", "line_number": 54, "usage_type": "attribute"}, {"api_name": "source.gui.ui_main_window.MainWindow", "line_number": 55, "usage_type": "call"}, {"api_name": "qdarkstyle.load_stylesheet_pyqt5", "line_number": 59, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 63, "usage_type": "call"}, {"api_name": "server.EliteQuant", "line_number": 67, "usage_type": "name"}, {"api_name": "server.libelitequant.tradingengine_", "line_number": 67, "usage_type": "call"}, {"api_name": "server.EliteQuant.run", "line_number": 68, "usage_type": "call"}, {"api_name": "server.EliteQuant", "line_number": 68, "usage_type": "name"}, {"api_name": "os.kill", "line_number": 72, "usage_type": "call"}, {"api_name": "signal.SIGINT", "line_number": 72, "usage_type": "argument"}, {"api_name": "multiprocessing.Process", "line_number": 77, "usage_type": "call"}, {"api_name": "atexit.register", "line_number": 79, "usage_type": "call"}]} +{"seq_id": "11162685237", "text": "# import necessary modules\nimport tensorflow as tf\nimport pandas as pd\nimport tkinter as tk\n\n#new object of tk class\nmain_window = tk.Tk()\n\n# title of our window\nmain_window.title(\"ConcreForce\")\n\n# size, color of the window\nmain_window.geometry(\"1200x800\")\nmain_window.config(bg = \"#000000\")\n\n# sample label\nlabel = tk.Label(main_window, text = \"ConcreForce - AI Concrete Strength Predictor\", font=(\"Arial\", 22))\nlabel.pack()\n\n# label for cement\nlabel_cement = tk.Label(main_window, text=\"Cement (kg/m^3):\", font=(\"Arial\", 14))\nlabel_cement.place(x=100, y=100)\n\n# input for cement\ncement_input = tk.DoubleVar()\n\n# entry widget for the input\ncement_entry = tk.Entry(main_window, textvariable=cement_input, font=(\"Arial\", 14))\ncement_entry.place(x=400, y=100)\n\n# label for slag\nlabel_slag = tk.Label(main_window, text=\"Slag (kg/m^3):\", font=(\"Arial\", 14))\nlabel_slag.place(x=100, y=150)\n\n# input for slag\nslag_input = tk.DoubleVar()\n# entry widget\nslag_entry = tk.Entry(main_window, textvariable=slag_input, font=(\"Arial\", 14))\nslag_entry.place(x= 400, y= 150)\n\n# label for fly ash\nlabel_fly_ash = tk.Label(main_window, text=\"Fly ash (kg/m^3):\", font=(\"Arial\", 14))\nlabel_fly_ash.place(x=100, y=200)\n\n# input for flyash\nfly_ash_input = tk.DoubleVar()\n# entry widget\nfly_ash_entry = tk.Entry(main_window, textvariable=fly_ash_input, font=(\"Arial\", 14))\nfly_ash_entry.place(x= 400, y= 200)\n\n# label for water\nlabel_water = tk.Label(main_window, text=\"Water (kg/m^3):\", font=(\"Arial\", 14))\nlabel_water.place(x=100, y=250)\n\n# input for water\nwater_input = tk.DoubleVar()\n# entry widget\nwater_entry = tk.Entry(main_window, textvariable=water_input, font=(\"Arial\", 14))\nwater_entry.place(x= 400, y= 250)\n\n# label for superplasticizer\nlabel_superplasticizer = tk.Label(main_window, text=\"Superplasticizer (kg/m^3):\", font=(\"Arial\", 14))\nlabel_superplasticizer.place(x=100, y=300)\n\n# input for superplasticizer\nsuperplasticizer_input = tk.DoubleVar()\n# entry widget\nsuperplasticizer_entry = tk.Entry(main_window, textvariable=superplasticizer_input, font=(\"Arial\", 14))\nsuperplasticizer_entry.place(x= 400, y= 300)\n\n# label for coarse aggregate\nlabel_coarse_aggregate = tk.Label(main_window, text=\"Coarse Aggregate (kg/m^3):\", font=(\"Arial\", 14))\nlabel_coarse_aggregate.place(x=100, y=350)\n\n# input for coarse_aggregate\ncoarse_aggregate_input = tk.DoubleVar()\n# entry widget\ncoarse_aggregate_entry = tk.Entry(main_window, textvariable=coarse_aggregate_input, font=(\"Arial\", 14))\ncoarse_aggregate_entry.place(x= 400, y= 350)\n\n\n# Input label for fine aggregate\nlabel_fine_aggregate = tk.Label(main_window, text=\"Fine Aggregate (kg/m^3):\", font=(\"Arial\", 14))\nlabel_fine_aggregate.place(x=100, y=400)\n\n# input for fine_aggregate\nfine_aggregate_input = tk.DoubleVar()\n# entry widget\nfine_aggregate_entry = tk.Entry(main_window, textvariable=fine_aggregate_input, font=(\"Arial\", 14))\nfine_aggregate_entry.place(x= 400, y= 400)\n\n# Input label for age\nlabel_age = tk.Label(main_window, text=\"Age (days):\", font=(\"Arial\", 14))\nlabel_age.place(x=100, y=450)\n\n# input for age\nage_input = tk.DoubleVar()\n# entry widget\nage_entry = tk.Entry(main_window, textvariable=age_input, font=(\"Arial\", 14))\nage_entry.place(x= 400, y= 450)\n\n# load the data\ndata = pd.read_csv('Concrete_Data.csv')\n\n# splitting the data into input and output variables\nx = data.drop(\"csMPa\", axis = 1)\ny = data[\"csMPa\"]\n\n\n\n\nfrom sklearn.model_selection import train_test_split\n\nx_train, x_test, y_train, y_test = train_test_split(x, y, train_size=0.80, shuffle=True, random_state=42)\n\n# preprocessing (normalizing the data)\n# we'll see if we need this later\n# (we dont, normalizing it made it worse by a mae of 2)\n\n#making the model\n\nmodel = tf.keras.Sequential([\n tf.keras.layers.Dense(50, activation = \"relu\"),\n tf.keras.layers.Dense(40, activation = \"relu\"),\n tf.keras.layers.Dense(30, activation = \"relu\"),\n tf.keras.layers.Dense(15, activation = \"relu\"),\n tf.keras.layers.Dense(10, activation = \"relu\"),\n tf.keras.layers.Dense(5, activation = \"relu\"),\n tf.keras.layers.Dense(1, activation = tf.keras.activations.linear)\n])\n\n# compile the model\n\nmodel.compile(loss=tf.keras.losses.mean_absolute_error,\n optimizer=tf.keras.optimizers.Adam(learning_rate= 0.001),\n metrics=[\"mae\"])\n\n# fit the model\n\n#history = model.fit(x_train, y_train, epochs=300, verbose=1, validation_data=(x_test, y_test) )\n\n#model.save('concrete_strength_prediction')\n\nmodel = tf.keras.models.load_model('concrete_strength_prediction.h5')\n\n\noutput_label = tk.Label(main_window)\noutput_label.place(x = 200, y = 600)\noutput_label.config(width=50, height=2)\n\n\n\ndef display ():\n user_data = pd.DataFrame({'cement': cement_input.get(),\n 'slag': slag_input.get(),\n 'flyash': fly_ash_input.get(),\n 'water': water_input.get(),\n 'superplasticizer': superplasticizer_input.get(),\n 'coarseaggregate': coarse_aggregate_input.get(),\n 'fineaggregate': fine_aggregate_input.get(),\n 'age': age_input.get()},\n index=['0'])\n output_label.configure(text=\"The estimation is \" + \"{:.3f}\".format(float(model.predict(user_data))) + \" MegaPascal\", font= (\"Arial\", 15))\n\nestimate_button = tk.Button(main_window, text=\"Estimate!\",font=\"Arial\", command=display, width= 10, height= 5)\nestimate_button.place(x = 900, y = 300 )\nmain_window.mainloop()\n\n\n", "repo_name": "beweme11/ConcreForce", "sub_path": "main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 5545, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "tkinter.Tk", "line_number": 7, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 17, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 21, "usage_type": "call"}, {"api_name": "tkinter.DoubleVar", "line_number": 25, "usage_type": "call"}, {"api_name": "tkinter.Entry", "line_number": 28, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 32, "usage_type": "call"}, {"api_name": "tkinter.DoubleVar", "line_number": 36, "usage_type": "call"}, {"api_name": "tkinter.Entry", "line_number": 38, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 42, "usage_type": "call"}, {"api_name": "tkinter.DoubleVar", "line_number": 46, "usage_type": "call"}, {"api_name": "tkinter.Entry", "line_number": 48, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 52, "usage_type": "call"}, {"api_name": "tkinter.DoubleVar", "line_number": 56, "usage_type": "call"}, {"api_name": "tkinter.Entry", "line_number": 58, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 62, "usage_type": "call"}, {"api_name": "tkinter.DoubleVar", "line_number": 66, "usage_type": "call"}, {"api_name": "tkinter.Entry", "line_number": 68, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 72, "usage_type": "call"}, {"api_name": "tkinter.DoubleVar", "line_number": 76, "usage_type": "call"}, {"api_name": "tkinter.Entry", "line_number": 78, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 83, "usage_type": "call"}, {"api_name": "tkinter.DoubleVar", "line_number": 87, "usage_type": "call"}, {"api_name": "tkinter.Entry", "line_number": 89, "usage_type": "call"}, {"api_name": "tkinter.Label", "line_number": 93, "usage_type": "call"}, {"api_name": "tkinter.DoubleVar", "line_number": 97, "usage_type": "call"}, {"api_name": "tkinter.Entry", "line_number": 99, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 103, "usage_type": "call"}, {"api_name": "sklearn.model_selection.train_test_split", "line_number": 114, "usage_type": "call"}, {"api_name": "tensorflow.keras.Sequential", "line_number": 122, "usage_type": "call"}, {"api_name": "tensorflow.keras", "line_number": 122, "usage_type": "attribute"}, {"api_name": "tensorflow.keras.layers.Dense", "line_number": 123, "usage_type": "call"}, {"api_name": "tensorflow.keras", "line_number": 123, "usage_type": "attribute"}, {"api_name": "tensorflow.keras.layers.Dense", "line_number": 124, "usage_type": "call"}, {"api_name": "tensorflow.keras", "line_number": 124, "usage_type": "attribute"}, {"api_name": "tensorflow.keras.layers.Dense", "line_number": 125, "usage_type": "call"}, {"api_name": "tensorflow.keras", "line_number": 125, "usage_type": "attribute"}, {"api_name": "tensorflow.keras.layers.Dense", "line_number": 126, "usage_type": "call"}, {"api_name": "tensorflow.keras", "line_number": 126, "usage_type": "attribute"}, {"api_name": "tensorflow.keras.layers.Dense", "line_number": 127, "usage_type": "call"}, {"api_name": "tensorflow.keras", "line_number": 127, "usage_type": "attribute"}, {"api_name": "tensorflow.keras.layers.Dense", "line_number": 128, "usage_type": "call"}, {"api_name": "tensorflow.keras", "line_number": 128, "usage_type": "attribute"}, {"api_name": "tensorflow.keras.layers.Dense", "line_number": 129, "usage_type": "call"}, {"api_name": "tensorflow.keras", "line_number": 129, "usage_type": "attribute"}, {"api_name": "tensorflow.keras", "line_number": 134, "usage_type": "attribute"}, {"api_name": "tensorflow.keras.optimizers.Adam", "line_number": 135, "usage_type": "call"}, {"api_name": "tensorflow.keras", "line_number": 135, "usage_type": "attribute"}, {"api_name": "tensorflow.keras.models.load_model", "line_number": 144, "usage_type": "call"}, {"api_name": "tensorflow.keras", "line_number": 144, "usage_type": "attribute"}, {"api_name": "tkinter.Label", "line_number": 147, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 154, "usage_type": "call"}, {"api_name": "tkinter.Button", "line_number": 165, "usage_type": "call"}]} +{"seq_id": "5662326741", "text": "import random\nimport smtplib\nimport datetime as dt\nimport pandas\nfrom dotenv import load_dotenv\nimport os\n\n\ndef send_email(to_email, body):\n load_dotenv()\n my_email = os.getenv(\"my_email\")\n password = os.getenv(\"password\")\n with smtplib.SMTP(\"smtp.gmail.com\", 587) as connection:\n connection.starttls()\n connection.login(user=my_email, password=password)\n connection.sendmail(\n from_addr=my_email,\n to_addrs=to_email,\n msg=f\"Subject: Happy Birthday!\\n\\n {body}\")\n\n\n# 1. Update the birthdays.csv\ndef update_birthdays():\n new_dict = {\n \"name\": [\"Aaron\", \"Tori\", \"Bentley\", \"Tucker\", \"Minnie Mouse\"],\n \"email\": [\"aboyles05@gmail.com\", \"aboyles05@gmail.com\", \"aboyles05@gmail.com\", \"aboyles05@gmail.com\",\n \"aboyles05@gmail.com\"],\n \"year\": [1990, 1994, 2016, 2016, 2019],\n \"month\": [10, 9, 1, 2, 12],\n \"day\": [15, 25, 6, 14, 29]\n }\n new_frame = pandas.DataFrame(new_dict)\n new_frame.to_csv(\"birthdays.csv\", mode=\"a\", index=False, header=False)\n\n\n# 2. Check if today matches a birthday in the birthdays.csv\ndata = pandas.read_csv(\"birthdays.csv\")\nnow = dt.datetime.now()\nmonth = now.month\nday = now.day\ncurrent_birthdays = data[(data[\"month\"] == month) & (data[\"day\"] == day)]\nbirthday_dict = {data_row[\"name\"]: data_row.email for (index, data_row) in current_birthdays.iterrows()}\nPLACEHOLDER = \"[NAME]\"\nfor person in birthday_dict:\n # create birthday letters\n random_num = random.randint(1, 3)\n with open(f\"letter_templates/letter_{random_num}.txt\") as letter:\n letter_content = letter.read()\n birthday_letter = letter_content.replace(PLACEHOLDER, person)\n # Send the letter generated in step 3 to that person's email address.\n send_email(to_email=birthday_dict.get(person), body=birthday_letter)\n\n", "repo_name": "aaronb05/birthday_wisher", "sub_path": "main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 1854, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "dotenv.load_dotenv", "line_number": 10, "usage_type": "call"}, {"api_name": "os.getenv", "line_number": 11, "usage_type": "call"}, {"api_name": "os.getenv", "line_number": 12, "usage_type": "call"}, {"api_name": "smtplib.SMTP", "line_number": 13, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 32, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 37, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 38, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 38, "usage_type": "attribute"}, {"api_name": "random.randint", "line_number": 46, "usage_type": "call"}]} +{"seq_id": "9800386023", "text": "from fastapi import FastAPI\nfrom fastapi.staticfiles import StaticFiles\n\ndescription = \"\"\"\nChimichangApp API helps you do awesome stuff. 🚀\n\n## Items\n\nYou can **read items**.\n\n## Users\n\nYou will be able to:\n\n* **Create users** (_not implemented_).\n* **Read users** (_not implemented_).\n\"\"\"\n\n\ntags_metadata = [\n {\n \"name\": \"users\",\n \"description\": \"Operations with users. The **login** logic is also here.\",\n },\n {\n \"name\": \"items\",\n \"description\": \"Manage items. So _fancy_ they have their own docs.\",\n \"externalDocs\": {\n \"description\": \"Items external docs\",\n \"url\": \"https://fastapi.tiangolo.com/\",\n },\n },\n]\n\n\napp = FastAPI(\n title=\"Good API\",\n description=description,\n version=\"0.0.1\",\n terms_of_service=\"http://localhost/terms/\",\n contact={\n \"name\": \"Felix\",\n \"url\": \"http://localhost/contact\",\n \"email\": \"felix@localhost.com\",\n },\n license_info={\n \"name\": \"Apache 2.0\",\n \"url\": \"https://www.apache.org/licenses/LICENSE-2.0.html\",\n },\n openapi_tags=tags_metadata,\n openapi_url=\"/api/v1/openapi.json\",\n docs_url=\"/documentation\",\n redoc_url=None,\n)\n\n\n@app.get(\"/items/\", tags=[\"items\"])\nasync def read_items():\n return [\n {\"name\": \"Katana\"},\n ]\n\n\n@app.get(\"/users/\", tags=[\"users\"])\nasync def get_users():\n return [\n {\"name\": \"Felix\"},\n ]\n\n\napp.mount(\"/static\", StaticFiles(directory=\"/tmp\"), name=\"static\")\n", "repo_name": "tinylambda/keep", "sub_path": "module_fastapi/fastapi_meta_and_doc.py", "file_name": "fastapi_meta_and_doc.py", "file_ext": "py", "file_size_in_byte": 1488, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "21", "api": [{"api_name": "fastapi.FastAPI", "line_number": 36, "usage_type": "call"}, {"api_name": "fastapi.staticfiles.StaticFiles", "line_number": 71, "usage_type": "call"}]} +{"seq_id": "16880471318", "text": "import functools\nimport json\n\nimport requests\nfrom django.http import JsonResponse\nfrom django.shortcuts import render, HttpResponse, redirect\nfrom urllib.parse import urlencode\n\n# Create your views here.\nfrom app01 import models\n\n\ndef auth(func):\n @functools.wraps(func)\n def inner(request, *args, **kwargs):\n user_info = request.session.get('user_info')\n if not user_info:\n return redirect('/login/')\n return func(request, *args, **kwargs)\n\n return inner\n\n\ndef login(request):\n if request.method == 'POST':\n user = request.POST.get('user')\n pwd = request.POST.get('pwd')\n user_obj = models.UserInfo.objects.filter(username=user, password=pwd).first()\n if user_obj:\n request.session['user_info'] = {'id': user_obj.id, 'name': user_obj.username, 'uid': user_obj.uid}\n return redirect('/bind/')\n\n return render(request, 'login.html')\n\n\n@auth # bind = auth(bind)\ndef bind(request):\n \"\"\"\n 登录后,关注公众号 并绑定个人微信\n\n \"\"\"\n print(request.session['user_info'])\n return render(request, 'bind.html')\n\n\n@auth\ndef bind_qcode(request):\n \"\"\"\n 前端向后端发送ajax请求到此,我们生成二维码数据返回\n :param request:\n :return:\n \"\"\"\n # token :b5b87bf9590ca8d260ac4d7e9e2a75a2\n if request.method == 'GET':\n ret = {'code': 1000}\n try:\n access_url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid={appid}&redirect_uri={redirect_uri}&response_type=code&scope=snsapi_userinfo&state={state}#wechat_redirect'\n access_url = access_url.format(\n appid=\"wx8aa094571ee97536\",\n redirect_uri='http://39.108.134.78:8000/callback',\n state=request.session['user_info']['uid']\n )\n\n ret['data'] = access_url\n\n except Exception as e:\n ret['code'] = 1001\n ret['msg'] = str(e)\n\n return JsonResponse(ret)\n\n\ndef callback(request):\n \"\"\"\n 发送二次请求,以通过微信的认证,认证后拿到用户的openid\n :param request:\n :return:\n \"\"\"\n # 1. 获取微信的code\n code = request.GET.get('code')\n # 2. 获取用户uid\n state = request.GET.get('state')\n\n ret = requests.get(url='https://api.weixin.qq.com/sns/oauth2/access_token', params={\n \"appid\": \"wx8aa094571ee97536\",\n \"secret\": \"779a492b89fe2a9c369531cd35ea200d\",\n \"code\": code,\n \"grant_type\": \"authorization_code\"\n\n }).json()\n\n open_id = ret.get(\"openid\") # 通过微信验证后从微信返回的结果中拿到openid\n if open_id:\n models.UserInfo.objects.filter(uid=state).update(wx_id=open_id) # 将用户的微信ID存入数据库\n response = \"

授权成功 %s

\" % open_id\n\n else:\n response = \"

用户扫码之后,手机上的提示

\"\n return HttpResponse(response)\n\n\ndef sendmsg(request):\n def get_access_token():\n result = requests.get('https://api.weixin.qq.com/cgi-bin/token', params={\n \"grant_type\": \"client_credential\",\n \"appid\": \"wx8aa094571ee97536\",\n \"appsecret\": \"779a492b89fe2a9c369531cd35ea200d\"\n }).json()\n if result.get(\"access_token\"):\n access_token = result.get(\"access_token\")\n else:\n access_token = None\n return access_token\n\n access_token = get_access_token()\n openid1 = models.UserInfo.objects.filter(id=1).first().wx_id\n openid2 = models.UserInfo.objects.filter(id=2).first().wx_id\n\n def send_custom_msg():\n body = {\n \"touser\": [openid1, openid2],\n \"msgtype\": \"text\",\n \"text\": {\"content\": \"耗时24h终于等到你\"}\n }\n\n response = requests.post(url='https://api.weixin.qq.com/cgi-bin/message/mass/send',\n params={\n \"access_token\": access_token\n },\n data=bytes(json.dumps(body, ensure_ascii=False), encoding='utf-8')\n )\n result = response.json()\n return result\n\n result = send_custom_msg()\n if result.get('errcode') == 0:\n return HttpResponse('发送成功')\n return HttpResponse('发送失败')\n\n\n", "repo_name": "luffy-org/WXBOX", "sub_path": "app01/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 4343, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "django.shortcuts.redirect", "line_number": 18, "usage_type": "call"}, {"api_name": "functools.wraps", "line_number": 14, "usage_type": "call"}, {"api_name": "app01.models.UserInfo.objects.filter", "line_number": 28, "usage_type": "call"}, {"api_name": "app01.models.UserInfo", "line_number": 28, "usage_type": "attribute"}, {"api_name": "app01.models", "line_number": 28, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 31, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 33, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 43, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 70, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 84, "usage_type": "call"}, {"api_name": "app01.models.UserInfo.objects.filter", "line_number": 94, "usage_type": "call"}, {"api_name": "app01.models.UserInfo", "line_number": 94, "usage_type": "attribute"}, {"api_name": "app01.models", "line_number": 94, "usage_type": "name"}, {"api_name": "django.shortcuts.HttpResponse", "line_number": 99, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 104, "usage_type": "call"}, {"api_name": "app01.models.UserInfo.objects.filter", "line_number": 116, "usage_type": "call"}, {"api_name": "app01.models.UserInfo", "line_number": 116, "usage_type": "attribute"}, {"api_name": "app01.models", "line_number": 116, "usage_type": "name"}, {"api_name": "app01.models.UserInfo.objects.filter", "line_number": 117, "usage_type": "call"}, {"api_name": "app01.models.UserInfo", "line_number": 117, "usage_type": "attribute"}, {"api_name": "app01.models", "line_number": 117, "usage_type": "name"}, {"api_name": "requests.post", "line_number": 126, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 130, "usage_type": "call"}, {"api_name": "django.shortcuts.HttpResponse", "line_number": 137, "usage_type": "call"}, {"api_name": "django.shortcuts.HttpResponse", "line_number": 138, "usage_type": "call"}]} +{"seq_id": "31139903076", "text": "from contextlib import asynccontextmanager\nimport uvicorn\n\nfrom fastapi import FastAPI\nfrom fastapi.responses import ORJSONResponse\n\nfrom src.api import healthcheck, user\nfrom src.core.db.repository import create_tables, close_connection\nfrom src.core.queue.rabbit_sender import message_broker\n\n@asynccontextmanager\nasync def lifespan(app: FastAPI):\n create_tables()\n await message_broker.connect()\n yield\n close_connection()\n await message_broker.stop()\n\n\napp = FastAPI(\n lifespan=lifespan,\n title='Awesome Auth Popug Service',\n docs_url='/api/openapi',\n openapi_url='/api/openapi.json',\n default_response_class=ORJSONResponse,\n)\n\napp.include_router(healthcheck.router)\napp.include_router(user.router)\n\nAPI_PREFIX = '/api'\n\n\nif __name__=='__main__':\n uvicorn.run(port=8888, log_level='info')", "repo_name": "NataliyaPavlova/Async_Architecture_touch_dev", "sub_path": "Auth/src/main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 825, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "fastapi.FastAPI", "line_number": 12, "usage_type": "name"}, {"api_name": "src.core.db.repository.create_tables", "line_number": 13, "usage_type": "call"}, {"api_name": "src.core.queue.rabbit_sender.message_broker.connect", "line_number": 14, "usage_type": "call"}, {"api_name": "src.core.queue.rabbit_sender.message_broker", "line_number": 14, "usage_type": "name"}, {"api_name": "src.core.db.repository.close_connection", "line_number": 16, "usage_type": "call"}, {"api_name": "src.core.queue.rabbit_sender.message_broker.stop", "line_number": 17, "usage_type": "call"}, {"api_name": "src.core.queue.rabbit_sender.message_broker", "line_number": 17, "usage_type": "name"}, {"api_name": "contextlib.asynccontextmanager", "line_number": 11, "usage_type": "name"}, {"api_name": "fastapi.FastAPI", "line_number": 20, "usage_type": "call"}, {"api_name": "fastapi.responses.ORJSONResponse", "line_number": 25, "usage_type": "name"}, {"api_name": "src.api.healthcheck.router", "line_number": 28, "usage_type": "attribute"}, {"api_name": "src.api.healthcheck", "line_number": 28, "usage_type": "name"}, {"api_name": "src.api.user.router", "line_number": 29, "usage_type": "attribute"}, {"api_name": "src.api.user", "line_number": 29, "usage_type": "name"}, {"api_name": "uvicorn.run", "line_number": 35, "usage_type": "call"}]} +{"seq_id": "24118015755", "text": "from django.db import models\nfrom django.utils.text import slugify\nfrom petstagram.basic.model_mixins import StrFromFieldsMixin\n\n# Create your models here.\n\n\nclass Pet(StrFromFieldsMixin, models.Model):\n str_fields = ('id', 'name')\n\n MAX_NAME = 30\n name = models.CharField(\n max_length=MAX_NAME,\n null=False,\n blank=False,\n )\n personal_photo = models.URLField(\n null=False,\n blank=False,\n )\n slug = models.SlugField(\n unique=True,\n null=True,\n blank=True,\n )\n date_of_birth = models.DateField(\n null=True,\n blank=True\n )\n\n # create unique slug and saves it automatically\n def save(self, *args, **kwargs):\n # Create/Update object from instance Pet\n super().save(*args, **kwargs)\n # If there is not created slug it creates a new one and updates the pet object\n if not self.slug:\n self.slug = slugify(f'{self.id}-{self.name}')\n \"\"\"\n Without the `if` the following scenario might happen:\n the url is `/pets/1-alba` and at later stage pet name is changed to albata \n the new url will be `/pets/1-albata`, but `/pets/1-alba` will not work.\n \"\"\"\n\n # Update / enters into built-in function save and continues saving the info in the DB\n return super().save(*args, **kwargs)\n\n # def __str__(self):\n # return f'ID = {self.id}; Name = {self.name}'\n", "repo_name": "Orminis/petstagram", "sub_path": "petstagram/pets/models.py", "file_name": "models.py", "file_ext": "py", "file_size_in_byte": 1441, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "petstagram.basic.model_mixins.StrFromFieldsMixin", "line_number": 8, "usage_type": "name"}, {"api_name": "django.db.models.Model", "line_number": 8, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 8, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 12, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 12, "usage_type": "name"}, {"api_name": "django.db.models.URLField", "line_number": 17, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 17, "usage_type": "name"}, {"api_name": "django.db.models.SlugField", "line_number": 21, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 21, "usage_type": "name"}, {"api_name": "django.db.models.DateField", "line_number": 26, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 26, "usage_type": "name"}, {"api_name": "django.utils.text.slugify", "line_number": 37, "usage_type": "call"}]} +{"seq_id": "16965480692", "text": "import numpy as np\nimport pdb\nfrom scipy import interpolate\nimport scipy.integrate as integrate\nimport scipy.signal as sig\nfrom scipy.interpolate import interp1d\n\n\n# Initial Parameters for Miscentering Grid\nRmin = 0.05\nRmax = 100\nnR = 150\nR_sigmag = np.logspace(np.log10(Rmin), np.log10(Rmax), nR)\n\n\nnphi = 50\nphi = np.linspace(0,2*np.pi,nphi)\nndmis = 50\nR_grid = np.zeros((ndmis,nphi,nR)) # 50 matrices of 50 matrices of matrices with 150 elements (with each element being 0)\nfor i in range(nR):\n R_grid[:,:,i] = R_sigmag[i]\n\nxmax = 5.\nd_mis = np.linspace(0,xmax,ndmis)\nd_mis_grid = np.zeros((ndmis,nphi,nR))\nfor i in range(ndmis):\n d_mis_grid[i,:,:] = d_mis[i]\np_mis = (d_mis/1.**2)*np.exp(-d_mis**2/(2.*1.**2))\np_mis = np.tile(p_mis,(nR,1))\np_mis = p_mis.T\n\n\nphi_grid = np.zeros((ndmis,nphi,nR))\nfor i in range(nphi):\n phi_grid[:,i,:] = phi[i]\n\n\ndef Sigmag(R, z, params, h0, splash):\n\n minr = 0.01\n maxr = 100.\n numr = 500\n rr = np.exp(np.linspace(np.log(minr), np.log(maxr), num = numr))\n\n if splash==1:\n ln_alpha, ln_beta, ln_gamma, ln_r_s, ln_r_t, ln_rho_O, ln_rho_s, se, lnmis, f_mis = params\n beta = 10**ln_beta\n gamma = 10**ln_gamma\n r_t = 10**ln_r_t\n f_trans = (1.+(rr/r_t)**beta)**(-1*gamma/beta)\n\n if splash==0:\n ln_alpha, ln_r_s, ln_rho_O, ln_rho_s, se, lnmis, f_mis = params\n f_trans = 1.0\n\n alpha = 10**ln_alpha\n mis = np.exp(lnmis+np.log(0.81))\n r_s = 10**ln_r_s\n rho_O = 10**ln_rho_O\n rho_s = 10**ln_rho_s\n r_o = 1.5/h0\n\n rho_gi = rho_s*np.exp((-2./alpha)*(((rr/r_s)**alpha)-1))\n rho_go = rho_O*(rr/r_o)**(-1*se)\n rho_g = rho_gi * f_trans + rho_go\n rho_g_func = interpolate.interp1d(rr, rho_g)\n\n sigmag = []\n for i in range(len(R)):\n func_evals = rho_g_func(np.sqrt(R[i]**2.+z**2.))\n sigmag.append(2*integrate.simps(func_evals, z))\n # it appears to make a difference how this integration is done...\n func = interp1d(R,sigmag,fill_value = \"extrapolate\")\n\n # Miscentering Corrections\n R_mis = np.sqrt(R_grid**2 + (d_mis_grid*mis)**2 + 2.*R_grid*(d_mis_grid*mis)*np.cos(phi_grid)) # EQ 12\n sigma_tem = func(R_mis)\n sigma_temp = np.mean(sigma_tem,axis=1)\n sigma_mis = np.average(sigma_temp,weights=p_mis,axis=0)\n sigma = func(R_sigmag)\n sigma_tot = (1.-f_mis)*sigma + f_mis*sigma_mis # EQ 11\n func_tot = interp1d(R_sigmag,sigma_tot,kind='linear')\n\n return func_tot(R)\n\ndef lnlike(theta, rdat, z, sig0, covinv0, h0, splash):\n ln_alpha, ln_beta, ln_gamma, ln_r_s, ln_r_t, ln_rho_O, ln_rho_s, se, lnmis, f_mis = theta\n sig_m = Sigmag(rdat, z, theta, h0, splash)\n vec = sig_m - sig0\n like = -0.5*np.matmul(np.matmul(vec,covinv0),vec.T)\n return like\n\ndef lnprior(theta):\n ln_alpha, ln_beta, ln_gamma, ln_r_s, ln_r_t, ln_rho_O, ln_rho_s, se, lnmis, f_mis = theta\n if -4. < ln_rho_O < 2. and -4. < ln_rho_s < 4. and np.log10(0.01) < ln_r_s < np.log10(5.0) and np.log10(0.1) < ln_r_t < np.log10(5.0) and 0.1 < se < 10. and 0.01 < f_mis < 0.99 and np.log(0.01) < lnmis < np.log(0.99):\n return -0.5*(-1.13-lnmis)**2/0.22**2 - 0.5*(ln_alpha - np.log10(0.19))**2/0.4**2 - 0.5*(ln_beta - np.log10(6.0))**2/0.4**2 - 0.5*(ln_gamma - np.log10(4.0))**2/0.4**2 -0.5*(f_mis-0.22)**2/0.11**2\n else:\n return -np.inf\n\ndef ln_prob(theta, rdat, z, sig0, covinv0, h0, splash):\n lp = lnprior(theta)\n if not np.isfinite(lp):\n return -np.inf\n lnl = lnlike(theta, rdat, z, sig0, covinv0, h0, splash) +lp\n lnl = lp\n print(lnl)\n print(lp)\n return lnl\n\n\ndef derivative_savgol(R, data, N=10000, window_length=5, polyorder=3):\n\n data_sm = sig.savgol_filter(np.log10(data), window_length=window_length, polyorder=polyorder)\n f = interpolate.interp1d(np.log10(R), data_sm, kind='cubic')\n\n # Evaluate spline across a very fine grid or radii\n lnrad_fine = np.linspace(np.log10(np.min(R)), np.log10(np.max(R)), num=N)\n lnsigma_fine = f(lnrad_fine)\n\n # Calculate derivative using finite differencing\n dlnsig_dlnr_fine = (lnsigma_fine[1:] - lnsigma_fine[:-1])/(lnrad_fine[1:] - lnrad_fine[:-1])\n\n return (lnrad_fine[1:]+lnrad_fine[:-1])/2, dlnsig_dlnr_fine\n\n# Alternative to DSigmag, results are basically identical...\ndef DelSigmag(R, z, params, h0, splash, N=100):\n\n sigma = Sigmag(R, z, params, h0, splash)\n # interpolate onto a finer grid just so the integration is smooth\n\n f = interpolate.interp1d(np.log10(R), np.log10(sigma), kind='cubic')\n rad_fine = np.linspace(np.log10(np.min(R)), np.log10(np.max(R)), num=N)\n\n Dsigma = []\n for i in range(len(rad_fine)-1):\n func_evals = f(rad_fine[:i+1])*2.*np.pi*rad_fine[:i+1]\n sigmag_sum = integrate.simps(func_evals, rad_fine[:i+1])\n sigmag_mean = sigmag_sum/(np.pi*rad_fine[i+1]**2)\n Dsigma.append(sigmag_mean - f(rad_fine[i+1]))\n\n f = interpolate.interp1d(rad_fine[1:], Dsigma, kind='cubic', bounds_error=False, fill_value=0)\n lnsigma_coarse = f(R)\n\n return lnsigma_coarse\n\ndef DSigmag(R, z, params, h0, splash, N=100):\n\n sigma = Sigmag(R, z, params, h0, splash)\n # interpolate onto a finer grid just so the integration is smooth\n f = interpolate.interp1d(np.log10(R), np.log10(sigma), kind='cubic')\n lnrad_fine = np.linspace(np.min(np.log10(R)), np.max(np.log10(R)), num=N)\n lnsigma_fine = f(lnrad_fine)\n\n R_fine = 10**lnrad_fine\n sigma_fine = 10**lnsigma_fine\n R_fine_mid = (R_fine[1:]+R_fine[:-1])/2\n dR_fine = R_fine[1:]-R_fine[:-1]\n sigma_fine_mid = (sigma_fine[1:]+sigma_fine[:-1])/2\n\n Dsigma = []\n\n for i in range(len(R_fine_mid)):\n Mean = np.sum(sigma_fine_mid[:i+1]*2*np.pi*R_fine_mid[:i+1]*dR_fine[:i+1])/np.sum(2*np.pi*R_fine_mid[:i+1]*dR_fine[:i+1])\n Dsigma.append(Mean-sigma_fine_mid[i])\n\n # interpolate back to original R grid\n f = interpolate.interp1d(R_fine_mid, Dsigma, kind='cubic', bounds_error=False, fill_value=0)\n lnsigma_coarse = f(R)\n\n return lnsigma_coarse\n\n\ndef lnlikelihoodD(params, R, z, data_vec, invcov, h0, splash):\n\n lnlike_priors = priors(params, h0, splash)\n lnlike_data = 0.0\n\n if (lnlike_priors > -1.0e5):\n\n model = DSigmag(R, z, params, h0, splash)\n diff = data_vec - model\n detinvcov = np.linalg.det(invcov)\n detcov = 1./detinvcov\n lnlike_data = -0.5*(len(data_vec)*np.log(2.*np.pi) + np.log(detcov)) -0.5*np.dot(diff, np.dot(invcov, diff))\n\n lnlike = lnlike_data + lnlike_priors\n\n return lnlike\n", "repo_name": "ajamsellem/Miscellany", "sub_path": "py_scripts/old/splashback_utils_v_Tae.py", "file_name": "splashback_utils_v_Tae.py", "file_ext": "py", "file_size_in_byte": 6491, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "numpy.logspace", "line_number": 13, "usage_type": "call"}, {"api_name": "numpy.log10", "line_number": 13, "usage_type": "call"}, {"api_name": "numpy.linspace", "line_number": 17, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 17, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 19, "usage_type": "call"}, {"api_name": "numpy.linspace", "line_number": 24, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 25, "usage_type": "call"}, {"api_name": "numpy.exp", "line_number": 28, "usage_type": "call"}, {"api_name": "numpy.tile", "line_number": 29, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 33, "usage_type": "call"}, {"api_name": "numpy.exp", "line_number": 43, "usage_type": "call"}, {"api_name": "numpy.linspace", "line_number": 43, "usage_type": "call"}, {"api_name": "numpy.log", "line_number": 43, "usage_type": "call"}, {"api_name": "numpy.exp", "line_number": 57, "usage_type": "call"}, {"api_name": "numpy.log", "line_number": 57, "usage_type": "call"}, {"api_name": "numpy.exp", "line_number": 63, "usage_type": "call"}, {"api_name": "scipy.interpolate.interp1d", "line_number": 66, "usage_type": "call"}, {"api_name": "scipy.interpolate", "line_number": 66, "usage_type": "name"}, {"api_name": "numpy.sqrt", "line_number": 70, "usage_type": "call"}, {"api_name": "scipy.integrate.simps", "line_number": 71, "usage_type": "call"}, {"api_name": "scipy.integrate", "line_number": 71, "usage_type": "name"}, {"api_name": "scipy.interpolate.interp1d", "line_number": 73, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 76, "usage_type": "call"}, {"api_name": "numpy.cos", "line_number": 76, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 78, "usage_type": "call"}, {"api_name": "numpy.average", "line_number": 79, "usage_type": "call"}, {"api_name": "scipy.interpolate.interp1d", "line_number": 82, "usage_type": "call"}, {"api_name": "numpy.matmul", "line_number": 90, "usage_type": "call"}, {"api_name": "numpy.log10", "line_number": 95, "usage_type": "call"}, {"api_name": "numpy.log", "line_number": 95, "usage_type": "call"}, {"api_name": "numpy.log10", "line_number": 96, "usage_type": "call"}, {"api_name": "numpy.inf", "line_number": 98, "usage_type": "attribute"}, {"api_name": "numpy.isfinite", "line_number": 102, "usage_type": "call"}, {"api_name": "numpy.inf", "line_number": 103, "usage_type": "attribute"}, {"api_name": "scipy.signal.savgol_filter", "line_number": 113, "usage_type": "call"}, {"api_name": "scipy.signal", "line_number": 113, "usage_type": "name"}, {"api_name": "numpy.log10", "line_number": 113, "usage_type": "call"}, {"api_name": "scipy.interpolate.interp1d", "line_number": 114, "usage_type": "call"}, {"api_name": "scipy.interpolate", "line_number": 114, "usage_type": "name"}, {"api_name": "numpy.log10", "line_number": 114, "usage_type": "call"}, {"api_name": "numpy.linspace", "line_number": 117, "usage_type": "call"}, {"api_name": "numpy.log10", "line_number": 117, "usage_type": "call"}, {"api_name": "numpy.min", "line_number": 117, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 117, "usage_type": "call"}, {"api_name": "scipy.interpolate.interp1d", "line_number": 131, "usage_type": "call"}, {"api_name": "scipy.interpolate", "line_number": 131, "usage_type": "name"}, {"api_name": "numpy.log10", "line_number": 131, "usage_type": "call"}, {"api_name": "numpy.linspace", "line_number": 132, "usage_type": "call"}, {"api_name": "numpy.log10", "line_number": 132, "usage_type": "call"}, {"api_name": "numpy.min", "line_number": 132, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 132, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 136, "usage_type": "attribute"}, {"api_name": "scipy.integrate.simps", "line_number": 137, "usage_type": "call"}, {"api_name": "scipy.integrate", "line_number": 137, "usage_type": "name"}, {"api_name": "numpy.pi", "line_number": 138, "usage_type": "attribute"}, {"api_name": "scipy.interpolate.interp1d", "line_number": 141, "usage_type": "call"}, {"api_name": "scipy.interpolate", "line_number": 141, "usage_type": "name"}, {"api_name": "scipy.interpolate.interp1d", "line_number": 150, "usage_type": "call"}, {"api_name": "scipy.interpolate", "line_number": 150, "usage_type": "name"}, {"api_name": "numpy.log10", "line_number": 150, "usage_type": "call"}, {"api_name": "numpy.linspace", "line_number": 151, "usage_type": "call"}, {"api_name": "numpy.min", "line_number": 151, "usage_type": "call"}, {"api_name": "numpy.log10", "line_number": 151, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 151, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 163, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 163, "usage_type": "attribute"}, {"api_name": "scipy.interpolate.interp1d", "line_number": 167, "usage_type": "call"}, {"api_name": "scipy.interpolate", "line_number": 167, "usage_type": "name"}, {"api_name": "numpy.linalg.det", "line_number": 182, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 182, "usage_type": "attribute"}, {"api_name": "numpy.log", "line_number": 184, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 184, "usage_type": "attribute"}, {"api_name": "numpy.dot", "line_number": 184, "usage_type": "call"}]} +{"seq_id": "19475724051", "text": "import datetime, sys\nfrom cusfpredict.predict import Predictor\nfrom cusfpredict.utils import *\n\n# Predictor Binary and GFS data location\nPRED_BINARY = \"./pred\"\nGFS_PATH = \"./gfs\"\n\n# Launch Parameters\nLAUNCH_TIME = datetime.datetime.utcnow() # Note that this time is interpreted as a UTC time\n\nLAUNCH_LAT = -34.9499\nLAUNCH_LON = 138.5194\nLAUNCH_ALT = 0.0\n\nASCENT_RATE = 5.0\nDESCENT_RATE = 5.0\nBURST_ALT = 30000.0\n\n# Output file\nOUTPUT_KML = \"prediction.kml\"\n\n# Create the predictor object.\npred = Predictor(bin_path=PRED_BINARY, gfs_path=GFS_PATH)\n\n# Run the prediction\nflight_path = pred.predict(\n\tlaunch_lat=LAUNCH_LAT,\n\tlaunch_lon=LAUNCH_LON,\n\tlaunch_alt=LAUNCH_ALT,\n\tascent_rate=ASCENT_RATE,\n\tdescent_rate=DESCENT_RATE,\n\tburst_alt=BURST_ALT,\n\tlaunch_time=LAUNCH_TIME)\n\n# Check the output makes sense\nif len(flight_path) == 1:\n\tprint(\"No Wind Data available for this prediction scenario!\")\n\tsys.exit(1)\n\n# Create a list of items to add into the KML output file\ngeom_items = []\n\n# Add the flight path track, and the landing location to the list\ngeom_items.append(flight_path_to_geometry(flight_path, comment=\"Predicted Flight Path\"))\ngeom_items.append(flight_path_landing_placemark(flight_path, comment=\"Predicted Landing Location\"))\n\n# Write everything in the list out to the KML file\nwrite_flight_path_kml(geom_items, filename=OUTPUT_KML, comment=\"Balloon Flight Prediction\")\n\n# Print out some basic information about the prediction\n# Launch time:\nlaunch_position = flight_path[0]\nprint(\"Launch Time: %s\" % datetime.datetime.utcfromtimestamp(launch_position[0]).isoformat())\nprint(\"Launch Location: %.4f, %.4f\" % (launch_position[1],launch_position[2]))\n\n# Landing position\nlanding_position = flight_path[-1]\nprint(\"Landing Time: %s\" % datetime.datetime.utcfromtimestamp(landing_position[0]).isoformat())\nprint(\"Landing Location: %.4f, %.4f\" % (landing_position[1],landing_position[2]))\n\n", "repo_name": "darksidelemm/cusf_predictor_wrapper", "sub_path": "apps/basic_example.py", "file_name": "basic_example.py", "file_ext": "py", "file_size_in_byte": 1891, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 19, "dataset": "github-code", "pt": "21", "api": [{"api_name": "datetime.datetime.utcnow", "line_number": 10, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 10, "usage_type": "attribute"}, {"api_name": "cusfpredict.predict.Predictor", "line_number": 24, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 39, "usage_type": "call"}, {"api_name": "datetime.datetime.utcfromtimestamp", "line_number": 54, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 54, "usage_type": "attribute"}, {"api_name": "datetime.datetime.utcfromtimestamp", "line_number": 59, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 59, "usage_type": "attribute"}]} +{"seq_id": "28807864152", "text": "import zipfile\nimport tarfile\nimport tempfile\nimport cPickle\nimport unipath\nimport numpy as np\nimport shutil\nfrom PIL import Image\nfrom io import BytesIO\nfrom unipath import Path\n\nVALID_EXT = ('.jpg', '.jpeg', '.png', '.bmp')\n\n\nclass BatchWriter(object):\n def __init__(self, data_path, img_size=32,\n channels=3, max_batch_size=10000):\n self.data_path = Path(data_path).child('batches')\n if not self.data_path.exists():\n self.data_path.mkdir(parents=True)\n self.img_size = img_size\n self.channels = channels\n self.max_batch_size = max_batch_size\n self.datasets = {}\n self.next_batch = 1\n self.train_range = None\n self.test_range = None\n\n def prepare_training(self, train_dset, test_dset):\n if train_dset is not None:\n train_data = self.preprocess_data(train_dset.data)\n train_batch_size = self.calculate_batch_size(train_data.shape[0])\n self.train_range = self.dump_batches(train_data,\n train_dset.output,\n train_dset.filenames,\n train_batch_size)\n test_data = self.preprocess_data(test_dset.data)\n test_batch_size = self.calculate_batch_size(test_data.shape[0])\n self.test_range = self.dump_batches(test_data,\n test_dset.output,\n test_dset.filenames,\n test_batch_size)\n if train_dset is None:\n label_names = test_dset.labels.copy()\n data = test_data\n batch_size = test_batch_size\n else:\n label_names = train_dset.labels.copy()\n label_names.update(test_dset.labels)\n data = np.vstack((train_data, test_data))\n batch_size = train_batch_size\n self.dump_meta_batch(data, label_names, batch_size)\n\n def dump_meta_batch(self, data, label_names, batch_size):\n mean = data.transpose().mean(axis=1).reshape((-1, 1))\n data_path = self.data_path.child('batches.meta')\n self.write_cifar_meta_batch(data_path, mean, label_names, batch_size)\n\n def dump_batches(self, data, output, filenames, batch_size):\n start_batch = self.next_batch\n for i, mark in enumerate(range(0, data.shape[0], batch_size)):\n slice_ = slice(mark, mark + batch_size)\n self.write_cifar_batch(\n self.data_path.child('data_batch_' + str(self.next_batch)),\n data[slice_].transpose(),\n output[slice_],\n filenames[slice_]\n )\n self.next_batch += 1\n return start_batch, self.next_batch - 1\n\n def write_cifar_batch(self, data_path, data, labels, filenames):\n data = {\n 'batch_label': '',\n 'labels': labels,\n 'data': data,\n 'filenames': filenames,\n }\n with open(data_path, 'wb') as f:\n cPickle.dump(data, f)\n\n def write_cifar_meta_batch(self, data_path, mean, label_names, batch_size):\n data = {\n 'data_mean': mean,\n 'label_names': label_names,\n 'num_cases_per_batch': batch_size,\n 'num_vis': mean.shape[0]\n }\n with open(data_path, 'wb') as f:\n cPickle.dump(data, f)\n\n def preprocess_data(self, dset_data):\n dset_size = int(np.sqrt(dset_data.shape[1] / self.channels))\n data = np.empty((dset_data.shape[0], self.img_size**2 * self.channels),\n dtype=np.uint8)\n if self.img_size != dset_size:\n for i in range(data.shape[0]):\n image = ConvImage.from_array(dset_data[i],\n self.channels,\n dset_size)\n image.to_size(self.img_size)\n data[i] = image.to_array()\n return data\n return dset_data\n\n def get_data_options(self):\n return ['--data-path=%s' % self.data_path,\n '--train-range=%s-%s' % self.train_range,\n '--test-range=%s-%s' % self.test_range,\n '--img-size=%s' % self.img_size,\n '--data-provider=cifar']\n\n def get_data_options_test(self):\n return ['--data-dir=%s' % self.data_path,\n '--test-range=%s-%s' % self.test_range,\n '--is-dataset=1']\n\n def calculate_batch_size(self, data_size):\n if data_size % self.max_batch_size == 0:\n return self.max_batch_size\n c = data_size / self.max_batch_size + 1\n return data_size / c\n\n\nclass ConvImage(object):\n def __init__(self, image):\n self.image = image\n\n @classmethod\n def from_archive(cls, archive, member):\n fp = BytesIO(archive.open_raw_member(member).read())\n return cls(Image.open(fp))\n\n @classmethod\n def from_array(cls, data, channels, size):\n rval = data.reshape((channels, size, size)).transpose([1, 2, 0])\n return cls(Image.fromarray(rval))\n\n def load(self):\n self.image.load()\n\n @property\n def size(self):\n return self.image.size\n\n def to_size(self, size):\n size_tuple = (size, size)\n if self.image.size != size_tuple:\n self.to_square()\n self.image.thumbnail(size_tuple, Image.ANTIALIAS)\n\n def to_square(self):\n w, h = self.image.size\n if w != h:\n min_dim = int(min(w, h))\n self.image = self.image.crop((w / 2 - min_dim / 2,\n h / 2 - min_dim / 2,\n w / 2 + min_dim / 2,\n h / 2 + min_dim / 2))\n\n def to_rgb(self, allow_grayscale=True):\n if self.image.mode == 'RGBA':\n self.image = rgba_to_rgb(self.image)\n elif self.image.mode == 'CMYK':\n self.image = self.image.convert('RGB')\n elif self.image.mode in ('L', 'P'):\n if allow_grayscale:\n self.image = grayscale_to_rgb(self.image)\n if self.image.mode != 'RGB':\n raise ValueError('Unknown image format')\n return self.image\n\n def to_array(self):\n return np.array(self.image, order='C')\\\n .transpose([2, 0, 1]).flatten('C')\n\n\nclass tempdir(object):\n def __enter__(self):\n self.tempdir = unipath.Path(tempfile.mkdtemp())\n return self.tempdir\n\n def __exit__(self, type_, value, traceback):\n shutil.rmtree(self.tempdir)\n\n\nclass cwd(object):\n def __init__(self, cwd):\n self.prev_cwd = unipath.FSPath.cwd()\n self.cwd = unipath.Path(cwd)\n if not self.cwd.exists():\n self.cwd.mkdir(parents=True)\n\n def __enter__(self):\n self.cwd.chdir()\n return self.cwd\n\n def __exit__(self, type_, value, traceback):\n self.prev_cwd.chdir()\n\n\ndef image_as_rgb(image, skip_grayscale=True, skip_unknown=True):\n if image.mode == 'RGBA':\n image = rgba_to_rgb(image)\n elif image.mode == 'CMYK':\n image = image.convert('RGB')\n elif image.mode in ('L', 'P'):\n if skip_grayscale:\n return None\n image = grayscale_to_rgb(image)\n elif image.mode != 'RGB':\n if skip_unknown:\n return None\n raise ValueError('Unknown image format')\n return image\n\n\ndef image_to_cifar(image, size=32):\n \"\"\"\n Convert PIL image to cifar image format\n\n Parameters\n ----------\n image: PIL.Image (loaded)\n image in a PIL format\n size: int, optional\n size of the image; default: 32\n original cifar images has size 32 (32x32 pixels)\n\n Returns\n -------\n rval: ndarray\n image in cifar format\n \"\"\"\n\n image = image_as_rgb(image, skip_grayscale=False, skip_unknown=False)\n image = resize_image(image, size)\n rval = np.array(image, order='C')\n rval = rval.transpose([2, 0, 1]).flatten('C')\n return rval\n\n\ndef crop_to_square(image):\n w, h = image.size\n if w != h:\n min_dim = int(min(w, h))\n image = image.crop((w / 2 - min_dim / 2, h / 2 - min_dim / 2,\n w / 2 + min_dim / 2, h / 2 + min_dim / 2))\n return image\n\n\ndef resize_image(image, size):\n size_tuple = (size, size)\n if image.size != size_tuple:\n image = crop_to_square(image)\n image.thumbnail(size_tuple, Image.ANTIALIAS)\n return image\n\n\ndef rgba_to_rgb(image, color=(255, 255, 255)):\n \"\"\"\n Alpha composite an RGBA Image with a specified color.\n\n Parameters\n ----------\n image: PIL.Image (loaded)\n RGBA image in PIL format\n color: tuple, optional\n tuple of 3 int, describes background of rgb image\n\n Returns\n -------\n rval: PIL.Image\n RGB image in PIL format\n\n Notes\n -----\n http://stackoverflow.com/questions/9166400/convert-rgba-png-to-rgb-with-pil\n \"\"\"\n\n rval = Image.new('RGB', image.size, color)\n rval.paste(image, mask=image.split()[3]) # 3 is the alpha channel\n return rval\n\n\ndef grayscale_to_rgb(image):\n \"\"\"\n Convert grayscale image to rgb\n\n Parameters\n ----------\n image: PIL.Image (loaded)\n grayscale image in PIL format\n\n Returns\n -------\n rval: PIL.Image\n rgb image in PIL format\n \"\"\"\n\n rval = Image.new('RGB', image.size)\n rval.paste(image)\n return rval\n\n\ndef cifar_image_to_pil(image, size=32, channels=3):\n \"\"\"\n Convert from cifar image format to PIL image\n\n Parameters\n ----------\n image: ndarray\n image in cifar format\n size: int, optional\n size of the image; default: 32\n original cifar images has size 32 (32x32 pixels)\n channels: int, optional\n channels in image; default: 3\n original cifar images has 3 channels\n\n Returns\n -------\n rval: PIL.Image\n image in a PIL format\n \"\"\"\n\n rval = image.reshape((channels, size, size)).transpose([1, 2, 0])\n return Image.fromarray(rval)\n\n\ndef images_to_batch(images, count, size=32, channels=3):\n \"\"\"\n Convert iterable of images to cifar batch\n\n Parameters\n ----------\n images: sequence\n sequence of images in PIL.Image format\n count: int\n number of images to process\n size: int, optional\n size of the image; default: 32\n channels: int, optional\n channels in image; default: 3\n\n Returns\n -------\n batch_data: ndarray\n ndarray of all images\n \"\"\"\n\n bytes = size * size * channels\n batch_data = np.empty((count, bytes), dtype=np.uint8)\n for i, image in enumerate(images):\n try:\n image.load()\n except IOError:\n # corrupted images\n pass\n batch_data[i, :] = image_to_cifar(image, size)\n return batch_data\n\n\ndef files_to_batch(files):\n images = (Image.open(fp) for fp in files)\n count = len(files)\n return images_to_batch(images, count)\n\n\ndef dir_to_cifar(source):\n labels = []\n files = []\n label_encoder = {}\n label_code = 0\n with cwd(source) as source:\n for class_path in source.listdir():\n fs = unipath.Path(class_path).walk(\n filter=lambda x: x.isfile() and x.lower().endswith(VALID_EXT)\n )\n fs = [x.lstrip('./') for x in fs]\n files.extend(fs)\n labels.extend([label_code] * len(fs))\n label_encoder[class_path.name] = label_code\n label_code += 1\n batch = files_to_batch(files)\n return batch, labels, [str(x) for x in files], label_encoder\n\n\ndef zip_to_cifar(zip_file):\n if not zipfile.is_zipfile(zip_file):\n raise ValueError('Not a zip file')\n z = zipfile.ZipFile(zip_file, mode='r')\n with tempdir() as d:\n with cwd(d):\n for member in z.namelist():\n z.extract(member)\n rval = dir_to_cifar('.')\n return rval\n\n\n#TODO: DANGEROUS do not use it on user's files, extractall not safe, read docs\ndef tar_to_cifar(tar_file):\n tar = tarfile.open(tar_file, 'r:gz')\n with tempdir() as d:\n with cwd(d):\n tar.extractall()\n rval = dir_to_cifar('.')\n return rval\n\n\ndef save_cifar_batch(fp, batch, labels, files, transpose=False):\n rng = np.random.RandomState(777)\n rng.shuffle(batch)\n rng.seed(777)\n rng.shuffle(labels)\n rng.seed(777)\n rng.shuffle(files)\n size = batch.shape[0] / 6\n for i in range(6):\n start = size*i\n stop = start + size\n minibatch = batch[start:stop, :]\n if transpose:\n minibatch = minibatch.transpose()\n data = {\n 'batch_label': '',\n 'labels': labels[start:stop],\n 'data': minibatch,\n 'filenames': files[start:stop],\n }\n with open(fp + '_' + str(i+1), 'wb') as f:\n cPickle.dump(data, f)\n\n\ndef save_batches_meta(fp, batch, encoder, num_cases_per_batch,\n num_vis=32 * 32 * 3, transpose=False):\n if transpose:\n mean = batch.transpose().mean(axis=1).reshape((-1, 1))\n else:\n mean = batch.mean(axis=0).reshape((1, -1))\n data = {\n 'data_mean': mean,\n 'label_names': encoder.keys(),\n 'num_cases_per_batch': num_cases_per_batch,\n 'num_vis': num_vis\n }\n with open(fp, 'wb') as f:\n cPickle.dump(data, f)\n\n\ndef unpack_cifar_batch(data, dest):\n \"\"\"\n Unpacking cifar file format to directory\n\n Parameters\n ----------\n data: dict\n cifar batch file\n dest: str\n path where store resulting data\n \"\"\"\n\n batch = data['data']\n with cwd(dest):\n for l in set(data['labels']):\n unipath.Path(l).mkdir()\n for i, (f, label) in enumerate(zip(data['filenames'], data['labels'])):\n image = cifar_image_to_pil(batch[i])\n image.save(unipath.Path(label).child(unipath.Path(f).name))\n\n\ndef load_cifar_batch(fp, transpose=False):\n with open(fp) as f:\n data = cPickle.load(f)\n if transpose:\n data['data'] = data['data'].transpose()\n return data\n\n\ndef unpack_cifar10():\n files = []\n dest = '/tmp/result'\n shutil.rmtree(dest)\n for i in range(1, 6):\n files.append('./cifar-10-batches-py/data_batch_' + str(i))\n files.append('./cifar-10-batches-py/test_batch')\n for fn in files:\n data = load_cifar_batch(fn)\n unpack_cifar_batch(data, dest)\n\n\ndef construct_predict_batch(images):\n labels = [0] * len(images)\n data = images_to_batch((Image.open(i) for i in images), len(images)).transpose()\n mean = data.mean(axis=0)\n batch = {\n 'batch_label': '',\n 'labels': labels,\n 'data': data,\n 'filenames': [image.name for image in images]\n }\n return cPickle.dumps(batch), mean\n\n\ndef test_cifar10_convert():\n with tempdir() as td:\n data = load_cifar_batch('./cifar-10-batches-py/data_batch_1')\n unpack_cifar_batch(data, td)\n batch, labels, files, encoder = dir_to_cifar(td)\n batch = sorted(zip(batch, files), key=lambda x: data['filenames'].index(unipath.Path(x[1]).name))\n batch = zip(*batch)[0]\n assert (batch == data['data']).all()\n labels = sorted(zip(labels, files), key=lambda x: data['filenames'].index(unipath.Path(x[1]).name))\n labels = zip(*labels)[0]\n assert all(x == y for x, y in zip(labels, data['labels']))\n", "repo_name": "deniskolokol/dlic", "sub_path": "back_end/core/shared/cifar.py", "file_name": "cifar.py", "file_ext": "py", "file_size_in_byte": 15491, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "unipath.Path", "line_number": 18, "usage_type": "call"}, {"api_name": "numpy.vstack", "line_number": 50, "usage_type": "call"}, {"api_name": "cPickle.dump", "line_number": 80, "usage_type": "call"}, {"api_name": "cPickle.dump", "line_number": 90, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 93, "usage_type": "call"}, {"api_name": "numpy.empty", "line_number": 94, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 95, "usage_type": "attribute"}, {"api_name": "io.BytesIO", "line_number": 131, "usage_type": "call"}, {"api_name": "PIL.Image.open", "line_number": 132, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 132, "usage_type": "name"}, {"api_name": "PIL.Image.fromarray", "line_number": 137, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 137, "usage_type": "name"}, {"api_name": "PIL.Image.ANTIALIAS", "line_number": 150, "usage_type": "attribute"}, {"api_name": "PIL.Image", "line_number": 150, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 174, "usage_type": "call"}, {"api_name": "unipath.Path", "line_number": 180, "usage_type": "call"}, {"api_name": "tempfile.mkdtemp", "line_number": 180, "usage_type": "call"}, {"api_name": "shutil.rmtree", "line_number": 184, "usage_type": "call"}, {"api_name": "unipath.FSPath.cwd", "line_number": 189, "usage_type": "call"}, {"api_name": "unipath.FSPath", "line_number": 189, "usage_type": "attribute"}, {"api_name": "unipath.Path", "line_number": 190, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 238, "usage_type": "call"}, {"api_name": "PIL.Image.ANTIALIAS", "line_number": 256, "usage_type": "attribute"}, {"api_name": "PIL.Image", "line_number": 256, "usage_type": "name"}, {"api_name": "PIL.Image.new", "line_number": 281, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 281, "usage_type": "name"}, {"api_name": "PIL.Image.new", "line_number": 301, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 301, "usage_type": "name"}, {"api_name": "PIL.Image.fromarray", "line_number": 328, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 328, "usage_type": "name"}, {"api_name": "numpy.empty", "line_number": 353, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 353, "usage_type": "attribute"}, {"api_name": "PIL.Image.open", "line_number": 365, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 365, "usage_type": "name"}, {"api_name": "unipath.Path", "line_number": 377, "usage_type": "call"}, {"api_name": "zipfile.is_zipfile", "line_number": 390, "usage_type": "call"}, {"api_name": "zipfile.ZipFile", "line_number": 392, "usage_type": "call"}, {"api_name": "tarfile.open", "line_number": 403, "usage_type": "call"}, {"api_name": "numpy.random.RandomState", "line_number": 412, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 412, "usage_type": "attribute"}, {"api_name": "cPickle.dump", "line_number": 432, "usage_type": "call"}, {"api_name": "cPickle.dump", "line_number": 448, "usage_type": "call"}, {"api_name": "unipath.Path", "line_number": 466, "usage_type": "call"}, {"api_name": "unipath.Path", "line_number": 469, "usage_type": "call"}, {"api_name": "cPickle.load", "line_number": 474, "usage_type": "call"}, {"api_name": "shutil.rmtree", "line_number": 483, "usage_type": "call"}, {"api_name": "PIL.Image.open", "line_number": 494, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 494, "usage_type": "name"}, {"api_name": "cPickle.dumps", "line_number": 502, "usage_type": "call"}, {"api_name": "unipath.Path", "line_number": 510, "usage_type": "call"}, {"api_name": "unipath.Path", "line_number": 513, "usage_type": "call"}]} +{"seq_id": "7012090561", "text": "import matplotlib.pyplot as plt\nimport numpy as np\nimport sklearn\nimport sklearn.datasets\nimport sklearn.linear_model\n\ndef plot_decision_boundary(model, X, Y):\n # 设坐标轴宽度和高度\n #x[n,:]表示在n个数组(维)中取全部数据,直观来说,x[n,:]就是取第n集合的所有数据,\n x_min, x_max = X[0, :].min() - 1, X[0, :].max() + 1\n y_min, y_max = X[1, :].min() - 1, X[1, :].max() + 1\n h = 0.01\n # 生成网格点坐标矩阵(np.meshgrid)xx(1008,1030)yy(1008,1030)\n xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))\n # Predict the function value for the whole grid\n #\n ''' np.r_是按列连接两个矩阵,就是把两矩阵上下相加,要求列数相等;\n np.c_是按行连接两个矩阵,就是把两矩阵左右相加,要求行数相等。\n numpy中的ravel()、flatten()、squeeze()都有将多维数组转换为一维数组的功能,区别:\n ravel():如果没有必要,不会产生源数据的副本\n flatten():返回源数据的副本\n squeeze():只能对维数为1的维度降维\n '''\n ravel_xx = xx.ravel()#revel.xx(1038240,)\n ravel_ = np.c_[ravel_xx, yy.ravel()]#revel_(1038240,2)\n Z = model(ravel_)#Z(1,1038240)\n Z = Z.reshape(xx.shape)\n ''' \n plt.contourf 与 plt.contour 区别:\n f:filled,也即对等高线间的填充区域进行填充(使用不同的颜色);\n contourf:将不会再绘制等高线(显然不同的颜色分界就表示等高线本身),\n '''\n plt.contourf(xx, yy, Z, cmap=plt.cm.Spectral)\n plt.ylabel('x2')\n plt.xlabel('x1')\n plt.scatter(X[0, :], X[1, :], c=Y.reshape(X[0, :].shape), cmap=plt.cm.Spectral)\n \n\ndef sigmoid(x):\n \"\"\"\n Compute the sigmoid of x\n\n Arguments:\n x -- A scalar or numpy array of any size.\n\n Return:\n s -- sigmoid(x)\n \"\"\"\n s = 1/(1+np.exp(-x))\n return s\n\ndef load_planar_dataset():\n np.random.seed(1)\n m = 400 # number of examples\n N = int(m/2) # number of points per class\n D = 2 # dimensionality\n X = np.zeros((m,D)) # data matrix where each row is a single example\n Y = np.zeros((m,1), dtype='uint8') # labels vector (0 for red, 1 for blue)\n a = 4 # maximum ray of the flower\n\n for j in range(2):\n ix = range(N*j,N*(j+1))\n t = np.linspace(j*3.12,(j+1)*3.12,N) + np.random.randn(N)*0.2 # theta\n r = a*np.sin(4*t) + np.random.randn(N)*0.2 # radius\n X[ix] = np.c_[r*np.sin(t), r*np.cos(t)]\n Y[ix] = j\n \n X = X.T\n Y = Y.T\n\n return X, Y\n\ndef load_extra_datasets(): \n N = 200\n noisy_circles = sklearn.datasets.make_circles(n_samples=N, factor=.5, noise=.3)\n noisy_moons = sklearn.datasets.make_moons(n_samples=N, noise=.2)\n blobs = sklearn.datasets.make_blobs(n_samples=N, random_state=5, n_features=2, centers=6)\n gaussian_quantiles = sklearn.datasets.make_gaussian_quantiles(mean=None, cov=0.5, n_samples=N, n_features=2, n_classes=2, shuffle=True, random_state=None)\n no_structure = np.random.rand(N, 2), np.random.rand(N, 2)\n \n return noisy_circles, noisy_moons, blobs, gaussian_quantiles, no_structure", "repo_name": "YangYaoCD/MyPython", "sub_path": "WuEnDa/week3/planar_utils.py", "file_name": "planar_utils.py", "file_ext": "py", "file_size_in_byte": 3212, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "21", "api": [{"api_name": "numpy.meshgrid", "line_number": 14, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 14, "usage_type": "call"}, {"api_name": "numpy.c_", "line_number": 25, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.contourf", "line_number": 33, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 33, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.cm", "line_number": 33, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 34, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 34, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 35, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 35, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 36, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 36, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.cm", "line_number": 36, "usage_type": "attribute"}, {"api_name": "numpy.exp", "line_number": 49, "usage_type": "call"}, {"api_name": "numpy.random.seed", "line_number": 53, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 53, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 57, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 58, "usage_type": "call"}, {"api_name": "numpy.linspace", "line_number": 63, "usage_type": "call"}, {"api_name": "numpy.random.randn", "line_number": 63, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 63, "usage_type": "attribute"}, {"api_name": "numpy.sin", "line_number": 64, "usage_type": "call"}, {"api_name": "numpy.random.randn", "line_number": 64, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 64, "usage_type": "attribute"}, {"api_name": "numpy.c_", "line_number": 65, "usage_type": "attribute"}, {"api_name": "numpy.sin", "line_number": 65, "usage_type": "call"}, {"api_name": "numpy.cos", "line_number": 65, "usage_type": "call"}, {"api_name": "sklearn.datasets.make_circles", "line_number": 75, "usage_type": "call"}, {"api_name": "sklearn.datasets", "line_number": 75, "usage_type": "attribute"}, {"api_name": "sklearn.datasets.make_moons", "line_number": 76, "usage_type": "call"}, {"api_name": "sklearn.datasets", "line_number": 76, "usage_type": "attribute"}, {"api_name": "sklearn.datasets.make_blobs", "line_number": 77, "usage_type": "call"}, {"api_name": "sklearn.datasets", "line_number": 77, "usage_type": "attribute"}, {"api_name": "sklearn.datasets.make_gaussian_quantiles", "line_number": 78, "usage_type": "call"}, {"api_name": "sklearn.datasets", "line_number": 78, "usage_type": "attribute"}, {"api_name": "numpy.random.rand", "line_number": 79, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 79, "usage_type": "attribute"}]} +{"seq_id": "13471566211", "text": "# https://github.com/Hvass-Labs/TensorFlow-Tutorials/blob/master/11_Adversarial_Examples.ipynb\n\n# -*- coding: utf-8 -*-\n\n\nimport tensorflow as tf, numpy as np, matplotlib.pyplot as plt, _pickle as pickle\nimport os, sys, re, tarfile, datetime\nfrom six.moves import urllib\nfrom scipy.misc import imread, imresize\n\n\ncls_target = 300 # bookcase\nnoise_limit = 3\nrequired_score = 0.99\nmax_iterations = 100\nsave_dir = \"./temp/logfile\"\nif not os.path.exists(save_dir):\n os.makedirs(save_dir)\nsave_path = os.path.join(save_dir, 'savefile.ckpt')\n\n\n# load data which we will classify as bookcase #########################################################################\nimage_path = \"/Users/Sungchul/Dropbox/Images/parrot.jpeg\"\nimage_data = tf.gfile.FastGFile(image_path, 'rb').read()\n\nimg_true = imread(image_path)\nprint(img_true.dtype, img_true.shape)\nplt.imshow(img_true)\nplt.show()\n# load data which we will classify as bookcase #########################################################################\n\n\n# Inception-v3 model download and extract if not exist #################################################################\nDATA_URL = 'http://download.tensorflow.org/models/image/imagenet/inception-2015-12-05.tgz' # Inception-v3 model URL\ndest_directory = './tmp/imagenet' # directory where Inception-v3 model is downloaded\nif not os.path.exists(dest_directory):\n os.makedirs(dest_directory)\nfilename = DATA_URL.split('/')[-1] # inception-2015-12-05.tgz\nfilepath = os.path.join(dest_directory, filename) # ./tmp/imagenet/inception-2015-12-05.tgz\nif not os.path.exists(filepath): # download Inception-v3 model if not exist\n def _progress(count, block_size, total_size):\n sys.stdout.write('\\r>> Downloading %s %.1f%%' % (\n filename, float(count * block_size) / float(total_size) * 100.0))\n sys.stdout.flush()\n filepath, _ = urllib.request.urlretrieve(DATA_URL, filepath, _progress)\n print()\n statinfo = os.stat(filepath)\n print('Succesfully downloaded', filename, statinfo.st_size, 'bytes.')\ntarfile.open(filepath, 'r:gz').extractall(dest_directory) # tarfile extract\n# Inception-v3 model download and extract if not exist #################################################################\n\n\n# Creates graph from saved graph_def.pb. ###############################################################################\n# Open the graph-def file for binary reading.\npath = os.path.join(dest_directory, 'classify_image_graph_def.pb')\nwith tf.gfile.FastGFile(path, 'rb') as f:\n # TensorFlow graphs are saved to disk as so-called Protocol Buffers\n # aka. proto-bufs which is a file-format that works on multiple platforms.\n # In this case it is saved as a binary file.\n graph_def = tf.GraphDef() # First we need to create an empty graph-def.\n graph_def.ParseFromString(f.read()) # Then we load the proto-buf file into the graph-def.\n tf.import_graph_def(graph_def, name='') # Finally we import the graph-def to the default TensorFlow graph.\n# Creates graph from saved graph_def.pb. ###############################################################################\n\n\n# 정수 형태의 node ID를 인간이 이해할 수 있는 레이블로 변환 ########################################################################\nclass NodeLookup(object):\n def __init__(self,\n label_lookup_path=None,\n uid_lookup_path=None):\n if not label_lookup_path:\n label_lookup_path = os.path.join(\n './tmp/imagenet', 'imagenet_2012_challenge_label_map_proto.pbtxt')\n if not uid_lookup_path:\n uid_lookup_path = os.path.join(\n './tmp/imagenet', 'imagenet_synset_to_human_label_map.txt')\n self.node_lookup = self.load(label_lookup_path, uid_lookup_path)\n\n def load(self, label_lookup_path, uid_lookup_path):\n \"\"\"각각의 softmax node에 대해 인간이 읽을 수 있는 영어 단어를 로드 함.\n Args:\n label_lookup_path: 정수 node ID에 대한 문자 UID.\n uid_lookup_path: 인간이 읽을 수 있는 문자에 대한 문자 UID.\n Returns:\n 정수 node ID로부터 인간이 읽을 수 있는 문자에 대한 dict.\n \"\"\"\n if not tf.gfile.Exists(uid_lookup_path):\n tf.logging.fatal('File does not exist %s', uid_lookup_path)\n if not tf.gfile.Exists(label_lookup_path):\n tf.logging.fatal('File does not exist %s', label_lookup_path)\n\n # 문자 UID로부터 인간이 읽을 수 있는 문자로의 맵핑을 로드함.\n proto_as_ascii_lines = tf.gfile.GFile(uid_lookup_path).readlines()\n uid_to_human = {}\n p = re.compile(r'[n\\d]*[ \\S,]*')\n for line in proto_as_ascii_lines:\n parsed_items = p.findall(line)\n uid = parsed_items[0]\n human_string = parsed_items[2]\n uid_to_human[uid] = human_string\n\n # 문자 UID로부터 정수 node ID에 대한 맵핑을 로드함.\n node_id_to_uid = {}\n proto_as_ascii = tf.gfile.GFile(label_lookup_path).readlines()\n for line in proto_as_ascii:\n if line.startswith(' target_class:'):\n target_class = int(line.split(': ')[1])\n if line.startswith(' target_class_string:'):\n target_class_string = line.split(': ')[1]\n node_id_to_uid[target_class] = target_class_string[1:-2]\n\n # 마지막으로 정수 node ID로부터 인간이 읽을 수 있는 문자로의 맵핑을 로드함.\n node_id_to_name = {}\n for key, val in node_id_to_uid.items():\n if val not in uid_to_human:\n tf.logging.fatal('Failed to locate: %s', val)\n name = uid_to_human[val]\n node_id_to_name[key] = name\n\n return node_id_to_name\n\n def id_to_string(self, node_id):\n if node_id not in self.node_lookup:\n return ''\n return self.node_lookup[node_id]\n# 정수 형태의 node ID를 인간이 이해할 수 있는 레이블로 변환 ########################################################################\n\n\n# plot of original, original+noise, noise ##############################################################################\ndef normalize_image(x):\n x_min = x.min()\n x_max = x.max()\n x_norm = (x - x_min) / (x_max - x_min) # Normalize so all values are between 0.0 and 1.0\n return x_norm\n\ndef plot_images(image, noise, noisy_image,\n name_source, name_target,\n score_source, score_source_org, score_target):\n \"\"\"\n Plot the image, the noisy image and the noise.\n Also shows the class-names and scores.\n\n Note that the noise is amplified to use the full range of\n colours, otherwise if the noise is very low it would be\n hard to see.\n\n image: Original input image.\n noise: Noise that has been added to the image.\n noisy_image: Input image + noise.\n name_source: Name of the source-class.\n name_target: Name of the target-class.\n score_source: Score for the source-class.\n score_source_org: Original score for the source-class.\n score_target: Score for the target-class.\n \"\"\"\n fig, axes = plt.subplots(1, 3, figsize=(10, 10)) # Create figure with sub-plots.\n fig.subplots_adjust(hspace=0.1, wspace=0.1) # Adjust vertical spacing.\n\n smooth = True # Use interpolation to smooth pixels?\n if smooth:\n interpolation = 'spline16'\n else:\n interpolation = 'nearest'\n\n # Plot the original image.\n # Note that the pixel-values are normalized to the [0.0, 1.0]\n # range by dividing with 255.\n ax = axes.flat[0]\n ax.imshow(image.reshape((299, 299, 3)) / 255.0, interpolation=interpolation)\n msg = \"Original Image:\\n{0} ({1:.2%})\"\n xlabel = msg.format(name_source, score_source_org)\n ax.set_xlabel(xlabel)\n\n # Plot the noisy image.\n ax = axes.flat[1]\n ax.imshow(image.reshape((299, 299, 3)) / 255.0, interpolation=interpolation)\n msg = \"Image + Noise:\\n{0} ({1:.2%})\\n{2} ({3:.2%})\"\n xlabel = msg.format(name_source, score_source, name_target, score_target)\n ax.set_xlabel(xlabel)\n\n # Plot the noise.\n # The colours are amplified otherwise they would be hard to see.\n ax = axes.flat[2]\n ax.imshow(normalize_image(noise), interpolation=interpolation)\n xlabel = \"Amplified Noise\"\n ax.set_xlabel(xlabel)\n\n # Remove ticks from all the plots.\n for ax in axes.flat:\n ax.set_xticks([])\n ax.set_yticks([])\n\n plt.show()\n# plot of original, original+noise, noise ##############################################################################\n\n\n# top k prediction #####################################################################################################\nwith tf.Session() as session:\n tf.global_variables_initializer().run()\n\n # construction of adversarial network based on Inception-v3 model\n # 몇가지 유용한 텐서들:\n # 'softmax:0' : Scaled last layer tensor for 1000 labels\n # \"softmax/logits:0\" : Unscaled last layer tensor for 1000 labels\n # 'pool_3:0' : Next to last layer tensor of 2048 units\n # \"ResizeBilinear:0\" : Tensor for feeding resized decoded input images.\n # \"DecodeJpeg:0\" : Input layer tensor for feeding decoded input images.\n # 'DecodeJpeg/contents:0' : Input layer tensor for feeding jpeg input images.\n prob_tensor = session.graph.get_tensor_by_name('softmax:0')\n score_tensor = session.graph.get_tensor_by_name(\"softmax/logits:0\")\n pool3_tensor = session.graph.get_tensor_by_name('pool_3:0')\n resized_image_tensor = session.graph.get_tensor_by_name(\"ResizeBilinear:0\")\n decoded_image_tensor = session.graph.get_tensor_by_name(\"DecodeJpeg:0\")\n jpeg_image_tensor = session.graph.get_tensor_by_name('DecodeJpeg/contents:0')\n\n # placeholder for target class-number\n pl_cls_target = tf.placeholder(dtype=tf.int32)\n loss = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=score_tensor, labels=[pl_cls_target])\n\n # Get the gradient for the loss-function with regard to the resized input image.\n gradient = tf.gradients(loss, resized_image_tensor)\n\n # data preprocessing - put original image into Inception-v3 and save output of ResizeBilinear:0 node of Inception-v3\n # We will add a noise on this resized 299 x 299 x 3 image to classify as a bookcase\n feed_dict = {jpeg_image_tensor: image_data}\n pred, image = session.run([prob_tensor, resized_image_tensor], feed_dict=feed_dict)\n pred = np.squeeze(pred) # Convert to one-dimensional array.\n cls_source = np.argmax(pred) # Predicted class-number.\n score_source_org = pred.max() # Score for the predicted class (aka. probability or confidence).\n\n # check the class name of original image and target class name\n node_lookup = NodeLookup() # node ID --> 영어 단어 lookup을 생성한다.\n name_source = node_lookup.id_to_string(cls_source) # Names for the source and target classes.\n name_target = node_lookup.id_to_string(cls_target) # Names for the source and target classes.\n print(name_source, name_target)\n\n # training to construct an adversarial noise\n noise = 0\n for i in range(max_iterations):\n print(\"Iteration:\", i)\n noisy_image = image + noise # The noisy image is just the sum of the input image and noise.\n noisy_image = np.clip(a=noisy_image, a_min=0.0, a_max=255.0)\n\n feed_dict = {resized_image_tensor: noisy_image, pl_cls_target: cls_target}\n pred, grad = session.run([prob_tensor, gradient], feed_dict=feed_dict)\n pred = np.squeeze(pred)\n\n score_source = pred[cls_source]\n score_target = pred[cls_target]\n\n grad = np.array(grad).squeeze()\n grad_absmax = np.abs(grad).max()\n if grad_absmax < 1e-10:\n grad_absmax = 1e-10\n step_size = 7 / grad_absmax\n\n msg = \"Source score: {0:>7.2%}, class-number: {1:>4}, class-name: {2}\"\n print(msg.format(score_source, cls_source, name_source))\n msg = \"Target score: {0:>7.2%}, class-number: {1:>4}, class-name: {2}\"\n print(msg.format(score_target, cls_target, name_target))\n msg = \"Gradient min: {0:>9.6f}, max: {1:>9.6f}, stepsize: {2:>9.2f}\"\n print(msg.format(grad.min(), grad.max(), step_size))\n print()\n\n # If the score for the target-class is not high enough.\n if score_target < required_score:\n noise -= step_size * grad\n noise = np.clip(a=noise, a_min=-noise_limit, a_max=noise_limit)\n else:\n break\n\n # Plot the image and the noise.\n plot_images(image=image, noise=noise, noisy_image=noisy_image,\n name_source=name_source, name_target=name_target,\n score_source=score_source,\n score_source_org=score_source_org,\n score_target=score_target)\n\n # Print some statistics for the noise.\n msg = \"Noise min: {0:.3f}, max: {1:.3f}, mean: {2:.3f}, std: {3:.3f}\"\n print(msg.format(noise.min(), noise.max(), noise.mean(), noise.std()))", "repo_name": "JunyoungJang/Python", "sub_path": "ML.GAN/1 CIFAR-10 adversarial noise.py", "file_name": "1 CIFAR-10 adversarial noise.py", "file_ext": "py", "file_size_in_byte": 13038, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "os.path.exists", "line_number": 17, "usage_type": "call"}, {"api_name": "os.path", "line_number": 17, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 18, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 19, "usage_type": "call"}, {"api_name": "os.path", "line_number": 19, "usage_type": "attribute"}, {"api_name": "tensorflow.gfile.FastGFile", "line_number": 24, "usage_type": "call"}, {"api_name": "tensorflow.gfile", "line_number": 24, "usage_type": "attribute"}, {"api_name": "scipy.misc.imread", "line_number": 26, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 28, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 28, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 29, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 29, "usage_type": "name"}, {"api_name": "os.path.exists", "line_number": 36, "usage_type": "call"}, {"api_name": "os.path", "line_number": 36, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 37, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 39, "usage_type": "call"}, {"api_name": "os.path", "line_number": 39, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 40, "usage_type": "call"}, {"api_name": "os.path", "line_number": 40, "usage_type": "attribute"}, {"api_name": "sys.stdout.write", "line_number": 42, "usage_type": "call"}, {"api_name": "sys.stdout", "line_number": 42, "usage_type": "attribute"}, {"api_name": "sys.stdout.flush", "line_number": 44, "usage_type": "call"}, {"api_name": "sys.stdout", "line_number": 44, "usage_type": "attribute"}, {"api_name": "six.moves.urllib.request.urlretrieve", "line_number": 45, "usage_type": "call"}, {"api_name": "six.moves.urllib.request", "line_number": 45, "usage_type": "attribute"}, {"api_name": "six.moves.urllib", "line_number": 45, "usage_type": "name"}, {"api_name": "os.stat", "line_number": 47, "usage_type": "call"}, {"api_name": "tarfile.open", "line_number": 49, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 55, "usage_type": "call"}, {"api_name": "os.path", "line_number": 55, "usage_type": "attribute"}, {"api_name": "tensorflow.gfile.FastGFile", "line_number": 56, "usage_type": "call"}, {"api_name": "tensorflow.gfile", "line_number": 56, "usage_type": "attribute"}, {"api_name": "tensorflow.GraphDef", "line_number": 60, "usage_type": "call"}, {"api_name": "tensorflow.import_graph_def", "line_number": 62, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 72, "usage_type": "call"}, {"api_name": "os.path", "line_number": 72, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 75, "usage_type": "call"}, {"api_name": "os.path", "line_number": 75, "usage_type": "attribute"}, {"api_name": "tensorflow.gfile.Exists", "line_number": 87, "usage_type": "call"}, {"api_name": "tensorflow.gfile", "line_number": 87, "usage_type": "attribute"}, {"api_name": "tensorflow.logging.fatal", "line_number": 88, "usage_type": "call"}, {"api_name": "tensorflow.logging", "line_number": 88, "usage_type": "attribute"}, {"api_name": "tensorflow.gfile.Exists", "line_number": 89, "usage_type": "call"}, {"api_name": "tensorflow.gfile", "line_number": 89, "usage_type": "attribute"}, {"api_name": "tensorflow.logging.fatal", "line_number": 90, "usage_type": "call"}, {"api_name": "tensorflow.logging", "line_number": 90, "usage_type": "attribute"}, {"api_name": "tensorflow.gfile.GFile", "line_number": 93, "usage_type": "call"}, {"api_name": "tensorflow.gfile", "line_number": 93, "usage_type": "attribute"}, {"api_name": "re.compile", "line_number": 95, "usage_type": "call"}, {"api_name": "tensorflow.gfile.GFile", "line_number": 104, "usage_type": "call"}, {"api_name": "tensorflow.gfile", "line_number": 104, "usage_type": "attribute"}, {"api_name": "tensorflow.logging.fatal", "line_number": 116, "usage_type": "call"}, {"api_name": "tensorflow.logging", "line_number": 116, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 156, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 156, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 193, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 193, "usage_type": "name"}, {"api_name": "tensorflow.Session", "line_number": 198, "usage_type": "call"}, {"api_name": "tensorflow.global_variables_initializer", "line_number": 199, "usage_type": "call"}, {"api_name": "tensorflow.placeholder", "line_number": 217, "usage_type": "call"}, {"api_name": "tensorflow.int32", "line_number": 217, "usage_type": "attribute"}, {"api_name": "tensorflow.nn.sparse_softmax_cross_entropy_with_logits", "line_number": 218, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 218, "usage_type": "attribute"}, {"api_name": "tensorflow.gradients", "line_number": 221, "usage_type": "call"}, {"api_name": "numpy.squeeze", "line_number": 227, "usage_type": "call"}, {"api_name": "numpy.argmax", "line_number": 228, "usage_type": "call"}, {"api_name": "numpy.clip", "line_number": 242, "usage_type": "call"}, {"api_name": "numpy.squeeze", "line_number": 246, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 251, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 252, "usage_type": "call"}, {"api_name": "numpy.clip", "line_number": 268, "usage_type": "call"}]} +{"seq_id": "18485018567", "text": "import logging, psycopg2, psycopg2.extras, time\nfrom psycopg2.extensions import AsIs\nfrom psycopg2.extras import execute_values\n\n\nclass Db(object):\n \"\"\"\n Database handler\n \"\"\"\n __config = {\n 'user': 'postgres',\n 'password': 'Jk7aWctVX5',\n 'host': '127.0.0.1',\n 'database': 'trademark'\n }\n\n def __init__(self):\n self.logger = logging.getLogger(__name__)\n try:\n self.cnx = psycopg2.connect(**self.__config)\n self.cur = self.cnx.cursor(cursor_factory=psycopg2.extras.RealDictCursor)\n self.cur.execute(\"SET SEARCH_PATH = %s\" % 'trademark_app_python')\n self.cnx.commit()\n # self.logger.info('Connected to database')\n except psycopg2.Error as err:\n self.logger.error(err)\n\n def insert_dict(self, d, table):\n if d is None or table is None:\n logging.error('INSERT ERROR: Missing dict or table')\n return None\n keys = d.keys()\n columns = ', '.join(keys)\n values = ', '.join(['%({})s'.format(k) for k in keys])\n start_time = time.time()\n q = 'INSERT INTO {0} ({1}) values ({2}) RETURNING id'.format(table, columns, values)\n try:\n q = self.cur.mogrify(q, d)\n print(q)\n exit()\n self.cur.execute(q)\n self.cnx.commit()\n last_row = self.cur.fetchone()\n self.logger.debug('Inserted id [%s] in table %s [%s sec]', last_row['id'], table, time.time() - start_time)\n return last_row['id']\n except psycopg2.Error as err:\n self.logger.error(err)\n self.cnx.rollback()\n return None\n\n def insert_dict2(self, list1, table):\n if l is None or table is None:\n logging.error('INSERT ERROR: Missing dict or table')\n return None\n keys = l[0].keys()\n columns = ', '.join(keys)\n # values = ', '.join(['%({})s'.format(k) for k in keys])\n # values = ', '.join(['%s' for k in keys])\n values = []\n for d in list1:\n values.append(list(d.values()))\n print(values)\n start_time = time.time()\n q = 'INSERT INTO {0} ({1}) values (%s) RETURNING id'.format(table, columns)\n print(q)\n try:\n execute_values(self.cur, q, values)\n # q = self.cur.mogrify(q, l)\n print(q)\n exit()\n self.cur.execute(q)\n self.cnx.commit()\n last_row = self.cur.fetchone()\n self.logger.debug('Inserted id [%s] in table %s [%s sec]', last_row['id'], table, time.time() - start_time)\n return last_row['id']\n except psycopg2.Error as err:\n self.logger.error(err)\n self.cnx.rollback()\n return None\n\ndict1 = {'ime': 'Vasko', 'prezime': 'Kelkocev', 'v': 38}\ndict2 = {'ime': 'Viki', 'prezime': 'Kelkocev', 'v': 36}\ndict3 = {'ime': 'Ema', 'prezime': 'Kelkocev', 'v': 1}\nl = [dict1, dict2, dict3]\n\ndbc = Db()\ndbc.insert_dict2(l, 'tabela')\n", "repo_name": "vkelk/uspto_trademark_parser", "sub_path": "multiinsert.py", "file_name": "multiinsert.py", "file_ext": "py", "file_size_in_byte": 3042, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "21", "api": [{"api_name": "logging.getLogger", "line_number": 18, "usage_type": "call"}, {"api_name": "psycopg2.connect", "line_number": 20, "usage_type": "call"}, {"api_name": "psycopg2.extras", "line_number": 21, "usage_type": "attribute"}, {"api_name": "psycopg2.Error", "line_number": 25, "usage_type": "attribute"}, {"api_name": "logging.error", "line_number": 30, "usage_type": "call"}, {"api_name": "time.time", "line_number": 35, "usage_type": "call"}, {"api_name": "time.time", "line_number": 44, "usage_type": "call"}, {"api_name": "psycopg2.Error", "line_number": 46, "usage_type": "attribute"}, {"api_name": "logging.error", "line_number": 53, "usage_type": "call"}, {"api_name": "time.time", "line_number": 63, "usage_type": "call"}, {"api_name": "psycopg2.extras.execute_values", "line_number": 67, "usage_type": "call"}, {"api_name": "time.time", "line_number": 74, "usage_type": "call"}, {"api_name": "psycopg2.Error", "line_number": 76, "usage_type": "attribute"}]} +{"seq_id": "39137625468", "text": "#C:\\Users\\han\\AppData\\Local\\Programs\\Python\\Python37-32\\Scripts\nimport requests, json\nimport time\nimport zulip\nimport os\nimport datetime\nimport izyrtm_prop\n\nfilePath = os.getcwd()+'/snapshot/'\n\ndef getSessionId():\n\n loginParams = {'user': izyrtm_prop.apm_id, 'password':izyrtm_prop.apm_pw}\n loginHeader = {'Content-Type':'application/json'}\n loginUrl = izyrtm_prop.apm_url+'/login'\n\n print('1_'+loginUrl+' / '+izyrtm_prop.apm_id+' / '+izyrtm_prop.apm_pw)\n response = requests.post(url=loginUrl, headers=loginHeader, data=json.dumps(loginParams), verify=False)\n #print(response.json())\n #print(response.headers)\n print('1_')\n #print(response.content)\n cookieValue = response.cookies.get('grafana_session')\n return cookieValue\n\ndef getSnapShot(sessionId, panelId, startDate, endDate):\n \n if startDate is '':\n endDate = datetime.datetime.now()\n endDateMil = str(int(endDate.timestamp()*1000))\n startDate = endDate - datetime.timedelta(hours = 3)\n startDateMil = str(int(startDate.timestamp()*1000))\n else:\n startDateMil = startDate\n endDateMil = endDate\n\n snapShotUrl = izyrtm_prop.apm_url+'/render/dashboard-solo/db/docker-and-system-monitoring?orgId=1&panelId='+panelId+'&from='+startDateMil+'&to='+endDateMil+'&width=1000&height=500'\n snapShotCookies = {'grafana_session': sessionId}\n #snapShotHeader = {'Content-Type':'application/json'}\n\n #snapShotParams = 'orgId=1&panelId=8&from=1568985607884&to=1569072007884&width=1000&height=500'\n\n response = requests.get(url=snapShotUrl, cookies=snapShotCookies, verify=False)\n print('2_'+str(sessionId))\n #print(response.content)\n return response\n\ndef saveFile(fileName, response):\n if not(os.path.isdir(filePath)):\n os.makedirs(os.path.join(filePath))\n\n open(filePath+fileName, 'wb').write(response.content)\n\ndef uploadFile(fileName, bSite, bEmail, bApiKey):\n client = zulip.Client(site=bSite, email=bEmail, api_key=bApiKey)\n\n # Upload a file\n path_to_file = filePath + fileName\n with open(path_to_file, 'rb') as fp:\n result = client.call_endpoint(\n 'user_uploads',\n method='POST',\n files=[fp]\n )\n #print(result)\n return getZulipFilePath(result)\n\ndef getZulipFilePath(result):\n data = result.get('uri')\n return data\n\nif __name__ == '__main__':\n sessionId = getSessionId()\n response = getSnapShot(sessionId, '8', '','')\n\n timestamp = int(time.time()*1000.0)\n fileName = str(timestamp)+'.png'\n saveFile(fileName, response)\n #uploadedFileUri = uploadFile(fileName)\n", "repo_name": "izyrtm/izyrtm-server", "sub_path": "rtmBot/izyrtm_call.py", "file_name": "izyrtm_call.py", "file_ext": "py", "file_size_in_byte": 2616, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "os.getcwd", "line_number": 9, "usage_type": "call"}, {"api_name": "izyrtm_prop.apm_id", "line_number": 13, "usage_type": "attribute"}, {"api_name": "izyrtm_prop.apm_pw", "line_number": 13, "usage_type": "attribute"}, {"api_name": "izyrtm_prop.apm_url", "line_number": 15, "usage_type": "attribute"}, {"api_name": "izyrtm_prop.apm_id", "line_number": 17, "usage_type": "attribute"}, {"api_name": "izyrtm_prop.apm_pw", "line_number": 17, "usage_type": "attribute"}, {"api_name": "requests.post", "line_number": 18, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 18, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 29, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 29, "usage_type": "attribute"}, {"api_name": "datetime.timedelta", "line_number": 31, "usage_type": "call"}, {"api_name": "izyrtm_prop.apm_url", "line_number": 37, "usage_type": "attribute"}, {"api_name": "requests.get", "line_number": 43, "usage_type": "call"}, {"api_name": "os.path.isdir", "line_number": 49, "usage_type": "call"}, {"api_name": "os.path", "line_number": 49, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 50, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 50, "usage_type": "call"}, {"api_name": "os.path", "line_number": 50, "usage_type": "attribute"}, {"api_name": "zulip.Client", "line_number": 55, "usage_type": "call"}, {"api_name": "time.time", "line_number": 76, "usage_type": "call"}]} +{"seq_id": "26793113331", "text": "from time import sleep\nimport requests\nfrom bs4 import BeautifulSoup\n\n# helper function to write html to file\ndef writeHTML(fileName, html):\n f = open(fileName, \"w+\")\n f.write(html)\n f.close()\n\n# helper function to convert incremental to string including leading zeroes\ndef incToString(incremental):\n incString = str(incremental)\n while len(incString) < 6:\n incString = \"0\" + incString\n return incString\n\nif __name__ == '__main__':\n rootPath = \"/storage/jeremy/imf/exec-archives/\"\n rootHtmlName = \"/storage/jeremy/imf/exec-archives/html/\"\n permURL = 'https://archivescatalog.imf.org/Details/ArchiveExecutive/'\n brokenTracker = 0\n totalReqs = 0\n\n # URL is incrementable - starting with last accessed page (.../125221935.html)\n for incremental in range(221935, 322149):\n totalReqs += 1\n if (incremental % 100 == 0):\n print(\"Made it to \" + incToString(incremental))\n\n #create OG request\n iterURL = permURL + str(incremental + 125000000)\n headers = {\n 'User-Agent': 'Haile Terry: hailedterry@gmail.com'\n }\n # response = requests.get(iterURL)\n response = requests.get(iterURL, headers=headers)\n\n # parse for record and hierarchy\n soup = BeautifulSoup(response.content, 'html.parser')\n record = soup.find(class_='record')\n hierarchy = soup.find(class_='hierarchy')\n\n # if no record, save in special folder and continue to next iteration\n if record == None:\n title = soup.find(\"title\").text.strip()\n fileName = rootHtmlName + \"other/\"\n\n # for requests rejected by server failure\n if title == \"Request Rejected\":\n fileName += \"request-rejected/\"\n brokenTracker += 1\n # for records that do not exist & returned search home page\n elif \"Simple search\" in title:\n fileName += \"no-record/\"\n # catch-all for any others\n else:\n fileName += \"unknown-error/\"\n brokenTracker += 1\n \n fileName += incToString(incremental) + \".html\"\n writeHTML(fileName, soup.prettify())\n\n # if broken for 50 iterations, print debug statements and stop\n if brokenTracker >= 50:\n print(\"Broken for 50 iterations, stopping on \" + incToString(incremental))\n print(\"Total reqs before stopping: \" + str(totalReqs))\n break\n continue\n\n # parse for file type\n fileType = record.find(class_=\"label\", string=\"Level of description\").parent.find(class_=\"value\").text\n \n # set file path based on file type and/or missing hierarchy\n htmlName = rootHtmlName\n writeable = record.prettify()\n if hierarchy == None:\n htmlName += \"other/no-hierarchy/\"\n else:\n if fileType == \"item\" or fileType == \"collection\" or fileType == \"series\" or fileType == \"sub-series\":\n htmlName += fileType + \"/\"\n else:\n htmlName += \"other/other-file-type/\"\n writeable += \"\\n\\n\" + hierarchy.prettify()\n htmlName += incToString(incremental) + \".html\"\n\n # save html to new file\n writeHTML(htmlName, writeable)\n\n # create second request for PDF\n if fileType == \"item\":\n linkContainer = record.find(class_='ais-image-container')\n\n # if link container does not exist, save in special folder and continue to next iteration\n if (linkContainer == None):\n htmlName = rootHtmlName + \"other/no-link-container/\" + incToString(incremental) + \".html\"\n writeHTML(htmlName, soup.prettify())\n continue\n\n pdfURL = linkContainer.find('a')['href']\n\n # if no href found, save in special folder and continue to next iteration\n if (pdfURL == None):\n htmlName = rootHtmlName + \"other/no-url/\" + incToString(incremental) + \".html\"\n writeHTML(htmlName, soup.prettify())\n continue\n pdfResp = requests.get(pdfURL)\n\n # save PDF to new text file\n pdfName = rootPath + \"pdfs/\" + incToString(incremental) + \".pdf\"\n f2 = open(pdfName, \"wb\")\n f2.write(pdfResp.content)\n f2.close()\n\n brokenTracker = 0\n sleep (1)\n\n # less file, inside 'F'\n # come back to 125061624 - 125065837\n\n # if no record try again 10 times before giving up\n\n # check for duplicate files due to multiple processes running", "repo_name": "optimisms/dhl-scrapers", "sub_path": "imf/scraper-imf-exec-archives.py", "file_name": "scraper-imf-exec-archives.py", "file_ext": "py", "file_size_in_byte": 4651, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "requests.get", "line_number": 37, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 40, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 107, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 116, "usage_type": "call"}]} +{"seq_id": "16624541941", "text": "import requests\nimport bs4\n\nclass Retriever(object):\n urlcount = 0\n sites = {}\n \n def scrapeGoogleNews(self):\n \"\"\" To get a list of news URL's from google \"\"\"\n \n # Google news URL to use\n gUrl=\"http://news.google.com/\"\n \n # Getting google news page\n response = requests.get(gUrl) \n \n # Putting page into beautifulsoap\n soup = bs4.BeautifulSoup(response.content)\n\n for a in soup.find_all('a', id=True):\n # extracting 'href' attribute values from Tag a\n temp = a['href']\n \n # Removing google sites\n if \"google\" not in temp:\n temp = temp.strip()\n if not self.sites.has_key(temp):\n self.sites[temp] = temp\n\n # Updating self.urelcount to list found urls\n self.urlcount = self.sites.__len__()\n\n def getNumberOfSites(self):\n \"\"\" Returns the number of URL's \"\"\"\n return self.urlcount\n \n def getSitesDict(self):\n \"\"\" Returns dictionary containing sites as keys and values \"\"\"\n return self.sites\n\n\n\nif __name__ == \"__main__\":\n '''Test Class'''\n c = Retriever()\n c.scrapeGoogleNews()\n print(c.getSitesDict())\n", "repo_name": "voite1/news_analysis", "sub_path": "google/ScrapeGoogle.py", "file_name": "ScrapeGoogle.py", "file_ext": "py", "file_size_in_byte": 1254, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "requests.get", "line_number": 15, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 18, "usage_type": "call"}]} +{"seq_id": "23020390937", "text": "from skimage import data, segmentation, color\nfrom skimage.exposure import histogram\nimport matplotlib.pyplot as plt\nfrom skimage.future import graph\nimport numpy as np\n\n\ndef create_mask(filename, n_segments=400, n_cuts=10):\n img = data.load(filename)\n\n labels1 = segmentation.slic(img, n_segments=n_segments)\n\n rag = graph.rag_mean_color(img, labels1, mode='similarity')\n labels2 = graph.cut_normalized(labels1, rag, num_cuts=n_cuts)\n\n return labels2, img\n\ndef save_segments(labels, img, image_name, mask=-1):\n for value in np.unique(labels):\n temp_label = np.where(labels == value, value, mask)\n # This creates a white-black image\n temp_out = color.label2rgb(temp_label, img, bg_label=mask, colors=['white', 'black'], image_alpha=0, alpha=1)\n\n # This overlays on the average of background\n # temp_out = color.label2rgb(temp_label, img, kind='avg')\n\n plt.imshow(temp_out)\n plt.axis('off')\n plt.savefig('vocabulary/' + image_name + '_mask_{}'.format(value) + '.jpg')\n\n\nif __name__ == \"__main__\":\n file = '/Pictures/2_1279.jpg'\n image_name = file.split('/')[10].split('.')[0]\n\n labels, img = create_mask(file)\n\n save_segments(labels, img, image_name)\n\n\n\n", "repo_name": "jonahhdeykin/uml_project", "sub_path": "n_cut_image.py", "file_name": "n_cut_image.py", "file_ext": "py", "file_size_in_byte": 1239, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "21", "api": [{"api_name": "skimage.data.load", "line_number": 9, "usage_type": "call"}, {"api_name": "skimage.data", "line_number": 9, "usage_type": "name"}, {"api_name": "skimage.segmentation.slic", "line_number": 11, "usage_type": "call"}, {"api_name": "skimage.segmentation", "line_number": 11, "usage_type": "name"}, {"api_name": "skimage.future.graph.rag_mean_color", "line_number": 13, "usage_type": "call"}, {"api_name": "skimage.future.graph", "line_number": 13, "usage_type": "name"}, {"api_name": "skimage.future.graph.cut_normalized", "line_number": 14, "usage_type": "call"}, {"api_name": "skimage.future.graph", "line_number": 14, "usage_type": "name"}, {"api_name": "numpy.unique", "line_number": 19, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 20, "usage_type": "call"}, {"api_name": "skimage.color.label2rgb", "line_number": 22, "usage_type": "call"}, {"api_name": "skimage.color", "line_number": 22, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 27, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 27, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.axis", "line_number": 28, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 28, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 29, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 29, "usage_type": "name"}]} +{"seq_id": "21473810495", "text": "import argparse\nfrom soda_data.sdneo import HF_TOKEN\nfrom huggingface_hub import HfApi\n\nif __name__ == \"__main__\":\n\n parser = argparse.ArgumentParser(description=\"Converts XML data into AI ready data and uploads it to the huggingface repository.\")\n parser.add_argument(\"--local_folder\", default=\"/data/neo_dumps\", help=\"Directory where the neo dumps are located.\")\n parser.add_argument(\"--repo_name\", default=\"EMBO/SourceData\", help=\"Name of the repository where the dataset will be uploaded.\")\n parser.add_argument(\"--path_repo\", default=\"neo_dumps\", help=\"Name of the repository where the dataset will be uploaded.\")\n parser.add_argument(\"--token\", default=\"\", help=\"Huggingface token to upload the dataset.\")\n args = parser.parse_args()\n\n if args.repo_name:\n # Use the huggingface api to upload the data to the hub\n token = args.token if args.token else HF_TOKEN\n if not token:\n raise ValueError(\"No token provided. Please provide a token to upload the data to the hub.\")\n api = HfApi(\n token=token,\n )\n api.upload_folder(\n folder_path=args.local_folder,\n path_in_repo=args.path_repo,\n repo_id=args.repo_name,\n repo_type=\"dataset\",\n token=token,\n )\n", "repo_name": "source-data/soda-data", "sub_path": "src/soda_data/dataproc/upload_neo_dump.py", "file_name": "upload_neo_dump.py", "file_ext": "py", "file_size_in_byte": 1299, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 7, "usage_type": "call"}, {"api_name": "soda_data.sdneo.HF_TOKEN", "line_number": 16, "usage_type": "name"}, {"api_name": "huggingface_hub.HfApi", "line_number": 19, "usage_type": "call"}]} +{"seq_id": "74951766131", "text": "from django.shortcuts import render\nfrom PyDictionary import PyDictionary\nimport dictionary\n# Create your views here.\ndef index(request):\n return render(request, 'index.html')\ndef word(request):\n search = request.GET.get('search')\n dictionary = PyDictionary()\n meaning = dictionary.meaning(search)\n context = {\n 'meaning': meaning, \n 'search': search\n }\n return render(request, 'word.html', context)\n\n", "repo_name": "alineralncs/EnglishDictionary", "sub_path": "dictionary/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 436, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "21", "api": [{"api_name": "django.shortcuts.render", "line_number": 6, "usage_type": "call"}, {"api_name": "PyDictionary.PyDictionary", "line_number": 9, "usage_type": "call"}, {"api_name": "dictionary.meaning", "line_number": 10, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 15, "usage_type": "call"}]} +{"seq_id": "14041859489", "text": "import ply.lex as lex\n\nfrom pdp12_asm import pdp12_perm_sym\n\n\ndef lap6_lex():\n mode = \"lmode\"\n\n tokens = (\n \"COMMA\",\n \"ASTERISK\",\n \"STATEMENT_END\",\n \"EQUALS\",\n \"PLUS\",\n \"MINUS\",\n \"DOT\",\n \"TAPE_DIRECTION\",\n \"AMPERSAND\",\n \"EXCLAMATION\",\n \"BACKSLASH\",\n\n \"NUMBER\",\n \"SYMBOL\",\n \"INSTRUCTION\",\n \"P_OPERATE_1\",\n \"P_OPERATE_2\",\n \"P_EXTENDED_ARITHMETIC\",\n \"P_EXTENDED_ARITHMETIC_LONG\",\n \"P_CLA\",\n\n \"ASMIFZ\",\n \"ASMIFN\",\n \"ASMIFM\",\n \"ASMSKP\",\n \"DECIMAL\",\n \"EJECT\",\n \"FIELD\",\n \"I\",\n \"LIST\",\n \"LISTAPE\",\n \"LMODE\",\n \"LODSYM\",\n \"NOLIST\",\n \"OCTAL\",\n \"PAGE\",\n \"PMODE\",\n \"SAVSYM\",\n \"SEGMNT\",\n \"TEXT\",\n \"Z\",\n )\n\n t_PLUS = r\"\\+\"\n t_MINUS = r\"\\-\"\n t_EXCLAMATION = r\"\\!\"\n t_COMMA = r\"\\,\"\n t_EQUALS = r\"\\=\"\n t_ASTERISK = r\"\\*\"\n t_DOT = r\"\\.\"\n\n def t_COMMENT(t):\n r\"\"\"\\/[^\\r\\n|\\r|\\n]*\"\"\"\n\n def t_NUMBER(t):\n r\"\"\"\\d+\"\"\"\n return t\n\n def t_SYMBOL(t):\n r\"\"\"[a-zA-Z][a-zA-Z0-9]*\"\"\"\n if t.value.lower() in pdp12_perm_sym.all_instructions:\n # Not-so-pretty separation of \"microcoded\" instruction classes for special handling\n nonlocal mode\n t.type = \"INSTRUCTION\"\n if mode == \"pmode\" and pdp12_perm_sym.all_instructions[t.value.lower()][\"class\"] in [\"P_OPERATE_1\",\n \"P_OPERATE_2\",\n \"P_EXTENDED_ARITHMETIC\",\n \"P_EXTENDED_ARITHMETIC_LONG\",\n \"P_CLA\"]:\n t.type = pdp12_perm_sym.all_instructions[t.value.lower()][\"class\"]\n elif t.value.lower() in pdp12_perm_sym.all_pseudo_op:\n if t.value.lower() == \"pmode\" or t.value.lower() == \"lmode\":\n mode = t.value.lower()\n t.type = t.value.upper()\n return t\n\n def t_semicolon(t):\n r\"\"\";\"\"\"\n t.type = \"STATEMENT_END\"\n return t\n\n def t_newline(t):\n r\"\"\"\\n|\\r|\\r\\n|\\f\"\"\"\n t.lexer.lineno += 1\n t.type = \"STATEMENT_END\"\n return t\n\n t_ignore = \" \\t;\"\n\n def t_error(t):\n print(f\"Illegal character \\\"{t.value[0]}\\\"\")\n t.lexer.skip(1)\n\n instance = lex.lex()\n return instance\n", "repo_name": "jnowaczek/pdp12-asm", "sub_path": "src/pdp12_asm/asm_lexer.py", "file_name": "asm_lexer.py", "file_ext": "py", "file_size_in_byte": 2693, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 4, "dataset": "github-code", "pt": "21", "api": [{"api_name": "pdp12_asm.pdp12_perm_sym.all_instructions", "line_number": 70, "usage_type": "attribute"}, {"api_name": "pdp12_asm.pdp12_perm_sym", "line_number": 70, "usage_type": "name"}, {"api_name": "pdp12_asm.pdp12_perm_sym.all_instructions", "line_number": 74, "usage_type": "attribute"}, {"api_name": "pdp12_asm.pdp12_perm_sym", "line_number": 74, "usage_type": "name"}, {"api_name": "pdp12_asm.pdp12_perm_sym.all_instructions", "line_number": 79, "usage_type": "attribute"}, {"api_name": "pdp12_asm.pdp12_perm_sym", "line_number": 79, "usage_type": "name"}, {"api_name": "pdp12_asm.pdp12_perm_sym.all_pseudo_op", "line_number": 80, "usage_type": "attribute"}, {"api_name": "pdp12_asm.pdp12_perm_sym", "line_number": 80, "usage_type": "name"}, {"api_name": "ply.lex.lex", "line_number": 103, "usage_type": "call"}, {"api_name": "ply.lex", "line_number": 103, "usage_type": "name"}]} +{"seq_id": "74570397172", "text": "\"\"\"\nAuthor - Luke Quinn\nCapabilties - 1) Creating numpy pickle file to imporve load speeds\n 2) General purpose PCA\n \nNote this requires you to have the exon.csv file present\n\"\"\"\nimport numpy as np\nimport csv\nimport pickle\nimport matplotlib as mpl\nmpl.use('Agg')\nimport matplotlib.pyplot as plt\nimport time\n\n# see https://github.com/jacoblevine/PhenoGraph\nimport phenograph\nfrom sklearn.decomposition import TruncatedSVD\nfrom scipy import sparse\nfrom sklearn.manifold import TSNE\n\n\n\n\ndef PCAWrapper(data):\n dataT ,variences = SVDWrapper(data, dim=2) # note this returns data.T as a sparse TrucatedSVD\n Xaxis = \"PC-1, Var=\" + str(variences[0])\n Yaxis = \"PC-2, Var=\" + str(variences[1])\n\n DrawScatterPlot(dataT.T, \"PCA of Gene data\", labelX=Xaxis, labelY=Yaxis)\n \n\ndef BuildNumpyArray(save=False):\n \n data = np.zeros((50281, 15928),dtype=np.float64)\n with open('human_MTG_2018-06-14_exon-matrix.csv') as csv_file:\n csv_reader = csv.reader(csv_file,delimiter=',', quoting=csv.QUOTE_NONE)\n matCount = 0\n for i,row in enumerate(csv_reader): \n if i > 0:\n geneData = np.array(row[1:], dtype=np.dtype(np.float64))\n data[matCount] = geneData\n matCount += 1\n if save:\n print(\"Saving matrix\")\n np.save(\"matrixPickle\", data)\n\n print(\"Data read but not reduced here\")\n return data\n\n\n\n\ndef get_genes_to_delete():\n with open('human_MTG_2018-06-14_genes-rows.csv') as file:\n entrez_ids_to_delete = []\n for l in csv.reader(file, quotechar='\"', delimiter=',', quoting=csv.QUOTE_ALL, skipinitialspace=True):\n if 'X' in l[1] or 'Y' in l[1]:\n entrez_id = l[2]\n entrez_ids_to_delete.append(entrez_id)\n\n return entrez_ids_to_delete\n\ndef get_samples_to_delete():\n with open('human_MTG_2018-06-14_samples-columns.csv') as file:\n samples_to_delete = []\n next(file)\n sample_name = 0\n total_reads = 19\n percent_exon = 20\n percent_intron = 21\n percent_aligned_reads_total = 28\n reads_unique = 25\n for l in csv.reader(file, quotechar='\"', delimiter=',', quoting=csv.QUOTE_ALL, skipinitialspace=True):\n # the total value doesn't change anything so may not be necessary\n total_aligned_to_exon_intron = (float(l[percent_exon]) + float(l[percent_intron])) * float(l[total_reads]) / 100.0\n if float(l[reads_unique]) <= 50 or float(l[percent_aligned_reads_total]) <= 40 or total_aligned_to_exon_intron <= 500000:\n samples_to_delete.append(l[sample_name])\n\n return samples_to_delete\n\ndef BuildFilteredNumpyArray(save=False):\n genesToDelete = get_genes_to_delete()\n samplesToDelete = get_samples_to_delete()\n\n data = np.zeros((50281 - len(genesToDelete), 15928),dtype=np.float64)\n with open('human_MTG_2018-06-14_exon-matrix.csv') as csv_file:\n csv_reader = csv.reader(csv_file,delimiter=',', quoting=csv.QUOTE_NONE)\n matCount = 0\n samples_header = None\n for i,row in enumerate(csv_reader):\n if i == 0:\n samples_header = row\n if i > 0 and row[0].strip('\\\"') not in genesToDelete:\n geneData = np.array(row[1:], dtype=np.dtype(np.float64))\n data[matCount] = geneData\n matCount += 1\n columnIndicesToDelete = []\n\n for i,name in enumerate(samples_header):\n if name.strip('\\\"') in samplesToDelete:\n columnIndicesToDelete.append(i)\n data = np.delete(data, columnIndicesToDelete, axis=1)\n #remove 0 rows\n data = data[~np.all(data == 0, axis=1)]\n\n\n if save:\n print(\"Saving matrix\")\n np.save(\"matrixPickle\", data)\n\n print(\"Data read but not reduced here\")\n return data, columnIndicesToDelete\n\n\ndef DisplayPCAOnExonMatrix(data):\n \n #if not data:\n # data = np.load('./matrixPickle.npy')\n\n new_data, variances, eigenvectors = PCA(data)\n\n y = []\n total = 0\n for point in variances:\n y.append(point)\n total += point\n if total > 50:\n print(\"It took \" + str(len(y)) + \" to account for \" + str(total) + \" of the variance\")\n break\n \n x = [i for i in range(len(y))]\n\n plt.figure()\n plt.plot(x,y)\n plt.xlabel('Dimension')\n plt.ylabel('Captured Variance')\n\n plt.savefig('./VariancePlot.png')\n\n np.save('Variances', variances)\n\n \"\"\"\n plt.figure()\n plt.plot(new_data[0,:], new_data[1:], 'x')\n plt.title('PCA modded data') \n plt.savefig('./2dPCAPlot.png')\n \"\"\"\n\ndef Testsetup():\n y = np.random.random_integers(1,100, 100)\n plt.figure()\n plt.stem(y.ravel())\n plt.xlabel('Linear')\n plt.ylabel('Random')\n plt.savefig('./Temp.png')\n\ndef DrawScatterPlot(data, name, labelX='X', labelY='Y', colour_seq=None):\n plt.figure()\n plt.scatter(data[0,:], data[1,:], c=colour_seq, s=1)\n plt.title(name)\n plt.xlabel(labelX)\n plt.ylabel(labelY)\n name = \"./\" + name.replace(\" \", \"\") + str(time.time()) + \".png\"\n plt.savefig(name, transparent=True)\n\ndef VariableSubset(data):\n # cut cells who have less than 1000 genes\n \n keep_cells = np.count_nonzero(data, axis=0) > 1000\n data = data[:,keep_cells]\n #cut genes with low variabilty\n keep_genes = np.std(data, axis=1) > 0\n data = data[keep_genes]\n\n data /= np.sum(data, axis=0) # convert to percents\n data *= 1e6 # convert percents to cpm\n data += 1 # add 1 for log transform\n data = np.log(data) # log transform\n print(\"The variable subset shape is :\", data.shape)\n return data\n\n\ndef SVDWrapper(data, dim=50):\n data = sparse.csr_matrix(data.T)\n svd = TruncatedSVD(n_components=dim, n_iter=7, random_state=42)\n svd.fit(data)\n return svd.transform(data), svd.explained_variance_ratio_\n\ndef TSNEWrapper(data):\n return TSNE(n_components=2).fit_transform(data)\n\ndef TSNEPipeline(data):\n\n print(\"Starting SVD at: \", time.time())\n data = SVDWrapper(data, dim=20)[0] # note this returns data.T as a sparse TrucatedSVD\n print(\"SVD complete at: \" , time.time())\n print(\"result shape is \", data.shape)\n print(\"Starting TSNE ... \")\n Y = TSNEWrapper(data)\n print(\"TSNE finished at \", time.time())\n print(Y.shape)\n return Y.T\n\n\ndef SubsetsBasedOnType(data, ignoreIdx):\n\n keep_cols_exc = []\n keep_cols_inb = []\n keep_cols_non_nerual = []\n \n with open('human_MTG_2018-06-14_samples-columns.csv') as csv_file:\n csv_reader = csv.reader(csv_file,delimiter=',')\n line_count = 0\n for row in csv_reader:\n if line_count in ignoreIdx:\n line_count += 1\n continue\n if \"Inh\" in row[-1]:\n keep_cols_inb.append(line_count)\n elif \"Exc\" in row[-1]:\n keep_cols_exc.append(line_count)\n else:\n keep_cols_non_nerual.append(line_count)\n line_count += 1\n \n return (keep_cols_exc, keep_cols_inb, keep_cols_non_nerual)\n\ndef PhenoClusterSubsets(data, subsets_indices):\n\n print(\"Clustering 1\")\n exc_colours, graph, Q = phenograph.cluster(data[subsets_indices[0]])\n print(\"Clustering 2\")\n inb_colours, graph, Q = phenograph.cluster(data[subsets_indices[1]])\n print(\"Clustering 3\")\n non_neural_colours, graph, Q = phenograph.cluster(data[subsets_indices[2]])\n\n print(np.max(exc_colours))\n print(np.max(inb_colours))\n print(np.max(non_neural_colours))\n\n exc_colours += 1\n \n inb_colours += (np.max(exc_colours) + 1)\n non_neural_colours += (np.max(inb_colours) + 1) \n return (exc_colours, inb_colours, non_neural_colours)\n\ndef merge_arrays_inorder(idx, poll_array):\n\n idx1 = 0\n idx2 = 0\n\n orderedIdx = []\n orderedPoll = []\n\n while idx1 + idx2 < len(idx[0]) + len(idx[1]):\n if idx1 >= len(idx[0]):\n orderedIdx.append(idx2)\n orderedPoll.append(poll_array[1][idx2])\n idx2 += 1\n elif idx2 >= len(idx[1]):\n orderedIdx.append(idx1)\n orderedPoll.append(poll_array[0][idx1])\n idx1 += 1\n elif idx[0][idx1] < idx[1][idx2]:\n orderedIdx.append(idx1)\n orderedPoll.append(poll_array[0][idx1])\n idx1 += 1\n else:\n orderedIdx.append(idx2)\n orderedPoll.append(poll_array[1][idx2])\n idx2 += 1\n\n return orderedIdx, orderedPoll\n\ndef AgglogClusterSubsets(data, subsets_indices):\n\n print(\"Clustering Exc \")\n cluster1 = agg(n_clusters=24).fit(data[subsets_indices[0]])\n print(\"Clustering Inb \")\n cluster2 = agg(n_clusters=45).fit(data[subsets_indices[1]])\n print(\"Clustering Non-Neural \")\n cluster3 = agg(n_clusters=6).fit(data[subsets_indices[2]])\n\n exc_colours = cluster1.labels_\n inb_colours = cluster2.labels_\n non_neural_colours = cluster3.labels_\n\n print(np.max(exc_colours))\n print(np.max(inb_colours))\n print(np.max(non_neural_colours))\n\n # builds a colour sequences that increases in number\n inb_colours += (np.max(exc_colours) + 1)\n non_neural_colours += (np.max(inb_colours) + 1)\n print(np.max(non_neural_colours))\n return (exc_colours, inb_colours, non_neural_colours)\n\ndef ColourPlot(data, name, subsets_indices, colours, labelX1=\"\", labelY1=\"\"):\n \n print(\"Building Colour Sequence\") \n # 3 way merge sort\n idxT, colourT = merge_arrays_inorder((subsets_indices[0], subsets_indices[1]), (colours[0], colours[1]))\n inorder, colour_seq = merge_arrays_inorder((idxT, subsets_indices[2]), (colourT, colours[2]))\n colour_seq = colour_seq[:-1] # chop the last one off\n\n print(\"Ploting Data\") \n DrawScatterPlot(data, name, labelX=labelX1, labelY=labelY1, colour_seq=colour_seq)\n \ndef ColourPlotAdv(data, name, subsets_indices, colours):\n\n idxT, colourT = merge_arrays_inorder((subsets_indices[0], subsets_indices[1]), (colours[0], colours[1]))\n inorder, colour_seq = merge_arrays_inorder((idxT, subsets_indices[2]), (colourT, colours[2]))\n colour_seq = colour_seq[:-1] # chop the last one off\n\n fig, ax = plt.subplots(1,1, figsize=(6,6))\n\n cmap = plt.cm.gist_ncar\n cmaplist = [cmap(i) for i in range(cmap.N)]\n cmaplist[0] = (.5, .5, .5, 1.0)\n\n cmap = mpl.colors.LinearSegmentedColormap.from_list('Custom cmap', cmaplist, cmap.N)\n bounds = np.linspace(0,1,75)\n norm = mpl.colors.BoundaryNorm(bounds, cmap.N)\n scat = ax.scatter(data[0,:], data[1,:], c=colour_seq,s=1, cmap=cmap, norm=norm)\n ax.set_title(\"Better colors?\")\n name = \"./\" + name.replace(\" \", \"\") + str(time.time()) + \".png\"\n plt.savefig(name, transparent=True)\n\ndef Main():\n\n #data = BuildNumpyArray(True) # load array\n data, removedIdx = BuildFilteredNumpyArray()\n #data = np.load('matrixPickle.npy') # load saved data \n\n data = VariableSubset(data) # make subeset\n\n print(\"Spliting Based on type\")\n subsets_indices = SubsetsBasedOnType(data, removedIdx)\n \n #print(\"PhenoClustering\")\n #colours = AgglogClusterSubsets(data, subsets_indices)\n colours = PhenoClusterSubsets(data, subsets_indices)\n\n #PCAWrapper(data)\n\n print(\"Start TSNE\")\n projection = TSNEPipeline(data)\n #DrawScatterPlot(projection,\"Gene data mapping using T-SNE Projection\", labelX=\"T-SNE X\", labelY=\"T-SNE Y\")\n ColourPlot(projection,\"Gene data TSNE projection coupled with Phenograph clustering\", subsets_indices, colours, labelX1=\"TSNE Dim 1\", labelY1=\"TSNE Dim 2\")\n\n\nif __name__ == \"__main__\":\n Main()\n", "repo_name": "JRDetwiler/gene-expression", "sub_path": "clustering.py", "file_name": "clustering.py", "file_ext": "py", "file_size_in_byte": 11584, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "matplotlib.use", "line_number": 12, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 35, "usage_type": "call"}, {"api_name": "numpy.float64", "line_number": 35, "usage_type": "attribute"}, {"api_name": "csv.reader", "line_number": 37, "usage_type": "call"}, {"api_name": "csv.QUOTE_NONE", "line_number": 37, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 41, "usage_type": "call"}, {"api_name": "numpy.dtype", "line_number": 41, "usage_type": "call"}, {"api_name": "numpy.float64", "line_number": 41, "usage_type": "attribute"}, {"api_name": "numpy.save", "line_number": 46, "usage_type": "call"}, {"api_name": "csv.reader", "line_number": 57, "usage_type": "call"}, {"api_name": "csv.QUOTE_ALL", "line_number": 57, "usage_type": "attribute"}, {"api_name": "csv.reader", "line_number": 74, "usage_type": "call"}, {"api_name": "csv.QUOTE_ALL", "line_number": 74, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 86, "usage_type": "call"}, {"api_name": "numpy.float64", "line_number": 86, "usage_type": "attribute"}, {"api_name": "csv.reader", "line_number": 88, "usage_type": "call"}, {"api_name": "csv.QUOTE_NONE", "line_number": 88, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 95, "usage_type": "call"}, {"api_name": "numpy.dtype", "line_number": 95, "usage_type": "call"}, {"api_name": "numpy.float64", "line_number": 95, "usage_type": "attribute"}, {"api_name": "numpy.delete", "line_number": 103, "usage_type": "call"}, {"api_name": "numpy.all", "line_number": 105, "usage_type": "call"}, {"api_name": "numpy.save", "line_number": 110, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 134, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 134, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 135, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 135, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 136, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 136, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 137, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 137, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 139, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 139, "usage_type": "name"}, {"api_name": "numpy.save", "line_number": 141, "usage_type": "call"}, {"api_name": "numpy.random.random_integers", "line_number": 151, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 151, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 152, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 152, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.stem", "line_number": 153, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 153, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 154, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 154, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 155, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 155, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 156, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 156, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 159, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 159, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 160, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 160, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 161, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 161, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 162, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 162, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 163, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 163, "usage_type": "name"}, {"api_name": "time.time", "line_number": 164, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 165, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 165, "usage_type": "name"}, {"api_name": "numpy.count_nonzero", "line_number": 170, "usage_type": "call"}, {"api_name": "numpy.std", "line_number": 173, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 176, "usage_type": "call"}, {"api_name": "numpy.log", "line_number": 179, "usage_type": "call"}, {"api_name": "scipy.sparse.csr_matrix", "line_number": 185, "usage_type": "call"}, {"api_name": "scipy.sparse", "line_number": 185, "usage_type": "name"}, {"api_name": "sklearn.decomposition.TruncatedSVD", "line_number": 186, "usage_type": "call"}, {"api_name": "sklearn.manifold.TSNE", "line_number": 191, "usage_type": "call"}, {"api_name": "time.time", "line_number": 195, "usage_type": "call"}, {"api_name": "time.time", "line_number": 197, "usage_type": "call"}, {"api_name": "time.time", "line_number": 201, "usage_type": "call"}, {"api_name": "csv.reader", "line_number": 213, "usage_type": "call"}, {"api_name": "phenograph.cluster", "line_number": 232, "usage_type": "call"}, {"api_name": "phenograph.cluster", "line_number": 234, "usage_type": "call"}, {"api_name": "phenograph.cluster", "line_number": 236, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 238, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 239, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 240, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 244, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 245, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 289, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 290, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 291, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 294, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 295, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 296, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 316, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 316, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.cm", "line_number": 318, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot", "line_number": 318, "usage_type": "name"}, {"api_name": "matplotlib.colors.LinearSegmentedColormap.from_list", "line_number": 322, "usage_type": "call"}, {"api_name": "matplotlib.colors", "line_number": 322, "usage_type": "attribute"}, {"api_name": "numpy.linspace", "line_number": 323, "usage_type": "call"}, {"api_name": "matplotlib.colors.BoundaryNorm", "line_number": 324, "usage_type": "call"}, {"api_name": "matplotlib.colors", "line_number": 324, "usage_type": "attribute"}, {"api_name": "time.time", "line_number": 327, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 328, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 328, "usage_type": "name"}]} +{"seq_id": "19052805027", "text": "import ROOT\nimport os\nfrom array import array\nfrom parseBetaResultsToExcel import *\nfrom ROOTFile import RootFile\nfrom daq_info import DAQInfo\nfrom get_time_res import Get_Time_Resolution\nimport logging, coloredlogs\n\nimport sys\nsys.path.append(f'{os.environ[\"BETASCOPE_SCRIPTS\"]}/UDI_reader/')\nfrom UDI_reader import UDI_reader\n\nlogging.basicConfig()\nlog = logging.getLogger(__name__)\ncoloredlogs.install(level=\"INFO\", logger=log)\n\n\ndef ParseINItoROOT(fname=\"_results.ini\"):\n data_ini = configparser.ConfigParser()\n data_ini.read(fname)\n data_ini_section = data_ini.sections()\n log.info(data_ini_section)\n\n dut_trig = [\"DUT\"]\n\n # look for description file generated by the DAQ\n description_file = DAQInfo()\n for descr in os.listdir(\"./\"):\n if \"_Description.ini\" in descr:\n description_file = DAQInfo.open(descr)\n log.info(\"found DAQ description file\")\n break\n\n sensor_name = description_file.full_name\n\n # total transipedence (include amp)\n resistance = 4700\n\n # Get stuff from UDI file\n try:\n UDI_number = description_file.dut_udi\n reader = UDI_reader()\n pin_charge = reader.get_pin_charge(UDI_number)\n foot_cv = reader.get_foot(UDI_number)\n except:\n pin_charge = 0.\n foot_cv = 0.\n\n my_trig_name = description_file.trig_name.lower()\n if \"hpk\" in my_trig_name and \"s8664\" in my_trig_name:\n my_trig_name = \"hpks8664\"\n\n res50_result = Get_Time_Resolution(\n f\"run_info_v{os.environ['RUN_INFO_VER']}.ini\",\n \"50\",\n description_file.scope.lower(),\n my_trig_name,\n description_file.run_number,\n )\n\n res20_result = Get_Time_Resolution(\n f\"run_info_v{os.environ['RUN_INFO_VER']}.ini\",\n \"20\",\n description_file.scope.lower(),\n my_trig_name,\n description_file.run_number,\n )\n\n res_tmax = Get_Time_Resolution(\n f\"run_info_v{os.environ['RUN_INFO_VER']}.ini\",\n \"tmax\",\n description_file.scope.lower(),\n my_trig_name,\n description_file.run_number,\n )\n\n res_fit_tmax = Get_Time_Resolution(\n f\"run_info_v{os.environ['RUN_INFO_VER']}.ini\",\n \"fit_tmax\",\n description_file.scope.lower(),\n my_trig_name,\n description_file.run_number,\n )\n\n res_zerox_tmax = Get_Time_Resolution(\n f\"run_info_v{os.environ['RUN_INFO_VER']}.ini\",\n \"zero_cross_tmax\",\n description_file.scope.lower(),\n my_trig_name,\n description_file.run_number,\n )\n\n leakage_data = Read_Current(f\"run_info_v{os.environ['RUN_INFO_VER']}.ini\")\n\n for ch in dut_trig:\n rowCounter = 1\n\n output_file = RootFile(\n \"_results.root\",\n f\"run{description_file.run_number}\",\n f\"{os.getcwd()}/_results.ini\",\n )\n for par in INI_TO_EXCEL.keys():\n if \"sensor_name\" in par:\n output_file.create_char_branch(par)\n output_file.set_char_branch_value(par, sensor_name)\n elif \"run_number\" in par:\n output_file.create_branch(par, \"i\")\n elif \"time_resolution\" in par:\n output_file.create_branch(par, \"d\")\n else:\n if INI_TO_EXCEL[par][0] == None:\n continue\n output_file.create_branch(par, \"d\")\n\n for bias in data_ini_section:\n myRunNum = f\"{description_file.run_number}->{rowCounter}\"\n if ch in bias:\n run_header = bias.split(\",\")\n Bias = run_header[1].replace(\"V\", \"\")\n cycle = run_header[2]\n for par in INI_TO_EXCEL.keys():\n if par == \"sensor_name\":\n continue\n elif par == \"run_number\":\n continue\n elif par == \"temperature\":\n try:\n Temp = config[bias][\"temperature\"]\n except:\n Temp = \"-30\"\n output_file.set_branch_value(par, float(Temp))\n elif par == \"bias_voltage\":\n output_file.set_branch_value(par, float(Bias))\n elif par == \"cycle\":\n output_file.set_branch_value(par, float(cycle))\n elif par == \"resistance\":\n output_file.set_branch_value(par, float(resistance))\n elif par == \"pin_charge\":\n output_file.set_branch_value(par, float(pin_charge))\n elif par == \"foot_cv\":\n output_file.set_branch_value(par, float(foot_cv))\n elif par == \"time_resolution_50\":\n output_file.set_branch_value(\n par, res50_result[(float(Bias), int(cycle))][3]\n )\n elif par == \"time_resolution_50_err\":\n output_file.set_branch_value(\n par, res50_result[(float(Bias), int(cycle))][4]\n )\n elif par == \"time_resolution_20\":\n output_file.set_branch_value(\n par, res20_result[(float(Bias), int(cycle))][3]\n )\n elif par == \"time_resolution_20_err\":\n output_file.set_branch_value(\n par, res20_result[(float(Bias), int(cycle))][4]\n )\n elif \"time_resolution_tmax\" in par:\n if res_tmax is None:\n continue\n else:\n if \"err\" in par:\n output_file.set_branch_value(\n par, res_tmax[(float(Bias), int(cycle))][4]\n )\n else:\n output_file.set_branch_value(\n par, res_tmax[(float(Bias), int(cycle))][3]\n )\n elif \"time_resolution_fit_tmax\" in par:\n if res_fit_tmax is None:\n continue\n else:\n if \"err\" in par:\n output_file.set_branch_value(\n par, res_fit_tmax[(float(Bias), int(cycle))][4]\n )\n else:\n output_file.set_branch_value(\n par, res_fit_tmax[(float(Bias), int(cycle))][3]\n )\n elif \"time_resolution_zero_x_tmax\" in par:\n if res_zerox_tmax is None:\n continue\n else:\n if \"err\" in par:\n output_file.set_branch_value(\n par, res_zerox_tmax[(float(Bias), int(cycle))][4]\n )\n else:\n output_file.set_branch_value(\n par, res_zerox_tmax[(float(Bias), int(cycle))][3]\n )\n elif par == \"leakage\":\n output_file.set_branch_value(\n par, leakage_data[(float(Bias), int(cycle))][3]\n )\n else:\n data_ini_key = INI_TO_EXCEL[par][0]\n if data_ini_key == None:\n continue\n try:\n value = data_ini[bias][data_ini_key]\n output_file.set_branch_value(par, float(value))\n except:\n continue\n else:\n continue\n output_file.fill()\n\n\ndef parseINItoROOT2(fileout, title=\"Hi\", run_folder=\"./\", fname=\"_results.ini\"):\n fileout.cd()\n config = configparser.ConfigParser()\n config.read(fname)\n config_section = config.sections()\n # print(config_section)\n\n description_file = None\n try:\n for descr in os.listdir(run_folder):\n if \"_Description.ini\" in descr:\n description_file = configparser.ConfigParser()\n description_file.read(descr)\n print(\"found DAQ description file\")\n break\n except Exception as e:\n print(Exception)\n\n dut_trig = [\"DUT\"]\n\n branches = {}\n\n print(title)\n RunNum = title.split(\"_\")[1]\n SensorName = title\n trigBias = 395\n Temp = 0\n\n if \"_20C\" in title:\n Temp = 20\n trigBias = 420\n if \"_neg30C\" in title:\n trigBias = 390\n Temp = -30\n if \"_neg20C\" in title:\n Temp = -20\n if \"_neg10C\" in title:\n Temp = -10\n\n if description_file:\n try:\n RunNum = description_file[\"Run_Description\"][\"Run_Number\"]\n SensorName = description_file[\"Run_Description\"][\"DUT_Senor_Name\"]\n SensorName += (\n \"-Fluence \"\n + description_file[\"Run_Description\"][\"DUT_Fluence_Type\"]\n + \"-\"\n + description_file[\"Run_Description\"][\"DUT_Fluence\"]\n )\n SensorName += (\n \"--\"\n + description_file[\"Run_Description\"][\"DUT_Readout_Board\"]\n + \"-\"\n + description_file[\"Run_Description\"][\"DUT_Readout_Board_Number\"]\n )\n\n Temp = description_file[\"Run_Description\"][\"Temperature\"]\n trigBias = description_file[\"Run_Description\"][\"Trigger_Voltage\"]\n except Exception as e:\n print(Exception)\n\n Resistance = 4700\n\n # Get stuff from UDI file\n try:\n UDI_number = description_file.dut_udi\n reader = UDI_reader()\n pin_charge = reader.get_pin_charge(UDI_number)\n foot_cv = reader.get_foot(UDI_number)\n except:\n pin_charge = 0.\n foot_cv = 0.\n\n for ch in dut_trig:\n rowCounter = 1\n # print RunNum, title\n ttree = ROOT.TTree(str(RunNum), title)\n for par in INI_TO_EXCEL.keys():\n if \"SensorName\" in par:\n branches[par] = array(\"b\").frombytes(str(SensorName).encode())\n ttree.Branch(par, branches[par], f\"{par}/C\")\n elif \"runNumber\" in par:\n continue\n else:\n branches[par] = array(\"d\", [0])\n ttree.Branch(par, branches[par], f\"{par}/D\")\n\n for bias in config_section:\n myRunNum = str(RunNum) + \"->\" + str(rowCounter)\n if ch in bias:\n if ch != \"Trig\":\n run_header = bias.split(\",\")\n Bias = run_header[1].replace(\"V\", \"\")\n cycle = run_header[2]\n else:\n try:\n SensorName = description_file[\"Run_Description\"][\n \"Trigger_Sensor_Name\"\n ]\n except:\n pass\n Bias = config[bias][\"trigger_bias\"]\n run_header = bias.split(\",\")\n cycle = run_header[2]\n for par in par_list:\n if par == \"SensorName\":\n continue\n elif par == \"runNumber\":\n continue\n elif par == \"Temp\":\n try:\n Temp = config[bias][\"temperature\"]\n except:\n Temp = \"-30\"\n branches[par][0] = float(Temp)\n elif par == \"Bias\":\n branches[par][0] = float(Bias)\n elif par == \"cycle\":\n branches[par][0] = float(cycle)\n elif par == \"Resistance\":\n branches[par][0] = float(Resistance)\n elif par == \"pin_charge\":\n branches[par][0] = float(pin_charge)\n elif par == \"foot_cv\":\n branches[par][0] = float(foot_cv)\n else:\n try:\n branches[par][0] = float(config[bias][par])\n except:\n branches[par][0] = 0\n\n ttree.Fill()\n\n ttree.Write() # \"run\"+str(RunNum), ROOT.TObject.kOverwrite)\n\n\ndef ParseRawINIToROOT(filename=\"raw_results.ini\"):\n config = configparser.ConfigParser()\n config.read(filename)\n output_file = RootFile(\"raw_results.root\", \"raw\")\n created_branches = False\n for sec in config.sections():\n if not created_branches:\n for key in config[sec]:\n output_file.create_branch(key, \"d\")\n output_file.create_branch(\"bias\", \"d\")\n output_file.create_branch(\"cycle\", \"i\")\n created_branches = True\n for key in config[sec]:\n output_file[key][0] = float(config[sec][key])\n run_header = sec.split(\",\")\n output_file[\"bias\"][0] = float(run_header[0].replace(\"V\", \"\"))\n cycle = int(run_header[1])\n output_file.fill()\n\n\nif __name__ == \"__main__\":\n ParseINItoROOT()\n ParseRawINIToROOT()\n", "repo_name": "neko-0/HGTD_BetaScope_FW_Test", "sub_path": "scripts/betaScope_pyScript/result_parser/parseINItoROOT.py", "file_name": "parseINItoROOT.py", "file_ext": "py", "file_size_in_byte": 13565, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "21", "api": [{"api_name": "sys.path.append", "line_number": 11, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 11, "usage_type": "attribute"}, {"api_name": "os.environ", "line_number": 11, "usage_type": "attribute"}, {"api_name": "logging.basicConfig", "line_number": 14, "usage_type": "call"}, {"api_name": "logging.getLogger", "line_number": 15, "usage_type": "call"}, {"api_name": "coloredlogs.install", "line_number": 16, "usage_type": "call"}, {"api_name": "daq_info.DAQInfo", "line_number": 28, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 29, "usage_type": "call"}, {"api_name": "daq_info.DAQInfo.open", "line_number": 31, "usage_type": "call"}, {"api_name": "daq_info.DAQInfo", "line_number": 31, "usage_type": "name"}, {"api_name": "UDI_reader.UDI_reader", "line_number": 43, "usage_type": "call"}, {"api_name": "get_time_res.Get_Time_Resolution", "line_number": 54, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 55, "usage_type": "attribute"}, {"api_name": "get_time_res.Get_Time_Resolution", "line_number": 62, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 63, "usage_type": "attribute"}, {"api_name": "get_time_res.Get_Time_Resolution", "line_number": 70, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 71, "usage_type": "attribute"}, {"api_name": "get_time_res.Get_Time_Resolution", "line_number": 78, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 79, "usage_type": "attribute"}, {"api_name": "get_time_res.Get_Time_Resolution", "line_number": 86, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 87, "usage_type": "attribute"}, {"api_name": "os.environ", "line_number": 94, "usage_type": "attribute"}, {"api_name": "ROOTFile.RootFile", "line_number": 99, "usage_type": "call"}, {"api_name": "os.getcwd", "line_number": 102, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 223, "usage_type": "call"}, {"api_name": "UDI_reader.UDI_reader", "line_number": 280, "usage_type": "call"}, {"api_name": "ROOT.TTree", "line_number": 290, "usage_type": "call"}, {"api_name": "array.array", "line_number": 293, "usage_type": "call"}, {"api_name": "array.array", "line_number": 298, "usage_type": "call"}, {"api_name": "ROOTFile.RootFile", "line_number": 353, "usage_type": "call"}]} +{"seq_id": "28304503107", "text": "from selenium import webdriver\nimport time\n\n\nclass Webpage:\n def __init__(self, url):\n self.url = url\n self.driver = webdriver.Chrome()\n self.driver.get(url)\n\n\nclass Youtube(Webpage):\n def loadEntirePage(self):\n while True:\n time.sleep(9)\n try:\n response = self.driver.execute_script(\n \"document.getElementsByClassName\"\n \"('load-more-button')[0].click()\")\n except:\n print('done!')\n break\n\n\nif __name__ == '__main__':\n likedVideos = Youtube(\n 'https://www.youtube.co.uk/playlist?list=LLvI2sZXK-MUg5fsusK3l4LA')\n # likedVideos.loadEntirePage()\n\n\n# driver.get('https://www.youtube.co.uk/playlist?list=LLvI2sZXK-MUg5fsusK3l4LA')\n# buttonLoadMore = driver.find_element_by_xpath('//*[@id=\"pl-video\n# -list\"]/button')\n# buttonLoadMore = driver.find_element_by_class_name('load-more-button')\n# buttonLoadMore.click()\n# window.scrollTo(0, document.body.scrollHeight); document.\n# getElementsByClassName('load-more-button')[0].click() // document.\n# getElementsByClassName('button')[0].click(); ''')\n", "repo_name": "Argoniton/Video-Management", "sub_path": "WebpageClass.py", "file_name": "WebpageClass.py", "file_ext": "py", "file_size_in_byte": 1153, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "selenium.webdriver.Chrome", "line_number": 8, "usage_type": "call"}, {"api_name": "selenium.webdriver", "line_number": 8, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 15, "usage_type": "call"}]} +{"seq_id": "13728383113", "text": "#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\"\"\"\nAuthor:\n\tAntony Smith - T.S.E. [July 2020]\n\nDescription:\n\tTHIS VERSION IS FOR 4 DEMO UNITS - (MAKE FULL SCREEN)\n\tGCP MQTT to MY GC-Platform\n\tMain control GUI for Omnigo IoT project\n\tRaspberry Pi Zero + PiCamera + APDS9960\n\nPrimary Functions:\n\tGUI functionality:\n\t\t-> Widget placement + Colour schemes\t\t\t- [complete]\n\t\t-> Real-time label udpates (count/info)\t\t\t- [complete]\n\t\t-> Multi-Threading\t\t\t\t\t\t\t\t- [complete]\n\t\t-> multiple windows in parallel operation\t\t- [complete]\n\tAPDS9960 gesture sensor counting method \t\t\t- [complete]\n\tPiCamera & OPENCV QR Code reading\t\t\t\t\t- [complete]\n\tScan Kit & Staff ID + storage method\t\t\t\t- [complete]\n\tExit code required to leave GUI\t\t\t\t\t\t- [complete]\n\tDrop-down menu stage selector\t\t\t\t\t\t- [complete]\n\tJSON data format conversion\t\t\t\t\t\t\t- [complete]\n\tUpload data to Google Cloud IoT-Core \t\t\t\t- [complete]\n\nChanges required:\n\tcv2 Camera window NOT destroyed\t\t\t\t\t\t- [incomplete]\n\tCounter thread NOT ending\t\t\t\t\t\t\t- [incomplete]\n\tRe-Scan ID's later?\t\t\t\t\t\t\t\t\t- [incomplete]\n\t\t\nNotes:\n\tQR-Code scanner:\n\t\t-> exits after 3x confirmed QR reads\n\t\t-> 'q' exit prematurely\n\t\t-> EXIT CODE: 3529# ('*' to Delete)\n\tGCP connectivity requires:\n\t\t-> 'jwt_maker.py' to create JWT security key\n\t\t-> ssl security files: \n\t\t\t=> roots.pem\n\t\t\t=> rsa_private.pem\n\nUSAGE:\n\tpython main.py\n\"\"\"\n###################\n# import packages #\n###################\n\n## GUI PACKAGES ##\nfrom Tkinter import *\t\t\t\t\t# GUI package\nimport tkFont\t\t\t\t\t\t\t# GUI package\nfrom functools import partial\t\t\t# passing argument to button?\n\n## MULTI-TASKING FUNCTIONS ##\nimport threading\t\t\t\t\t\t# Multi-Threading\n\n## GENERAL MAINTENANCE ##\nimport sys\t\t\t\t\t\t\t\t# Possibly remove ? ? ?\nimport time\t\t\t\t\t\t\t\t# time travel\nimport traceback\t\t\t\t\t\t# Error logging\nimport datetime\t\t\t\t\t\t\t# Get real-time data\n\n## \tQR CODE IMPORTS ##\nfrom picamera import PiCamera\t\t\t# Testing the Camera\nfrom imutils.video import VideoStream\t# Video access library\nfrom pyzbar import pyzbar\t\t\t\t# Decoding the QR Code\nimport imutils \t\t\t\t\t\t\t# A little slice of Magic\nimport cv2\t\t\t\t\t\t\t\t# When you stare into the matrix...\n\n## GESTURE IMPORTS ##\nfrom apds9960.const import *\nfrom apds9960 import APDS9960\nimport smbus\n\n## JSON File and GCP ##\nimport json\t\t\t\t\t\t\t\t# JSON conversion functions\nimport jwt\t\t\t\t\t\t\t\t# Create JSON security token \nimport paho.mqtt.client as mqtt\t\t\t# MQTT connectivity\n\n\n###################\n## GLOBAL DEFS ##\n###################\nbtn_state1 = 0\t\t\t\t\t\t\t\t\t\t# changed to tri-state (0/1/2)\ncsv_file = \"barcodes.csv\"\t\t\t\t\t\t\t# guess what this is?\nOptionList = [\"SETUP\",\"THRU\",\"SMT\",\"INSP\",\"EXIT\"] \t# Drop Down Menu Options\n# Some technical requirements\nport = 1\nbus = smbus.SMBus(port)\napds = APDS9960(bus)\n\n\n###################\n## MAIN FUNCTION ##\n###################\ndef main():\n\tglobal thr1\t\t\t\t\t\t\t\t\t\t# thread flag\n\tglobal thr2\t\t\t\t\t\t\t\t\t\t# thread flag\n\tglobal Cnt\t\t\t\t\t\t\t\t\t\t# PCB count value\n\tglobal GestDone\t\t\t\t\t\t\t\t\t# Exit Gesture flag\n\tglobal pin\t \t\t\t\t\t\t\t\t\t# Exit Code Value\n\tglobal CodeDone\t\t\t\t\t\t\t\t\t# Exit Code - flag\n\tglobal qrData\t\t\t\t\t\t\t\t\t# Get QR Data\n\tglobal iotJSON\t\t\t\t\t\t\t\t\t# Converted to JSON format\n\tglobal firstScan\t\t\t\t\t\t\t\t# (createJSON) - only store certain data on first scan\n\tglobal projectStat\t\t\t\t\t# (createJSON) - project start or stop\n\tglobal staffID\t\t\t\t\t\t# (createJSON) - Extracted Staff ID\n\t\n\tlay=[]\t\t\t\t\t\t\t\t\t\t\t# layering windows??\n\tCodeDone = False\t\t\t\t\t\t\t\t# Exit Code - negative\n\tpin = ''\t\t\t\t\t\t\t\t\t\t# Exit Code - blank string\n\tGestDone = False\t\t\t\t\t\t\t\t# Gesture count - flag\n\tCnt = 0\t\t\t\t\t\t\t\t\t\t\t# PCB Counter start value\n\tinfo = \"feedback...\"\t\t\t\t\t\t\t# GUI feedback information - OPTIONAL\n\tID_match = 0\t\t\t\t\t\t\t\t\t# ID Scan - initial staff ID status\n\tqrData = \"data from qr code\"\t\t\t\t\t# initialise to string format\n\tiotJSON = \"upload\"\t\t\t\t\t\t\t\t# initialise to string format\n\tfirstScan = 0\t\t\t\t\t\t\t\t\t# initialise for 1st data update\n\tstaffKit = 0\t\t\t\t\t\t\t\t\t# initialise to kit_ID 1st\n\t\n\t## Define some project-based variables to be used below ##\n\tssl_private_key_filepath = './certs/rsa_private.pem' # ''\n\tssl_algorithm = 'RS256' # '' # Either RS256 or ES256\n\troot_cert_filepath = './certs/roots.pem' # ''\n\tproject_id = 'iot-omnigo1' # ''\n\tgcp_location = 'us-central1' # ''\n\tregistry_id = 'omnigo_registry' # ''\n\tdevice_id = 'omnigo_device1' # ''\n\t\n\t## Proiject Information dictionary ##\n\tglobal dataDict\n\tdataDict = {'CLIENT'\t: 'xxx',\t\t\t# Client Name\n\t\t\t\t'PROJECT'\t: '0',\t\t\t\t# Project ID\n\t\t\t\t'STAGE'\t\t: 'xxx',\t\t\t# Operational Stage (setup/smt/thru/insp)\n\t\t\t\t'BOARDS'\t: '0',\t\t\t\t# Number PC-Boards\n\t\t\t\t'PANELS'\t: '0',\t\t\t\t# Number of panels\n\t\t\t\t'STAFF_ID'\t: '0',\t\t\t\t# Staff member ID number\n\t\t\t\t'DATE'\t\t: '00-00-2020',\t\t# Project start date\n\t\t\t\t'TIME'\t\t: '00:00',\t\t\t# Time of each board swiped\n\t\t\t\t'START'\t\t: '00:00',\t\t\t# Stage - start time \n\t\t\t\t'STOP'\t\t: '00:00',\t\t\t# Stage - end time\n\t\t\t\t'REASON'\t: 'null',\t\t\t# Reason the stage was stopped\n\t\t\t\t'SERIAL'\t: '0' }\t\t\t\t# Barcode serial number - Later\n\n\t## Get the current time/date ##\n\tcur_time = datetime.datetime.utcnow()\n\t\n\ttry:\n\t\ttry:\n\t\t\t################\n\t\t\t## QR SCANNER ##\n\t\t\t################\n\t\t\tdef QR_Scan():\n\t\t\t\tglobal qrData\t\t\t\t\t\t\t\t\t# globalise QR Data\n\t\t\t\tglobal staffID\t\t\t\t\t\t\t\t\t# Extracted Staff ID\n\t\t\t\tinit_time = time.time()\t\t\t\t\t\t\t# no. of secs since 1 Jan 1970\n\t\t\t\twinName = \"SCAN-ID\"\t\t\t\t\t\t\t\t# name the video window\n\t\t\t\tscnCnt = 0\t\t\t\t\t\t\t\t\t\t# Number of ID confirmations\n\t\t\t\tdone = \"kit\"\t\t\t\t\t\t\t\t\t# which scan is complete\n\t\t\t\tstaffKit = 0\t\t\t\t\t\t\t\t\t# Which ID - kit_ID[0] / Staff_ID[1]\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t## initialize video stream & warm up camera sensor\n\t\t\t\tprint(\"[INFO] starting video stream...\")\n\t\t\t\tvs = VideoStream(usePiCamera=True).start()\n\t\t\t\ttime.sleep(2.0)\t\t\t\t\t\t\t\t\t# Allow video to stabalise\n\t\t\t\tcv2.namedWindow(winName)\n\t\t\t\tcv2.moveWindow(winName, 1,1)\n\t\t\t\t\t\t\t\t\n\t\t\t\t## Loop over the frames from the video stream #\n\t\t\t\t## Time-Out after 35 secs ##\n\t\t\t\twhile time.time()-init_time < 35:\n\t\t\t\t\t## grab the frame from the threaded video stream and r\n\t\t\t\t\t## resize it to have a maximum width of 400 pixels\n\t\t\t\t\tframe = vs.read()\n\t\t\t\t\tframe = imutils.rotate(frame, 90)\t\t\t# rotate 90 due to camera mount\n\t\t\t\t\tframe = imutils.resize(frame, width=400)\n\t\t\t\t \n\t\t\t\t\t## find & decode the barcodes in each frame\n\t\t\t\t\tbarcodes = pyzbar.decode(frame)\n\n\t\t\t\t\t## loop over the detected barcodes\n\t\t\t\t\tfor barcode in barcodes:\n\t\t\t\t\t\t## extract bounding box location & draw around barcode\n\t\t\t\t\t\t(x, y, w, h) = barcode.rect\n\t\t\t\t\t\tcv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 255), 2)\n\t\t\t\t \n\t\t\t\t\t\t## the barcode data is a bytes object so if we want to draw it\n\t\t\t\t\t\t## on our output image we need to convert it to a string first\n\t\t\t\t\t\tbarcodeData = barcode.data.decode(\"utf-8\")\n\t\t\t\t\t\tbarcodeType = barcode.type\n\t\t\t\t \n\t\t\t\t\t\t## Indicate Which barcode is found ##\n\t\t\t\t\t\tif staffKit == 0:\n\t\t\t\t\t\t\tstaffKit = 1\t\t\t\t\t\t# toggle to staff\n\t\t\t\t\t\t\ttext = \"- KIT ID -\"\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tstaffKit = 0\t\t\t\t\t\t# toggle back to kit\n\t\t\t\t\t\t\ttext = \"- STAFF ID -\"\n\t\t\t\t\t\t\n\t\t\t\t\t\tcv2.putText(frame, text, (x, y - 10),\n\t\t\t\t\t\t\tcv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t## REMOVED - Store QR Data to CSV file ##\n\t\t\t\t\t\t\n\t\t\t\t\t\t## Count QR Reads ##\n\t\t\t\t\t\tscnCnt += 1\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t## If QR Code is Read 3 times ##\n\t\t\t\t\t\tif scnCnt == 5:\n\t\t\t\t\t\t\t#scnCnt = 0\t\t\t\t\t\t\t# clear the counter\n\t\t\t\t\t\t\tif done == \"kit\":\n\t\t\t\t\t\t\t\tqrData = barcodeData\t\t\t# Copy QR Data\n\t\t\t\t\t\t\t\tdone = \"staff\"\t\t\t\t\t# exit the loop\n\t\t\t\t\t\t\telif done == \"staff\":\n\t\t\t\t\t\t\t\tstaffID = barcodeData\t\t\t# store staff_ID\n\t\t\t\t\t\t\t\tdone = \"y\" \t\t\t\t\t\t# exit scan mode\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t## QR Image - CHANGE INDICATOR ##\n\t\t\t\t\t\t\tfont = cv2.FONT_HERSHEY_SIMPLEX\n\t\t\t\t\t\t\ttext = \"~DONE~\"\n\t\t\t\t\t\t\ttextsize = cv2.getTextSize(text, font, 1, 2)[0]\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t## Get coords based on boundry ##\n\t\t\t\t\t\t\ttextX = (frame.shape[1] - textsize[0]) /2\n\t\t\t\t\t\t\ttextY = (frame.shape[0] - textsize[1]) /2\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t## Add text centered in image ##\n\t\t\t\t\t\t\tcv2.putText(frame, text, (textX, textY), font, 2, (0, 255, 0), 3)\n\n\t\t\t\t\t## FOR FULL SCREEN ? ? - FIX ##\n\t\t\t\t\t#cv2.namedWindow(winName, cv2.WINDOW_NORMAL)# create a named window\n\t\t\t\t\t#cv2.namedWindow(winName)\n\t\t\t\t\t#cv2.moveWindow(winName, 20,20)\t\t\t\t# set window placement\n\t\t\t\t\t## Get window to full screen ##\n\t\t\t\t\t#cv2.setWindowProperty(winName, cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_FULLSCREEN) \n\t\t\t\t\t\n\t\t\t\t\t## Show the output frame ##\n\t\t\t\t\tcv2.imshow(winName, frame)\n\t\t\t\t\tkey = cv2.waitKey(1) & 0xFF\n\t\t\t\t\t\n\t\t\t\t\t# Pause for QR swap ##\n\t\t\t\t\tif scnCnt == 5:\n\t\t\t\t\t\ttime.sleep(3)\t\t\n\t\t\t\t\t\tscnCnt = 0\t\n\t\t\t\t \n\t\t\t\t\t## if the `q` key was pressed, break from the loop ##\n\t\t\t\t\tif key == ord(\"q\"):\n\t\t\t\t\t\tbreak\n\t\t\t\t\t## if ID confirmed 3 times ##\n\t\t\t\t\telif done == \"y\":\n\t\t\t\t\t\t#print(qrData)\t\t\t\t\t\t\t# REMOVE\n\t\t\t\t\t\t#print(staffID)\t\t\t\t\t\t\t# REMOVE\n\t\t\t\t\t\tbreak\n\t\t\t\t\n\t\t\t\t## close the output CSV file do a bit of cleanup ##\n\t\t\t\tprint(\"[INFO] cleaning up...\")\n\t\t\t\t\"\"\"\n\t\t\t\t## Impossible to Destroy Video Window ##\n\t\t\t\tcv2.waitKey(0)\n\t\t\t\tvs.stop()\n\t\t\t\tcv2.destroyWindow(winName)\t\t\t\t\t\t# destroy specific window??\n\t\t\t\tfor i in range (1,5):\n\t\t\t\t\tcv2.waitKey(1)\n\t\t\t\twin.destroy()\n\t\t\t\t\"\"\"\n\t\t\t\tvs.stop()\t\t\t\t\t\t\t\t\t\t# stop video stream\n\t\t\t\tcv2.destroyAllWindows()\t\t\t\t\t\t\t# NOT destroying??\n\t\t\t\t#lift_window()\t\t\t\t\t\t\t\t\t# Put GUI on the top\n\t\t\t\twin.lift()\n\t\t\t\t\n\t\t\t\n\t\t\t#########################\n\t\t\t## FAKE COUNTER - DEMO ##\n\t\t\t#########################\n\t\t\tdef fake_gesture():\n\t\t\t\tglobal Cnt\t\t\t\t\t# Double defined?\n\t\t\t\tglobal GestDone\t\t\t\t# Exit Gesture loop\n\t\t\t\t\n\t\t\t\tCnt = 0\t\t\t\t\t\t# initialised\n\t\t\t\tsendCnt = 0\t\t\t\t\t# Could make global?\n\t\t\t\tGestDone = False\n\n\t\t\t\t## Button click to exit? ##\n\t\t\t\twhile GestDone == False:\n\t\t\t\t\t## SWIPE ##\n\t\t\t\t\tCnt += 1\t\t\t\t# increment board count\n\n\t\t\t\t\t## Continuously update GUI Label ##\n\t\t\t\t\tupdate_label()\n\t\t\t\t\t\t\n\t\t\t\t\t## ON EVERY 3RD COUNT ##\n\t\t\t\t\tsendCnt += 1\n\t\t\t\t\tif sendCnt == 3:\n\t\t\t\t\t\thandleData(Cnt)\n\t\t\t\t\t\tsendCnt = 0\n\n\t\t\t\t\ttime.sleep(2)\t\t\t# every 2 seconds\n\n\n\t\t\t#####################\n\t\t\t## GESTURE COUNTER ##\n\t\t\t#####################\n\t\t\tdef get_gesture():\n\t\t\t\tglobal Cnt\t\t\t\t\t# Double defined?\n\t\t\t\tglobal GestDone\t\t\t\t# Exit Gesture loop\n\t\t\t\tCnt = 0\t\t\t\t\t\t# Double defined?\n\t\t\t\tdirect = 'none'\t\t\t\t# Direction of swipe\n\t\t\t\tsendCnt = 0\t\t\t\t\t# Could make global?\n\n\t\t\t\tGestDone = False\t\t\t# initialise on function call\n\t\t\t\t\n\t\t\t\tdirs = {\n\t\t\t\t\tAPDS9960_DIR_NONE: \"none\",\n\t\t\t\t\tAPDS9960_DIR_LEFT: \"left\",\n\t\t\t\t\tAPDS9960_DIR_RIGHT: \"right\",\n\t\t\t\t\tAPDS9960_DIR_UP: \"up\",\n\t\t\t\t\tAPDS9960_DIR_DOWN: \"down\",\n\t\t\t\t\tAPDS9960_DIR_NEAR: \"near\",\n\t\t\t\t\tAPDS9960_DIR_FAR: \"far\",\n\t\t\t\t\t}\n\t\t\t\ttry:\n\t\t\t\t\t# Set the proximity threshold\n\t\t\t\t\tapds.setProximityIntLowThreshold(50)\n\t\t\t\t\t\t\n\t\t\t\t\tprint(\"CAPTURE GESTURES:\")\t\t\t\t\t\t# remove\n\t\t\t\t\tprint(\"=================\")\t\t\t\t\t\t# remove\n\t\t\t\t\tapds.enableGestureSensor()\n\t\t\t\t\t\n\t\t\t\t\t## EXIT the Gesture Thread ? ##\n\t\t\t\t\twhile GestDone == False:\t\t\t\t\t\t# while True:\n\t\t\t\t\t\ttime.sleep(0.5)\n\t\t\t\t\t\tif apds.isGestureAvailable():\n\t\t\t\t\t\t\tmotion = apds.readGesture()\n\t\t\t\t\t\t\tdirect = dirs.get(motion, \"unknown\")\n\t\t\t\t\t\t\t#print(\"Gesture = {}\".format(direct))\t# remove\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tif direct == \"left\":\n\t\t\t\t\t\t\t\tCnt += 1\t\t\t\t\t# May need upper limit?\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\telif direct == \"up\":\n\t\t\t\t\t\t\t\tCnt += 1\t\t\t\t\t# May need upper limit?\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\telif direct == \"right\":\n\t\t\t\t\t\t\t\tif Cnt > 0:\t\t\t\t\t# Avoid negative situations\n\t\t\t\t\t\t\t\t\tCnt -= 1\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\telif direct == \"down\":\n\t\t\t\t\t\t\t\tif Cnt > 0:\t\t\t\t\t# Avoid negative situations\n\t\t\t\t\t\t\t\t\tCnt -= 1\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t## Continuously update GUI Label ##\n\t\t\t\t\t\t\tupdate_label()\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t## ON EVERY 3RD COUNT ##\n\t\t\t\t\t\t\tsendCnt += 1\n\t\t\t\t\t\t\tif sendCnt == 3:\n\t\t\t\t\t\t\t\tsendCnt = 0\n\t\t\t\t\t\t\t\thandleData(Cnt, sendCnt)\n\t\t\t\t\t\t\n\n\t\t\t\t## Do before exiting Gesture Mode ##\n\t\t\t\tfinally:\n\t\t\t\t\t## Zero Counter - On Next Count ##\n\t\t\t\t\tCnt = 0 \t\t\t\t\t\t\t\t# zero the count value\n\t\t\t\t\tupdate_label()\t\t\t\t\t\t\t# update the GUI label\n\n\n\t\t\t## Initialise both Threads (not started yet) ##\n\t\t\tthreads = []\t\t\t\t\t\t\t\t\t\t# create thread list\n\t\t\tthr1 = 0\t\t\t\t\t\t\t\t\t\t\t# thread 1 flag\n\t\t\tthr2 = 0\t\t\t\t\t\t\t\t\t\t\t# thread 2 flag\n\t\t\t\n\t\t\t##############################\n\t\t\t## BUTTON: EMPLOYEE ID SCAN ##\n\t\t\t##############################\n\t\t\tdef btn_start():\n\t\t\t\t## Gesture counter #\n\t\t\t\tglobal GestDone\t\t\t\t\t\t\t\t# Exit Gesture mode flag\n\t\t\t\tglobal thr1\t\t\t\t\t\t\t\t\t# thread flag\n\t\t\t\tglobal Cnt\t\t\t\t\t\t\t\t\t# make global again?\n\t\t\t\t## ID Scanner #\n\t\t\t\tglobal thr2\n\t\t\t\tglobal btn_state1\t\t\t\t\t\t\t# changed top tri-state\n\t\t\t\tglobal info\n\t\t\t\t## GCP JSON ##\n\t\t\t\tglobal qrData\t\t\t\t\t\t\t\t# Pass QR Code data to JSON creator\n\t\t\t\tglobal iotJSON\t\t\t\t\t\t\t\t# Convert to JSON & publish\n\n\t\t\t\t\n\t\t\t\t## Start new thread each time - Counter ##\n\t\t\t\tif thr1 == 0:\n\t\t\t\t\t#t1 = threading.Thread(target=get_gesture)\t# Not started yet\n\t\t\t\t\tt1 = threading.Thread(target=fake_gesture)\t# Not started yet\n\t\t\t\t\tthreads.append(t1)\t\t\t\t\t\t\t# for multiple threads\n\t\t\t\t\n\t\t\t\t## Start new thread each time - ID Scan ##\n\t\t\t\tif thr2 == 0:\n\t\t\t\t\tt2 = threading.Thread(target=QR_Scan)\t# Not started yet\n\t\t\t\t\tthreads.append(t2)\t\t\t\t\t\t# for multiple threads\n\t\t\t\t\n\t\t\t\t## START ID SCAN ROUTINE #\n\t\t\t\tif btn_state1 == 0:\n\t\t\t\t\tprint(\"READING QR CODE...\")\t\t\t\t# REMOVE\t\n\t\t\t\t\tbigButton[\"text\"] = \"START\\nCOUNT\"\t\t# Change Button Title\n\t\t\t\t\t\n\t\t\t\t\t## Update GUI Info Tab ##\n\t\t\t\t\tinfo = \"Info: Video Window Starting...\"\n\t\t\t\t\tupdate_label()\n\t\t\t\t\t## If thread not started (can't start twice?)\n\t\t\t\t\tif thr2 == 0:\n\t\t\t\t\t\tthr2 = 1\t\t\t\t\t\t\t# toggle flag\n\t\t\t\t\t\tt2.start()\t\t\t\t\t\t\t# start QR Reader thread\n\n\t\t\t\t\tbtn_state1 = 1\t\t\t\t\t\t\t# To \"START COUNTER\"\n\t\t\t\t\t\n\t\t\t\t## START COUNT ROUTINE #\n\t\t\t\telif btn_state1 == 1:\n\t\t\t\t\tprint(\"START COUNTING ROUTINE NOW...\")\t# REMOVE\n\t\t\t\t\t\n\t\t\t\t\tbigButton[\"text\"] = \"STOP\\nCOUNT\"\t\t# button label change\n\t\t\t\t\tinfo = \"Info: Started Counting...\"\t\t# User info\n\t\t\t\t\tCnt = 0\t\t\t\t\t\t\t\t\t# zero counter\n\t\t\t\t\t\n\t\t\t\t\t## If thread not started (can't start twice?)\n\t\t\t\t\tif thr1 == 0:\n\t\t\t\t\t\tprint(\"start gesture thread\")\n\t\t\t\t\t\tthr1 = 1\t\t\t\t\t\t\t# toggle flag\n\t\t\t\t\t\tt1.start()\t\t\t\t\t\t\t# start gesture thread\n\t\t\t\t\t\n\t\t\t\t\t## Update GUI information ##\n\t\t\t\t\tupdate_label()\n\t\t\t\t\t\n\t\t\t\t\tbtn_state1 = 2\t\t\t\t\t\t\t# To \"STOP COUNTER\"\n\t\t\t\t\n\t\t\t\t## END COUNT ROUTINE #\n\t\t\t\telif btn_state1 == 2:\n\t\t\t\t\tprint(\"STOP COUNT\")\t\t\t\t\t\t# REMOVE\n\t\t\t\t\tbigButton[\"text\"] = \"START\\nCOUNT\"\n\t\t\t\t\tinfo = \"Info: Counting Complete\"\n\t\t\t\t\t\n\t\t\t\t\t## If thread was started ##\n\t\t\t\t\tif thr1 == 1:\t\t\t\t\t\t\t# Can't start thread again? - REMOVE?\n\t\t\t\t\t\tthr1 = 0\t\t\t\t\t\t\t# Clear thread flag\n\t\t\t\t\t\tGestDone = True\t\t\t\t\t\t# Break out of Gesture funtion\n\t\t\t\t\t\t## Close the thread ##\n\t\t\t\t\t\t#t1.join()\t\t\t\t\t\t\t# ERROR - reference\n\t\t\t\t\t\t\n\t\t\t\t\t\t## Update GUI information ##\n\t\t\t\t\t\tupdate_label()\n\t\t\t\t\t\n\t\t\t\t\tbtn_state1 = 1\t\t\t\t\t\t\t# Back to \"START COUNTER\"\n\t\t\t\n\t\t\t\n\t\t\t################################\n\t\t\t## CREATE JSON DATA STRUCTURE ##\n\t\t\t## PUBLISH TO GCP VIA MQTT\t ##\n\t\t\t################################\n\t\t\tdef handleData(Cnt):\n\t\t\t\tglobal qrData\t\t\t\t\t\t\t\t\t# QR Data to create JSON string\n\t\t\t\tglobal iotJSON\t\t\t\t\t\t\t\t\t# returned JSON string\n\t\t\t\t\n\t\t\t\t#print(\"PCB: {}\".format(Cnt))\n\n\t\t\t\tiotJSON = createJSON(qrData, Cnt)\t\t\t# Convert to JSON format\n\t\t\t\t#print(\"JSON Created...\")\t\t\t\t\t# REMOVE\n\t\t\t\t#print(\"{}\".format(iotJSON)) \t\t\t\t# REMOVE\n\t\t\t\t\t\n\t\t\t\t#print(\"Publish GCP!\")\t\t\t\t\t\t# REMOVE\n\t\t\t\tiot_publish(iotJSON)\t\t\t\t\t\t# Publish JSON Data\n\t\t\t\tprint(\"PUBLISHED...\")\t\t\t\t\t\t# REMOVE\n\t\t\t\n\t\t\t\n\t\t\t####################################\n\t\t\t## DATA CLASS FOR JSON CONVERSION ##\n\t\t\t####################################\n\t\t\tclass OmniData:\n\t\t\t\tCLIENT \t= 'TSE'\n\t\t\t\tPROJECT = 515151515\n\t\t\t\tSTAGE \t= 'NULL'\n\t\t\t\tBOARDS \t= 0\n\t\t\t\tPANELS \t= 0\n\t\t\t\tSTAFF_ID = 000\n\t\t\t\tDATE \t= '01-01-2020'\n\t\t\t\tTIME \t= '00:00'\n\t\t\t\tSTART \t= '00:00'\n\t\t\t\tSTOP \t= '00:00'\n\t\t\t\tREASON \t= 'NULL'\n\t\t\t\tSERIAL \t= 121212121\n\n\n\t\t\t##################################\n\t\t\t## UPDATE ALL INFO DATA \t\t## \n\t\t\t## CREATE JSON STRING AND STORE\t## \n\t\t\t##################################\n\t\t\tdef createJSON(qrData, Cnt):\n\t\t\t\tglobal firstScan\t\t\t\t\t\t\t\t\t# only store certain data on first scan\n\t\t\t\tglobal projectStat\t\t\t\t\t\t\t\t\t# project start or stop\n\t\t\t\tglobal staffID\t\t\t\t\t\t\t\t\t\t# Extracted Staff ID from QR Scan2\n\t\t\t\tglobal dataDict\n\t\t\t\tglobal staffKit\t\t\t\t\t\t\t\t\t\t# kitID[0] OR staffID[1]\n\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t## Get Startup Information - Time & Date on 'SETUP' stage ##\n\t\t\t\tnow = datetime.datetime.now()\t\t\t\t\t\t# Get 'nows' date & time\n\t\t\t\t#current_date = now.strftime(\"%Y-%m-%d\")\t\t\t# Extract date\n\t\t\t\tcurrent_time = now.strftime(\"%H:%M:%S\")\t\t\t\t# Extract time\n\t\t\t\t\n\t\t\t\t## Update only on 1st QR Scan ##\n\t\t\t\tif firstScan == 0:\n\t\t\t\t\t## Extract data with ',' delimiter - Directly into Global Disctionary ##\n\t\t\t\t\tdataDict = dict(i.split('=') for i in qrData.split(','))\n\t\t\t\t\tfirstScan = 1\t\t\t\t\t\t\t\t\t# RETURN TO '0' EVERY TIME SCAN IS OPENED \n\t\t\t\t\tcurrent_date = now.strftime(\"%Y-%m-%d\")\t\t\t# Extract date\n\t\t\t\t\tdataDict['STAFF_ID'] = staffID\t\t\t\t\t\t# Update Staff ID\t\t- on startup\n\t\t\t\t\tdataDict['DATE'] = current_date\t\t\t\t\t# insert current date\n\t\t\t\t\tdataDict['TIME'] = current_time\t\t\t\t\t# insert current date\n\n\t\t\t\t## Depending on KIT or STAFF qrScan ##\n\t\t\t\t# if start/stop:\n\t\t\t\tdataDict['START'] = current_time\t\t\t\t\t# insert current time\n\t\t\t\t# else:\n\t\t\t\tdataDict['STOP'] = current_time\t\t\t\t\t# insert current time\n\n\t\t\t\t## Continuously Update PCB Value ##\n\t\t\t\tdataDict['BOARDS'] = Cnt\t\t\t\t\t\t\t# Update board count \t- every count\n\n\t\t\t\t#print(dataDict)\n\n\t\t\t\t## Mirror dictionary data to data class ##\n\t\t\t\t## EDIT: Use loop to import new data ##\n\t\t\t\tOmniData1 = OmniData()\t\t\t\t\t\t\t\t# get object characteristics\n\t\t\t\tOmniData1.CLIENT \t= dataDict['CLIENT']\n\t\t\t\tOmniData1.PROJECT \t= dataDict['PROJECT']\n\t\t\t\tOmniData1.STAGE \t= dataDict['STAGE']\n\t\t\t\tOmniData1.BOARDS \t= dataDict['BOARDS']\n\t\t\t\tOmniData1.PANELS \t= dataDict['PANELS']\n\t\t\t\tOmniData1.STAFF_ID \t= dataDict['STAFF_ID']\n\t\t\t\tOmniData1.DATE \t\t= dataDict['DATE']\n\t\t\t\tOmniData1.TIME \t\t= dataDict['TIME']\n\t\t\t\tOmniData1.START \t= dataDict['START']\n\t\t\t\tOmniData1.STOP \t\t= dataDict['STOP']\n\t\t\t\tOmniData1.REASON \t= dataDict['REASON']\n\t\t\t\tOmniData1.SERIAL \t= dataDict['SERIAL']\n\n\t\t\t\t#print(OmniData1.__dict__)\n\n\t\t\t\t## Convert Data Class to JSON string ##\n\t\t\t\t## NOTE: Data fields are not created in the same order ##\n\t\t\t\tjsonStr = json.dumps(OmniData1.__dict__)\n\n\t\t\t\t#print(jsonStr)\n\n\t\t\t\t## Pass JSON string back ##\n\t\t\t\treturn jsonStr\n\t\t\t\n\t\t\t\n\t\t\t##############################\n\t\t\t## CREATE THE JWT TOKEN KEY ##\n\t\t\t##############################\n\t\t\tdef create_jwt():\n\t\t\t\ttoken = {\n\t\t\t\t\t'iat': cur_time,\n\t\t\t\t\t'exp': cur_time + datetime.timedelta(minutes=60),\n\t\t\t\t\t'aud': project_id\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\twith open(ssl_private_key_filepath, 'r') as f:\n\t\t\t\t\tprivate_key = f.read()\n\t\t\t\t\t\n\t\t\t\treturn jwt.encode(token, private_key, ssl_algorithm)\n\t\t\t\n\t\t\t\n\t\t\t##################################\n\t\t\t## CONNECT VIA MQTT AND PUBLISH ##\n\t\t\t##################################\n\t\t\tdef iot_publish(iotJSON):\n\t\t\t\t_CLIENT_ID = 'projects/{}/locations/{}/registries/{}/devices/{}'.format(project_id, gcp_location, registry_id, device_id)\n\t\t\t\t_MQTT_TOPIC = '/devices/{}/events'.format(device_id)\n\n\t\t\t\tclient = mqtt.Client(client_id=_CLIENT_ID)\n\t\t\t\t# authorization is handled purely with JWT, no user/pass, so username can be whatever\n\t\t\t\tclient.username_pw_set(\n\t\t\t\t\tusername='unused',\n\t\t\t\t\tpassword=create_jwt())\n\n\t\t\t\tdef error_str(rc):\n\t\t\t\t\treturn '{}: {}'.format(rc, mqtt.error_string(rc))\n\n\t\t\t\tdef on_connect(unusued_client, unused_userdata, unused_flags, rc):\n\t\t\t\t\tprint('on_connect', error_str(rc))\n\n\t\t\t\tdef on_publish(unused_client, unused_userdata, unused_mid):\n\t\t\t\t\tprint('on_publish')\n\n\t\t\t\tclient.on_connect = on_connect\n\t\t\t\tclient.on_publish = on_publish\n\n\t\t\t\tclient.tls_set(ca_certs=root_cert_filepath) # Replace this with 3rd party cert if that was used when creating registry\n\t\t\t\tclient.connect('mqtt.googleapis.com', 8883)\n\t\t\t\tclient.loop_start()\n\t\t\t\t\n\t\t\t\t\"\"\"\n\t\t\t\t## Single Publish ##\n\t\t\t\tpayload = iotJSON\n\t\t\t\t## Actually publish the Data ## \n\t\t\t\tclient.publish(_MQTT_TOPIC, payload, qos=1)\n\t\t\t\t## View the payload data ##\n\t\t\t\tprint(\"{}\\n\".format(payload))\t\t\t\t\n\t\t\t\ttime.sleep(1)\n\t\t\t\tclient.loop_stop()\n\t\t\t\t\"\"\"\n\t\t\t\t\n\t\t\t\t## Multiple Publishes to IoT Core (~Twice~) ##\n\t\t\t\tfor i in range(1, 3):\n\t\t\t\t\tpayload = iotJSON\t\t\t\t\t\t\t# move data to payload\n\t\t\t\t\t\n\t\t\t\t\t## Actually publish the Data ## \n\t\t\t\t\tclient.publish(_MQTT_TOPIC, payload, qos=1)\n\t\t\t\t\t#print(\"{}\\n\".format(payload))\t\t\t\t# REMOVE\t\t\t\n\t\t\t\t\t\n\t\t\t\t\ttime.sleep(1)\t\t\t\t\t\t\t\t# REQUIRED ? ?\n\t\t\t\t\tclient.loop_stop()\t\t\t\t\t\t\t# Close loop\n\t\t\t\t\n\n\t\t\t############################\n\t\t\t# DROP DOWN MENU CALLBACK ##\n\t\t\t############################\n\t\t\tdef callback(*args):\n\t\t\t\tglobal info \n\t\t\n\t\t\t\t# Update info bar in 'main.py'\n\t\t\t\tinfo = \"Info: stage - {}\".format(dropD.get())\t# New 'info' message\n\t\t\t\tupdate_label()\t\t\t\t\t\t\t\t\t# Update GUI Info label\n\t\t\t\t\n\t\t\t\t## Begin Exit Routine ##\n\t\t\t\tif dropD.get() == \"EXIT\":\n\t\t\t\t\texitProgram()\n\t\t\t\t## Update Stage to Dictionary ##\n\t\t\t\telse:\n\t\t\t\t\tdataDict['STAGE'] = dropD.get()\n\t\t\t\n\t\t\t\n\t\t\t###########################\n\t\t\t## REALTIME LABEL UPDATE ##\n\t\t\t###########################\n\t\t\tdef update_label():\n\t\t\t\tglobal Cnt\n\t\t\t\tglobal info\n\t\t\t\t\n\t\t\t\t## Update Count Label ##\n\t\t\t\tlabel_4.config(text=\"- {} -\".format(Cnt), font = myFont1)\n\t\t\t\t## Update Info Label ##\n\t\t\t\tlabel_6.config(text=\"{}\".format(info), font = \"Helvetica 10\")\n\t\t\t\n\t\t\t\n\t\t\t#########################\n\t\t\t## BRING WINDOW TO TOP ##\n\t\t\t#########################\n\t\t\t\"\"\"\n\t\t\tdef lift_window():\n\t\t\t\tprint(\"Lift Window\")\n\t\t\t\twin.lift()\n\t\t\t\"\"\"\n\t\t\t\n\t\t\t###############################\n\t\t\t## NUMERICAL EXIT CODE ENTRY ##\n\t\t\t###############################\n\t\t\tdef code(value):\n\t\t\t\tglobal pin\t\t\t\t\t\t\t\t\t# \n\t\t\t\tglobal ExCode\t\t\t\t\t\t\t\t# \n\n\t\t\t\t## '*' Key presses ##\n\t\t\t\tif value == '*':\n\t\t\t\t\t## remove last digit from `pin` ##\n\t\t\t\t\tpin = pin[:-1]\n\t\t\t\t\n\t\t\t\t## '#' Key presses ##\n\t\t\t\telif value == '#':\n\t\t\t\t\t## check pin ##\n\t\t\t\t\tif pin == \"3529\":\t\t\t\t\t\t# Set pin number here!\n\t\t\t\t\t\tprint(\"PIN OK\")\t\t\t\t\t\t# console - REMOVE\n\t\t\t\t\t\tpin = ''\t\t\t\t\t\t\t# clear `pin`\n\t\t\t\t\t\t#ExCode = True \t\t\t\t\t\t# Set ExCode\n\t\t\t\t\t\tKeyPadExit(True)\t\t\t\t\t# Close keypad window\n\t\t\t\t\telse:\n\t\t\t\t\t\tprint(\"INCORRECT PIN!\")\t\t\t\t# console - REMOVE\n\t\t\t\t\t\tpin = ''\t\t\t\t\t\t\t# clear `pin`\n\t\t\t\t\t\t\n\t\t\t\t\t\t# After 3 attempts - Close keypad window\n\t\t\t\t\t\tKeyPadExit(False)\t\t\t\t\t# must be repeatable\n\n\t\t\t\t## Any digit keys pressed ##\n\t\t\t\telse:\n\t\t\t\t\tpin += value\t\t\t\t\t\t\t# Add digit to pin\n\t\t\t\t\n\t\t\t\t#print(\"Current: \" + pin)\t\t\t\t\t# show input code\n\t\t\t\n\t\t\t\n\t\t\t##########################\n\t\t\t## CREATE KEYPAD WINDOW ##\n\t\t\t##########################\n\t\t\tdef KeyPadWin():\n\t\t\t\t## Define keypad keys ##\n\t\t\t\tkeys = [\n\t\t\t\t\t['1', '2', '3'], \n\t\t\t\t\t['4', '5', '6'], \n\t\t\t\t\t['7', '8', '9'], \n\t\t\t\t\t['*', '9', '#'], \n\t\t\t\t]\n\t\t\t\t## Create new Window ##\n\t\t\t\tkeyPadWin = Toplevel(win)\n\t\t\t\tlay.append(keyPadWin)\n\t\t\t\tkeyPadWin.title(\"EXIT CODE\")\n\t\t\t\t\n\t\t\t\t## Create buttons using `keys`\n\t\t\t\tfor y, row in enumerate(keys, 1):\n\t\t\t\t\tfor x, key in enumerate(row):\n\t\t\t\t\t\t# `lambda` inside `for` has to use `val=key:code(val)` \n\t\t\t\t\t\t# instead of direct `code(key)`\n\t\t\t\t\t\tb = Button(keyPadWin, text=key, command=lambda val=key:code(val))\n\t\t\t\t\t\tb.grid(row=y, column=x, ipadx=10, ipady=10)\n\t\t\t\n\t\t\t\n\t\t\t########################\n\t\t\t## EXIT KEYPAD WINDOW ##\n\t\t\t########################\n\t\t\tdef KeyPadExit(CodeDone):\n\t\t\t\tglobal info\t\t\t\t\t\t\t\t\t\t# App information\n\t\t\t\t\n\t\t\t\tprint(\"[INFO] Destroy Window...\")\t\t\t# REMOVE\n\t\t\t\tkeyPadWin = lay[0]\t\t\t\t\t\t\t\t# DON'T THINK THIS WORKING??\n\t\t\t\t\n\t\t\t\tif CodeDone == True:\n\t\t\t\t\tprint(\"[INFO] Quit Main Program!!\")\t\t# REMOVE\n\t\t\t\t\t## Destroy All Windows ##\n\t\t\t\t\t## NOT DESTROYING CV2 WINDOW ? ? ##\n\t\t\t\t\twin.quit()\n\t\t\t\t\twin.destroy()\n\t\t\t\t\tsys.exit(0)\n\t\t\t\telse:\n\t\t\t\t\t## Info: Exit Failed ##\n\t\t\t\t\tinfo = \"Info: Exit Code Incorrect\"\t\t\t# New 'info' message\n\t\t\t\t\tupdate_label()\t\t\t\t\t\t\t\t# Update GUI Info label \n\t\t\t\t\tprint(\"[INFO] Exit Code Incorrect\")\t\t# REMOVE\n\t\t\t\t\t\t\n\t\t\t\t\t## Destroy Keypad Window ##\n\t\t\t\t\tkeyPadWin.destroy()\t\t\t\t\t\t\t\n\t\t\t\t\tkeyPadWin.update()\t\t\t\t\t\t\t# --- Only works once? ? ?\n\t\t\t\n\t\t\t\n\t\t\t##########################\n\t\t\t## EXIT AND DESTROY GUI ##\n\t\t\t##########################\n\t\t\tdef exitProgram():\n\t\t\t\tglobal thr1\t\t\t\t\t\t\t\t\t\t# Thread exitted correctly\n\t\t\t\tglobal info\t\t\t\t\t\t\t\t\t\t# App information\n\t\t\t\tglobal ExCode\t\t\t\t\t\t\t\t\t# code correct/incorrect - flag\n\t\t\t\t\n\t\t\t\tExCode = False\t\t\t\t\t\t\t\t\t# Normally Blocked\n\t\t\t\t\n\t\t\t\t## Check thread ended properly ##\n\t\t\t\tif thr1 == 0:\n\t\t\t\t\t## Enter Exit Code ##\n\t\t\t\t\tKeyPadWin()\t\t\t\t\t\t\t\t\t# keypad input\n\t\t\t\telse:\n\t\t\t\t\tprint(\"Still busy...\")\t\t\t\t\t\t# console - REMOVE\n\n\n\t\t\t## INITIALISE NEW WINDOW ##\n\t\t\twin = Tk()\n\t\t\t## Define the Fonts:\n\t\t\tmyFont1 = tkFont.Font(family = 'Helvetica', size = 30, weight = 'bold')\n\t\t\tmyFont2 = tkFont.Font(family = 'Helvetica', size = 12, weight = 'bold')\n\n\t\t\t# SETUP WINDOW PARAMTERS ##\n\t\t\twin.title(\"OMNIGO\")\t\t\t\t\t\t\t# define window title\n\t\t\twin.geometry('480x320+0+0')\t\t\t\t\t# define screen size\t- swap\n\t\t\t#win.attributes(\"-fullscreen\", True)\t\t# full screen GUI\t\t- swap\n\t\t\twin.configure(background = \"gray15\")\t\t# set colour\n\t\t\t\n\t\t\t# DROP-DOWN MENU ##\n\t\t\tdropD = StringVar(win)\n\t\t\tdropD.set(\"Stage\")\n\n\t\t\topt = OptionMenu(win, dropD, *OptionList)\n\t\t\topt.config( width=5, \n\t\t\t\t\t\tfont=('Helvetica', 10), \n\t\t\t\t\t\tbg\t\t= \"gray15\",\n\t\t\t\t\t\tfg \t\t= \"gray64\",)\n\t\t\topt.pack(side=\"top\", anchor=\"nw\")\n\t\t\t\n\t\t\t# EXIT BUTTON - REMOVED ##\n\t\t\t\n\t\t\t# OMNIGO TITLE ##\n\t\t\tlabel_2 = Label(win, \n\t\t\t\t\t\t\ttext \t= \"- OMNIGO -\", \n\t\t\t\t\t\t\tbg \t\t= \"gray15\",\n\t\t\t\t\t\t\tfg \t\t= \"OrangeRed2\",\n\t\t\t\t\t\t\trelief \t= \"solid\",\n\t\t\t\t\t\t\tfont \t= \"Helvetica 36\",\n\t\t\t\t\t\t\twidth \t= 11,\n\t\t\t\t\t\t\theight\t= 1)\n\t\t\t# SPACER ##\n\t\t\tlabel_3 = Label(win, \n\t\t\t\t\t\t\ttext\t= \" \", \n\t\t\t\t\t\t\tbg \t\t= \"gray15\",\n\t\t\t\t\t\t\tfont \t= \"Helvetica 18\")\n\t\t\t\n\t\t\t# Place objects ##\n\t\t\tlabel_2.pack(padx=10)\n\t\t\tlabel_3.pack(padx=10)\n\t\t\t\n\t\t\t# STOP/START BUTTON ##\n\t\t\tbigButton = Button(win, \n\t\t\t\t\t\t\t\ttext \t= \"SCAN\\n- ID -\", \n\t\t\t\t\t\t\t\tfont \t= myFont1, \n\t\t\t\t\t\t\t\tcommand = btn_start,\t# btn_cnt,\n\t\t\t\t\t\t\t\tfg \t\t= \"Red4\",\n\t\t\t\t\t\t\t\tbg \t\t= \"gray45\",\n\t\t\t\t\t\t\t\theight \t= 2, \n\t\t\t\t\t\t\t\twidth \t= 12)\n\t\t\tbigButton.pack(anchor=CENTER)\t\t\t\t# place the object\n\t\t\t\t\n\t\t\t# SPACER ##\n\t\t\tlabel_5 = Label(win, \n\t\t\t\t\t\t\ttext\t= \" \", \n\t\t\t\t\t\t\tbg \t\t= \"gray15\",\n\t\t\t\t\t\t\tfont \t= \"Helvetica 14\")\n\t\t\t# COUNTER ##\n\t\t\tlabel_4 = Label(win, \n\t\t\t\t\t\t\ttext\t= \"- {} -\".format(Cnt), \n\t\t\t\t\t\t\tfg \t\t= \"OrangeRed2\",\n\t\t\t\t\t\t\tbg \t\t= \"gray15\",\n\t\t\t\t\t\t\tfont \t= \"Helvetica 30\")\n\t\t\t# INFORMATION ##\n\t\t\tlabel_6 = Label(win, \n\t\t\t\t\t\t\ttext\t= \"info: {}\".format(info), \n\t\t\t\t\t\t\tfg \t\t= \"OrangeRed2\",\n\t\t\t\t\t\t\tbg \t\t= \"gray15\",\n\t\t\t\t\t\t\tfont \t= \"Helvetica 10\")\n\t\t\t\t\t\t\t\n\t\t\t# Place more objects ##\n\t\t\tlabel_5.pack(padx=10)\t\t\t\t\t\t# spcer from button\n\t\t\tlabel_4.pack(padx=10)\t\t\t\t\t\t# PCB counter\n\t\t\tlabel_6.pack(anchor=SW)\t\t\t\t\t\t# PCB counter\n\t\t\t\n\t\t\t# DROP-DOWN Function Call ##\n\t\t\tdropD.trace(\"w\", callback)\n\t\t\t\n\t\t\t# GUI main loop ##\n\t\t\tmainloop()\n\t\t\t\n\t\t# Ctrl+C will exit the program correctly\n\t\texcept KeyboardInterrupt:\n\t\t\tprint(\"main.py - keyboard interupt\")\n\t\t\tsys.exit(0)\n\t\t\n\t# Any Main Errors saved to log.txt file:\n\texcept Exception:\n\t\tprint(\"main.py - Exception reached\")\n\t\tlog = open(\"log.txt\", 'w')\n\t\ttraceback.print_exc(file=log)\n\t\tsys.exit(0)\n\n\nif __name__ == \"__main__\":\tmain()\n", "repo_name": "ANTZ314/raspi", "sub_path": "GUI/omnigo/main2.py", "file_name": "main2.py", "file_ext": "py", "file_size_in_byte": 26885, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "smbus.SMBus", "line_number": 90, "usage_type": "call"}, {"api_name": "apds9960.APDS9960", "line_number": 91, "usage_type": "call"}, {"api_name": "datetime.datetime.utcnow", "line_number": 147, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 147, "usage_type": "attribute"}, {"api_name": "time.time", "line_number": 157, "usage_type": "call"}, {"api_name": "imutils.video.VideoStream", "line_number": 166, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 167, "usage_type": "call"}, {"api_name": "cv2.namedWindow", "line_number": 168, "usage_type": "call"}, {"api_name": "cv2.moveWindow", "line_number": 169, "usage_type": "call"}, {"api_name": "time.time", "line_number": 173, "usage_type": "call"}, {"api_name": "imutils.rotate", "line_number": 177, "usage_type": "call"}, {"api_name": "imutils.resize", "line_number": 178, "usage_type": "call"}, {"api_name": "pyzbar.pyzbar.decode", "line_number": 181, "usage_type": "call"}, {"api_name": "pyzbar.pyzbar", "line_number": 181, "usage_type": "name"}, {"api_name": "cv2.rectangle", "line_number": 187, "usage_type": "call"}, {"api_name": "cv2.putText", "line_number": 202, "usage_type": "call"}, {"api_name": "cv2.FONT_HERSHEY_SIMPLEX", "line_number": 203, "usage_type": "attribute"}, {"api_name": "cv2.FONT_HERSHEY_SIMPLEX", "line_number": 221, "usage_type": "attribute"}, {"api_name": "cv2.getTextSize", "line_number": 223, "usage_type": "call"}, {"api_name": "cv2.putText", "line_number": 230, "usage_type": "call"}, {"api_name": "cv2.imshow", "line_number": 240, "usage_type": "call"}, {"api_name": "cv2.waitKey", "line_number": 241, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 245, "usage_type": "call"}, {"api_name": "cv2.destroyAllWindows", "line_number": 269, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 299, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 333, "usage_type": "call"}, {"api_name": "threading.Thread", "line_number": 395, "usage_type": "call"}, {"api_name": "threading.Thread", "line_number": 400, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 505, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 505, "usage_type": "attribute"}, {"api_name": "json.dumps", "line_number": 550, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 564, "usage_type": "call"}, {"api_name": "jwt.encode", "line_number": 571, "usage_type": "call"}, {"api_name": "paho.mqtt.client.Client", "line_number": 581, "usage_type": "call"}, {"api_name": "paho.mqtt.client", "line_number": 581, "usage_type": "name"}, {"api_name": "paho.mqtt.client.error_string", "line_number": 588, "usage_type": "call"}, {"api_name": "paho.mqtt.client", "line_number": 588, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 622, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 740, "usage_type": "call"}, {"api_name": "tkFont.Font", "line_number": 773, "usage_type": "call"}, {"api_name": "tkFont.Font", "line_number": 774, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 857, "usage_type": "call"}, {"api_name": "traceback.print_exc", "line_number": 863, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 864, "usage_type": "call"}]} +{"seq_id": "9725189765", "text": "import numpy as np\r\nimport matplotlib.pyplot as plt\r\nx = 10\r\nx1 = pow(x,2)\r\nx2 = pow(x,3)\r\ntheta = 45\r\ny1 = np.sin(theta)\r\ny2 = np.cos(theta)\r\nmeshPoints = np.linspace(-1, 1, 500)\r\nmeshPoints1 = meshPoints[53]\r\nplt.plot(meshPoints,np.sin(2*np.pi*meshPoints))\r\nplt.show()\r\n", "repo_name": "alirezashadmani/Python", "sub_path": "Ex10_1.py", "file_name": "Ex10_1.py", "file_ext": "py", "file_size_in_byte": 272, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "21", "api": [{"api_name": "numpy.sin", "line_number": 7, "usage_type": "call"}, {"api_name": "numpy.cos", "line_number": 8, "usage_type": "call"}, {"api_name": "numpy.linspace", "line_number": 9, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 11, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 11, "usage_type": "name"}, {"api_name": "numpy.sin", "line_number": 11, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 11, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.show", "line_number": 12, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 12, "usage_type": "name"}]} +{"seq_id": "3085575741", "text": "from typing import List;\nimport os;\nfrom array import *\nimport numpy as np\nimport networkx as nx\nimport matplotlib.pyplot as plt # Optional, for visualizati\n\n\ndef read_input(file_name):\n current_path = os.path.dirname(__file__)\n lines = []\n try:\n with open(os.path.join(current_path, file_name), 'r') as file:\n for line in file:\n lines.append(line.strip()) # Remove any leading or trailing whitespace\n except Exception as e:\n print(f\"An error occurred: {e}\")\n return lines\n\ndef convert_map(lines):\n map = []\n\n for line_idx, line in enumerate(lines):\n current_line = []\n for ele_idx, element in enumerate(line):\n if element >= 'a' and element <= 'z':\n element = ord(element) - ord('a')\n current_line.append(element)\n map.append(current_line)\n return map \n\n\ndef create_directional_graph(num_nodes, connections):\n boolean_map = np.full((num_nodes, num_nodes), False)\n \n for connection in connections:\n from_node, to_node = connection\n boolean_map[from_node, to_node] = True # Set True for directional connection\n \n return boolean_map\n\n\ndef is_climbable(node_from, node_to) -> bool:\n if node_from == 'S' or node_to == 'S' or node_from == 'E' or node_to == 'E' : \n return True\n if node_from < node_to or node_from - node_to == 1: #can go down and 1 step up\n return True\n return False\n\n\ndef create_directional_tuples(input_data):\n #input data should be list(list())\n #iterate throgh lines\n len_cols = len(input_data[0])\n len_rows = len(input_data)\n\n directional_tuples = []\n for row_idx, row in enumerate(input_data):\n for col_idx, element in enumerate(row):\n current_index = row_idx * len_cols + col_idx \n if row_idx > 0:\n if is_climbable(element,input_data[row_idx - 1][col_idx]): #above\n directional_tuples.append((current_index, row_idx - 1 * len_cols + col_idx))\n print(f\"added {(current_index, row_idx - 1 * len_cols + col_idx)}\")\n if row_idx < len_rows - 1:\n if is_climbable(element,input_data[row_idx + 1][col_idx]): #below\n directional_tuples.append((current_index, row_idx + 1 * len_cols + col_idx))\n print(f\"added {(current_index, row_idx + 1 * len_cols + col_idx)}\")\n if col_idx < len_cols - 1:\n if is_climbable(element,input_data[row_idx][col_idx + 1]): #right\n directional_tuples.append((current_index, row_idx * len_cols + col_idx + 1))\n print(f\"added {(current_index, row_idx * len_cols + col_idx + 1)}\")\n if col_idx > 0:\n if is_climbable(element,input_data[row_idx][col_idx - 1]): #left\n directional_tuples.append((current_index, row_idx * len_cols + col_idx - 1))\n print(f\"added {(current_index, row_idx * len_cols + col_idx - 1)}\")\n return directional_tuples\n \n\ndef dijkstra_algorithm(graph, source):\n num_of_nodes = len(graph)\n visited = np.full(num_of_nodes, False)\n previous = np.full(num_of_nodes, None)\n distances = np.full(num_of_nodes, np.inf)\n distances[source] = 0\n\n for _ in range(num_of_nodes):\n current = np.argmin(distances * ~visited)\n visited[current] = True\n\n for neighbor in range(num_of_nodes):\n if not visited[neighbor] and graph[current, neighbor]:\n new_distance = distances[current] + 1 # Assuming all edges have weight 1\n if new_distance < distances[neighbor]:\n distances[neighbor] = new_distance\n \n return distances\n \n\ndef dijkstra_boolean_map(boolean_map, source):\n num_nodes = boolean_map.shape[0]\n distances = np.full(num_nodes, np.inf)\n visited = np.full(num_nodes, False)\n distances[source] = 0\n\n for _ in range(num_nodes):\n current = np.argmin(distances * ~visited)\n visited[current] = True\n\n for neighbor in range(num_nodes):\n if not visited[neighbor] and boolean_map[current, neighbor]:\n new_distance = distances[current] + 1 # Assuming all edges have weight 1\n if new_distance < distances[neighbor]:\n distances[neighbor] = new_distance\n\n return distances\n\n\"\"\"\n\n 1 function Dijkstra(Graph, source):\n 2 \n 3 for each vertex v in Graph.Vertices:\n 4 dist[v] ← INFINITY\n 5 prev[v] ← UNDEFINED\n 6 add v to Q\n 7 dist[source] ← 0\n 8 \n 9 while Q is not empty:\n10 u ← vertex in Q with min dist[u]\n11 remove u from Q\n12 \n13 for each neighbor v of u still in Q:\n14 alt ← dist[u] + Graph.Edges(u, v)\n15 if alt < dist[v]:\n16 dist[v] ← alt\n17 prev[v] ← u\n18\n19 return dist[], prev[]\n\n\"\"\"\n\nlines = read_input(\"text_input.txt\")\nlines_2 = [\n [ 'S', 'a', 'd'],\n [ 'a', 'c', 'd'],\n [ 'b', 'c', 'E'],\n ]\nmap = convert_map(lines_2)\n\ndir_tuples = create_directional_tuples(map)\nprint(dir_tuples)\n\nadjacency_matrix = create_directional_graph(len(dir_tuples), dir_tuples)\nfor line in adjacency_matrix:\n print(line)\n\nret_val = dijkstra_algorithm(adjacency_matrix, 0)\nfor line in ret_val:\n print(line)\n\n# Create a directed graph from the adjacency matrix\nG = nx.DiGraph()\n\nnum_nodes = len(adjacency_matrix)\nG.add_nodes_from(range(num_nodes)) # Add nodes to the graph\n\n# Add directed edges based on the adjacency matrix\nfor i in range(num_nodes):\n for j in range(num_nodes):\n if adjacency_matrix[i][j]:\n G.add_edge(i, j)\n\n# Visualize the graph (optional)\npos = nx.spring_layout(G) # Position nodes using Fruchterman-Reingold force-directed algorithm\nnx.draw(G, pos, with_labels=True, node_size=500, node_color='skyblue', font_weight='bold', font_size=10, arrows=True)\nplt.show()", "repo_name": "bLeadDev/adventOfCode2022_py", "sub_path": "aoc.py", "file_name": "aoc.py", "file_ext": "py", "file_size_in_byte": 6028, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "os.path.dirname", "line_number": 10, "usage_type": "call"}, {"api_name": "os.path", "line_number": 10, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 13, "usage_type": "call"}, {"api_name": "os.path", "line_number": 13, "usage_type": "attribute"}, {"api_name": "numpy.full", "line_number": 34, "usage_type": "call"}, {"api_name": "numpy.full", "line_number": 82, "usage_type": "call"}, {"api_name": "numpy.full", "line_number": 83, "usage_type": "call"}, {"api_name": "numpy.full", "line_number": 84, "usage_type": "call"}, {"api_name": "numpy.inf", "line_number": 84, "usage_type": "attribute"}, {"api_name": "numpy.argmin", "line_number": 88, "usage_type": "call"}, {"api_name": "numpy.full", "line_number": 102, "usage_type": "call"}, {"api_name": "numpy.inf", "line_number": 102, "usage_type": "attribute"}, {"api_name": "numpy.full", "line_number": 103, "usage_type": "call"}, {"api_name": "numpy.argmin", "line_number": 107, "usage_type": "call"}, {"api_name": "networkx.DiGraph", "line_number": 162, "usage_type": "call"}, {"api_name": "networkx.spring_layout", "line_number": 174, "usage_type": "call"}, {"api_name": "networkx.draw", "line_number": 175, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.show", "line_number": 176, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 176, "usage_type": "name"}]} +{"seq_id": "3906297431", "text": "import os\n# Third party requirements\nimport numpy as np\nimport matplotlib.pylab as plt\n# Local imports\nimport pasam as ps\n\n# Constants\n_LOC_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\n# Computational lattice\nnodes = [np.arange(-179, 180, 2), np.arange(-89, 90, 2)]\nlattice = ps.Lattice(nodes)\n\n# Sampler\nratio = 2.0\nsampler = ps.GantryDominant2D(lattice=lattice, ratio=ratio, order='max_random')\n\n# Set prior probability\nfile_energy = os.path.join(_LOC_DIR, 'data', 'prior_energy_sin_180x90.txt')\nprior_energy = ps.LatticeMap.from_txt(file_energy)\nsampler.set_prior_prob(prior_energy, energy=True)\n\n# Set and check validity of prior conditioning\nfile_cond = os.path.join(_LOC_DIR, 'data', 'restrictions_180x90.txt')\nconditions = [file_cond]\nsampler.set_prior_cond(conditions, validate=True)\n\n# Sample Trajectory\ntrajectory = sampler()\n\n# Plot the Result\nmap_ = sampler.prior_cond * sampler.prior_prob\nvalues = np.reshape(map_.values, lattice.nnodes_dim, order='F')\n\n_, ax = plt.subplots()\nmin_x, max_x = nodes[0][0], nodes[0][-1]\nmin_y, max_y = nodes[1][0], nodes[1][-1]\nim_args = {\n 'origin': 'lower',\n 'cmap': 'viridis',\n 'extent': [min_x, max_x, min_y, max_y],\n}\nax.imshow(values.transpose(), **im_args)\nax.set(xticks=np.arange(min_x, max_x+1, (max_x - min_x)//2),\n yticks=np.arange(min_y, max_y+1, (max_y - min_y)//2))\nax.plot(*np.array(trajectory.points).transpose(), 'r')\n\n# Plot settings\nfont_size = 12\nplt.rc('xtick', labelsize=font_size)\nplt.rc('ytick', labelsize=font_size)\n\n# Save the results\nfile_fig = os.path.join(_LOC_DIR, 'figures', 'trajectory.png')\nplt.savefig(file_fig)\nprint(f'\\nThe result is saved under {file_fig}')\n", "repo_name": "jaegglic/pasam", "sub_path": "examples/GantryDominant2D/plot_trajectory.py", "file_name": "plot_trajectory.py", "file_ext": "py", "file_size_in_byte": 1684, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "os.path.dirname", "line_number": 9, "usage_type": "call"}, {"api_name": "os.path", "line_number": 9, "usage_type": "attribute"}, {"api_name": "os.path.abspath", "line_number": 9, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 12, "usage_type": "call"}, {"api_name": "pasam.Lattice", "line_number": 13, "usage_type": "call"}, {"api_name": "pasam.GantryDominant2D", "line_number": 17, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 20, "usage_type": "call"}, {"api_name": "os.path", "line_number": 20, "usage_type": "attribute"}, {"api_name": "pasam.LatticeMap.from_txt", "line_number": 21, "usage_type": "call"}, {"api_name": "pasam.LatticeMap", "line_number": 21, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 25, "usage_type": "call"}, {"api_name": "os.path", "line_number": 25, "usage_type": "attribute"}, {"api_name": "numpy.reshape", "line_number": 34, "usage_type": "call"}, {"api_name": "matplotlib.pylab.subplots", "line_number": 36, "usage_type": "call"}, {"api_name": "matplotlib.pylab", "line_number": 36, "usage_type": "name"}, {"api_name": "numpy.arange", "line_number": 45, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 46, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 47, "usage_type": "call"}, {"api_name": "matplotlib.pylab.rc", "line_number": 51, "usage_type": "call"}, {"api_name": "matplotlib.pylab", "line_number": 51, "usage_type": "name"}, {"api_name": "matplotlib.pylab.rc", "line_number": 52, "usage_type": "call"}, {"api_name": "matplotlib.pylab", "line_number": 52, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 55, "usage_type": "call"}, {"api_name": "os.path", "line_number": 55, "usage_type": "attribute"}, {"api_name": "matplotlib.pylab.savefig", "line_number": 56, "usage_type": "call"}, {"api_name": "matplotlib.pylab", "line_number": 56, "usage_type": "name"}]} +{"seq_id": "16017710301", "text": "import csv\nimport os\nimport codecs\nimport argparse\nimport civis\nfrom dotenv import load_dotenv\nfrom services import Postgres\nfrom common import replace_bom, yes_no\nfrom constants import van_to_clarity\n\n\ndef generate_base(for_clarity=False):\n \"\"\"\n List of currently rejected voters from the cure universe without a phone number in VAN.\n \"\"\"\n if for_clarity:\n query = (\n 'SELECT '\n ' myv_van_id as van_id, '\n ' voters.first_name, '\n ' voters.last_name, '\n ' voters.resident_address, '\n ' voters.city, '\n ' voters.state, '\n ' voters.zip, '\n ' voters.mailing_address '\n )\n else:\n query = 'SELECT voters.registration_number as sos_id, myv_van_id as van_id, voters.first_name, voters.last_name '\n\n query = query + (\n 'FROM voters, survey_responses, voter_demographics '\n 'WHERE voters.registration_number = survey_responses.registration_number '\n 'AND survey_responses.registration_number = voter_demographics.registration_number '\n 'AND best_number IS NULL '\n 'AND best_number_type IS NULL '\n 'AND cell IS NULL '\n 'AND landline IS NULL '\n 'AND voters.ballot_status IS NOT NULL'\n )\n with Postgres(**postgres_args) as cursor:\n cursor.execute(query)\n return {dict(row)['van_id']: dict(row) for row in cursor.fetchall()}\n\n\ndef process_clarity_csv():\n with Postgres(**postgres_args) as cursor:\n cursor.execute('SELECT * FROM wrong_numbers')\n wrong_numbers = {(dict(row)['van_id'], dict(row)['number']) for row in cursor.fetchall()}\n cursor.execute('SELECT * FROM right_numbers')\n right_numbers = {(dict(row)['van_id'], dict(row)['number']) for row in cursor.fetchall()}\n\n replace_bom('from_clarity.csv')\n\n clarity_dict = {}\n\n with codecs.open('from_clarity.csv', encoding='utf-8', errors='ignore') as f:\n for row in csv.DictReader(f):\n clarity_phone = row['ts_phone'] if (int(row['van_id']), row['ts_phone']) not in wrong_numbers and row['ts_phone'] != '\\\\N' else None\n clarity_cell = row['ts_wireless'] if (int(row['van_id']), row['ts_wireless']) not in wrong_numbers and row['ts_wireless'] != '\\\\N' else None\n clarity_dict[int(row['van_id'])] = {\n 'clarity_phone': clarity_phone,\n 'clarity_cell': clarity_cell,\n 'clarity_phone_type': row['ts_phonetype'] if clarity_phone else None,\n 'phone_verified': row['ts_phone'] in right_numbers,\n 'cell_verified': row['ts_wireless'] in right_numbers,\n }\n return clarity_dict\n\n\ndef upload_numbers(upload_type):\n query = (\n f'INSERT INTO {upload_type}_numbers (van_id, number, source)'\n 'VALUES (%s, %s, %s) '\n 'ON CONFLICT DO NOTHING'\n )\n with Postgres(**postgres_args) as cursor:\n with open(f'phones/{upload_type}_numbers.csv') as f:\n for row in csv.DictReader(f):\n cursor.execute(query, (row['van_id'], row['number'], row['source']))\n\n\ndef generate_list():\n if os.path.exists('phone_list.csv'):\n os.remove('phone_list.csv')\n\n base_dict = generate_base()\n clarity_dict = process_clarity_csv()\n\n with open('phones/phone_list.csv', 'w') as f:\n headers = [\n 'sos_id',\n 'van_id',\n 'first_name',\n 'last_name',\n 'clarity_phone',\n 'clarity_cell',\n 'clarity_phone_type',\n 'phone_verified',\n 'cell_verified'\n ]\n writer = csv.DictWriter(f, headers)\n writer.writeheader()\n for van_id, clarity_values in clarity_dict.items():\n # skip clarity numbers we no longer care about\n if van_id not in base_dict:\n continue\n else:\n base_dict[van_id] = {**base_dict[van_id], **clarity_values}\n for van_id in base_dict.keys():\n if van_id not in clarity_dict:\n base_dict[van_id] = {\n **base_dict[van_id],\n 'clarity_phone': None,\n 'clarity_cell': None,\n 'clarity_phone_type': None,\n 'phone_verified': None,\n 'cell_verified': None\n }\n rows = []\n for key in base_dict.keys():\n rows.append({'van_id': key, **base_dict[key]})\n writer.writerows(rows)\n\n\ndef create_for_clarity():\n if os.path.exists('for_clarity.csv'):\n os.remove('for_clarity.csv')\n\n replace_bom('phones/not_yet_contacted.csv')\n\n with codecs.open('phones/not_yet_contacted.csv') as f:\n rows = [row for row in csv.DictReader(f) if not row.get('Pref Phone ') or row.get('Pref Phone ').strip() == '']\n\n for_clarity_rows = [{van_to_clarity[k]: v for k, v in row.items() if k in van_to_clarity} for row in rows]\n\n with open('phones/for_clarity.csv', 'w') as f:\n writer = csv.DictWriter(f, van_to_clarity.values())\n writer.writeheader()\n writer.writerows(for_clarity_rows)\n\n\ndef get_cure_universe(currently_rejected=False, no_contact=False, has_number=False, has_cell=False, missing_number=False):\n query = (\n 'SELECT '\n ' survey_responses.myv_van_id as van_id, '\n ' voters.first_name as first, '\n ' voters.last_name as last, '\n ' voters.county as county, '\n ' voters.ballot_status as status, '\n ' voter_demographics.best_number as best, '\n ' voter_demographics.cell '\n 'FROM voters, survey_responses, voter_demographics '\n 'WHERE voters.registration_number = survey_responses.registration_number '\n 'AND dscc_support_score >= 50'\n )\n\n if currently_rejected:\n query += 'AND voters.ballot_status IS NOT NULL '\n\n if no_contact:\n query += (\n 'AND survey_responses.registration_number = voter_demographics.registration_number '\n 'AND auditor_contact_date IS NULL '\n 'AND has_plan_date IS NULL '\n 'AND plan_date IS NULL '\n )\n\n if has_cell:\n query += (\n 'AND ( '\n ' cell IS NOT NULL OR '\n ' (best_number IS NOT NULL AND best_number_type = \\'C\\') '\n ')'\n )\n elif has_number:\n query += 'AND best_number IS NOT NULL'\n elif missing_number:\n query += 'AND best_number IS NULL'\n\n with Postgres(**postgres_args) as cursor:\n cursor.execute(query)\n return [dict(row) for row in cursor.fetchall()]\n\n\ndef get_opt_outs():\n van_ids = set()\n with open('phones/opt_out.csv') as f:\n for row in csv.DictReader(f):\n van_ids.add(int(row['van_id']))\n return van_ids\n\n\ndef get_van_numbers():\n numbers = {}\n with open('phones/not_yet_contacted.csv') as f:\n for row in csv.DictReader(f):\n if row.get('Pref Phone '):\n numbers[int(row['Voter File VANID'])] = row.get('Pref Phone ')\n return numbers\n\n\ndef get_clarity_numbers():\n numbers = {}\n with open('phones/from_clarity.csv') as f:\n for row in csv.DictReader(f):\n clarity_phone = row['ts_phone'] if row['ts_phone'] != '\\\\N' and row['ts_phonetype'] == 'Wireless' else None\n clarity_cell = row['ts_wireless'] if row['ts_wireless'] != '\\\\N' else None\n numbers[int(row['van_id'])] = clarity_cell or clarity_phone\n return numbers\n\n\ndef get_voter_info(cursor, registration_number):\n query = (\n 'SELECT first_name as first, last_name as last, county, ballot_status as status '\n 'FROM voters '\n 'WHERE registration_number = %s'\n )\n cursor.execute(query, (registration_number,))\n result = cursor.fetchone()\n if not result:\n return None\n return dict(result)\n\n\ndef get_best_cell_for_van_ids(van_ids):\n query = (\n 'SELECT myv_van_id as van_id, sos_id, best_number, cell '\n 'FROM my_state.person as p, states_shared_pipeline.myv_001_best_phones as ph '\n 'WHERE p.national_myv_van_id = ph.national_myv_van_id '\n 'AND (best_number_type = \\'C\\' OR cell IS NOT NULL) '\n f'AND p.myv_van_id IN {tuple(van_ids)}'\n )\n\n if os.path.exists('phones/cell_phones.csv'):\n os.remove('phones/cell_phones.csv')\n\n fut = civis.io.civis_to_csv(\n filename='phones/cell_phones.csv',\n sql=query,\n database='Dover',\n )\n fut.result()\n\n\ndef get_sos_ids_for_van_ids(van_ids):\n query = (\n 'SELECT myv_van_id as van_id, sos_id '\n 'FROM my_state.person as p '\n f'WHERE p.myv_van_id IN {tuple(van_ids)}'\n )\n\n if os.path.exists('phones/sos_ids.csv'):\n os.remove('phones/sos_ids.csv')\n\n fut = civis.io.civis_to_csv(\n filename='phones/sos_ids.csv',\n sql=query,\n database='Dover',\n )\n fut.result()\n\n\ndef follow_up_texts():\n if os.path.exists(f'phones/deficient_follow_up_{args.day}.csv'):\n os.remove(f'phones/deficient_follow_up_{args.day}.csv')\n\n if os.path.exists(f'phones/defective_follow_up_{args.day}.csv'):\n os.remove(f'phones/defective_follow_up_{args.day}.csv')\n\n van_ids = set()\n van_phones = {}\n with open('phones/contacted_currently_rejected.csv') as f:\n for row in csv.DictReader(f):\n van_ids.add(row['Voter File VANID'])\n van_phones[row['Voter File VANID']] = row['Pref Phone ']\n get_best_cell_for_van_ids(van_ids)\n get_sos_ids_for_van_ids(van_ids)\n\n sos_ids = {}\n with open('phones/sos_ids.csv') as f:\n for row in csv.DictReader(f):\n sos_ids[row['van_id']] = int(row['sos_id'])\n\n cells = {}\n with open('phones/cell_phones.csv') as f:\n for row in csv.DictReader(f):\n cells[row['van_id']] = row['cell'] or row['best_number']\n\n rows_to_write = []\n with Postgres(**postgres_args) as cursor:\n for van_id in van_ids:\n\n if van_id not in cells:\n cell = van_phones[van_id]\n if not cell:\n continue\n else:\n cell = cells[van_id]\n\n voter_info = get_voter_info(cursor, sos_ids[van_id])\n if not voter_info:\n continue\n\n rows_to_write.append({\n 'van_id': van_id,\n 'cell': cell,\n **voter_info\n })\n\n deficient_targets = [row for row in rows_to_write if row['status'] and 'Deficient' in row['status']]\n defective_targets = [row for row in rows_to_write if row['status'] and 'Defective' in row['status']]\n\n for target in deficient_targets:\n del target['status']\n\n for target in defective_targets:\n del target['status']\n\n with open(f'phones/deficient_follow_up_{args.day}.csv', 'w') as f:\n headers = [\n 'van_id',\n 'first',\n 'last',\n 'county',\n 'cell'\n ]\n writer = csv.DictWriter(f, headers)\n writer.writeheader()\n writer.writerows(deficient_targets)\n\n with open(f'phones/defective_follow_up_{args.day}.csv', 'w') as f:\n headers = [\n 'van_id',\n 'first',\n 'last',\n 'county',\n 'cell'\n ]\n writer = csv.DictWriter(f, headers)\n writer.writeheader()\n writer.writerows(defective_targets)\n\n\ndef generate_text_universe():\n if os.path.exists(f'defective_{args.day}.csv'):\n os.remove(f'defective_{args.day}.csv')\n\n if os.path.exists(f'deficient_{args.day}.csv'):\n os.remove(f'deficient_{args.day}.csv')\n\n targets_w_cells = get_cure_universe(currently_rejected=True, no_contact=True, has_cell=True)\n targets_wo_numbers = get_cure_universe(currently_rejected=True, no_contact=True, missing_number=True)\n\n for target in targets_w_cells:\n if target.get('cell'):\n del target['best']\n else:\n target['cell'] = target['best']\n del target['best']\n\n for target in targets_wo_numbers:\n del target['best']\n\n # try the latest rejected VAN file\n van_numbers = get_van_numbers()\n for target in targets_wo_numbers:\n if target['van_id'] in van_numbers:\n # assume cell, there is no way to know so send the text\n target['cell'] = van_numbers[target['van_id']]\n\n # try the latest Clarity file\n clarity_numbers = get_clarity_numbers()\n for target in targets_wo_numbers:\n if 'cell' in target:\n continue\n if target['van_id'] in clarity_numbers:\n target['cell'] = clarity_numbers[target['van_id']]\n\n # screen out opt outs or previously contacted voters (via text -- not yet uploaded to VAN)\n targets_w_cells += [target for target in targets_wo_numbers if target['cell']]\n opt_outs = get_opt_outs()\n targets_w_cells = [target for target in targets_w_cells if target['van_id'] not in opt_outs]\n\n # remove anyone not in the rejected non-contacted cure universe\n van_ids = set()\n with open('phones/not_yet_contacted.csv') as f:\n for row in csv.DictReader(f):\n van_ids.add(int(row['Voter File VANID']))\n targets_w_cells = [target for target in targets_w_cells if target['van_id'] in van_ids]\n\n deficient_targets = [target for target in targets_w_cells if target['status'] == 'Deficient Affidavit/ Incomplete']\n defective_targets = [target for target in targets_w_cells if target['status'] == 'Defective Affidavit/Envelope']\n\n for target in deficient_targets:\n del target['status']\n\n for target in defective_targets:\n del target['status']\n\n with open(f'phones/deficient_{args.day}.csv', 'w') as f:\n headers = [\n 'van_id',\n 'first',\n 'last',\n 'county',\n 'cell'\n ]\n writer = csv.DictWriter(f, headers)\n writer.writeheader()\n writer.writerows(deficient_targets)\n\n with open(f'phones/defective_{args.day}.csv', 'w') as f:\n headers = [\n 'van_id',\n 'first',\n 'last',\n 'county',\n 'cell'\n ]\n writer = csv.DictWriter(f, headers)\n writer.writeheader()\n writer.writerows(defective_targets)\n\n\ndef main():\n if args.upload_wrong_numbers:\n upload_numbers('wrong')\n\n if args.upload_right_numbers:\n upload_numbers('right')\n\n if args.generate_list:\n generate_list()\n\n if args.for_clarity:\n create_for_clarity()\n\n if args.generate_text_universe:\n generate_text_universe()\n\n if args.follow_up_texts:\n follow_up_texts()\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('-w', dest='upload_wrong_numbers', action='store_true', default=False)\n parser.add_argument('-r', dest='upload_right_numbers', action='store_true', default=False)\n parser.add_argument('-o', dest='generate_list', action='store_true', default=False)\n parser.add_argument('-c', dest='for_clarity', action='store_true', default=False)\n parser.add_argument('-t', dest='generate_text_universe', action='store_true', default=False)\n parser.add_argument('-f', dest='follow_up_texts', action='store_true', default=False)\n parser.add_argument('-d', dest='day')\n args = parser.parse_args()\n\n load_dotenv()\n\n is_prod = yes_no('Target production?')\n if is_prod:\n postgres_args = {\n 'host': os.getenv('POSTGRES_HOST'),\n 'port': int(os.getenv('POSTGRES_PORT')),\n 'user': os.getenv('POSTGRES_USER'),\n 'password': os.getenv('POSTGRES_PASSWORD'),\n 'dbname': os.getenv('POSTGRES_DB'),\n }\n else:\n postgres_args = {\n 'host': os.getenv('DEV_POSTGRES_HOST'),\n 'port': int(os.getenv('DEV_POSTGRES_PORT')),\n 'user': os.getenv('DEV_POSTGRES_USER'),\n 'password': os.getenv('DEV_POSTGRES_PASSWORD'),\n 'dbname': os.getenv('DEV_POSTGRES_DB'),\n }\n\n main()\n", "repo_name": "mcculleydj/ballot-cure", "sub_path": "phones.py", "file_name": "phones.py", "file_ext": "py", "file_size_in_byte": 16081, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "services.Postgres", "line_number": 41, "usage_type": "call"}, {"api_name": "services.Postgres", "line_number": 47, "usage_type": "call"}, {"api_name": "common.replace_bom", "line_number": 53, "usage_type": "call"}, {"api_name": "codecs.open", "line_number": 57, "usage_type": "call"}, {"api_name": "csv.DictReader", "line_number": 58, "usage_type": "call"}, {"api_name": "services.Postgres", "line_number": 77, "usage_type": "call"}, {"api_name": "csv.DictReader", "line_number": 79, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 84, "usage_type": "call"}, {"api_name": "os.path", "line_number": 84, "usage_type": "attribute"}, {"api_name": "os.remove", "line_number": 85, "usage_type": "call"}, {"api_name": "csv.DictWriter", "line_number": 102, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 127, "usage_type": "call"}, {"api_name": "os.path", "line_number": 127, "usage_type": "attribute"}, {"api_name": "os.remove", "line_number": 128, "usage_type": "call"}, {"api_name": "common.replace_bom", "line_number": 130, "usage_type": "call"}, {"api_name": "codecs.open", "line_number": 132, "usage_type": "call"}, {"api_name": "csv.DictReader", "line_number": 133, "usage_type": "call"}, {"api_name": "constants.van_to_clarity", "line_number": 135, "usage_type": "name"}, {"api_name": "csv.DictWriter", "line_number": 138, "usage_type": "call"}, {"api_name": "constants.van_to_clarity.values", "line_number": 138, "usage_type": "call"}, {"api_name": "constants.van_to_clarity", "line_number": 138, "usage_type": "name"}, {"api_name": "services.Postgres", "line_number": 181, "usage_type": "call"}, {"api_name": "csv.DictReader", "line_number": 189, "usage_type": "call"}, {"api_name": "csv.DictReader", "line_number": 197, "usage_type": "call"}, {"api_name": "csv.DictReader", "line_number": 206, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 235, "usage_type": "call"}, {"api_name": "os.path", "line_number": 235, "usage_type": "attribute"}, {"api_name": "os.remove", "line_number": 236, "usage_type": "call"}, {"api_name": "civis.io.civis_to_csv", "line_number": 238, "usage_type": "call"}, {"api_name": "civis.io", "line_number": 238, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 253, "usage_type": "call"}, {"api_name": "os.path", "line_number": 253, "usage_type": "attribute"}, {"api_name": "os.remove", "line_number": 254, "usage_type": "call"}, {"api_name": "civis.io.civis_to_csv", "line_number": 256, "usage_type": "call"}, {"api_name": "civis.io", "line_number": 256, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 265, "usage_type": "call"}, {"api_name": "os.path", "line_number": 265, "usage_type": "attribute"}, {"api_name": "os.remove", "line_number": 266, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 268, "usage_type": "call"}, {"api_name": "os.path", "line_number": 268, "usage_type": "attribute"}, {"api_name": "os.remove", "line_number": 269, "usage_type": "call"}, {"api_name": "csv.DictReader", "line_number": 274, "usage_type": "call"}, {"api_name": "csv.DictReader", "line_number": 282, "usage_type": "call"}, {"api_name": "csv.DictReader", "line_number": 287, "usage_type": "call"}, {"api_name": "services.Postgres", "line_number": 291, "usage_type": "call"}, {"api_name": "csv.DictWriter", "line_number": 328, "usage_type": "call"}, {"api_name": "csv.DictWriter", "line_number": 340, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 346, "usage_type": "call"}, {"api_name": "os.path", "line_number": 346, "usage_type": "attribute"}, {"api_name": "os.remove", "line_number": 347, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 349, "usage_type": "call"}, {"api_name": "os.path", "line_number": 349, "usage_type": "attribute"}, {"api_name": "os.remove", "line_number": 350, "usage_type": "call"}, {"api_name": "csv.DictReader", "line_number": 388, "usage_type": "call"}, {"api_name": "csv.DictWriter", "line_number": 409, "usage_type": "call"}, {"api_name": "csv.DictWriter", "line_number": 421, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 447, "usage_type": "call"}, {"api_name": "dotenv.load_dotenv", "line_number": 457, "usage_type": "call"}, {"api_name": "common.yes_no", "line_number": 459, "usage_type": "call"}, {"api_name": "os.getenv", "line_number": 462, "usage_type": "call"}, {"api_name": "os.getenv", "line_number": 463, "usage_type": "call"}, {"api_name": "os.getenv", "line_number": 464, "usage_type": "call"}, {"api_name": "os.getenv", "line_number": 465, "usage_type": "call"}, {"api_name": "os.getenv", "line_number": 466, "usage_type": "call"}, {"api_name": "os.getenv", "line_number": 470, "usage_type": "call"}, {"api_name": "os.getenv", "line_number": 471, "usage_type": "call"}, {"api_name": "os.getenv", "line_number": 472, "usage_type": "call"}, {"api_name": "os.getenv", "line_number": 473, "usage_type": "call"}, {"api_name": "os.getenv", "line_number": 474, "usage_type": "call"}]} +{"seq_id": "70567742453", "text": "import asyncio\n\nfrom .log import logger\n\n\nasync def run_shell(command):\n p = await asyncio.create_subprocess_shell(command)\n await p.wait()\n if p.returncode != 0:\n logger.info('run_shell failed: {}'.format(command))\n\n\nasync def wait_until_done(task):\n while not task.done():\n await asyncio.sleep(.1)\n\n\n# https://stackoverflow.com/a/45430833\nclass Timer:\n def __init__(self, timeout, callback, once=False):\n self.timeout = timeout\n self.callback = callback\n self.once = once\n self._task = asyncio.ensure_future(self._job())\n\n async def _job(self):\n while not self.once:\n await asyncio.sleep(self.timeout)\n await self.callback()\n\n def cancel(self):\n self._task.cancel()\n\n\ndef is_holiday(date):\n try:\n import holidays\n return date in holidays.Netherlands()\n except:\n return False\n\n\ndef chunks(l, n):\n \"\"\"Yield successive n-sized chunks from l.\n\n Taken from https://stackoverflow.com/a/312464\n Changed to only return chunks of size `n`, NOT smaller.\n \"\"\"\n for i in range(0, len(l)-n+1, n):\n yield l[i:i + n]\n", "repo_name": "c0deaddict/led-table", "sub_path": "server/server/utils.py", "file_name": "utils.py", "file_ext": "py", "file_size_in_byte": 1152, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "21", "api": [{"api_name": "asyncio.create_subprocess_shell", "line_number": 7, "usage_type": "call"}, {"api_name": "log.logger.info", "line_number": 10, "usage_type": "call"}, {"api_name": "log.logger", "line_number": 10, "usage_type": "name"}, {"api_name": "asyncio.sleep", "line_number": 15, "usage_type": "call"}, {"api_name": "asyncio.ensure_future", "line_number": 24, "usage_type": "call"}, {"api_name": "asyncio.sleep", "line_number": 28, "usage_type": "call"}, {"api_name": "holidays.Netherlands", "line_number": 38, "usage_type": "call"}]} +{"seq_id": "187248516", "text": "#!/usr/bin/env python3\n\"\"\"This script do the postprocessing of the test results.\n\nAuthor: Xavier Corbillon\nIMT Atlantique\n\"\"\"\n\nimport argparse\nimport os\nimport logging\n\nfrom Helpers import GetIniConfParser, GetGlobalUserManager, GetGlobalStatistics\n\nif __name__ == '__main__':\n # create logger with 'spam_application'\n logger = logging.getLogger('TestManager')\n logger.setLevel(logging.DEBUG)\n # create file handler which logs even debug messages\n fh = logging.FileHandler('testManagerStats.log')\n fh.setLevel(logging.DEBUG)\n # create console handler with a higher log level\n ch = logging.StreamHandler()\n ch.setLevel(logging.DEBUG)\n # create formatter and add it to the handlers\n formatter = logging.Formatter(\n '%(asctime)s - %(name)s - %(levelname)s - %(message)s'\n )\n fh.setFormatter(formatter)\n ch.setFormatter(formatter)\n # add the handlers to the logger\n logger.addHandler(fh)\n logger.addHandler(ch)\n\n logger.info('Start the TestManager')\n\n # get program arguments\n parser = argparse.ArgumentParser(\n description='GUI to run head position measurements')\n parser.add_argument('--configFile', '-c',\n type=str,\n help='path to the configuration file [config.ini]',\n default='config.ini'\n )\n parser.add_argument('--withVideo', action='store_true',\n help='if set compute heatmap videos',\n )\n\n args = parser.parse_args()\n\n # parse the ini file\n iniConfParser = GetIniConfParser(args.configFile, ch=ch, fh=fh)\n\n # parse existing user file\n userManager = GetGlobalUserManager(os.path.join(\n iniConfParser.resultFolder,\n '.private_existingUsers.txt'\n ),\n iniConfParser.resultFolder\n )\n\n # Init the global statistics object\n stats = GetGlobalStatistics(userManager)\n\n print(args.withVideo)\n stats.RunComputation(args.withVideo)\n", "repo_name": "xmar/360Degree_Head_Movement_Dataset", "sub_path": "PythonInterface/PostProcessing.py", "file_name": "PostProcessing.py", "file_ext": "py", "file_size_in_byte": 2068, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 31, "dataset": "github-code", "pt": "21", "api": [{"api_name": "logging.getLogger", "line_number": 16, "usage_type": "call"}, {"api_name": "logging.DEBUG", "line_number": 17, "usage_type": "attribute"}, {"api_name": "logging.FileHandler", "line_number": 19, "usage_type": "call"}, {"api_name": "logging.DEBUG", "line_number": 20, "usage_type": "attribute"}, {"api_name": "logging.StreamHandler", "line_number": 22, "usage_type": "call"}, {"api_name": "logging.DEBUG", "line_number": 23, "usage_type": "attribute"}, {"api_name": "logging.Formatter", "line_number": 25, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 37, "usage_type": "call"}, {"api_name": "Helpers.GetIniConfParser", "line_number": 51, "usage_type": "call"}, {"api_name": "Helpers.GetGlobalUserManager", "line_number": 54, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 54, "usage_type": "call"}, {"api_name": "os.path", "line_number": 54, "usage_type": "attribute"}, {"api_name": "Helpers.GetGlobalStatistics", "line_number": 62, "usage_type": "call"}]} +{"seq_id": "7012152431", "text": "# coding=utf-8\n\n\"\"\"\nAuthor : YangYao\nDate : 2020/5/31 10:25\n\nxlsx文件的读写\n\"\"\"\n\nimport openpyxl\n\n\ndef write_excel_xlsx(path, sheet_name, value):\n index = len(value)\n workbook = openpyxl.Workbook()\n sheet = workbook.active\n sheet.title = sheet_name\n for i in range(0, index):\n for j in range(0, len(value[i])):\n sheet.cell(row=i + 1, column=j + 1, value=str(value[i][j]))\n workbook.save(path)\n print(\"xlsx格式表格写入数据成功!\")\n\n\ndef read_excel_xlsx(path, sheet_name):\n workbook = openpyxl.load_workbook(path)\n # sheet = wb.get_sheet_by_name(sheet_name)这种方式已经弃用,不建议使用\n sheet = workbook[sheet_name]\n for row in sheet.rows:\n for cell in row:\n print(cell.value, \"\\t\", end=\"\")\n # print(sheet.rows)\n # print(list(sheet.rows)[0])\n # print(list(sheet.rows)[0][0].value)\n\n\ndef opera_xlsx(path1, path2, sheet_name1, sheet_name2, col):\n workbook2 = openpyxl.Workbook()\n sheet2 = workbook2.active\n sheet2.title = sheet_name2\n\n workbook1 = openpyxl.load_workbook(path1)\n sheet1 = workbook1[sheet_name1]\n\n print(\"\\n复制:\")\n print(sheet1.cell(row=1, column=1).value)\n print(sheet1.max_row)\n for i in range(sheet1.max_row):\n for j in range(sheet1.max_column):\n sheet2.cell(row=i + 1, column=j + 1).value = sheet1.cell(row=i + 1, column=j + 1).value\n\n sum=0.0\n for i in range(sheet1.max_row):\n if i!=0:\n sum=sum+float(sheet1.cell(row=i+1,column=3).value)\n sheet2.cell(row=sheet1.max_row + 1, column=3).value = sum\n\n workbook2.save(path2)\n print(\"xlsx格式表格写入数据成功!\")\n\n\nbook_name_xlsx = 'xlsx格式测试工作簿.xlsx'\noperator_name_xlsx = 'operator.xlsx'\nsheet_name_xlsx = 'xlsx格式测试表'\nvalue = [[\"姓名\", \"性别\", \"年龄\", \"城市\", \"职业\"],\n [\"111\", \"女\", \"66\", \"石家庄\", \"运维工程师\"],\n [\"222\", \"男\", \"55\", \"南京\", \"饭店老板\"],\n [\"333\", \"女\", \"27\", \"苏州\", \"保安\"], ]\n\nwrite_excel_xlsx(book_name_xlsx, sheet_name_xlsx, value)\nread_excel_xlsx(book_name_xlsx, sheet_name_xlsx)\n\nopera_xlsx(book_name_xlsx, operator_name_xlsx, sheet_name_xlsx, sheet_name_xlsx, 1)\n", "repo_name": "YangYaoCD/MyPython", "sub_path": "excel/Demo2.py", "file_name": "Demo2.py", "file_ext": "py", "file_size_in_byte": 2231, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "21", "api": [{"api_name": "openpyxl.Workbook", "line_number": 15, "usage_type": "call"}, {"api_name": "openpyxl.load_workbook", "line_number": 26, "usage_type": "call"}, {"api_name": "openpyxl.Workbook", "line_number": 38, "usage_type": "call"}, {"api_name": "openpyxl.load_workbook", "line_number": 42, "usage_type": "call"}]} +{"seq_id": "17475488643", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nDesc:\nCreated on 21.07.23 17:32\n@author: malle\n\"\"\"\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom pathlib import Path\nimport xarray as xr\nimport rioxarray\nimport seaborn as sns\nimport datetime\nimport glob\nimport pandas as pd\nimport platform\n\n\ndef open_file_all(run_in, id_veg_99, id_dem_3000, id_domain):\n print(run_in)\n if run_in.__contains__('deg') | run_in.__contains__('new'):\n gpp_in = xr.open_dataset(bf / run_in / 're_FPSN_SP_MONTH_SUM.nc') # already in units of gC m-2 mo-1\n evap_in = xr.open_dataset(bf / run_in / 're_QFLX_EVAP_TOT.nc')\n else:\n gpp_in = xr.open_dataset(bf / run_in / 'FPSN_SP_MONTH_SUM.nc') # already in units of gC m-2 mo-1\n evap_in = xr.open_dataset(glob.glob(str(bf / run_in) + '/QFLX_EVAP_TOT*')[0]) * 3600 * 24 # mm/s to mm/day\n\n evap_in_sum_mon = evap_in.resample(time='1M').sum()\n\n gpp_in.coords['mask_veg'] = (('lat', 'lon'), (id_veg_99 * 1).squeeze().data)\n gpp_in.coords['mask_3000'] = (('lat', 'lon'), np.flipud((id_dem_3000 * 1).squeeze().data))\n gpp_in.coords['domain'] = (('lat', 'lon'), (id_domain * 1).squeeze().data)\n datetimeindex = gpp_in.indexes['time'].to_datetimeindex()\n gpp_in['time'] = datetimeindex\n\n evap_in_sum_mon.coords['mask_veg'] = (('lat', 'lon'), (id_veg_99 * 1).squeeze().data)\n evap_in_sum_mon.coords['mask_3000'] = (('lat', 'lon'), np.flipud((id_dem_3000 * 1).squeeze().data))\n evap_in_sum_mon.coords['domain'] = (('lat', 'lon'), (id_domain * 1).squeeze().data)\n datetimeindex = evap_in_sum_mon.indexes['time'].to_datetimeindex()\n evap_in_sum_mon['time'] = datetimeindex\n\n gpp_avg = gpp_in.where((gpp_in.mask_veg == 1) & (gpp_in.domain == 0)).mean(dim=['lat', 'lon'], skipna=True)\n evap_avg = evap_in_sum_mon.where((evap_in_sum_mon.mask_veg == 1) &\n (evap_in_sum_mon.domain == 0)).mean(dim=['lat', 'lon'], skipna=True)\n\n gpp_avg_3000 = gpp_in.where((gpp_in.mask_veg == 1) & (gpp_in.domain == 0) &\n (gpp_in.mask_3000 == 0)).mean(dim=['lat', 'lon'], skipna=True)\n evap_avg_3000 = evap_in_sum_mon.where((evap_in_sum_mon.mask_veg == 1) & (evap_in_sum_mon.mask_3000 == 0) &\n (evap_in_sum_mon.domain == 0)).mean(dim=['lat', 'lon'], skipna=True)\n\n return gpp_avg, evap_avg, gpp_avg_3000, evap_avg_3000\n\n\ndef make_dfs(oshd1km_hr, oshd1km_gl, oshd025_gl, oshd05_gl, cru1km_hr, cru1km_gl, cru025_gl, cru05_gl,\n cru_l_1km_hr, cru_l_1km_gl, cru_l_025_gl, cru_l_05_gl):\n df_oshd1km_hr = pd.Series(oshd1km_hr.DATA, name=r'Clim$_{OSHD 1km}$+LU$_{HR 1km}$', index=oshd1km_hr.time)\n df_oshd1km_gl = pd.Series(oshd1km_gl.DATA, name=r'Clim$_{OSHD 1km}$+LU$_{Gl 1km}$', index=oshd1km_gl.time)\n df_oshd025 = pd.Series(oshd025_gl.DATA, name=r'Clim$_{OSHD 0.25\\degree}$+LU$_{Gl 0.25\\degree}$',\n index=oshd025_gl.time)\n df_oshd05 = pd.Series(oshd05_gl.DATA, name=r'Clim$_{OSHD 0.5\\degree}$+LU$_{Gl 0.5\\degree}$', index=oshd05_gl.time)\n df_cru1km_hr_l = pd.Series(cru_l_1km_hr.DATA, name=r'Clim$_{CRU* 1km}$+LU$_{HR 1km}$', index=cru_l_1km_hr.time)\n df_cru1km_gl_l = pd.Series(cru_l_1km_gl.DATA, name=r'Clim$_{CRU* 1km}$+LU$_{Gl 1km}$', index=cru_l_1km_gl.time)\n df_cru025_l = pd.Series(cru_l_025_gl.DATA, name=r'Clim$_{CRU* 0.25\\degree}$+LU$_{Gl 0.25\\degree}$',\n index=cru_l_025_gl.time)\n df_crud05_l = pd.Series(cru_l_05_gl.DATA, name=r'Clim$_{CRU* 0.5\\degree}$+LU$_{Gl 0.5\\degree}$',\n index=cru_l_05_gl.time)\n df_cru1km_hr = pd.Series(cru1km_hr.DATA, name=r'Clim$_{CRU 1km}$+LU$_{HR 1km}$', index=cru1km_hr.time)\n df_cru1km_gl = pd.Series(cru1km_gl.DATA, name=r'Clim$_{CRU 1km}$+LU$_{Gl 1km}$', index=cru1km_gl.time)\n df_cru025 = pd.Series(cru025_gl.DATA, name=r'Clim$_{CRU 0.25\\degree}$+LU$_{Gl 0.25\\degree}$', index=cru025_gl.time)\n df_cru05 = pd.Series(cru05_gl.DATA, name=r'Clim$_{CRU 0.5\\degree}$+LU$_{Gl 0.5\\degree}$', index=cru05_gl.time)\n df_all = pd.concat([df_oshd1km_hr, df_oshd1km_gl, df_oshd025, df_oshd05,\n df_cru1km_hr_l, df_cru1km_gl_l, df_cru025_l, df_crud05_l,\n df_cru1km_hr, df_cru1km_gl, df_cru025, df_cru05], axis=1)\n return df_all\n\n\nif __name__ == '__main__':\n\n if platform.system() == 'Windows':\n bf = Path('L:\\malle\\CLM5_CH')\n else:\n bf = Path('/home/lud11/malle/CLM5_CH')\n\n bf_plots = bf / 'snow_eco_new/gpp_snow/'\n\n surf_in = xr.open_dataset(bf / 'surfdata_1km_CH_v3_hist_16pfts_Irrig_CMIP6_NEW.nc')\n id_surf_99 = surf_in.PCT_NATVEG > 99\n\n oshd_in = xr.open_dataset(bf / 'OSHD_FILES' / 'FPSN_SP_MONTH_SUM.nc')\n id_dom = np.isnan(oshd_in.DATA.isel(time=0))\n\n dem = rioxarray.open_rasterio(bf / 'BAFU_DEM_2020_1000.tif')\n id_1000 = (dem > 0) & (dem < 1000)\n id_2000 = (dem >= 1000) & (dem < 2000)\n id_3000 = (dem >= 2000)\n\n my_pal = {r'Clim$_{CRU 1km}$+LU$_{HR 1km}$': (217 / 255, 95 / 255, 2 / 255),\n r'Clim$_{CRU 1km}$+LU$_{Gl 1km}$': (217 / 255, 95 / 255, 2 / 255),\n r'Clim$_{CRU 0.25\\degree}$+LU$_{Gl 0.25\\degree}$': (217 / 255, 95 / 255, 2 / 255),\n r'Clim$_{CRU 0.5\\degree}$+LU$_{Gl 0.5\\degree}$': (217 / 255, 95 / 255, 2 / 255),\n\n r'Clim$_{CRU* 1km}$+LU$_{HR 1km}$': (117 / 255, 112 / 255, 179 / 255),\n r'Clim$_{CRU* 1km}$+LU$_{Gl 1km}$': (117 / 255, 112 / 255, 179 / 255),\n r'Clim$_{CRU* 0.25\\degree}$+LU$_{Gl 0.25\\degree}$': (117 / 255, 112 / 255, 179 / 255),\n r'Clim$_{CRU* 0.5\\degree}$+LU$_{Gl 0.5\\degree}$': (117 / 255, 112 / 255, 179 / 255),\n\n r'Clim$_{OSHD 1km}$+LU$_{HR 1km}$': (27 / 255, 158 / 255, 119 / 255),\n r'Clim$_{OSHD 1km}$+LU$_{Gl 1km}$': (27 / 255, 158 / 255, 119 / 255),\n r'Clim$_{OSHD 0.25\\degree}$+LU$_{Gl 0.25\\degree}$': (27 / 255, 158 / 255, 119 / 255),\n r'Clim$_{OSHD 0.5\\degree}$+LU$_{Gl 0.5\\degree}$': (27 / 255, 158 / 255, 119 / 255)}\n\n gpp_oshd1km_HR, evap_oshd1km_HR, gpp_oshd1km_HR_3000, evap_oshd1km_HR_3000 = \\\n open_file_all('OSHD_FILES', id_surf_99, id_3000, id_dom)\n gpp_oshd1km_GL, evap_oshd1km_GL, gpp_oshd1km_GL_3000, evap_oshd1km_GL_3000 = \\\n open_file_all('OSHD_FILES_OLD', id_surf_99, id_3000, id_dom)\n gpp_oshd025, evap_oshd025, gpp_oshd025_3000, evap_oshd025_3000 = \\\n open_file_all('OSHD_FILES_025_new', id_surf_99, id_3000, id_dom)\n gpp_oshd05, evap_oshd05, gpp_oshd05_3000, evap_oshd05_3000 = \\\n open_file_all('OSHD_FILES_05_new', id_surf_99, id_3000, id_dom)\n\n gpp_cruL1km_HR, evap_cruL1km_HR, gpp_cruL1km_HR_3000, evap_cruL1km_HR_3000 = \\\n open_file_all('CRUJRA_FILES', id_surf_99, id_3000, id_dom)\n gpp_cruL1km_GL, evap_cruL1km_GL, gpp_cruL1km_GL_3000, evap_cruL1km_GL_3000 = \\\n open_file_all('CRUJRA_FILES_OLD', id_surf_99, id_3000, id_dom)\n gpp_cruL025, evap_cruL025, gpp_cruL025_3000, evap_cruL025_3000 = \\\n open_file_all('CRUJRA_FILES_025deg_cru_new_lapse', id_surf_99, id_3000, id_dom)\n gpp_cruL05, evap_cruL05, gpp_cruL05_3000, evap_cruL05_3000 = \\\n open_file_all('CRUJRA_FILES_05deg_cru_new_lapse', id_surf_99, id_3000, id_dom)\n\n gpp_cru1km_HR, evap_cru1km_HR, gpp_cru1km_HR_3000, evap_cru1km_HR_3000 = \\\n open_file_all('CRUJRA_FILES_noLapse', id_surf_99, id_3000, id_dom)\n gpp_cru1km_GL, evap_cru1km_GL, gpp_cru1km_GL_3000, evap_cru1km_GL_3000 = \\\n open_file_all('CRUJRA_FILES_noLapse_OLD', id_surf_99, id_3000, id_dom)\n gpp_cru025, evap_cru025, gpp_cru025_3000, evap_cru025_3000 = \\\n open_file_all('CRUJRA_FILES_025deg_cru_new', id_surf_99, id_3000, id_dom)\n gpp_cru05, evap_cru05, gpp_cru05_3000, evap_cru05_3000 = \\\n open_file_all('CRUJRA_FILES_05deg_cru_new', id_surf_99, id_3000, id_dom)\n\n df_gpp = make_dfs(gpp_oshd1km_HR, gpp_oshd1km_GL, gpp_oshd025, gpp_oshd05, gpp_cru1km_HR, gpp_cru1km_GL, gpp_cru025,\n gpp_cru05, gpp_cruL1km_HR, gpp_cruL1km_GL, gpp_cruL025, gpp_cruL05)\n\n df_evap = make_dfs(evap_oshd1km_HR, evap_oshd1km_GL, evap_oshd025, evap_oshd05, evap_cru1km_HR, evap_cru1km_GL,\n evap_cru025, evap_cru05, evap_cruL1km_HR, evap_cruL1km_GL, evap_cruL025, evap_cruL05)\n\n df_gpp_3000 = make_dfs(gpp_oshd1km_HR_3000, gpp_oshd1km_GL_3000, gpp_oshd025_3000, gpp_oshd05_3000,\n gpp_cru1km_HR_3000, gpp_cru1km_GL_3000, gpp_cru025_3000, gpp_cru05_3000, gpp_cruL1km_HR_3000,\n gpp_cruL1km_GL_3000, gpp_cruL025_3000, gpp_cruL05_3000)\n\n df_evap_3000 = make_dfs(evap_oshd1km_HR_3000, evap_oshd1km_GL_3000, evap_oshd025_3000, evap_oshd05_3000,\n evap_cru1km_HR_3000, evap_cru1km_GL_3000, evap_cru025_3000, evap_cru05_3000,\n evap_cruL1km_HR_3000, evap_cruL1km_GL_3000, evap_cruL025_3000, evap_cruL05_3000)\n\n dstart = datetime.datetime(2017, 1, 1)\n dend = datetime.datetime(2020, 1, 1)\n dstart_zoom = datetime.datetime(2018, 5, 15)\n dend_zoom = datetime.datetime(2018, 8, 15)\n\n fig = plt.figure(figsize=(10, 7))\n axes = fig.add_subplot(211)\n spl = sns.lineplot(data=df_gpp, ax=axes, palette=my_pal)\n axes.set_xlim([dstart, dend])\n axes.yaxis.grid(True)\n axes.xaxis.grid(True)\n axes.set_ylabel('GPP [gC m$^{-2}$ month$^{-1}$]')\n for line in spl.lines[::4]:\n line.set_linestyle(\"-\")\n for line in spl.lines[1::4]:\n line.set_linestyle(\"--\")\n for line in spl.lines[2::4]:\n line.set_linestyle(\"-.\")\n for line in spl.lines[3::4]:\n line.set_linestyle(\":\")\n spl.axvline(dstart_zoom, linestyle='--', color='cornflowerblue', linewidth=0.9)\n spl.axvline(dend_zoom, linestyle='--', color='cornflowerblue', linewidth=0.9)\n spl.legend(loc='upper left', bbox_to_anchor=(0.1, 1.45), ncol=3)\n\n axes = fig.add_subplot(212)\n spl = sns.lineplot(data=df_evap, ax=axes, palette=my_pal, legend=False)\n axes.set_xlim([dstart, dend])\n axes.yaxis.grid(True)\n axes.xaxis.grid(True)\n axes.set_ylabel('ET [mm month$^{-1}$]')\n for line in spl.lines[::4]:\n line.set_linestyle(\"-\")\n for line in spl.lines[1::4]:\n line.set_linestyle(\"--\")\n for line in spl.lines[2::4]:\n line.set_linestyle(\"-.\")\n for line in spl.lines[3::4]:\n line.set_linestyle(\":\")\n plt.tight_layout()\n spl.axvline(dstart_zoom, linestyle='--', color='cornflowerblue', linewidth=0.9)\n spl.axvline(dend_zoom, linestyle='--', color='cornflowerblue', linewidth=0.9)\n plt.show()\n fig.savefig(bf_plots / 'temporal_gpp_evap.png', dpi=500, bbox_inches='tight', facecolor='white', transparent=False)\n\n fig = plt.figure(figsize=(10, 7))\n axes = fig.add_subplot(211)\n spl = sns.lineplot(data=df_gpp_3000, ax=axes, palette=my_pal)\n axes.set_xlim([dstart, dend])\n axes.yaxis.grid(True)\n axes.xaxis.grid(True)\n for line in spl.lines[::4]:\n line.set_linestyle(\"-\")\n for line in spl.lines[1::4]:\n line.set_linestyle(\"--\")\n for line in spl.lines[2::4]:\n line.set_linestyle(\"-.\")\n for line in spl.lines[3::4]:\n line.set_linestyle(\":\")\n spl.legend(loc='upper left', bbox_to_anchor=(0.1, 1.45), ncol=3)\n spl.axvline(dstart_zoom, linestyle='--', color='cornflowerblue', linewidth=0.9)\n spl.axvline(dend_zoom, linestyle='--', color='cornflowerblue', linewidth=0.9)\n axes.set_ylabel('GPP [gC m$^{-2}$ month$^{-1}$]')\n\n axes = fig.add_subplot(212)\n spl = sns.lineplot(data=df_evap_3000, ax=axes, palette=my_pal, legend=False)\n axes.set_xlim([dstart, dend])\n axes.yaxis.grid(True)\n axes.xaxis.grid(True)\n axes.set_ylabel('ET [mm month$^{-1}$]')\n for line in spl.lines[::4]:\n line.set_linestyle(\"-\")\n for line in spl.lines[1::4]:\n line.set_linestyle(\"--\")\n for line in spl.lines[2::4]:\n line.set_linestyle(\"-.\")\n for line in spl.lines[3::4]:\n line.set_linestyle(\":\")\n plt.tight_layout()\n spl.axvline(dstart_zoom, linestyle='--', color='cornflowerblue', linewidth=0.9)\n spl.axvline(dend_zoom, linestyle='--', color='cornflowerblue', linewidth=0.9)\n plt.show()\n fig.savefig(bf_plots / 'temporal_gpp_evap_3000.png', dpi=500, bbox_inches='tight', facecolor='white',\n transparent=False)\n\n # zoom plot\n fig = plt.figure(figsize=(5, 7))\n axes = fig.add_subplot(211)\n spl = sns.lineplot(data=df_gpp, ax=axes, palette=my_pal, legend=False)\n axes.set_xlim([dstart_zoom, dend_zoom])\n axes.set_ylim([150, 240])\n axes.yaxis.grid(True)\n axes.xaxis.grid(True)\n axes.set_ylabel('GPP [gC m$^{-2}$ month$^{-1}$]')\n for line in spl.lines[::4]:\n line.set_linestyle(\"-\")\n for line in spl.lines[1::4]:\n line.set_linestyle(\"--\")\n for line in spl.lines[2::4]:\n line.set_linestyle(\"-.\")\n for line in spl.lines[3::4]:\n line.set_linestyle(\":\")\n axes.tick_params(labelbottom=False)\n\n axes = fig.add_subplot(212)\n spl = sns.lineplot(data=df_evap, ax=axes, palette=my_pal, legend=False)\n axes.set_xlim([dstart_zoom, dend_zoom])\n axes.set_ylim([30, 130])\n axes.yaxis.grid(True)\n axes.xaxis.grid(True)\n axes.set_ylabel('ET [mm month$^{-1}$]')\n for line in spl.lines[::4]:\n line.set_linestyle(\"-\")\n for line in spl.lines[1::4]:\n line.set_linestyle(\"--\")\n for line in spl.lines[2::4]:\n line.set_linestyle(\"-.\")\n for line in spl.lines[3::4]:\n line.set_linestyle(\":\")\n axes.tick_params(axis='x', rotation=90)\n plt.tight_layout()\n plt.show()\n fig.savefig(bf_plots / 'temporal_gpp_evap_zoom.png', dpi=500, bbox_inches='tight', facecolor='white',\n transparent=False)\n\n fig = plt.figure(figsize=(5, 7))\n axes = fig.add_subplot(211)\n spl = sns.lineplot(data=df_gpp_3000, ax=axes, palette=my_pal, legend=False)\n axes.set_xlim([dstart_zoom, dend_zoom])\n axes.set_ylim([150, 250])\n axes.yaxis.grid(True)\n axes.xaxis.grid(True)\n axes.set_ylabel('GPP [gC m$^{-2}$ month$^{-1}$]')\n for line in spl.lines[::4]:\n line.set_linestyle(\"-\")\n for line in spl.lines[1::4]:\n line.set_linestyle(\"--\")\n for line in spl.lines[2::4]:\n line.set_linestyle(\"-.\")\n for line in spl.lines[3::4]:\n line.set_linestyle(\":\")\n axes.tick_params(labelbottom=False)\n\n axes = fig.add_subplot(212)\n spl = sns.lineplot(data=df_evap_3000, ax=axes, palette=my_pal, legend=False)\n axes.set_xlim([dstart_zoom, dend_zoom])\n axes.set_ylim([30, 130])\n axes.yaxis.grid(True)\n axes.xaxis.grid(True)\n axes.set_ylabel('ET [mm month$^{-1}$]')\n for line in spl.lines[::4]:\n line.set_linestyle(\"-\")\n for line in spl.lines[1::4]:\n line.set_linestyle(\"--\")\n for line in spl.lines[2::4]:\n line.set_linestyle(\"-.\")\n for line in spl.lines[3::4]:\n line.set_linestyle(\":\")\n axes.tick_params(axis='x', rotation=90)\n plt.tight_layout()\n plt.show()\n fig.savefig(bf_plots / 'temporal_gpp_evap_zoom_3000.png', dpi=500, bbox_inches='tight', facecolor='white',\n transparent=False)\n", "repo_name": "johanna-malle/CLM5_CH", "sub_path": "clm5_analysis/figures/supp_figure_s7.py", "file_name": "supp_figure_s7.py", "file_ext": "py", "file_size_in_byte": 15124, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "xarray.open_dataset", "line_number": 24, "usage_type": "call"}, {"api_name": "xarray.open_dataset", "line_number": 25, "usage_type": "call"}, {"api_name": "xarray.open_dataset", "line_number": 27, "usage_type": "call"}, {"api_name": "xarray.open_dataset", "line_number": 28, "usage_type": "call"}, {"api_name": "glob.glob", "line_number": 28, "usage_type": "call"}, {"api_name": "numpy.flipud", "line_number": 33, "usage_type": "call"}, {"api_name": "numpy.flipud", "line_number": 39, "usage_type": "call"}, {"api_name": "pandas.Series", "line_number": 58, "usage_type": "call"}, {"api_name": "pandas.Series", "line_number": 59, "usage_type": "call"}, {"api_name": "pandas.Series", "line_number": 60, "usage_type": "call"}, {"api_name": "pandas.Series", "line_number": 62, "usage_type": "call"}, {"api_name": "pandas.Series", "line_number": 63, "usage_type": "call"}, {"api_name": "pandas.Series", "line_number": 64, "usage_type": "call"}, {"api_name": "pandas.Series", "line_number": 65, "usage_type": "call"}, {"api_name": "pandas.Series", "line_number": 67, "usage_type": "call"}, {"api_name": "pandas.Series", "line_number": 69, "usage_type": "call"}, {"api_name": "pandas.Series", "line_number": 70, "usage_type": "call"}, {"api_name": "pandas.Series", "line_number": 71, "usage_type": "call"}, {"api_name": "pandas.Series", "line_number": 72, "usage_type": "call"}, {"api_name": "pandas.concat", "line_number": 73, "usage_type": "call"}, {"api_name": "platform.system", "line_number": 81, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 82, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 84, "usage_type": "call"}, {"api_name": "xarray.open_dataset", "line_number": 88, "usage_type": "call"}, {"api_name": "xarray.open_dataset", "line_number": 91, "usage_type": "call"}, {"api_name": "numpy.isnan", "line_number": 92, "usage_type": "call"}, {"api_name": "rioxarray.open_rasterio", "line_number": 94, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 155, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 156, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 157, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 158, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 160, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 160, "usage_type": "name"}, {"api_name": "seaborn.lineplot", "line_number": 162, "usage_type": "call"}, {"api_name": "seaborn.lineplot", "line_number": 180, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.tight_layout", "line_number": 193, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 193, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 196, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 196, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 199, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 199, "usage_type": "name"}, {"api_name": "seaborn.lineplot", "line_number": 201, "usage_type": "call"}, {"api_name": "seaborn.lineplot", "line_number": 219, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.tight_layout", "line_number": 232, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 232, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 235, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 235, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 240, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 240, "usage_type": "name"}, {"api_name": "seaborn.lineplot", "line_number": 242, "usage_type": "call"}, {"api_name": "seaborn.lineplot", "line_number": 259, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.tight_layout", "line_number": 274, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 274, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 275, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 275, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 279, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 279, "usage_type": "name"}, {"api_name": "seaborn.lineplot", "line_number": 281, "usage_type": "call"}, {"api_name": "seaborn.lineplot", "line_number": 298, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.tight_layout", "line_number": 313, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 313, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 314, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 314, "usage_type": "name"}]} +{"seq_id": "25057388147", "text": "#複数のエクセルブックから必要な情報を読み取る\r\n\r\nfrom openpyxl import Workbook, load_workbook\r\nfrom pathlib import Path\r\n\r\ncount = input(\"作成するシート数:\")\r\n\r\nwb_new = Workbook()\r\nws_new = wb_new.active\r\nws_new.title = '一覧表'\r\n\r\nws_new[\"B2\"] = \"部署名\"\r\nws_new[\"C2\"] = \"氏名\"\r\n\r\npath = Path(\"./books\")\r\n\r\nfor i, file in enumerate(path.glob(\"*.xlsx\")):\r\n wb = load_workbook(file, read_only=True) #reado_only=Trueで元データへの変更を禁止\r\n ws = wb[\"チェックリスト\"]\r\n row_no = i + 3\r\n ws_new[f\"B{row_no}\"] = ws[\"C2\"].value\r\n ws_new[f\"C{row_no}\"] = ws[\"C3\"].value\r\n\r\nwb.save(\"一覧表.xlsx\")", "repo_name": "jun-yoshiyoshi/python_for_excel", "sub_path": "read_books.py", "file_name": "read_books.py", "file_ext": "py", "file_size_in_byte": 666, "program_lang": "python", "lang": "ja", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "openpyxl.Workbook", "line_number": 8, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 15, "usage_type": "call"}, {"api_name": "openpyxl.load_workbook", "line_number": 18, "usage_type": "call"}]} +{"seq_id": "35274069836", "text": "import uuid, os, openai\nimport pandas as pd\nfrom flask import Flask, request, make_response, render_template, session, url_for, redirect,jsonify\nfrom flask import stream_with_context, Response\nfrom flask_session import Session\nfrom werkzeug.security import generate_password_hash, check_password_hash\nfrom dotenv import load_dotenv\nfrom time import sleep\nfrom traceback import print_exc\nload_dotenv()\n\nfrom sqlalchemy import create_engine\nimport chromadb\nfrom chromadb.utils import embedding_functions\nfrom chromadb.config import Settings\n\nfrom prompts import *\n\nopenai.api_type = \"azure\"\nopenai.api_base = \"https://alagantgpt2.openai.azure.com/\"\nopenai.api_version = \"2023-07-01-preview\"\nopenai.api_key = os.getenv(\"AZURE_API_KEY\")\n#openai.api_key = os.getenv(\"OPENAI_API_KEY\")\n \nUPLOAD_FOLDER = 'uploaded_files'\nCATEGORIES = ['INFO', 'DEBUG', 'ERROR', 'WARNING']\nchat_history = [{\"role\":\"assistant\",\"content\":\"Hi! I'm here to help you analyze the log file you provided. Feel free to ask any questions and I will do my best to assist you.\"}]\nchat_render = chat_history.copy()\nsearch_result = []\n\napp = Flask(__name__)\napp.secret_key = 'asidfj0saf20j0jf02932j23f0'\n# Configure session to use filesystem (server-side session)\napp.config['SESSION_TYPE'] = 'filesystem'\napp.config['SESSION_FILE_DIR'] = os.path.join(os.getcwd(), 'flask_session') # Directory where session files will be stored\n\n# Initialize the session extension\nSession(app)\n\n\nchroma_client = chromadb.PersistentClient(path=\"db\")\n\ncohere_ef = embedding_functions.CohereEmbeddingFunction(\n api_key=os.getenv(\"COHERE_API_KEY\"), \n model_name=\"multilingual-22-12\"\n)\n\n\n@app.route('/', methods=['GET', 'POST'])\ndef index():\n if 'user_id' not in session:\n session['user_id'] = str(uuid.uuid4()) # Generates a unique ID\n print(\"New user\",session['user_id'])\n\n #check if file user_id exists\n filename = f\"{session['user_id']}\"\n if not os.path.exists(os.path.join(UPLOAD_FOLDER, filename)):\n return render_template('upload.jinja', user_id=session['user_id'])\n \n\n return render_template('index.jinja', user_id=session['user_id'])\n\ndef __extract_and_format_timestamp(df: pd.DataFrame) -> pd.DataFrame:\n df['timestamp'] = df[[0, 1, 2]].apply(lambda row: ' '.join(row.values.astype(str)), axis=1)\n df.drop(columns=[0, 1, 2], inplace=True)\n df.loc[:, 'timestamp'] = pd.to_datetime(df['timestamp'], format='%b %d %H:%M:%S', errors='coerce')\n \n # Because the log file does not contain the year, we assume it is the current year.\n # Otherwise it would be autofilled with 1900, which is unintuitive for users.\n df.loc[:, 'timestamp'] = df['timestamp'].apply(lambda x: x.replace(year=2023))\n\n # Remove rows with invalid timestamps (e.g. empty lines)\n df.dropna(axis=0, how='any', inplace=True)\n return df\n\ndef __read_file_to_df(filename: str) -> pd.DataFrame:\n if not os.path.exists(filename):\n raise FileNotFoundError(f\"File {filename} does not exist\")\n else:\n with open(filename, 'r',encoding=\"utf-8\") as f:\n lines = f.readlines()\n\n # Create a DataFrame\n return pd.DataFrame(lines, columns=['Text'])\n \n\ndef __extract_and_clean_program(df: pd.DataFrame) -> pd.DataFrame:\n df['program'] = df.loc[:, 4].str.replace(r'(\\[.*\\])?:', '', regex=True)\n df.drop(columns=[4], inplace=True)\n return df\n\ndef __rename_and_drop_columns(df: pd.DataFrame, old_keys, new_keys) -> pd.DataFrame:\n df.rename(columns=dict(zip(old_keys, new_keys)), inplace=True)\n return df\n\ndef select_rows(df: pd.DataFrame, from_timestamp, to_timestamp) -> pd.DataFrame:\n \"\"\"\n Select rows from a between two timestamps inclusive.\n\n :param df: DataFrame to select rows from\n :param from_timestamp: Start timestamp\n :param to_timestamp: End timestamp\n \"\"\"\n return df[(df['timestamp'] >= from_timestamp) & (df['timestamp'] <= to_timestamp)]\n\ndef select_rows_with(df: pd.DataFrame, keyword:str) -> pd.DataFrame:\n \"\"\"\n Select rows from a DataFrame that contain a specific keyword.\n\n :param keyword: Keyword to search for\n :param df: DataFrame to select rows from\n \"\"\"\n return df[df['message'].str.contains(keyword)]\n\ndef select_rows(df: pd.DataFrame, from_line: int, to_line: int) -> pd.DataFrame:\n \"\"\"\n Select rows from a DataFrame between two line numbers inclusive start line and exlusive end line number.\n\n :param df: DataFrame to select rows from\n :param from_line: Start line number, inclusive\n :param to_line: End line number, exclusive\n \"\"\"\n return df.iloc[from_line:to_line]\n\ndef process_file(filename):\n df = __read_file_to_df(filename= os.path.join(UPLOAD_FOLDER, filename))\n\n # Split the 'Text' column at the 5th space\n df = df['Text'].str.split(' ', n=5, expand=True)\n\n df = __extract_and_format_timestamp(df)\n df = __extract_and_clean_program(df)\n df = __rename_and_drop_columns(df, [3, 5], ['device', 'message'])\n\n #df.to_csv(os.path.join('data', filename + \".csv\"), index=True)\n #df.reset_index(inplace=True, drop=False, names='line_number')\n\n # Create SQLAlchemy engine\n #engine = create_engine(\"mysql+mysqlconnector://pinda:Usgov123!Epic@20.122.110.183/logalyzer\")\n\n # Write DataFrame to MySQL\n #df.to_sql('log_data', con=engine, if_exists='replace', index=False)\n\n def chunk_list(lines,metadatas,ids, chunk_size):\n for i in range(0, len(ids), chunk_size):\n yield (lines[i:i + chunk_size],metadatas[i:i + chunk_size],ids[i:i + chunk_size])\n \n print(df)\n print(\"This is starting to cook\")\n lines_to_embed = []\n ids = []\n metadatas = []\n \n for i, row in df.iterrows():\n ids.append(str(i))\n message = row[\"message\"]\n category = \"info\"\n if (\"debug\" in message.lower()): category = \"debug\"\n elif (\"error\" in message.lower() or \"failed\" in message.lower()): category = \"error\"\n elif (\"warning\" in message.lower()): category = \"warning\"\n\n\n program = row[\"program\"]\n lines_to_embed.append(f\"{program} - {message}\")\n metadatas.append({\n \"timestamp\": str(row[\"timestamp\"]),\n \"device\": row[\"device\"],\n \"program\": program,\n \"category\": category \n }) \n\n collection = chroma_client.get_or_create_collection(name=filename,embedding_function=cohere_ef)\n if (collection.count() == 0):\n for lines,metadata,idd in chunk_list(lines_to_embed,metadatas,ids, 5000):\n collection.add(\n documents = lines,\n metadatas = metadata,\n ids = idd\n )\n\n\n##this method is called when user uploads a file\n@app.route('/send-file', methods=['POST'])\ndef send_file():\n if 'user_id' not in session:\n return redirect(url_for('index'))\n\n file = request.files['file']\n if file:\n filename = f\"{session['user_id']}\"\n if not os.path.exists(UPLOAD_FOLDER):\n os.makedirs(UPLOAD_FOLDER)\n save_path = os.path.join(UPLOAD_FOLDER, filename)\n file.save(save_path)\n\n ##process file\n process_file(filename)\n else:\n return 'No file selected'\n \n return redirect(url_for('index'))\n\ndef chroma_to_dataframe(collection_name):\n collection = chroma_client.get_collection(collection_name,embedding_function=cohere_ef)\n lines = collection.get()\n\n # Initialize lists to store data\n line_ids = []\n devices = []\n messages = []\n timestamps = []\n programs = []\n categories = []\n\n # Assuming 'lines' is a list of dictionaries\n for i,line in enumerate(lines[\"ids\"]):\n metadata = lines[\"metadatas\"][i]\n devices.append(metadata.get('device'))\n messages.append(lines[\"documents\"][i].split(\" - \",1)[1])\n timestamps.append(metadata.get('timestamp'))\n programs.append(metadata.get('program'))\n categories.append(metadata.get(\"category\"))\n\n # Create a DataFrame\n df = pd.DataFrame({\n 'device': devices,\n 'message': messages,\n 'timestamp': timestamps,\n 'program': programs,\n 'category':categories\n })\n \n return df\n\ndef chroma_to_list_dicts(collection_name):\n df = chroma_to_dataframe(session['user_id'])\n \n ## Handle NaT (Not-a-Time) values\n df = df.where(pd.notna(df), None)\n\n # Format the timestamp column\n if 'timestamp' in df.columns and df['timestamp'].dtype == ' rangee*2:\n # If distance to next element is more than 1.0, add both -0.5 and +0.5\n if (first_in_threshold): percentages2.append(current_value - rangee)\n percentages2.append(current_value + rangee)\n first_in_threshold = True\n else:\n # If distance is 1.0 or less, only add -0.5\n if (first_in_threshold): percentages2.append(current_value - rangee)\n first_in_threshold = False\n else:\n # For the last element, add both -0.5 and +0.5\n percentages2.append(current_value + rangee)\n percentages2.append(current_value - rangee)\n\n formatted_strings = []\n\n # Iterate through the sorted merged list\n merged_percentages = sorted(percentages1 + percentages2)\n for value in merged_percentages:\n if value in percentages1:\n formatted_strings.append(f\"rgba(255,255,0,1) {value}%\")\n elif value in percentages2:\n formatted_strings.append(f\"#1f1f1f {value}%\")\n \n return \"linear-gradient(180deg,\" + \",\".join(formatted_strings) + \")\"\n\n@app.route(\"/get-heatmap\", methods=[\"GET\"])\ndef get_heatmap():\n global search_result\n underline_lines = []\n for row in search_result:\n underline_lines.append(row[\"line_id\"])\n formatted_strings = create_heatmap_gradient(search_result)\n\n return jsonify({\"gradient\": formatted_strings, \"underline\": underline_lines})\n\n#remove chat history\n@app.route('/remove-chat-history', methods=['GET'])\ndef remove_chat_history():\n global chat_history\n global chat_render\n chat_history = []\n chat_render = []\n return jsonify([])\n\n@app.route('/get-chat-history', methods=['GET'])\ndef get_chat_history():\n global chat_history\n global chat_render\n return jsonify(chat_render)\n\n\nif __name__ == '__main__':\n app.run(host=\"0.0.0.0\",debug=False,port=8501)\n", "repo_name": "ArmykOliva/hackatum2023-logalyze", "sub_path": "flask_fun/__init__.py", "file_name": "__init__.py", "file_ext": "py", "file_size_in_byte": 17527, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "dotenv.load_dotenv", "line_number": 10, "usage_type": "call"}, {"api_name": "openai.api_type", "line_number": 19, "usage_type": "attribute"}, {"api_name": "openai.api_base", "line_number": 20, "usage_type": "attribute"}, {"api_name": "openai.api_version", "line_number": 21, "usage_type": "attribute"}, {"api_name": "openai.api_key", "line_number": 22, "usage_type": "attribute"}, {"api_name": "os.getenv", "line_number": 22, "usage_type": "call"}, {"api_name": "flask.Flask", "line_number": 31, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 35, "usage_type": "call"}, {"api_name": "os.path", "line_number": 35, "usage_type": "attribute"}, {"api_name": "os.getcwd", "line_number": 35, "usage_type": "call"}, {"api_name": "flask_session.Session", "line_number": 38, "usage_type": "call"}, {"api_name": "chromadb.PersistentClient", "line_number": 41, "usage_type": "call"}, {"api_name": "chromadb.utils.embedding_functions.CohereEmbeddingFunction", "line_number": 43, "usage_type": "call"}, {"api_name": "chromadb.utils.embedding_functions", "line_number": 43, "usage_type": "name"}, {"api_name": "os.getenv", "line_number": 44, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 51, "usage_type": "name"}, {"api_name": "flask.session", "line_number": 52, "usage_type": "name"}, {"api_name": "uuid.uuid4", "line_number": 52, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 53, "usage_type": "name"}, {"api_name": "flask.session", "line_number": 56, "usage_type": "name"}, {"api_name": "os.path.exists", "line_number": 57, "usage_type": "call"}, {"api_name": "os.path", "line_number": 57, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 57, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 58, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 58, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 61, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 61, "usage_type": "name"}, {"api_name": "pandas.DataFrame", "line_number": 63, "usage_type": "attribute"}, {"api_name": "pandas.to_datetime", "line_number": 66, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 77, "usage_type": "call"}, {"api_name": "os.path", "line_number": 77, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 84, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 76, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 87, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 92, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 96, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 106, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 115, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 126, "usage_type": "call"}, {"api_name": "os.path", "line_number": 126, "usage_type": "attribute"}, {"api_name": "flask.session", "line_number": 185, "usage_type": "name"}, {"api_name": "flask.redirect", "line_number": 186, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 186, "usage_type": "call"}, {"api_name": "flask.request.files", "line_number": 188, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 188, "usage_type": "name"}, {"api_name": "flask.session", "line_number": 190, "usage_type": "name"}, {"api_name": "os.path.exists", "line_number": 191, "usage_type": "call"}, {"api_name": "os.path", "line_number": 191, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 192, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 193, "usage_type": "call"}, {"api_name": "os.path", "line_number": 193, "usage_type": "attribute"}, {"api_name": "flask.redirect", "line_number": 201, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 201, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 225, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 236, "usage_type": "name"}, {"api_name": "pandas.notna", "line_number": 239, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 251, "usage_type": "name"}, {"api_name": "flask.session", "line_number": 260, "usage_type": "name"}, {"api_name": "flask.jsonify", "line_number": 261, "usage_type": "call"}, {"api_name": "openai.ChatCompletion.create", "line_number": 272, "usage_type": "call"}, {"api_name": "openai.ChatCompletion", "line_number": 272, "usage_type": "attribute"}, {"api_name": "openai.error", "line_number": 299, "usage_type": "attribute"}, {"api_name": "traceback.print_exc", "line_number": 301, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 302, "usage_type": "call"}, {"api_name": "openai.error", "line_number": 303, "usage_type": "attribute"}, {"api_name": "traceback.print_exc", "line_number": 304, "usage_type": "call"}, {"api_name": "openai.ChatCompletion.create", "line_number": 315, "usage_type": "call"}, {"api_name": "openai.ChatCompletion", "line_number": 315, "usage_type": "attribute"}, {"api_name": "openai.error", "line_number": 353, "usage_type": "attribute"}, {"api_name": "traceback.print_exc", "line_number": 355, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 356, "usage_type": "call"}, {"api_name": "openai.error", "line_number": 357, "usage_type": "attribute"}, {"api_name": "traceback.print_exc", "line_number": 358, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 363, "usage_type": "name"}, {"api_name": "flask.request.json.get", "line_number": 386, "usage_type": "call"}, {"api_name": "flask.request.json", "line_number": 386, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 386, "usage_type": "name"}, {"api_name": "flask.request.json.get", "line_number": 387, "usage_type": "call"}, {"api_name": "flask.request.json", "line_number": 387, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 387, "usage_type": "name"}, {"api_name": "flask.jsonify", "line_number": 390, "usage_type": "call"}, {"api_name": "flask.Response", "line_number": 408, "usage_type": "call"}, {"api_name": "flask.stream_with_context", "line_number": 408, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 412, "usage_type": "name"}, {"api_name": "flask.jsonify", "line_number": 465, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 474, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 480, "usage_type": "call"}]} +{"seq_id": "9747021710", "text": "import sys\nimport argparse\nimport cv2\n\ncount = 0\nvidcap = cv2.VideoCapture('/mnt/mars-beta/tochukwu/maestro/maestro_code/newData/eyetracker/world.mp4')\nsuccess,image = vidcap.read()\nsuccess = True\nwhile success:\n vidcap.set(cv2.CAP_PROP_POS_MSEC,(count*1000)) # added this line \n success,image = vidcap.read()\n print ('Read a new frame: ', success)\n cv2.imwrite(\"/mnt/mars-beta/tochukwu/maestro/maestro_code/BodycamImage/frame%d.jpg\" % count, image) # save frame as JPEG file\n count = count + 1", "repo_name": "onyeogulu/maestro_code", "sub_path": "video_conveter.py", "file_name": "video_conveter.py", "file_ext": "py", "file_size_in_byte": 509, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "cv2.VideoCapture", "line_number": 6, "usage_type": "call"}, {"api_name": "cv2.CAP_PROP_POS_MSEC", "line_number": 10, "usage_type": "attribute"}, {"api_name": "cv2.imwrite", "line_number": 13, "usage_type": "call"}]} +{"seq_id": "71475679733", "text": "#!/usr/bin/python\n\n# For example of use please see fence_cisco_mds\n\nimport re,pexpect\nfrom fencing import *\n\n## do not add code here.\n#BEGIN_VERSION_GENERATION\nRELEASE_VERSION = \"\"\nREDHAT_COPYRIGHT = \"\"\nBUILD_DATE = \"\"\n#END_VERSION_GENERATION\n\n# Fix for RHBZ#527844\ndef snmp_define_defaults ():\n\tall_opt[\"udpport\"][\"default\"]=\"161\"\n\tall_opt[\"ipport\"][\"default\"]=\"161\"\n\nclass FencingSnmp:\n\tdef __init__(self,options):\n\t\tself.options=options\n\n\t# Log message if user set verbose option\n\tdef log_command(self, message):\n\t\tif self.options[\"log\"] >= LOG_MODE_VERBOSE:\n\t\t\tself.options[\"debug_fh\"].write(message+\"\\n\")\n\n\tdef quote_for_run(self,str):\n\t\treturn ''.join(map(lambda x:x==r\"'\" and \"'\\\\''\" or x,str))\n\n\tdef complete_missed_params(self):\n\t\tmapping=[\n\t\t\t[['P','p','!E'],'self.options[\"-E\"]=\"authPriv\"'],\n\t\t\t[['!d','c','!l','!P','!p'],'self.options[\"-d\"]=\"2c\"']\n\t\t\t]\n\n\t\tfor val in mapping:\n\t\t\te=val[0]\n\n\t\t\tres=True\n\n\t\t\tfor item in e:\n\t\t\t\tif ((item[0]=='!') and (self.options.has_key(\"-\"+item[1]))):\n\t\t\t\t\tres=False\n\t\t\t\t\tbreak\n\n\t\t\t\tif ((item[0]!='!') and (not self.options.has_key(\"-\"+item[0]))):\n\t\t\t\t\tres=False\n\t\t\t\t\tbreak\n\n\t\t\tif res:\n\t\t\t\texec(val[1])\n\n\tdef prepare_cmd(self,command):\n\t\tcmd=\"@SNMPBIN@/%s -m '' -Oeqn \"%(command)\n\n\t\tself.complete_missed_params()\n\n\t\t#mapping from our option to snmpcmd option\n\t\tmapping=(('d','v'),('c','c'))\n\n\t\tfor item in mapping:\n\t\t\tif (self.options.has_key(\"-\"+item[0])):\n\t\t\t\tcmd+=\" -%s '%s'\"%(item[1],self.quote_for_run(self.options[\"-\"+item[0]]))\n\n\t\t# Some options make sense only for v3 (and for v1/2c can cause \"problems\")\n\t\tif (self.options.has_key(\"-d\")) and (self.options[\"-d\"] == \"3\"):\n\t\t\t# Mapping from our options to snmpcmd options for v3\n\t\t\tmapping_v3=(('b','a'),('E','l'),('B','x'),('P','X'),('p','A'),('l','u'))\n\t\t\tfor item in mapping_v3:\n\t\t\t\tif (self.options.has_key(\"-\"+item[0])):\n\t\t\t\t\tcmd+=\" -%s '%s'\"%(item[1],self.quote_for_run(self.options[\"-\"+item[0]]))\n\n\t\tforce_ipvx=\"\"\n\n\t\tif (self.options.has_key(\"-6\")):\n\t\t\tforce_ipvx=\"udp6:\"\n\n\t\tif (self.options.has_key(\"-4\")):\n\t\t\tforce_ipvx=\"udp:\"\n\n\t\tcmd+=\" '%s%s%s'\"%(force_ipvx, self.quote_for_run(self.options[\"-a\"]),\n\t\t\t\tself.options.has_key(\"-u\") and self.quote_for_run(\":\" + str (self.options[\"-u\"])) or \"\")\n\t\treturn cmd\n\n\tdef run_command(self,command,additional_timemout=0):\n\t\ttry:\n\t\t\tself.log_command(command)\n\n\t\t\t(res_output,res_code)=pexpect.run(command,int(self.options[\"-Y\"])+int(self.options[\"-y\"])+additional_timemout,True)\n\n\t\t\tif (res_code==None):\n\t\t\t\tfail(EC_TIMED_OUT)\n\n\t\t\tself.log_command(res_output)\n\n\t\t\tif (res_code!=0) or (re.search(\"^Error \", res_output, re.MULTILINE) != None):\n\t\t\t\tfail_usage(\"Returned %d: %s\"%(res_code,res_output))\n\t\texcept pexpect.ExceptionPexpect:\n\t\t\tfail_usage(\"Cannot run command %s\"%(command))\n\n\t\treturn res_output\n\n\tdef get(self,oid,additional_timemout=0):\n\t\tcmd=\"%s '%s'\"%(self.prepare_cmd(\"snmpget\"),self.quote_for_run(oid))\n\n\t\toutput=self.run_command(cmd,additional_timemout).splitlines()\n\n\t\treturn output[len(output)-1].split(None,1)\n\n\tdef set(self,oid,value,additional_timemout=0):\n\t\tmapping=((int,'i'),(str,'s'))\n\n\t\ttype=''\n\n\t\tfor item in mapping:\n\t\t\tif (isinstance(value,item[0])):\n\t\t\t\ttype=item[1]\n\t\t\t\tbreak\n\n\t\tcmd=\"%s '%s' %s '%s'\"%(self.prepare_cmd(\"snmpset\"),self.quote_for_run(oid),type,self.quote_for_run(str(value)))\n\n\t\tself.run_command(cmd,additional_timemout)\n\n\tdef walk(self,oid,additional_timemout=0):\n\t\tcmd=\"%s '%s'\"%(self.prepare_cmd(\"snmpwalk\"),self.quote_for_run(oid))\n\n\t\toutput=self.run_command(cmd,additional_timemout).splitlines()\n\n\t\treturn map(lambda x:x.split(None,1),filter(lambda y:len(y)>0 and y[0]=='.',output))\n", "repo_name": "beekhof/cluster", "sub_path": "fence/agents/lib/fencing_snmp.py.py", "file_name": "fencing_snmp.py.py", "file_ext": "py", "file_size_in_byte": 3581, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "21", "api": [{"api_name": "pexpect.run", "line_number": 91, "usage_type": "call"}, {"api_name": "re.search", "line_number": 98, "usage_type": "call"}, {"api_name": "re.MULTILINE", "line_number": 98, "usage_type": "attribute"}, {"api_name": "pexpect.ExceptionPexpect", "line_number": 100, "usage_type": "attribute"}]} +{"seq_id": "29424382563", "text": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom tensorflow.keras import models, Model\nfrom tensorflow.keras.layers import Conv2D,MaxPooling2D,Flatten,Dense,Dropout,BatchNormalization, AveragePooling2D, Input, GlobalAveragePooling2D\nfrom tensorflow.keras.utils import to_categorical, normalize\nfrom tensorflow.keras.optimizers import Adam, SGD\nfrom tensorflow.keras.regularizers import l1,l2\nfrom tensorflow.keras.initializers import RandomUniform, GlorotUniform, he_uniform\nfrom tensorflow.keras.callbacks import LearningRateScheduler, ReduceLROnPlateau, EarlyStopping, TensorBoard, ModelCheckpoint, Callback\nfrom tensorflow.keras.backend import get_value, set_value\nfrom train_helper import load_data, preprocess_data, plot_learncurve\nfrom sklearn.model_selection import train_test_split\nfrom time import process_time\nfrom lr_finder import LRFinder\nfrom sgdr import SGDRScheduler\nfrom cyclic_lr import CyclicLR\n\n\ndata_dir = '/home/kangle/dataset/PedBicCarData'\ndata_bunch = load_data(data_dir, 2, 2, 6, 1)\ndata_bunch = preprocess_data(data_bunch, 'cnn')\n\nmodel = models.Sequential()\nregularizer = None#l2(1e-4)\ninitializer = he_uniform()\nmodel.add(Conv2D(32, [3, 3], input_shape=data_bunch[\"train_data\"].shape[1:], activation='relu', kernel_initializer=initializer, kernel_regularizer=regularizer, padding='same', name='conv_1'))\nmodel.add(MaxPooling2D())\nmodel.add(Conv2D(64, [3, 3], activation='relu', kernel_initializer=initializer, kernel_regularizer=regularizer, padding='same', name='conv_2'))\nmodel.add(MaxPooling2D())\nmodel.add(Conv2D(128, [3, 3], activation='relu', kernel_initializer=initializer, kernel_regularizer=regularizer, padding='same', name='conv_3'))\nmodel.add(MaxPooling2D())\nmodel.add(Conv2D(256, [3, 3], activation='relu', kernel_initializer=initializer, kernel_regularizer=regularizer, padding='same', name='conv_4'))\nmodel.add(MaxPooling2D())\nmodel.add(Conv2D(256, [3, 3], activation='relu', kernel_initializer=initializer, kernel_regularizer=regularizer, padding='same', name='conv_5'))\nmodel.add(AveragePooling2D())\nmodel.add(Flatten())\n#model.add(GlobalAveragePooling2D())\n#model.add(Dense(512, activation='relu', kernel_initializer=initializer, kernel_regularizer=regularizer, name='dense_1'))\n#model.add(Dropout(0.2))\nmodel.add(Dense(256, activation='relu', kernel_initializer=initializer, kernel_regularizer=regularizer, name='dense_2'))\nmodel.add(Dropout(0.2))\nmodel.add(Dense(5, activation='softmax', name='dense_3'))\n\nmodel.summary()\n\nopt = Adam(learning_rate=1e-3)\n#opt = SGD(learning_rate=0.04, momentum=0.9, decay=1e-2)\nmodel.compile(optimizer=opt, loss='categorical_crossentropy', metrics=['accuracy'])\n\nnum_batchsize = 128\nnum_epochs = 30\nsteps = np.ceil(len(data_bunch[\"train_label\"])/num_batchsize)\n\n# learning rate range test\n# lr_finder = LRFinder(model, stop_factor=4)\n# lr_finder.find((train_data, train_label), steps_per_epoch=steps, start_lr=1e-6, lr_mult=1.01, batch_size=num_batchsize)\n# lr_finder.plot_loss()\n\n# SGDR learning rate policy\n# set learning rate range according to lr range test result\n# min_lr = 5e-5\n# max_lr = 2e-3\n# lr_scheduler = SGDRScheduler(min_lr, max_lr, steps, lr_decay=1.0, cycle_length=1, mult_factor=2)\n\n# one cycle learning rate policy\n# set max learning rate according to lr range test result\nmax_lr = 3e-4\n#lr_scheduler = CyclicLR(base_lr=max_lr/10, max_lr=max_lr, step_size=np.ceil(steps*num_epochs/2), max_momentum=0.95, min_momentum=0.85)\n\ndef piecewise_constant_fn(epoch):\n if epoch < 10:\n return 3e-4\n elif epoch < 20:\n return 1e-4\n else:\n return 5e-5\n\nlr_scheduler = LearningRateScheduler(piecewise_constant_fn)\n\nclass LearningRate_History(Callback):\n def __init__(self):\n self.history = {}\n\n def on_epoch_end(self, epoch, logs=None):\n self.history.setdefault('lr', []).append(get_value(self.model.optimizer.lr))\n\nlr_history = LearningRate_History()\n\n#lr_scheduler = ReduceLROnPlateau()\n\nearlystop_callback = EarlyStopping(monitor='val_loss', patience=10)\nlog_dir = \"/home/kangle/Projects/radar_object_classification\"\ntensorboard_callback = TensorBoard(log_dir=log_dir, histogram_freq=1)\ncheckpoint_callback = ModelCheckpoint('best_model.h5', monitor='val_loss', mode='min', save_best_only=True, verbose=1)\n\nhistory = model.fit(data_bunch[\"train_data\"],\n data_bunch[\"train_label\"],\n epochs=num_epochs,\n batch_size=num_batchsize,\n verbose=2,\n validation_data=(data_bunch[\"val_data\"], data_bunch[\"val_label\"]),\n callbacks=[lr_scheduler, lr_history])\n#models.save_model(model, 'best_model000')\n\n# load the saved best model\n# model = models.load_model('best_model.h5')\n\n# evaluate model\ntest_pred = model.predict(data_bunch[\"test_data\"])\n\nt_start = process_time()\n_,acc = model.evaluate(data_bunch[\"test_data\"], data_bunch[\"test_label\"], batch_size=num_batchsize, verbose=2)\nt_end = process_time()\nt_cost = t_end - t_start\nprint(f\"Test Accuracy: {acc:.4f}, Inference time: {t_cost:.2f}s\")\n\nplot_learncurve(\"CNN\", history=history)\n\nif 'lr' in lr_history.history:\n plt.plot(lr_history.history['lr'])\n plt.xlabel('epoch')\n plt.ylabel('learning rate')\n plt.title('Learning Rate Schedule')\n plt.show()\nelse:\n raise ValueError(\"no lr info in history.\")\n\nif 'lr' in lr_scheduler.history:\n plt.plot(lr_scheduler.history['lr'])\n plt.xlabel('iterations')\n plt.ylabel('learning rate')\n plt.title('Learning Rate Schedule')\n plt.show()\nelse:\n raise ValueError(\"no lr info in history.\")", "repo_name": "kathy-lee/automotive_target_classification", "sub_path": "CNN_classification.py", "file_name": "CNN_classification.py", "file_ext": "py", "file_size_in_byte": 5566, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 7, "dataset": "github-code", "pt": "21", "api": [{"api_name": "train_helper.load_data", "line_number": 20, "usage_type": "call"}, {"api_name": "train_helper.preprocess_data", "line_number": 21, "usage_type": "call"}, {"api_name": "tensorflow.keras.models.Sequential", "line_number": 23, "usage_type": "call"}, {"api_name": "tensorflow.keras.models", "line_number": 23, "usage_type": "name"}, {"api_name": "tensorflow.keras.initializers.he_uniform", "line_number": 25, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.Conv2D", "line_number": 26, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.MaxPooling2D", "line_number": 27, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.Conv2D", "line_number": 28, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.MaxPooling2D", "line_number": 29, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.Conv2D", "line_number": 30, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.MaxPooling2D", "line_number": 31, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.Conv2D", "line_number": 32, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.MaxPooling2D", "line_number": 33, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.Conv2D", "line_number": 34, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.AveragePooling2D", "line_number": 35, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.Flatten", "line_number": 36, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.Dense", "line_number": 40, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.Dropout", "line_number": 41, "usage_type": "call"}, {"api_name": "tensorflow.keras.layers.Dense", "line_number": 42, "usage_type": "call"}, {"api_name": "tensorflow.keras.optimizers.Adam", "line_number": 46, "usage_type": "call"}, {"api_name": "numpy.ceil", "line_number": 52, "usage_type": "call"}, {"api_name": "tensorflow.keras.callbacks.LearningRateScheduler", "line_number": 78, "usage_type": "call"}, {"api_name": "tensorflow.keras.callbacks.Callback", "line_number": 80, "usage_type": "name"}, {"api_name": "tensorflow.keras.backend.get_value", "line_number": 85, "usage_type": "call"}, {"api_name": "tensorflow.keras.callbacks.EarlyStopping", "line_number": 91, "usage_type": "call"}, {"api_name": "tensorflow.keras.callbacks.TensorBoard", "line_number": 93, "usage_type": "call"}, {"api_name": "tensorflow.keras.callbacks.ModelCheckpoint", "line_number": 94, "usage_type": "call"}, {"api_name": "time.process_time", "line_number": 111, "usage_type": "call"}, {"api_name": "time.process_time", "line_number": 113, "usage_type": "call"}, {"api_name": "train_helper.plot_learncurve", "line_number": 117, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 120, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 120, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 121, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 121, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 122, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 122, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 123, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 123, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 124, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 124, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 129, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 129, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 130, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 130, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 131, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 131, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 132, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 132, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 133, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 133, "usage_type": "name"}]} +{"seq_id": "32200319902", "text": "import pygame\nimport random\nimport math\n\npygame.init()\n#display\nscreen=pygame.display.set_mode((800,600))\npygame.display.set_caption('snake__kobra100')\nicon=pygame.image.load('anaconda.png')\npygame.display.set_icon(icon)\nbackground_pic=pygame.image.load('beautiful-space-background.1.png')\n#snake head\nsnake=pygame.image.load('snake_head.png')\nsnake_haed_x=400\nsnake_haed_y=300\nsnake_haed_x_change=0\nsnake_haed_y_change=0\n# body\nbody=pygame.image.load('body.png')\nbody_x=random.randint(64,736)\nbody_y=random.randint(64,536)\nbody_x_change=0\nbody_y_change=0\n\n\ndef body1(x, y):\n screen.blit(body, (x, y))\n\ndef snake_head(x,y):\n screen.blit(snake,(x,y))\n\n\n#eat\ndef iseat(snake_haed_x,snake_haed_y,food_x,food_y):\n d= math.sqrt(math.pow((snake_haed_x-food_x),2)+math.pow((snake_haed_y-food_y),2))\n if d<27:\n return True\n else:\n return False\n#game over\ndef isover(snake_haed_x,snake_haed_y,body_x,body_y):\n a=math.sqrt(math.pow((snake_haed_x-body_x),2)+math.pow((snake_haed_y-body_y),2))\n if a<45:\n return True\n else:\n return False\n # food\nfood = pygame.image.load('food.png')\nfood_x = random.randint(64, 736)\nfood_y = random.randint(64, 536)\nfood_x_change = 0\nfood_y_change = 0\nscore = 0\ndef food_(x,y):\n screen.blit(food,(x,y))\n\n\nrun =True\nwhile run:\n screen.fill((0,0,255))\n screen.blit(background_pic,(0,0))\n\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n run = False\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_LEFT:\n snake_haed_x_change = -1\n if event.key == pygame.K_RIGHT:\n snake_haed_x_change = 1\n\n\n if event.type == pygame.KEYUP:\n if event.key == pygame.K_UP:\n snake_haed_y_change = -1\n\n if event.key == pygame.K_DOWN:\n snake_haed_y_change = 1\n\n\n\n #movement of snake's head\n snake_haed_x += snake_haed_x_change\n snake_haed_y += snake_haed_y_change\n if snake_haed_x >800:\n snake_haed_x =0\n elif snake_haed_x <0:\n snake_haed_x =800\n if snake_haed_y > 600:\n snake_haed_y = 0\n elif snake_haed_y < 0:\n snake_haed_y = 600\n\n #food change\n\n eat = iseat(snake_haed_x, snake_haed_y, food_x, food_y)\n if eat:\n food_x_change1 = food_x_change+random.randint(64,736)\n food_y_change1 = food_y_change +random.randint(64,536)\n food_x=food_x_change1\n food_y=food_y_change1\n score=score+1\n print(score)\n # game over logic\n over =isover(snake_haed_x,snake_haed_y,body_x,body_y)\n if over:\n snake_haed_x=1000\n snake_haed_y=1000\n print(\"game over\")\n score=0\n\n #body movement\n body_x +=2\n body_y +=2\n body_x_change1 = body_x_change + random.random() * 0.1\n body_x_change2 = body_x_change + random.random() * (-0.1)\n body_y_change1 = body_y_change + random.random() * 0.1\n body_y_change2 = body_y_change + random.random() * (-0.1)\n\n if body_x< 0:\n body_x =body_x_change1\n\n elif body_x >800:\n\n\n body_x =body_x_change2\n\n if body_y <0:\n\n\n body_y += body_y_change1\n elif body_y >600:\n\n\n body_y = body_y_change2\n\n\n\n snake_head(snake_haed_x,snake_haed_y)\n food_(food_x,food_y)\n body1(body_x,body_y)\n pygame.display.update()", "repo_name": "nigam003/poka_game", "sub_path": "snake__kobra100.py", "file_name": "snake__kobra100.py", "file_ext": "py", "file_size_in_byte": 3343, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "pygame.init", "line_number": 5, "usage_type": "call"}, {"api_name": "pygame.display.set_mode", "line_number": 7, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 7, "usage_type": "attribute"}, {"api_name": "pygame.display.set_caption", "line_number": 8, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 8, "usage_type": "attribute"}, {"api_name": "pygame.image.load", "line_number": 9, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 9, "usage_type": "attribute"}, {"api_name": "pygame.display.set_icon", "line_number": 10, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 10, "usage_type": "attribute"}, {"api_name": "pygame.image.load", "line_number": 11, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 11, "usage_type": "attribute"}, {"api_name": "pygame.image.load", "line_number": 13, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 13, "usage_type": "attribute"}, {"api_name": "pygame.image.load", "line_number": 19, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 19, "usage_type": "attribute"}, {"api_name": "random.randint", "line_number": 20, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 21, "usage_type": "call"}, {"api_name": "math.sqrt", "line_number": 35, "usage_type": "call"}, {"api_name": "math.pow", "line_number": 35, "usage_type": "call"}, {"api_name": "math.sqrt", "line_number": 42, "usage_type": "call"}, {"api_name": "math.pow", "line_number": 42, "usage_type": "call"}, {"api_name": "pygame.image.load", "line_number": 48, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 48, "usage_type": "attribute"}, {"api_name": "random.randint", "line_number": 49, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 50, "usage_type": "call"}, {"api_name": "pygame.event.get", "line_number": 64, "usage_type": "call"}, {"api_name": "pygame.event", "line_number": 64, "usage_type": "attribute"}, {"api_name": "pygame.QUIT", "line_number": 65, "usage_type": "attribute"}, {"api_name": "pygame.KEYDOWN", "line_number": 67, "usage_type": "attribute"}, {"api_name": "pygame.K_LEFT", "line_number": 68, "usage_type": "attribute"}, {"api_name": "pygame.K_RIGHT", "line_number": 70, "usage_type": "attribute"}, {"api_name": "pygame.KEYUP", "line_number": 74, "usage_type": "attribute"}, {"api_name": "pygame.K_UP", "line_number": 75, "usage_type": "attribute"}, {"api_name": "pygame.K_DOWN", "line_number": 78, "usage_type": "attribute"}, {"api_name": "random.randint", "line_number": 99, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 100, "usage_type": "call"}, {"api_name": "random.random", "line_number": 116, "usage_type": "call"}, {"api_name": "random.random", "line_number": 117, "usage_type": "call"}, {"api_name": "random.random", "line_number": 118, "usage_type": "call"}, {"api_name": "random.random", "line_number": 119, "usage_type": "call"}, {"api_name": "pygame.display.update", "line_number": 143, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 143, "usage_type": "attribute"}]} +{"seq_id": "27820343545", "text": "import telebot\nfrom telebot import types\nimport requests\nfrom bs4 import BeautifulSoup as b\nfrom secret import API\n\nbot = telebot.TeleBot(API)\n\n@bot.message_handler(commands=['start'])\ndef send_welcome(message):\n bot.send_message(message.chat.id,f\"Здравствуйте {message.from_user.first_name}! Вас приветствует интернет-магазин. Для того, чтобы ознакомиться с нашими товарами, нажмите /menu. Для того, чтобы получить информацию о нашем магазине,\"\n f\" нажмите /help.\")\n\n@bot.message_handler(commands=['help'])\ndef help(message):\n bot.send_message(message.chat.id, f'Это чат-бот магазина Mark Formelle. Наш чат-бот покажет вам ассортимент продукции в выбранной категории. Для перехода к товарам нажмите /menu.')\n\n@bot.message_handler(commands=['menu'])\ndef menu(message):\n my_buttons = types.InlineKeyboardMarkup(row_width=2)\n button_socks = types.InlineKeyboardButton(text='Носки', callback_data='socks')\n button_tights = types.InlineKeyboardButton(text='Колготки', callback_data='tights')\n my_buttons.add(button_socks, button_tights)\n bot.send_message(message.chat.id, 'Выберите категорию товаров:', reply_markup=my_buttons)\n\n@bot.callback_query_handler(func=lambda call: True)\ndef callback_inline(call):\n if call.message:\n if call.data == 'tights':\n\n URL_tights = 'https://markformelle.by/catalog/zhenshchinam/noski-i-kolgotki/kolgotki-zhenskie/'\n r = requests.get(URL_tights)\n soup = b(r.text, 'html.parser')\n tigts_title = soup.select('div.catalog-name')\n tigts_price = soup.select('div.catalog-cost')\n for i in tigts_title:\n title = i.get_text()\n for j in tigts_price:\n price = j.get_text()\n bot.send_message(call.message.chat.id, title + price)\n\n elif call.data == 'socks':\n URL_socks = 'https://markformelle.by/catalog/zhenshchinam/noski-i-kolgotki/noski-zhen/poliamidnye-zhenskie/'\n r = requests.get(URL_socks)\n soup = b(r.text, 'html.parser')\n socks_title = soup.select('div.catalog-name')\n socks_price = soup.select('div.catalog-cost')\n for i in socks_title:\n title_socks = i.get_text()\n for j in socks_price:\n price_socks = j.get_text()\n bot.send_message(call.message.chat.id, title_socks + price_socks)\n\nbot.polling(none_stop=True)\n", "repo_name": "KatBelyaeva/Telebot-parser", "sub_path": "TelegramBot.py", "file_name": "TelegramBot.py", "file_ext": "py", "file_size_in_byte": 2753, "program_lang": "python", "lang": "ru", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "telebot.TeleBot", "line_number": 7, "usage_type": "call"}, {"api_name": "secret.API", "line_number": 7, "usage_type": "argument"}, {"api_name": "telebot.types.InlineKeyboardMarkup", "line_number": 20, "usage_type": "call"}, {"api_name": "telebot.types", "line_number": 20, "usage_type": "name"}, {"api_name": "telebot.types.InlineKeyboardButton", "line_number": 21, "usage_type": "call"}, {"api_name": "telebot.types", "line_number": 21, "usage_type": "name"}, {"api_name": "telebot.types.InlineKeyboardButton", "line_number": 22, "usage_type": "call"}, {"api_name": "telebot.types", "line_number": 22, "usage_type": "name"}, {"api_name": "requests.get", "line_number": 32, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 33, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 44, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 45, "usage_type": "call"}]} +{"seq_id": "20414902580", "text": "\"\"\"\nPython routines to apply world-coordinate system transformations\nbased on the simpler ZEA projection used SFD98 milky way dust map\n\nThis code is designed to be light-weight, and specialized. The general\nZEA projection is UNSUPPORTED. We handle two special cases \n\n - CRVAL = -90 -90 (south) \n - CRVAL = 90 90 (north)\n\nThe ZEA projection is described in\nhttp://fits.gsfc.nasa.gov/registry/tpvwcs/tpv.html\nand in:\n\"Representations of celestial coordinates in FITS\"\nCalabretta, M. R., and Greisen, E. W.,\nAstronomy & Astrophysics, 395, 1077-1122, 2002.\n\n\"\"\"\nfrom __future__ import print_function\n\n__author__ = \"Yu Feng and Martin White\"\n__version__ = \"0.9\"\n__email__ = \"yfeng1@berkeley.edu or mjwhite@lbl.gov\"\n__all__ = ['ang2pix','pix2ang','ang2pix_hdr','pix2ang_hdr']\n\n\n\"\"\"\nexample header:\nSIMPLE = T / Written by IDL: Sun May 9 11:19:26 1999\nBITPIX = -32 /\nNAXIS = 2 /\nNAXIS1 = 4096 /\nNAXIS2 = 4096 /\nDATE = '1999-05-09' / Creation date (CCYY-MM-DD) of FITS header\nOBJECT = 'E(B-V) ' /\nBUNIT = 'mag ' /\nCRPIX1 = 2048.50 / 1-indexed X pixel number of pole\nCRVAL1 = 90.0000 /\nCTYPE1 = 'GLON-ZEA' / X=sqrt(1-NSGP*sin(b))*cos(l)*SCALE\nCRPIX2 = 2048.50 / 1-indexed Y pixel number of pole\nCRVAL2 = 90.0000 /\nCTYPE2 = 'GLAT-ZEA' / Y=-NSGP*sqrt(1-NSGP*sin(b))*sin(l)*SCALE\nCD1_1 = -0.0395646818624 /\nCD1_2 = 0.00000 /\nCD2_1 = 0.00000 /\nCD2_2 = 0.0395646818624 /\nLONPOLE = 180 /\nLAM_NSGP= 1 / NSGP=+1 for north polar, =-1 for south polar\nLAM_SCAL= 2048 / SCALE=number of pixels from b=0 to b=90 deg\nAUTHOR = 'David J. Schlegel, Douglas P. Finkbeiner, and Marc Davis' /\n\"\"\"\n\nimport numpy \nimport math\n\ndef ang2pix_hdr(coord,hdr,zero_offset=True):\n \"\"\"\n Apply forward (ra,dec)->(x,y) simple ZEA transformation\n \n A convenience function for calling ang2pix, with the transformations\n described in a dictionary in the usual FITS header style for WCS\n transformations. \n \n Parameters\n ----------\n coord : array_like \n (ra, dec), RA and DEC (in decimal degrees, vectorized) \n hdr : dict\n WCS header as a dictionary\n zero_offset : boolean, optional,\n If True, the routine returns 0-indexed pixel coordinates\n (useful in Python or C) while if it is False pixels run from 1 (as in\n Fortran).\n\n Returns\n -------\n xy : array_like\n xy = (x, y) pixel numbers.\n \n \"\"\"\n if ('ZEA' not in hdr['CTYPE1'])|('ZEA' not in hdr['CTYPE2']):\n raise RuntimeError(\"Not a zea projection.\")\n cd, crpix, crval = parse_header(hdr, zero_offset)\n return(ang2pix(coord,cd,crpix,crval))\n #\n\ndef pix2ang_hdr(xy,hdr,zero_offset=True):\n \"\"\"\n Apply backward (x,y)->(ra,dec) simple ZEA transformation\n \n See :py:meth:`ang2pix_hdr`\n\n \"\"\"\n if ('ZEA' not in hdr['CTYPE1'])|('ZEA' not in hdr['CTYPE2']):\n raise RuntimeError(\"Not a zea plane projection.\")\n cd, crpix, crval = parse_header(hdr, zero_offset)\n return(pix2ang(xy,cd,crpix,crval))\n #\n\ndef parse_header(hdr, zero_offset):\n \"\"\"\n Parse a WCS header to arguments of pix2ang and ang2pix.\n\n Parameters\n ----------\n hdr : dict\n WCS header\n zero_offset : boolean\n If zero_offset is True, the routine assumes 0-indexed pixel coordinates\n (useful in Python or C) while if it is False pixels run from 1 \n (as in Fortran and Julia)\n\n Returns\n -------\n scale : float\n Scaling factor\n crpix : array_like\n center pixel coordniate; compensated for `zero_offset`\n nsgp : int\n North or South galactic pool.\n\n Raises\n ------\n RuntimeError:\n if the header does not contain enough fields.\n\n \"\"\"\n # Check to see whether the \"hdr\" dictionary contains the necessary\n # keywords.\n if ('CTYPE1' not in hdr)|('CTYPE2' not in hdr)|\\\n ('CRVAL1' not in hdr)|('CRVAL2' not in hdr)|\\\n ('CRPIX1' not in hdr)|('CRPIX2' not in hdr)|\\\n ('LAM_NSGP' not in hdr)|('LAM_SCAL' not in hdr):\n raise RuntimeError(\"Unable to parse header.\")\n crpix = numpy.array([hdr['CRPIX1'],hdr['CRPIX2']])\n nsgp = int(hdr['LAM_NSGP'])\n scale = int(hdr['LAM_SCAL'])\n\n if zero_offset:\n crpix -= 1\n return scale, crpix, nsgp\n \n\n\ndef ang2pix(coord,SCALE,CRPIX,NSGP):\n \"\"\"\n Convert RA, DEC to x,y, with simple ZEA transformation\n\n A simplified version of the ZEA Transform from coord = (ra, dec) \n to pixel xy coordinate according the the WCS header. \n\n Obviously PV distortion is not supported.\n\n No checking is performed if a given RA, DEC lies outside the range.\n\n Parameters\n ----------\n coord : array_like\n coord = (RA, DEC), RA and DEC (in decimal degrees, vectorized) \n SCALE : int\n scaling factor\n CRPIX : array_like\n center pixel number of x, y\n NSGP: int\n +1 for North, -1 for Sourth.\n\n Notes\n -----\n Look up Section 5.?.? of \n\n http://www.aanda.org/articles/aa/pdf/2002/45/aah3860.pdf \n\n Although the source code in \n\n https://code.google.com/p/astropysics/source/browse/astropysics/extinct.py\n\n maybe a better explanation of what is done.\n\n The transformation is used by SFD98 dust maps.\n \"\"\"\n coord = numpy.array(coord, dtype='f8').copy()\n view = coord\n if coord.ndim == 1:\n view = view.reshape(2, 1)\n xy = numpy.empty_like(view)\n # watch out, this may be wrong if the matrix is not diagonal\n\n l, b = view * (numpy.pi / 180.)\n \n #project from galactic longitude/latitude to lambert pixels (see SFD98)\n x = numpy.cos(l) * (1 - NSGP * numpy.sin(b))**0.5\n y = - NSGP *numpy.sin(l) * (1 - NSGP * numpy.sin(b))**0.5\n #now remap indecies - numpy arrays have y and x convention switched\n xy[0] = x\n xy[1] = y\n\n xy *= SCALE\n xy += numpy.array(CRPIX).reshape(2, 1)\n return xy.reshape(view.shape)\n #\n\n\ndef pix2ang(xy,SCALE,CRPIX,NSGP):\n \"\"\"\n Convert x, y to RA, DEC with simple ZEA transformation.\n\n See :py:meth:`ang2pix`\n\n \"\"\"\n xy = numpy.array(xy, dtype='f8').copy()\n coord = numpy.empty_like(xy)\n view = coord\n if coord.ndim == 1:\n view = view.reshape(2, 1)\n xy = xy.reshape(2, 1)\n\n xy -= numpy.array(CRPIX).reshape(2, 1)\n xy /= SCALE\n\n x, y = xy\n b = numpy.arcsin((1 - x ** 2 - y ** 2) * NSGP)\n l = numpy.arctan2(-NSGP * y, x)\n\n view[0] = l\n view[1] = b\n view *= 180. / numpy.pi\n view[0] %= 360.\n return(coord)\n\nif __name__ == '__main__':\n # perform some tests\n def compare(NSGP, ra, dec):\n from numpy.testing import assert_allclose\n from astropy import wcs\n header = dict(\n CTYPE1 = 'GLON-ZEA',# / ZEA \n CTYPE2 = 'GLAT-ZEA', # / ZEA\n CRPIX1 = 2048.5, # / Reference x \n CRPIX2 = 2048.5, # / Reference y \n CD1_1 = NSGP*-0.0395646818624, # / CD matrix\n CD1_2 = 0., # / CD matrix\n CD2_1 = 0., # / CD matrix\n CD2_2 = NSGP*0.0395646818624, # / CD matrix\n LONPOLE = 180,\n )\n header['CRVAL1'] = NSGP * 90. # / Reference RA \n header['CRVAL2'] = NSGP * 90.# / Reference Dec \n q = wcs.WCS(header)\n \n ra = [ra]\n dec = [dec]\n astropy = q.all_world2pix(numpy.array((ra, dec)).T, 1)\n ours = ang2pix((ra, dec), \n SCALE=2048,\n CRPIX=(2048.5,2048.5),\n NSGP=NSGP)\n back = pix2ang(ours, \n SCALE=2048,\n CRPIX=(2048.5,2048.5),\n NSGP=NSGP)\n\n print('transforming', ra, dec, 'at', ra, dec)\n print('roundtrip', back.T)\n print('astropy has', astropy)\n print('we have ', ours.T)\n assert_allclose(ours.T, astropy, rtol=1e-9)\n\n def test():\n compare(1, 31., 30)\n compare(1, 30., 30)\n compare(1, 30., 31)\n compare(1, -181., 31)\n compare(-1, 31., -30)\n compare(-1, 30., -30)\n compare(-1, 30., -31)\n compare(-1, -181., -31)\n test()\n", "repo_name": "desihub/imaginglss", "sub_path": "imaginglss/utils/wcs_simplezea.py", "file_name": "wcs_simplezea.py", "file_ext": "py", "file_size_in_byte": 8489, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 6, "dataset": "github-code", "pt": "21", "api": [{"api_name": "numpy.array", "line_number": 135, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 181, "usage_type": "call"}, {"api_name": "numpy.empty_like", "line_number": 185, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 188, "usage_type": "attribute"}, {"api_name": "numpy.cos", "line_number": 191, "usage_type": "call"}, {"api_name": "numpy.sin", "line_number": 191, "usage_type": "call"}, {"api_name": "numpy.sin", "line_number": 192, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 198, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 210, "usage_type": "call"}, {"api_name": "numpy.empty_like", "line_number": 211, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 217, "usage_type": "call"}, {"api_name": "numpy.arcsin", "line_number": 221, "usage_type": "call"}, {"api_name": "numpy.arctan2", "line_number": 222, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 226, "usage_type": "attribute"}, {"api_name": "astropy.wcs.WCS", "line_number": 248, "usage_type": "call"}, {"api_name": "astropy.wcs", "line_number": 248, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 252, "usage_type": "call"}, {"api_name": "numpy.testing.assert_allclose", "line_number": 266, "usage_type": "call"}]} +{"seq_id": "37045289757", "text": "from os import remove\r\nimport pandas as pd\r\nimport numpy as np\r\nimport datetime\r\n\r\ndef remove_specific_row_from_csv(file, column_name, *args):\r\n '''\r\n trouvé sur https://stackoverflow.com/questions/29725932/deleting-rows-with-python-in-a-csv-file\r\n :param file: file to remove the rows from\r\n :param column_name: The column that determines which row will be \r\n deleted (e.g. if Column == Name and row-*args\r\n contains \"Gavri\", All rows that contain this word will be deleted)\r\n :param args: Strings from the rows according to the conditions with \r\n the column\r\n '''\r\n row_to_remove = []\r\n for row_name in args:\r\n row_to_remove.append(row_name)\r\n try:\r\n df = pd.read_csv(file)\r\n for row in row_to_remove:\r\n df = df[eval(\"df.{}\".format(column_name)) != row]\r\n df.to_csv(file, index=False)\r\n except Exception as e:\r\n raise Exception(\"Error message....\")\r\n\r\ndef heurejournéeTimer(Timer):\r\n '''str -> float\r\n Date de format : \"2022-06-02 18:00:00\"\r\n retourne l'heure en secondes\r\n '''\r\n dheures = int(Timer[11:13])\r\n dminutes= int(Timer[14:16])\r\n dsecondes=int(Timer[17:19])\r\n return dheures*3600+dminutes*60+dsecondes\r\n\r\ndef UsableTimer(Date): #format \"2022-06-09T16:56:19+00:00\"\r\n \"\"\"str -> int*str*str\r\n on va tout passer en secondes,\r\n et prendre comme origine : 2022-10-01 00:00:00 c'est un samedi\r\n retourne le remps en sec depuis l'origine, le jour de la semaine, le mois\r\n return [secondes,\"lun\",\"jan\"] \"\"\"\r\n origine=\"2022-10-01 00:00:00\"\r\n semaine=[\"lun\",\"mar\",\"mer\",\"jeu\",\"ven\",\"sam\",\"dim\"]\r\n année=[\"jan\",\"fev\",\"mar\",\"avr\",\"mai\",\"jun\",\"jul\",\"aou\",\"sep\",\"oct\",\"nov\",\"dec\"]\r\n joursmois=[31,28,31,30,31,30,31,31,30,31,30,31]\r\n dannées= int(Date[0:4])-int(origine[0:4])\r\n dmois= (int(Date[5:7])-int(origine[5:7]))%12\r\n djours = (int(Date[8:10])-int(origine[8:10]))%joursmois[int(Date[5:7])-2]\r\n passagejoursmois=0\r\n for i in range(1,dmois+1):\r\n passagejoursmois += joursmois[int(Date[5:7])-(i+1)]\r\n joursemaine=semaine[(djours+5+ passagejoursmois +dannées*365)%7]\r\n moisannée=année[int(Date[5:7])-1]\r\n dheures = int(Date[11:13])-int(origine[11:13])\r\n dminutes= int(Date[14:16])-int(origine[14:16])\r\n dsecondes=int(Date[17:19])-int(origine[17:19])\r\n return [dsecondes + dminutes*60 + dheures*3600 + djours*24*3600 + passagejoursmois*24*3600 + dannées*365*24*3600,joursemaine,moisannée]\r\n\r\ndef UsableTimer_secondes(Timer):\r\n return UsableTimer(Timer)[0]\r\n\r\ndef UsableTimer_jour(date_string):\r\n date = datetime.datetime.strptime(date_string, \"%Y-%m-%d %H:%M:%S\")\r\n return date.strftime(\"%A\"), date.weekday()\r\n\r\ndef UsableTimer_mois(date_string):\r\n date = datetime.datetime.strptime(date_string, \"%Y-%m-%d %H:%M:%S\")\r\n return date.strftime(\"%B\"),date.month\r\n\r\ndef ajout_heure_jour(fichier):\r\n dof=pd.read_csv(fichier)\r\n dof[\"heure en seconde\"]=dof[\"Timer\"].apply(heurejournéeTimer)\r\n dof[\"secondes\"]=dof[\"Timer\"].apply(UsableTimer_secondes)\r\n dof[\"jour\"]=dof[\"Timer\"].apply(UsableTimer_jour)\r\n dof[\"mois\"]=dof[\"Timer\"].apply(UsableTimer_mois)\r\n dof.to_csv(fichier,mode='w',index=False,header=True)\r\n\r\ndef ajout_groupe(fichier):\r\n grille24 = np.load(\"grilles/grille24.npy\",allow_pickle=True)\r\n grille44 = np.load(\"grilles/grille44.npy\",allow_pickle=True)\r\n grille64 = np.load(\"grilles/grille64.npy\",allow_pickle=True)\r\n grille99 = np.load(\"grilles/grille99.npy\",allow_pickle=True)\r\n #grilles = [grille24,grille44,grille64,grille99]\r\n dico24,dico44,dico64,dico99=dict(),dict(),dict(),dict()\r\n for i in range(len(grille24)):\r\n for j in range(len(grille24[0])):\r\n for codestation in grille24[i][j]:\r\n dico24[codestation]=i*len(grille24[0])+j\r\n for i in range(len(grille44)):\r\n for j in range(len(grille44[0])):\r\n for codestation in grille44[i][j]:\r\n dico44[codestation]=i*len(grille44[0])+j\r\n for i in range(len(grille64)):\r\n for j in range(len(grille64[0])):\r\n for codestation in grille64[i][j]:\r\n dico64[codestation]=i*len(grille64[0])+j\r\n for i in range(len(grille99)):\r\n for j in range(len(grille99[0])):\r\n for codestation in grille99[i][j]:\r\n dico99[codestation]=i*len(grille99[0])+j\r\n print('fin de la création des dictionnaires')\r\n def determination_groupe(code,dico):\r\n return dico[str(code)]\r\n dof=pd.read_csv(fichier)\r\n dof[\"groupe24\"]=dof[\"Code Station\"].apply(determination_groupe,dico=dico24)\r\n dof[\"groupe44\"]=dof[\"Code Station\"].apply(determination_groupe,dico=dico44)\r\n dof[\"groupe64\"]=dof[\"Code Station\"].apply(determination_groupe,dico=dico64)\r\n dof[\"groupe99\"]=dof[\"Code Station\"].apply(determination_groupe,dico=dico99)\r\n dof.to_csv(fichier,mode='w',index=False,header=True)\r\n\r\ndef est_meme_date(dateVelib,dateMTO):\r\n \"\"\"dateVelib format : '2022-10-23 18:25:51'\r\n dateMTO format : '2022-10-23T00:00:00' \r\n retourne un booleen qui traduit si les dates sont identiques\"\"\"\r\n return dateVelib[0:10] == dateMTO[0:10]\r\n\r\ndef est_meme_heure(dateVelib,dateMTO):\r\n \"\"\"dateVelib format : '2022-10-23 18:25:51'\r\n dateMTO format : '2022-10-23T00:00:00' \r\n retourne un booleen qui traduit si les heures sont identiques\"\"\"\r\n return dateVelib[11:13] == dateMTO[11:13]\r\n\r\ndef Seconde_format_Timer(n):\r\n '''retourne l'heure en format Timer \"2022-06-02 00:56:16\" des secondes depuis 00:00'''\r\n h,m,s=(n//3600)%24,(n//60)%60,n%60\r\n res=\"2022-00-00 \"\r\n if h==0 :\r\n res= res + \"00:\"\r\n elif h<10:\r\n res=res+\"0\"+str(h)+\":\"\r\n elif h>=10:\r\n res=res+str(h)+\":\"\r\n if m==0 :\r\n res= res + \"00:\"\r\n elif m<10:\r\n res=res+\"0\"+str(m)+\":\"\r\n elif m>=10:\r\n res=res+str(m)+\":\"\r\n if s==0 :\r\n res= res + \"00\"\r\n elif s<10:\r\n res=res+\"0\"+str(s)\r\n elif s>=10:\r\n res=res+str(s)\r\n return res\r\n\r\ndef ajout_Timer(fichier):\r\n dof = pd.read_csv(fichier)\r\n dof[\"Timer\"] = dof[\"heure en seconde\"].apply(Seconde_format_Timer)\r\n dof.to_csv(fichier,mode='w',index=False,header=True)\r\n\r\ndef ajout_meteo(fichier,fichierMTO):\r\n meteo=pd.read_csv(fichierMTO)\r\n def application_meteo_feelslike(dateVelib):\r\n dateutile = dateVelib[:10] + 'T' + dateVelib[11:13] + ':00:00'\r\n return meteo.loc[ meteo['datetime']==dateutile ]['feelslike'].values[0]\r\n def application_meteo_windspeed(dateVelib):\r\n dateutile = dateVelib[:10] + 'T' + dateVelib[11:13] + ':00:00'\r\n return meteo.loc[ meteo['datetime']==dateutile ]['windspeed'].values[0]\r\n def application_meteo_conditions(dateVelib):\r\n dateutile = dateVelib[:10] + 'T' + dateVelib[11:13] + ':00:00'\r\n return meteo.loc[ meteo['datetime']==dateutile ]['conditions'].values[0]\r\n def application_meteo_precip(dateVelib):\r\n dateutile = dateVelib[:10] + 'T' + dateVelib[11:13] + ':00:00'\r\n return meteo.loc[ meteo['datetime']==dateutile ]['precip'].values[0]\r\n dof=pd.read_csv(fichier)\r\n dof['feelslike']=dof[\"Timer\"].apply(application_meteo_feelslike)\r\n dof['windspeed']=dof[\"Timer\"].apply(application_meteo_windspeed)\r\n dof['conditions']=dof[\"Timer\"].apply(application_meteo_conditions)\r\n dof['precip']=dof[\"Timer\"].apply(application_meteo_precip)\r\n dof.to_csv(fichier,mode='w',index=False,header=True)\r\n\r\ndef ajout_dummy(fichier,colonne):\r\n df = pd.read_csv(fichier)\r\n dico = {}\r\n curseur = 1\r\n res = []\r\n for i in df[colonne].values :\r\n if i not in dico :\r\n dico[i] = curseur\r\n curseur += 1\r\n res.append(dico[i])\r\n df[f'{colonne}_int'] = res\r\n df.to_csv(fichier,mode='w',index=False,header=True)\r\n\r\ndef ajout_int_conditions(fichier):\r\n df = pd.read_csv(fichier)\r\n dico = {'Partially cloudy': 1, 'Clear': 2, 'Overcast': 3, 'Rain, Overcast': 4, 'Rain, Partially cloudy': 5, 'Rain': 6, 'Snow, Rain, Overcast': 7, 'Snow, Overcast': 8}\r\n def application_conditions(conditions):\r\n return dico[conditions]\r\n df[\"conditions_int\"]=df[\"conditions\"].apply(application_conditions)\r\n df.to_csv(fichier,mode='w',index=False,header=True)", "repo_name": "Tamiir/TIPE", "sub_path": "traitement.py", "file_name": "traitement.py", "file_ext": "py", "file_size_in_byte": 8278, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "21", "api": [{"api_name": "pandas.read_csv", "line_number": 20, "usage_type": "call"}, {"api_name": "datetime.datetime.strptime", "line_number": 64, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 64, "usage_type": "attribute"}, {"api_name": "datetime.datetime.strptime", "line_number": 68, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 68, "usage_type": "attribute"}, {"api_name": "pandas.read_csv", "line_number": 72, "usage_type": "call"}, {"api_name": "numpy.load", "line_number": 80, "usage_type": "call"}, {"api_name": "numpy.load", "line_number": 81, "usage_type": "call"}, {"api_name": "numpy.load", "line_number": 82, "usage_type": "call"}, {"api_name": "numpy.load", "line_number": 83, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 105, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 149, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 154, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 167, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 175, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 188, "usage_type": "call"}]} +{"seq_id": "70283776372", "text": "__author__ = 'Hyeonsoo Youn'\n\nfrom bs4 import BeautifulSoup\nfrom selenium import webdriver\nfrom kafka import KafkaProducer\n\nimport psycopg2\nimport time\nimport json\nimport datetime\n\nconn_string = \"host='localhost' dbname ='collectData' user='postgres' password='secy'\"\n\n\ndef kafka_pub(wo_saveUpdated, wo_CoronavirusCase, wo_DeathNum, wo_RecoveredNum, wo_ActiveCase,\n wo_ActiveMildCondition, wo_ActiveSeriousCritical, wo_ClosedCase, wo_ClosedRecoverdDischarged,\n wo_ClosedDeath):\n now = datetime.datetime.now()\n nowDateTime = now.strftime('%Y-%m-%d %H:%M:%S')\n producer = KafkaProducer(bootstrap_servers=[\"211.194.13.200:9092\"])\n topicName = \"corona\"\n msg = {\"wo_saveUpdated\": wo_saveUpdated, \"wo_CoronavirusCase\": int(wo_CoronavirusCase), \"wo_DeathNum\": int(wo_DeathNum),\n \"wo_RecoveredNum\": int(wo_RecoveredNum), \"wo_ActiveCase\": int(wo_ActiveCase),\n \"wo_ActiveMildCondition\": int(wo_ActiveMildCondition), \"wo_ActiveSeriousCritical\": int(wo_ActiveSeriousCritical),\n \"wo_ClosedCase\": int(wo_ClosedCase), \"wo_ClosedRecoverdDischarged\": int(wo_ClosedRecoverdDischarged),\n \"wo_ClosedDeath\": int(wo_ClosedDeath), \"insertTime\": nowDateTime}\n\n def on_send_success(record_metadata):\n print(record_metadata.topic)\n print(record_metadata.partition)\n print(record_metadata.offset)\n\n # def on_send_error(excp):\n # log.error(\"error!!!\", exc_info=excp)\n\n producer = KafkaProducer(value_serializer=lambda m: json.dumps(msg).encode(\"ascii\"))\n producer.send(topicName, {'key': 'value'}).add_callback(on_send_success)\n\n producer.flush()\n\n producer = KafkaProducer(retries=5)\n\n\ndef createDB():\n conn = psycopg2.connect(conn_string)\n cur = conn.cursor()\n\n cur.execute(\"CREATE TABLE realtime_env_naver (\"\n \"seq SERIAL PRIMARY KEY, \"\n \"current_temperature TEXT, \"\n \"high_temperature TEXT, \"\n \"low_temperature TEXT, \"\n \"feel_temperature TEXT, \"\n \"time_rain_fall TEXT, \"\n \"fine_dust TEXT, \"\n \"ultra_fine_dust TEXT, \"\n \"ozone TEXT, \"\n \"server_update_time TEXT, \"\n \"creation_datetime TIMESTAMP DEFAULT CURRENT_TIMESTAMP);\")\n conn.commit()\n cur.close()\n conn.close()\n\n\ndef insertDB():\n conn = psycopg2.connect(conn_string)\n cur = conn.cursor()\n\n cur.execute(\"INSERT INTO realtime_env_naver(seq,\"\n \"current_temperature, \"\n \"high_temperature, \"\n \"low_temperature, \"\n \"feel_temperature, \"\n \"time_rain_fall, \"\n \"fine_dust, \"\n \"ultra_fine_dust, \"\n \"ozone, \"\n \"server_update_time) \"\n \"VALUES (nextval('realtime_env_naver_seq_seq'), %s, %s, %s, %s, %s, %s, %s, %s, %s)\", (\n currentTemperature, highTemperature, lowTemperature, feelTemperature,\n timeRainFall, fineDust, ultraFineDust, ozone, update))\n conn.commit()\n cur.close()\n conn.close()\n\n\ndef main():\n chrome_options = webdriver.ChromeOptions()\n chrome_options.add_argument('--headless')\n chrome_options.add_argument('--no-sandbox')\n chrome_options.add_argument('--disable-dev-shm-usage')\n\n driver = webdriver.Chrome('C:\\chromedriver.exe', chrome_options=chrome_options)\n\n count = True\n wo_saveUpdated = ''\n\n while 1:\n # driver.implicitly_wait(5)\n # headers={'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36'}\n driver.get('https://www.worldometers.info/coronavirus/')\n time.sleep(5)\n\n nowUpdated = driver.find_element_by_xpath(\"//div[normalize-space(@class)='content-inner']//div[2]\").text\n\n if count or len(saveUpdated) == 0:\n wo_CoronavirusCase = driver.find_element_by_xpath(\n \"//div[normalize-space(@class)='content-inner']//div[4]/div[1]/span[1]\").text.replace(',', '')\n wo_DeathNum = driver.find_element_by_xpath(\n \"//div[normalize-space(@class)='content-inner']//div[6]/div[1]/span[1]\").text.replace(',', '')\n wo_RecoveredNum = driver.find_element_by_xpath(\n \"//div[normalize-space(@class)='content-inner']//div[7]/div[1]/span[1]\").text.replace(',', '')\n wo_ActiveCase = driver.find_element_by_xpath(\n \"//div[normalize-space(@class)='content-inner']//div[9]/div[1]/div[2]/div[1]/div[1]/div[1]\").text.replace(\n ',', '')\n wo_ActiveMildCondition = driver.find_element_by_xpath(\n \"//div[normalize-space(@class)='content-inner']//div[9]/div[1]/div[2]/div[1]/div[1]/div[3]/div[1]/span[1]\").text.replace(\n ',', '')\n wo_ActiveSeriousCritical = driver.find_element_by_xpath(\n \"//div[normalize-space(@class)='content-inner']//div[9]/div[1]/div[2]/div[1]/div[1]/div[3]/div[2]/span[1]\").text.replace(\n ',', '')\n wo_ClosedCase = driver.find_element_by_xpath(\n \"//div[normalize-space(@class)='content-inner']//div[10]/div[1]/div[2]/div[1]/div[1]/div[1]\").text.replace(\n ',', '')\n wo_ClosedRecoverdDischarged = driver.find_element_by_xpath(\n \"//div[normalize-space(@class)='content-inner']//div[10]/div[1]/div[2]/div[1]/div[1]/div[3]/div[1]/span[1]\").text.replace(\n ',', '')\n wo_ClosedDeath = driver.find_element_by_xpath(\n \"//div[normalize-space(@class)='content-inner']//div[10]/div[1]/div[2]/div[1]/div[1]/div[3]/div[2]/span[1]\").text.replace(\n ',', '')\n\n wo_saveUpdated = nowUpdated\n print(wo_saveUpdated)\n print('\\n\\n전세계 상황')\n print(wo_CoronavirusCase)\n print(wo_DeathNum)\n print(wo_RecoveredNum)\n print(wo_ActiveCase)\n print(wo_ActiveMildCondition)\n print(wo_ActiveSeriousCritical)\n print(wo_ClosedCase)\n print(wo_ClosedRecoverdDischarged)\n print(wo_ClosedDeath)\n kafka_pub(wo_saveUpdated, wo_CoronavirusCase, wo_DeathNum, wo_RecoveredNum, wo_ActiveCase,\n wo_ActiveMildCondition, wo_ActiveSeriousCritical, wo_ClosedCase, wo_ClosedRecoverdDischarged,\n wo_ClosedDeath)\n count = False\n else:\n # 여기서부터 새롭게 업데이트된 데이터 받아오기\n if (nowUpdated != '-') and (wo_saveUpdated != nowUpdated):\n wo_CoronavirusCase = driver.find_element_by_xpath(\n \"//div[normalize-space(@class)='content-inner']//div[4]/div[1]/span[1]\").text.replace(',', '')\n wo_DeathNum = driver.find_element_by_xpath(\n \"//div[normalize-space(@class)='content-inner']//div[6]/div[1]/span[1]\").text.replace(',', '')\n wo_RecoveredNum = driver.find_element_by_xpath(\n \"//div[normalize-space(@class)='content-inner']//div[7]/div[1]/span[1]\").text.replace(',', '')\n wo_ActiveCase = driver.find_element_by_xpath(\n \"//div[normalize-space(@class)='content-inner']//div[9]/div[1]/div[2]/div[1]/div[1]/div[1]\").text.replace(\n ',', '')\n wo_ActiveMildCondition = driver.find_element_by_xpath(\n \"//div[normalize-space(@class)='content-inner']//div[9]/div[1]/div[2]/div[1]/div[1]/div[3]/div[1]/span[1]\").text.replace(\n ',', '')\n wo_ActiveSeriousCritical = driver.find_element_by_xpath(\n \"//div[normalize-space(@class)='content-inner']//div[9]/div[1]/div[2]/div[1]/div[1]/div[3]/div[2]/span[1]\").text.replace(\n ',', '')\n wo_ClosedCase = driver.find_element_by_xpath(\n \"//div[normalize-space(@class)='content-inner']//div[10]/div[1]/div[2]/div[1]/div[1]/div[1]\").text.replace(\n ',', '')\n wo_ClosedRecoverdDischarged = driver.find_element_by_xpath(\n \"//div[normalize-space(@class)='content-inner']//div[10]/div[1]/div[2]/div[1]/div[1]/div[3]/div[1]/span[1]\").text.replace(\n ',', '')\n wo_ClosedDeath = driver.find_element_by_xpath(\n \"//div[normalize-space(@class)='content-inner']//div[10]/div[1]/div[2]/div[1]/div[1]/div[3]/div[2]/span[1]\").text.replace(\n ',', '')\n\n wo_saveUpdated = nowUpdated\n print(wo_saveUpdated)\n print('\\n\\n전세계 상황')\n print(wo_CoronavirusCase)\n print(wo_DeathNum)\n print(wo_RecoveredNum)\n print(wo_ActiveCase)\n print(wo_ActiveMildCondition)\n print(wo_ActiveSeriousCritical)\n print(wo_ClosedCase)\n print(wo_ClosedRecoverdDischarged)\n print(wo_ClosedDeath)\n kafka_pub(wo_saveUpdated, wo_CoronavirusCase, wo_DeathNum, wo_RecoveredNum, wo_ActiveCase,\n wo_ActiveMildCondition, wo_ActiveSeriousCritical, wo_ClosedCase, wo_ClosedRecoverdDischarged,\n wo_ClosedDeath)\n\n\nif __name__ == \"__main__\":\n main()\n", "repo_name": "YounHS/Study_DataEngineering", "sub_path": "code/python/Corona/selenium_corona_crawling.py", "file_name": "selenium_corona_crawling.py", "file_ext": "py", "file_size_in_byte": 9412, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "21", "api": [{"api_name": "datetime.datetime.now", "line_number": 18, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 18, "usage_type": "attribute"}, {"api_name": "kafka.KafkaProducer", "line_number": 20, "usage_type": "call"}, {"api_name": "kafka.KafkaProducer", "line_number": 36, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 36, "usage_type": "call"}, {"api_name": "kafka.KafkaProducer", "line_number": 41, "usage_type": "call"}, {"api_name": "psycopg2.connect", "line_number": 45, "usage_type": "call"}, {"api_name": "psycopg2.connect", "line_number": 66, "usage_type": "call"}, {"api_name": "selenium.webdriver.ChromeOptions", "line_number": 88, "usage_type": "call"}, {"api_name": "selenium.webdriver", "line_number": 88, "usage_type": "name"}, {"api_name": "selenium.webdriver.Chrome", "line_number": 93, "usage_type": "call"}, {"api_name": "selenium.webdriver", "line_number": 93, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 102, "usage_type": "call"}]} +{"seq_id": "35878461816", "text": "## Ulas Kamaci - 2022-11-12\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport netCDF4, glob, datetime\nimport pandas as pd\nfrom dateutil import parser\nfrom iconfuv.misc import profiler\nfrom scipy.ndimage import convolve1d\n\ndef run1(\n file_dir_l2='/home/kamo/resources/icon-fuv/ncfiles/l2/2021/',\n save=False,\n savedir=None,\n save_suffix=None\n):\n\n files_l2 = glob.glob(file_dir_l2+'*')\n files_l2.sort()\n\n # dim0:[1:n, 0:s]\n times = []\n quals = []\n slts = []\n\n for file in files_l2:\n print(file)\n l2 = netCDF4.Dataset(file, 'r')\n qual = l2.variables['ICON_L25_Quality'][:]\n time = l2.variables['ICON_L25_UTC_Time'][:]\n time = np.array([parser.parse(i) for i in time])\n slt = l2.variables['ICON_L25_Local_Solar_Time'][:]\n l2.close()\n\n times.extend(time)\n quals.extend(qual)\n slts.extend(slt)\n\n if save:\n np.save(savedir+f'times_{save_suffix}', np.array(times))\n np.save(savedir+f'quals_{save_suffix}', np.array(quals))\n np.save(savedir+f'slts_{save_suffix}', np.array(slts))\n\n return times, quals, slts\n\ndef slt_comparison_plotter(times1, quals1, slts1, times2, quals2, slts2):\n qual1_1 = []\n qual5_1 = []\n qual1p_1 = []\n qual5p_1 = []\n qual1_2 = []\n qual5_2 = []\n qual1p_2 = []\n qual5p_2 = []\n slt_bins = [18,19,20,21,22,23,0,1,2,3,4,5]\n for i,slt in enumerate(slt_bins):\n print(slt)\n tind1 = (slts1[:,2]>=slt) & (slts1[:,2]=slt) & (slts2[:,2]=0.5))\n qual5_2.append(np.sum(quals2[tind2]>=0.5))\n if sum(tind1)>0:\n qual1p_1.append(qual1_1[i] / sum(tind1) / 6)\n qual5p_1.append(qual5_1[i] / sum(tind1) / 6)\n else:\n qual1p_1.append(0)\n qual5p_1.append(0)\n if sum(tind2)>0:\n qual1p_2.append(qual1_2[i] / sum(tind2) / 6)\n qual5p_2.append(qual5_2[i] / sum(tind2) / 6)\n else:\n qual1p_2.append(0)\n qual5p_2.append(0)\n\n slt_bins = [str(i) for i in slt_bins]\n plt.figure()\n plt.plot(slt_bins, qual1_1, '-o', label='2021')\n plt.plot(slt_bins, qual1_2, '-o', label='2022')\n plt.xlabel('SLTs')\n plt.ylabel('# of Quality 1 Retrievals')\n plt.title('# of Quality 1 Retrievals per SLT 2021 vs 2022')\n plt.grid(which='both', axis='both')\n plt.legend()\n plt.show()\n\n plt.figure()\n plt.plot(slt_bins, qual1p_1, '-o', label='2021')\n plt.plot(slt_bins, qual1p_2, '-o', label='2022')\n plt.xlabel('SLTs')\n plt.ylabel('% of Quality 1 Retrievals')\n plt.title('% of Quality 1 Retrievals per SLT 2021 vs 2022')\n plt.grid(which='both', axis='both')\n plt.legend()\n plt.show()\n\n plt.figure()\n plt.plot(slt_bins, qual5_1, '-o', label='2021')\n plt.plot(slt_bins, qual5_2, '-o', label='2022')\n plt.xlabel('SLTs')\n plt.ylabel('# of Quality >= 0.5 Retrievals')\n plt.title('# of Quality >= 0.5 Retrievals per SLT 2021 vs 2022')\n plt.grid(which='both', axis='both')\n plt.legend()\n plt.show()\n\n plt.figure()\n plt.plot(slt_bins, qual5p_1, '-o', label='2021')\n plt.plot(slt_bins, qual5p_2, '-o', label='2022')\n plt.xlabel('SLTs')\n plt.ylabel('% of Quality >= 0.5 Retrievals')\n plt.title('% of Quality >= 0.5 Retrievals per SLT 2021 vs 2022')\n plt.grid(which='both', axis='both')\n plt.legend()\n plt.show()\n \n\ndef monthly_comparison_plotter(times1, quals1, times2, quals2):\n qual1_1 = []\n qual5_1 = []\n qual1p_1 = []\n qual5p_1 = []\n qual1_2 = []\n qual5_2 = []\n qual1p_2 = []\n qual5p_2 = []\n for month in np.arange(12):\n tind1 = [True if times1[i].month==month+1 else False for i in range(len(times1))]\n tind2 = [True if times2[i].month==month+1 else False for i in range(len(times2))]\n if sum(tind1)>0:\n qual1_1.append(np.sum(quals1[tind1]==1))\n qual5_1.append(np.sum(quals1[tind1]>=0.5))\n qual1p_1.append(qual1_1[month] / sum(tind1) / 6)\n qual5p_1.append(qual5_1[month] / sum(tind1) / 6)\n else:\n qual1_1.append(np.nan)\n qual5_1.append(np.nan)\n qual1p_1.append(np.nan)\n qual5p_1.append(np.nan)\n if sum(tind2)>0:\n qual1_2.append(np.sum(quals2[tind2]==1))\n qual5_2.append(np.sum(quals2[tind2]>=0.5))\n qual1p_2.append(qual1_2[month] / sum(tind2) / 6)\n qual5p_2.append(qual5_2[month] / sum(tind2) / 6)\n else:\n qual1_2.append(np.nan)\n qual5_2.append(np.nan)\n qual1p_2.append(np.nan)\n qual5p_2.append(np.nan)\n \n month_bins = [str(i) for i in np.arange(12)+1]\n plt.figure()\n plt.plot(month_bins, qual1_1, '-o', label='2021')\n plt.plot(month_bins, qual1_2, '-o', label='2022')\n plt.xlabel('Months')\n plt.ylabel('# of Quality 1 Retrievals')\n plt.title('# of Quality 1 Retrievals per Month 2021 vs 2022')\n plt.grid(which='both', axis='both')\n plt.legend()\n plt.tight_layout()\n plt.show()\n\n plt.figure()\n plt.plot(month_bins, qual1p_1, '-o', label='2021')\n plt.plot(month_bins, qual1p_2, '-o', label='2022')\n plt.xlabel('Months')\n plt.ylabel('% of Quality 1 Retrievals')\n plt.title('% of Quality 1 Retrievals per Month 2021 vs 2022')\n plt.grid(which='both', axis='both')\n plt.legend()\n plt.tight_layout()\n plt.show()\n\n plt.figure()\n plt.plot(month_bins, qual5_1, '-o', label='2021')\n plt.plot(month_bins, qual5_2, '-o', label='2022')\n plt.xlabel('Months')\n plt.ylabel('# of Quality >= 0.5 Retrievals')\n plt.title('# of Quality >= 0.5 Retrievals per Month 2021 vs 2022')\n plt.grid(which='both', axis='both')\n plt.legend()\n plt.tight_layout()\n plt.show()\n\n plt.figure()\n plt.plot(month_bins, qual5p_1, '-o', label='2021')\n plt.plot(month_bins, qual5p_2, '-o', label='2022')\n plt.xlabel('Months')\n plt.ylabel('% of Quality >= 0.5 Retrievals')\n plt.title('% of Quality >= 0.5 Retrievals per Month 2021 vs 2022')\n plt.grid(which='both', axis='both')\n plt.legend()\n plt.tight_layout()\n plt.show()\n\nif __name__ == '__main__':\n dirr = '/home/kamo/resources/icon-fuv/ncfiles/l2/quality_trend_data/'\n times1 = np.load(dirr+'times_2021.npy', allow_pickle=True)\n quals1 = np.load(dirr+'quals_2021.npy')\n slts1 = np.load(dirr+'slts_2021.npy')\n times2 = np.load(dirr+'times_2022.npy', allow_pickle=True)\n quals2 = np.load(dirr+'quals_2022.npy')\n slts2 = np.load(dirr+'slts_2022.npy')\n monthly_comparison_plotter(times1, quals1, times2, quals2)\n # slt_comparison_plotter(times1, quals1, slts1, times2, quals2, slts2)\n # times, quals, slts = run1(file_dir_l2='/home/kamo/resources/icon-fuv/ncfiles/l2/2022/')\n", "repo_name": "UIUC-SINE/icon-fuv", "sub_path": "python3/scripts/quality_variability_plotter.py", "file_name": "quality_variability_plotter.py", "file_ext": "py", "file_size_in_byte": 6942, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "glob.glob", "line_number": 18, "usage_type": "call"}, {"api_name": "netCDF4.Dataset", "line_number": 28, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 31, "usage_type": "call"}, {"api_name": "dateutil.parser.parse", "line_number": 31, "usage_type": "call"}, {"api_name": "dateutil.parser", "line_number": 31, "usage_type": "name"}, {"api_name": "numpy.save", "line_number": 40, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 40, "usage_type": "call"}, {"api_name": "numpy.save", "line_number": 41, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 41, "usage_type": "call"}, {"api_name": "numpy.save", "line_number": 42, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 42, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 60, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 61, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 62, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 63, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 78, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 78, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 79, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 79, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 80, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 80, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 81, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 81, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 82, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 82, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 83, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 83, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.grid", "line_number": 84, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 84, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 85, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 85, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 86, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 86, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 88, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 88, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 89, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 89, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 90, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 90, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 91, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 91, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 92, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 92, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 93, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 93, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.grid", "line_number": 94, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 94, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 95, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 95, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 96, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 96, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 98, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 98, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 99, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 99, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 100, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 100, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 101, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 101, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 102, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 102, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 103, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 103, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.grid", "line_number": 104, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 104, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 105, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 105, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 106, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 106, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 108, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 108, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 109, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 109, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 110, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 110, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 111, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 111, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 112, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 112, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 113, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 113, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.grid", "line_number": 114, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 114, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 115, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 115, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 116, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 116, "usage_type": "name"}, {"api_name": "numpy.arange", "line_number": 128, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 132, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 133, "usage_type": "call"}, {"api_name": "numpy.nan", "line_number": 137, "usage_type": "attribute"}, {"api_name": "numpy.nan", "line_number": 138, "usage_type": "attribute"}, {"api_name": "numpy.nan", "line_number": 139, "usage_type": "attribute"}, {"api_name": "numpy.nan", "line_number": 140, "usage_type": "attribute"}, {"api_name": "numpy.sum", "line_number": 142, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 143, "usage_type": "call"}, {"api_name": "numpy.nan", "line_number": 147, "usage_type": "attribute"}, {"api_name": "numpy.nan", "line_number": 148, "usage_type": "attribute"}, {"api_name": "numpy.nan", "line_number": 149, "usage_type": "attribute"}, {"api_name": "numpy.nan", "line_number": 150, "usage_type": "attribute"}, {"api_name": "numpy.arange", "line_number": 152, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 153, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 153, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 154, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 154, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 155, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 155, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 156, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 156, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 157, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 157, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 158, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 158, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.grid", "line_number": 159, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 159, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 160, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 160, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.tight_layout", "line_number": 161, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 161, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 162, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 162, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 164, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 164, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 165, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 165, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 166, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 166, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 167, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 167, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 168, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 168, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 169, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 169, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.grid", "line_number": 170, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 170, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 171, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 171, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.tight_layout", "line_number": 172, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 172, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 173, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 173, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 175, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 175, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 176, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 176, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 177, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 177, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 178, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 178, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 179, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 179, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 180, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 180, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.grid", "line_number": 181, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 181, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 182, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 182, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.tight_layout", "line_number": 183, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 183, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 184, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 184, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 186, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 186, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 187, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 187, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 188, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 188, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 189, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 189, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 190, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 190, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 191, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 191, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.grid", "line_number": 192, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 192, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 193, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 193, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.tight_layout", "line_number": 194, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 194, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 195, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 195, "usage_type": "name"}, {"api_name": "numpy.load", "line_number": 199, "usage_type": "call"}, {"api_name": "numpy.load", "line_number": 200, "usage_type": "call"}, {"api_name": "numpy.load", "line_number": 201, "usage_type": "call"}, {"api_name": "numpy.load", "line_number": 202, "usage_type": "call"}, {"api_name": "numpy.load", "line_number": 203, "usage_type": "call"}, {"api_name": "numpy.load", "line_number": 204, "usage_type": "call"}]} +{"seq_id": "4618429204", "text": "import sys,os\nfrom Bio import SeqIO\nimport itertools\nimport datetime\nimport time\nimport argparse\n\nimportSAMPLE_ID = None\nBARCODE_FILE = None\nLOG_EVERY_N = 10000\nSEL_STRING = 'paired' #global-perhaps make this an arg in future versions\nVERSION = 'Version 3.0 - EDITED'\nDESCRIPTION = '''\\\n The goal is to separate single-cell RNAseq fastq files into two\n species specific subsets. We iterate through the\n mixed-genome bam file to select read IDs matching the extracted barcodes\n along with alignment scores, choosing the best score by genome.\n Read IDs matching both genomes are deleted.\n Finally, open paired-end fastq files (must be in current directory)\n and output barcode-matching records\n to one genome, non-matching to an alternate genome. Requires that\n IDs match in paired files.\n '''\n\ndef checkOptions():\n\n parser = argparse.ArgumentParser(usage='samtools view | splitByScore.py',description=DESCRIPTION)\n parser.add_argument('-v','--version', action='version', version=VERSION)\n parser.add_argument('-g','--genome',dest=\"sp1\",default='hg38',\n help='Selected genome identifier (default hg38)')\n parser.add_argument('-a','--altgenome',dest=\"sp2\",default='mm10',\n help='Non-matching genome identifier (default mm10)')\n parser.add_argument('-s','--sample',dest=\"sample_name\",required=True,default=None,\n help='Sample ID for insertion into file name')\n parser.add_argument('-e','--extension',dest='fastqext',default='fastq',\n help='Fastq file extension (default fastq)')\n parser.add_argument('-f','--fastqdir',dest='fastqdir',default='fastq',\n help='Directory with fastq files (default fastq)')\n parser.add_argument('-o','--output',dest=\"ofname\",default=None,\n help='File to log runtime output (default stdout)')\n\n args = parser.parse_args()\n return args\n\ndef getTag(tag, lis):\n '''\n Get optional tag from a SAM record.\n '''\n for t in lis:\n spl = t.split(':')\n if spl[0] == tag:\n return spl[-1]\n return None\n\ndef numFmt(value):\n\treturn '{:,}'.format(value)\n\ndef fastqOut(genome,genDict,fastqDir,fastqRoot):\n\tfastqInName = fastqRoot \n\tfastqOutName = fastqRoot.replace(SEL_STRING,genome) \n\tfastq_iter = SeqIO.parse(open(fastqDir + '/' +fastqInName),'fastq')\n\toutFile = open(fastqDir + '/' + fastqOutName, 'w')\n\tctr = 0\n\tfoundCtr = 0\n\tstartTime = time.time()\n\tfor rec in fastq_iter:\n\t\t\tctr += 1 \n\t\t\tif (rec.id in genDict): # record from chosen genotype\n\t\t\t\tfoundCtr += 1\n\t\t\t\tSeqIO.write(rec,outFile,'fastq')\n\t\t\telse: # record not in dict\n\t\t\t\tcontinue\n\tfastq_iter.close()\n\toutFile.close()\n\tendTime = time.time() \n\tprint(\"Read \" + numFmt(ctr) + \" records from \" + fastqInName + \" and output \" + numFmt(foundCtr) + \" records to \" + fastqOutName + \" in \" + '{:.2f}'.format(endTime - startTime) + \" seconds.\")\n\treturn None\n\ndef main():\n '''Main.'''\n opt = checkOptions()\n sp1 = opt.sp1\n sp2 = opt.sp2\n sampleName = opt.sample_name\n fastqExt = opt.fastqext\n fastqDir = opt.fastqdir\n vString = 'v3.0 - HG/RH'\n oFname = opt.ofname\n \n #create lists\n readEnds = [ \"_1\", \"_2\" ] #perhaps add this as an option in the future\n genomes = [ sp1, sp2 ]\n\n # initialize counts\n ReadCount = 0 # total reads input\n GoodCount = 0 # total matching reads input\n UnmappedCount = 0\n MissingAS = 0\n MissingCB = 0 # reads without a CB tag\n sp1Count = 0 # reads assigned to sp1 \n sp2Count = 0 # reads assigned to sp2\n \n # create dictionaries\n sp1IDs = dict() #dict to store current-best IDs and scores for sp1\n sp2IDs = dict() #dict to store current-best IDs and scores for sp2\n \n\n # parse SAM (stdin), extract best alignment scores, store in dict\n print(\"splitByScore_v3 run started \" + datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M\"))\n print(vString)\n print(\"Chosen species is \" + sp1 + \", alternate species is \" + sp2)\n \n # parse SAM (stdin), extract best alignment scores, store in dict\n f = sys.stdin\n start = time.time()\n for line in f:\n if line[0] == '@':\n continue #skip header\n ReadCount += 1 #found a read line\n spl = line.rstrip().split('\\t') #split into fields\n flag = int(spl[1])\n if flag & 0x4: \n UnmappedCount += 1\n\n #read is mapped\n GoodCount += 1\n # retrieve alignment score\n aScore = getTag('AS', spl[11:])\n if not aScore:\n MissingAS += 1\n continue\n aScore = int(aScore)\n \n readGenome = spl[2][:len(sp1)]\n if readGenome == sp1: #this read is from sp1\n if spl[0] in sp1IDs: #seen this read in sp1 before\n if aScore > sp1IDs[spl[0]]: # this read has better AS\n sp1IDs[spl[0]] = aScore #replace with better AS\n continue\n else:\n # previous read had equal or better AS -- do nothing\n continue\n elif spl[0] in sp2IDs: #was is seen in sp2 before?\n if aScore > sp2IDs[spl[0]]: #this new sp1 read is better than the old sp2 read\n del sp2IDs[spl[0]] #remove from sp2 dict\n sp2Count += -1 #decrement sp2 count\n sp1IDs[spl[0]] = aScore #add to sp1 dict\n sp1Count += 1 #increment sp1 count\n continue\n else: # score in sp2 is better than in sp1, do nothing\n continue\n else:\n #not seen this before - add it to sp1 dict\n sp1IDs[spl[0]] = aScore\n sp1Count += 1\n elif readGenome == sp2: #this read is from sp2\n if spl[0] in sp2IDs: #seen this read in sp2 before\n if aScore > sp2IDs[spl[0]]: #this read has better score\n sp2IDs[spl[0]] = aScore # replace with better AS\n continue\n else:\n # previous read had equal or better AS -- do nothing\n continue\n elif spl[0] in sp1IDs: # was this seen in sp1 before?\n if aScore > sp1IDs[spl[0]]: #this new sp2 read is better than the old sp1 read\n del sp1IDs[spl[0]] #remove from sp1 dict\n sp1Count += -1\n sp2IDs[spl[0]] = aScore #add to sp2 dict\n sp2Count += 1\n continue\n else: # score in sp1 is better than in sp2 -- do nothing\n continue\n else: #not seen this before, add it to sp2 dict\n sp2IDs[spl[0]] = aScore\n sp2Count += 1\n \n f.close() #done with stdin\n \n end = time.time()\n print(\"Parsing SAM output took \" + '{:.2f}'.format(end - start) + \" seconds.\")\n \n #Write status of ID matching to stdout or redirected to oFname\n print(\"Total \" + numFmt(ReadCount) + \" reads, \" + numFmt(GoodCount) + \" are aligned\" + numFmt(UnmappedCount) + \" are unmapped\")\n print(\"number that miss AS\", MissingAS)\n print(numFmt(sp1Count) + \" reads matching \" + sp1)\n print(numFmt(sp2Count) + \" reads matching \" + sp2)\n sys.stdout.flush() #to empty stdout buffer to file\n \n # Find paired-end fastq files.\n fastqs = [f for f in os.listdir(fastqDir) if f.endswith(fastqExt)]\n R1 = ''.join([f for f in fastqs if (readEnds[0] in f) & (SEL_STRING in f)]) \n R2 = ''.join([f for f in fastqs if (readEnds[1] in f) & (SEL_STRING in f)])\n fastqs = [ R1,R2 ]\n genDicts = [ sp1IDs, sp2IDs ]\n for genID,gen in enumerate(genomes):\n \tfor endID,readEnd in enumerate(readEnds):\n \t\tfastqOut(gen,genDicts[genID],fastqDir,fastqs[endID])\n \n print(\"splitByScore_v3 run ended \" + datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M\"))\n \n sys.exit(0)\n \nif __name__ == '__main__':\n main()", "repo_name": "rhart604/optimized", "sub_path": "byAS.py", "file_name": "byAS.py", "file_ext": "py", "file_size_in_byte": 7920, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 27, "usage_type": "call"}, {"api_name": "Bio.SeqIO.parse", "line_number": 61, "usage_type": "call"}, {"api_name": "Bio.SeqIO", "line_number": 61, "usage_type": "name"}, {"api_name": "time.time", "line_number": 65, "usage_type": "call"}, {"api_name": "Bio.SeqIO.write", "line_number": 70, "usage_type": "call"}, {"api_name": "Bio.SeqIO", "line_number": 70, "usage_type": "name"}, {"api_name": "time.time", "line_number": 75, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 109, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 109, "usage_type": "attribute"}, {"api_name": "sys.stdin", "line_number": 114, "usage_type": "attribute"}, {"api_name": "time.time", "line_number": 115, "usage_type": "call"}, {"api_name": "time.time", "line_number": 179, "usage_type": "call"}, {"api_name": "sys.stdout.flush", "line_number": 187, "usage_type": "call"}, {"api_name": "sys.stdout", "line_number": 187, "usage_type": "attribute"}, {"api_name": "os.listdir", "line_number": 190, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 199, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 199, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 201, "usage_type": "call"}]} +{"seq_id": "23155046866", "text": "#-*- coding:utf-8 -*-\nimport pymongo\nfrom Tokyo_logistic_topo.kml_tool import ITDKkml\nfrom Tokyo_logistic_topo.Tokyo_logic import TokyoTopo\nfrom Tokyo_logistic_topo.Tokyo_logic import TokyoTopo,ITDKkml\nclient = pymongo.MongoClient()\niii=TokyoTopo()\ncol_edge1 = client['itdkall_info']['edge_location_degree']\ncol_edge2 = client['itdkall_info']['edge_static_short_250']\n#两类边合体\ncol_edge_merge = client['itdkall_info']['merge']\ncol_edge_merge.drop()\nfor edge in col_edge1.find():\n if iii.get_distance(start=edge['start'],end=edge['end'])<400:\n docu = {'start':{'longitude':edge['start']['longitude'],'latitude':edge['start']['latitude']},\n 'end':{'longitude':edge['end']['longitude'], 'latitude':edge['end']['latitude']}}\n col_edge_merge.insert_one(docu)\nfor edge in col_edge2.find():\n docu = {'start':{'longitude':edge['start']['longitude'],'latitude':edge['start']['latitude']},\n 'end':{'longitude':edge['end']['longitude'], 'latitude':edge['end']['latitude']}}\n flag = col_edge_merge.find_one(docu)\n if not flag:\n col_edge_merge.insert_one(docu)\nfilename_KML = './file/日本整个第二层merge.kml'\nf=open(filename_KML,'w')\npaint = ITDKkml(f)\npaint.setting_line(line_color= 'ffb40014',line_hight_start=80000,line_hight_end=80000,line_width=1,altitudeMode='relativeToGround')\n#paint.setting_point(icon_path='juanjo_Router.png',point_hight=80000,point_scale=0.5)\npaint.head()\nfor edge in col_edge_merge.find():\n paint.draw_edge(start=edge['start'],end=edge['end'])\npaint.tail()\nf.close()", "repo_name": "DarkFunct/topoOfJapan", "sub_path": "东京逻辑布局/测试/将高度数的边和低长度的边合起来.py", "file_name": "将高度数的边和低长度的边合起来.py", "file_ext": "py", "file_size_in_byte": 1562, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "pymongo.MongoClient", "line_number": 6, "usage_type": "call"}, {"api_name": "Tokyo_logistic_topo.Tokyo_logic.TokyoTopo", "line_number": 7, "usage_type": "call"}, {"api_name": "Tokyo_logistic_topo.Tokyo_logic.ITDKkml", "line_number": 26, "usage_type": "call"}]} +{"seq_id": "24533163457", "text": "# !/usr/bin/env python\n# !-*-coding:utf-8 -*- \n'''\n@version: python3.7\n@file: RvNNEncoder.py\n@time: 7/9/2020 9:25 AM\n'''\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch\nfrom torch.autograd import Variable\nfrom util.Config import Config as cf\nfrom models.WeightedRvNN import WeightedBatchSubTreeEncoder\n\n\n# copy from https://github.com/zhangj111/astnn/blob/master/model.py\nclass BatchSubTreeEncoder(nn.Module):\n def __init__(self, vocab_size, embedding_dim, encode_dim, batch_size, use_gpu, pretrained_weight=None):\n super(BatchSubTreeEncoder, self).__init__()\n self.embedding = nn.Embedding(vocab_size, embedding_dim)\n self.encode_dim = encode_dim\n self.W_c = nn.Linear(embedding_dim, encode_dim)\n # self.W_l = nn.Linear(encode_dim, encode_dim)\n # self.W_r = nn.Linear(encode_dim, encode_dim)\n self.activation = F.relu\n self.stop = -1\n self.batch_size = batch_size\n self.use_gpu = use_gpu\n self.node_list = []\n self.th = torch.cuda if use_gpu else torch\n self.batch_node = None\n # pretrained embedding\n if pretrained_weight is not None:\n self.embedding.weight.data.copy_(torch.from_numpy(pretrained_weight))\n # self.embedding.weight.requires_grad = False\n\n def create_tensor(self, tensor):\n if self.use_gpu:\n return tensor.cuda()\n return tensor\n\n def traverse_mul(self, node, batch_index):\n size = len(node)\n if not size:\n return None\n batch_current = self.create_tensor(Variable(torch.zeros(size, self.encode_dim)))\n\n index, children_index = [], []\n current_node, children = [], []\n for i in range(size):\n try:\n if node[i][0] is not -1:\n index.append(i)\n current_node.append(node[i][0])\n temp = node[i][1:]\n c_num = len(temp)\n for j in range(c_num):\n if temp[j][0] is not -1:\n if len(children_index) <= j:\n children_index.append([i])\n children.append([temp[j]])\n else:\n children_index[j].append(i)\n children[j].append(temp[j])\n else:\n batch_index[i] = -1\n except:\n pass\n\n batch_current = self.W_c(batch_current.index_copy(0, Variable(self.th.LongTensor(index)),\n self.embedding(Variable(self.th.LongTensor(current_node)))))\n\n for c in range(len(children)):\n zeros = self.create_tensor(Variable(torch.zeros(size, self.encode_dim)))\n batch_children_index = [batch_index[i] for i in children_index[c]]\n tree = self.traverse_mul(children[c], batch_children_index)\n if tree is not None:\n batch_current += zeros.index_copy(0, Variable(self.th.LongTensor(children_index[c])), tree)\n # batch_current = F.tanh(batch_current)\n batch_index = [i for i in batch_index if i is not -1]\n b_in = Variable(self.th.LongTensor(batch_index))\n try:\n self.node_list.append(self.batch_node.index_copy(0, b_in, batch_current))\n except:\n pass\n return batch_current\n\n def forward(self, x, bs):\n self.batch_size = bs\n self.batch_node = self.create_tensor(Variable(torch.zeros(self.batch_size, self.encode_dim)))\n self.node_list = []\n self.traverse_mul(x, list(range(self.batch_size)))\n self.node_list = torch.stack(self.node_list)\n if cf.node_combine == \"max\":\n return torch.max(self.node_list, 0)[0]\n elif cf.node_combine == \"mean\":\n return torch.mean(self.node_list, 0)\n # return torch.max(self.node_list, 0)[0]\n\n\n# revise from https://github.com/zhangj111/astnn/blob/master/model.py\nclass BatchASTEncoder(nn.Module):\n # def __init__(self, embedding_dim, hidden_dim, vocab_size, encode_dim, label_size, batch_size, use_gpu=True, pretrained_weight=None):\n def __init__(self, embedding_dim, hidden_dim, vocab_size, encode_dim, batch_size, use_gpu=True,\n pretrained_weight=None):\n super(BatchASTEncoder, self).__init__()\n self.stop = [vocab_size - 1]\n self.hidden_dim = hidden_dim\n self.num_layers = 1\n # self.gpu = use_gpu\n self.gpu = use_gpu\n self.batch_size = batch_size\n self.vocab_size = vocab_size\n self.embedding_dim = embedding_dim\n self.encode_dim = encode_dim\n # self.label_size = label_size\n # class \"BatchTreeEncoder\"\n if cf.is_weighted_RvNN:\n self.encoder = WeightedBatchSubTreeEncoder(self.vocab_size, self.embedding_dim, self.encode_dim,\n self.batch_size, self.gpu, pretrained_weight)\n else:\n self.encoder = BatchSubTreeEncoder(self.vocab_size, self.embedding_dim, self.encode_dim,\n self.batch_size, self.gpu, pretrained_weight)\n # self.root2label = nn.Linear(self.encode_dim, self.label_size)\n # gru\n self.bigru = nn.GRU(self.encode_dim, self.hidden_dim, num_layers=self.num_layers, bidirectional=True,\n batch_first=True)\n # linear\n # self.hidden2label = nn.Linear(self.hidden_dim * 2, self.label_size)\n # hidden\n self.hidden = self.init_hidden()\n self.dropout = nn.Dropout(0.2)\n\n def init_hidden(self):\n if self.gpu is True:\n try:\n local_rank = torch.distributed.get_rank()\n except AssertionError:\n local_rank = 0\n device = torch.device(\"cuda\", local_rank)\n if isinstance(self.bigru, nn.LSTM):\n h0 = Variable(torch.zeros(self.num_layers * 2, self.batch_size, self.hidden_dim).cuda())\n c0 = Variable(torch.zeros(self.num_layers * 2, self.batch_size, self.hidden_dim).cuda())\n return h0.to(device), c0.to(device)\n return Variable(torch.zeros(self.num_layers * 2, self.batch_size, self.hidden_dim)).cuda().to(device)\n else:\n return Variable(torch.zeros(self.num_layers * 2, self.batch_size, self.hidden_dim))\n\n def get_zeros(self, num):\n zeros = Variable(torch.zeros(num, self.encode_dim))\n if self.gpu:\n return zeros.cuda()\n return zeros\n\n def forward(self, x):\n lens = [len(item) for item in x]\n max_len = max(lens)\n\n encodes = []\n for i in range(self.batch_size):\n try:\n for j in range(lens[i]):\n encodes.append(x[i][j])\n except:\n pass\n\n encodes = self.encoder(encodes, sum(lens))\n seq, start, end = [], 0, 0\n for i in range(self.batch_size):\n end += lens[i]\n if max_len - lens[i]:\n seq.append(self.get_zeros(max_len - lens[i]))\n seq.append(encodes[start:end])\n start = end\n encodes = torch.cat(seq)\n encodes = encodes.view(self.batch_size, max_len, -1)\n\n # gru\n gru_out, hidden = self.bigru(encodes, self.hidden)\n\n # gru_out = torch.transpose(gru_out, 1, 2)\n # pooling\n # gru_out = F.max_pool1d(gru_out, gru_out.size(2)).squeeze(2)\n # gru_out = gru_out[:,-1]\n\n # linear\n # y = self.hidden2label(gru_out)\n return gru_out, hidden\n # gru_out [1,3,20] [batch_size,seq_len,2*hidden_dim]\n # hidden [2,1,10] [batch_size,seq_len,2*hidden_dim]\n\n\n# revise from https://github.com/zhangj111/astnn/blob/master/model.py\nclass BatchASTRvNNEncoder(nn.Module):\n # def __init__(self, embedding_dim, hidden_dim, vocab_size, encode_dim, label_size, batch_size, use_gpu=True, pretrained_weight=None):\n def __init__(self, embedding_dim, vocab_size, encode_dim, batch_size, use_gpu=True, pretrained_weight=None):\n super(BatchASTRvNNEncoder, self).__init__()\n self.gpu = use_gpu\n self.batch_size = batch_size\n self.vocab_size = vocab_size\n self.embedding_dim = embedding_dim\n self.encode_dim = encode_dim\n if cf.is_weighted_RvNN:\n self.encoder = WeightedBatchSubTreeEncoder(self.vocab_size, self.embedding_dim, self.encode_dim,\n self.batch_size, self.gpu, pretrained_weight)\n else:\n self.encoder = BatchSubTreeEncoder(self.vocab_size, self.embedding_dim, self.encode_dim,\n self.batch_size, self.gpu, pretrained_weight)\n\n def get_zeros(self, num):\n zeros = Variable(torch.zeros(num, self.encode_dim))\n if self.gpu:\n return zeros.cuda()\n return zeros\n\n def forward(self, x):\n lens = [len(item) for item in x]\n max_len = max(lens)\n\n encodes = []\n for i in range(self.batch_size):\n try:\n for j in range(lens[i]):\n encodes.append(x[i][j])\n except:\n pass\n\n encodes = self.encoder(encodes, sum(lens))\n seq, start, end = [], 0, 0\n for i in range(self.batch_size):\n end += lens[i]\n if max_len - lens[i]:\n seq.append(self.get_zeros(max_len - lens[i]))\n seq.append(encodes[start:end])\n start = end\n encodes = torch.cat(seq)\n encodes = encodes.view(self.batch_size, max_len, -1)\n\n return encodes\n", "repo_name": "DeepSoftwareAnalytics/CAST", "sub_path": "source_code/models/RvNNEncoder.py", "file_name": "RvNNEncoder.py", "file_ext": "py", "file_size_in_byte": 9758, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 28, "dataset": "github-code", "pt": "21", "api": [{"api_name": "torch.nn.Module", "line_number": 17, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 17, "usage_type": "name"}, {"api_name": "torch.nn.Embedding", "line_number": 20, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 20, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 22, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 22, "usage_type": "name"}, {"api_name": "torch.nn.functional.relu", "line_number": 25, "usage_type": "attribute"}, {"api_name": "torch.nn.functional", "line_number": 25, "usage_type": "name"}, {"api_name": "torch.cuda", "line_number": 30, "usage_type": "attribute"}, {"api_name": "torch.from_numpy", "line_number": 34, "usage_type": "call"}, {"api_name": "torch.autograd.Variable", "line_number": 46, "usage_type": "call"}, {"api_name": "torch.zeros", "line_number": 46, "usage_type": "call"}, {"api_name": "torch.autograd.Variable", "line_number": 70, "usage_type": "call"}, {"api_name": "torch.autograd.Variable", "line_number": 71, "usage_type": "call"}, {"api_name": "torch.autograd.Variable", "line_number": 74, "usage_type": "call"}, {"api_name": "torch.zeros", "line_number": 74, "usage_type": "call"}, {"api_name": "torch.autograd.Variable", "line_number": 78, "usage_type": "call"}, {"api_name": "torch.autograd.Variable", "line_number": 81, "usage_type": "call"}, {"api_name": "torch.autograd.Variable", "line_number": 90, "usage_type": "call"}, {"api_name": "torch.zeros", "line_number": 90, "usage_type": "call"}, {"api_name": "torch.stack", "line_number": 93, "usage_type": "call"}, {"api_name": "util.Config.Config.node_combine", "line_number": 94, "usage_type": "attribute"}, {"api_name": "util.Config.Config", "line_number": 94, "usage_type": "name"}, {"api_name": "torch.max", "line_number": 95, "usage_type": "call"}, {"api_name": "util.Config.Config.node_combine", "line_number": 96, "usage_type": "attribute"}, {"api_name": "util.Config.Config", "line_number": 96, "usage_type": "name"}, {"api_name": "torch.mean", "line_number": 97, "usage_type": "call"}, {"api_name": "torch.nn.Module", "line_number": 102, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 102, "usage_type": "name"}, {"api_name": "util.Config.Config.is_weighted_RvNN", "line_number": 118, "usage_type": "attribute"}, {"api_name": "util.Config.Config", "line_number": 118, "usage_type": "name"}, {"api_name": "models.WeightedRvNN.WeightedBatchSubTreeEncoder", "line_number": 119, "usage_type": "call"}, {"api_name": "torch.nn.GRU", "line_number": 126, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 126, "usage_type": "name"}, {"api_name": "torch.nn.Dropout", "line_number": 132, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 132, "usage_type": "name"}, {"api_name": "torch.distributed.get_rank", "line_number": 137, "usage_type": "call"}, {"api_name": "torch.distributed", "line_number": 137, "usage_type": "attribute"}, {"api_name": "torch.device", "line_number": 140, "usage_type": "call"}, {"api_name": "torch.nn.LSTM", "line_number": 141, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 141, "usage_type": "name"}, {"api_name": "torch.autograd.Variable", "line_number": 142, "usage_type": "call"}, {"api_name": "torch.zeros", "line_number": 142, "usage_type": "call"}, {"api_name": "torch.autograd.Variable", "line_number": 143, "usage_type": "call"}, {"api_name": "torch.zeros", "line_number": 143, "usage_type": "call"}, {"api_name": "torch.autograd.Variable", "line_number": 145, "usage_type": "call"}, {"api_name": "torch.zeros", "line_number": 145, "usage_type": "call"}, {"api_name": "torch.autograd.Variable", "line_number": 147, "usage_type": "call"}, {"api_name": "torch.zeros", "line_number": 147, "usage_type": "call"}, {"api_name": "torch.autograd.Variable", "line_number": 150, "usage_type": "call"}, {"api_name": "torch.zeros", "line_number": 150, "usage_type": "call"}, {"api_name": "torch.cat", "line_number": 175, "usage_type": "call"}, {"api_name": "torch.nn.Module", "line_number": 194, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 194, "usage_type": "name"}, {"api_name": "util.Config.Config.is_weighted_RvNN", "line_number": 203, "usage_type": "attribute"}, {"api_name": "util.Config.Config", "line_number": 203, "usage_type": "name"}, {"api_name": "models.WeightedRvNN.WeightedBatchSubTreeEncoder", "line_number": 204, "usage_type": "call"}, {"api_name": "torch.autograd.Variable", "line_number": 211, "usage_type": "call"}, {"api_name": "torch.zeros", "line_number": 211, "usage_type": "call"}, {"api_name": "torch.cat", "line_number": 236, "usage_type": "call"}]} +{"seq_id": "28181061788", "text": "import os\nfrom flask import Flask, request, jsonify, abort\nfrom sqlalchemy import exc\nimport json\nfrom flask_cors import CORS\n\nfrom .database.models import db_drop_and_create_all, setup_db, Drink\nfrom .auth.auth import AuthError, requires_auth, get_token_auth_header\n\napp = Flask(__name__)\nsetup_db(app)\nCORS(app)\n\n\ndb_drop_and_create_all()\n\n# ROUTES\n\n@app.route('/drinks', methods=['GET'])\ndef get_drinks():\n \n # Get all the drinks from db\n drinks = Drink.query.all()\n \n # Transform drink to short data representation\n return jsonify({\n 'success': True,\n 'drinks': [drink.short() for drink in drinks]\n }), 200\n\n\n@app.route('/drinks-detail', methods=['GET'])\n@requires_auth('get:drinks-detail')\ndef get_drinks_detail(payload):\n \n # Get all the drinks from db\n drinks = Drink.query.all()\n \n # Transform drink to long data representation\n return jsonify({\n 'success': True,\n 'drinks': [drink.long() for drink in drinks]\n }), 200\n \n \n@app.route('/drinks', methods=['POST'])\n@requires_auth('post:drinks')\ndef create_drink(payload):\n # get the body\n body = request.get_json()\n \n try:\n # create new drink\n drink = Drink()\n drink.title = body['title']\n \n # Convert recipe to string\n drink.recipe = json.dumps(body['recipe'])\n \n # insert the new drink\n drink.insert()\n \n except Exception:\n abort(400)\n \n return jsonify({\n 'success': True,\n 'drinks': [drink.long()]\n }), 200\n\n\n@app.route('/drinks/', methods=['PATCH'])\n@requires_auth('patch:drinks')\ndef update_drink(payload, id):\n # Get the body\n body = request.get_json()\n \n # Get the drink with requested id\n drink = Drink.query.filter(Drink.id == id).one_or_none()\n \n # if no drink with given id abort\n if not drink:\n abort(404)\n \n try:\n body_title = body.get('tittle')\n body_recipe = body.get('recipe')\n \n # check if the title is the one is updated\n if body_title:\n drink.title = body_title\n \n if body_recipe:\n drink.recipe = json.dumpd(body['recipe'])\n \n # update the drink\n drink.update()\n \n except Exception:\n abort(400)\n \n return jsonify({\n 'success': True,\n 'drinks': [drink.long()]\n }), 200\n\n\n@app.route('/drinks/', methods=['DELETE'])\n@requires_auth('delete:drinks')\ndef delete_drink(payload, id):\n # Get the drink with requested id\n drink = Drink.query.filter(Drink.id == id).one_or_none()\n \n # if no drink with given id abort\n if not drink:\n abort(404)\n \n try:\n # delete the drink\n drink.delete()\n except Exception:\n abort(400)\n \n return jsonify({\n 'success': True,\n 'deleted': id\n }), 200\n\n# Error Handling\n\n@app.errorhandler(422)\ndef unprocessable(error):\n return jsonify({\n \"success\": False,\n \"error\": 422,\n \"message\": \"unprocessable\"\n }), 422\n\n\n@app.errorhandler(404)\ndef not_found(error):\n return jsonify({\n \"success\": False,\n \"error\": 404,\n \"message\": \"resource not found\"\n }), 404\n \n \n@app.errorhandler(401)\ndef unathorized(error):\n return jsonify({\n \"success\": False,\n \"error\": 401,\n \"message\": \"unauthorized\"\n }), 401\n \n \n@app.errorhandler(500)\ndef internal_server_error(error):\n return jsonify({\n \"success\": False,\n \"error\": 500,\n \"message\": \"internal server errror\"\n }), 500\n \n \n@app.errorhandler(400)\ndef bad_request(error):\n return jsonify({\n \"success\": False,\n \"error\": 400,\n \"message\": \"bad request\"\n }), 400\n \n \n@app.errorhandler(405)\ndef method_not_allowed(error):\n return jsonify({\n \"success\": False,\n \"error\": 405,\n \"message\": \"method not allowed\"\n }), 405\n \n\n@app.errorhandler(AuthError)\ndef auth_error(error):\n return jsonify({\n 'success': False,\n 'error': 401,\n 'message': 'unauthorized'\n }), 401\n\nif __name__ == '__main__':\n app.debug = True\n app.run()", "repo_name": "belovetech/coffee_shop", "sub_path": "backend/src/api.py", "file_name": "api.py", "file_ext": "py", "file_size_in_byte": 4228, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "flask.Flask", "line_number": 10, "usage_type": "call"}, {"api_name": "database.models.setup_db", "line_number": 11, "usage_type": "call"}, {"api_name": "flask_cors.CORS", "line_number": 12, "usage_type": "call"}, {"api_name": "database.models.db_drop_and_create_all", "line_number": 15, "usage_type": "call"}, {"api_name": "database.models.Drink.query.all", "line_number": 23, "usage_type": "call"}, {"api_name": "database.models.Drink.query", "line_number": 23, "usage_type": "attribute"}, {"api_name": "database.models.Drink", "line_number": 23, "usage_type": "name"}, {"api_name": "flask.jsonify", "line_number": 26, "usage_type": "call"}, {"api_name": "database.models.Drink.query.all", "line_number": 37, "usage_type": "call"}, {"api_name": "database.models.Drink.query", "line_number": 37, "usage_type": "attribute"}, {"api_name": "database.models.Drink", "line_number": 37, "usage_type": "name"}, {"api_name": "flask.jsonify", "line_number": 40, "usage_type": "call"}, {"api_name": "auth.auth.requires_auth", "line_number": 33, "usage_type": "call"}, {"api_name": "flask.request.get_json", "line_number": 50, "usage_type": "call"}, {"api_name": "flask.request", "line_number": 50, "usage_type": "name"}, {"api_name": "database.models.Drink", "line_number": 54, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 58, "usage_type": "call"}, {"api_name": "flask.abort", "line_number": 64, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 66, "usage_type": "call"}, {"api_name": "auth.auth.requires_auth", "line_number": 47, "usage_type": "call"}, {"api_name": "flask.request.get_json", "line_number": 76, "usage_type": "call"}, {"api_name": "flask.request", "line_number": 76, "usage_type": "name"}, {"api_name": "database.models.Drink.query.filter", "line_number": 79, "usage_type": "call"}, {"api_name": "database.models.Drink.query", "line_number": 79, "usage_type": "attribute"}, {"api_name": "database.models.Drink", "line_number": 79, "usage_type": "name"}, {"api_name": "database.models.Drink.id", "line_number": 79, "usage_type": "attribute"}, {"api_name": "flask.abort", "line_number": 83, "usage_type": "call"}, {"api_name": "json.dumpd", "line_number": 94, "usage_type": "call"}, {"api_name": "flask.abort", "line_number": 100, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 102, "usage_type": "call"}, {"api_name": "auth.auth.requires_auth", "line_number": 73, "usage_type": "call"}, {"api_name": "database.models.Drink.query.filter", "line_number": 112, "usage_type": "call"}, {"api_name": "database.models.Drink.query", "line_number": 112, "usage_type": "attribute"}, {"api_name": "database.models.Drink", "line_number": 112, "usage_type": "name"}, {"api_name": "database.models.Drink.id", "line_number": 112, "usage_type": "attribute"}, {"api_name": "flask.abort", "line_number": 116, "usage_type": "call"}, {"api_name": "flask.abort", "line_number": 122, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 124, "usage_type": "call"}, {"api_name": "auth.auth.requires_auth", "line_number": 109, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 133, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 142, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 151, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 160, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 169, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 178, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 187, "usage_type": "call"}, {"api_name": "auth.auth.AuthError", "line_number": 185, "usage_type": "argument"}]} +{"seq_id": "27337784441", "text": "import psycopg2\nimport psycopg2.extras\nimport logging\nimport sys\nimport os\n\nfrom app.lib.util import setup_logger\ndebug_logger = setup_logger('debug', 'tmp/app_info.log', logging.DEBUG)\napp_logger = setup_logger('info', 'tmp/app_info.log', logging.INFO)\n\nclass Timescale:\n def __init__(self):\n pass\n\n def connect(self, connection):\n try:\n keepalive_kwargs = {\n \"keepalives\": 1,\n \"keepalives_idle\": 30,\n \"keepalives_interval\": 5,\n \"keepalives_count\": 5,\n }\n self.connection = psycopg2.connect(connection, **keepalive_kwargs)\n self.connection.set_session(readonly=False)\n return 'ok'\n except Exception as ex:\n app_logger.error(ex)\n return str(ex)\n\n def disconnect(self):\n try:\n self.connection.close()\n self.connection = None\n except Exception as ex:\n app_logger.error(ex)\n return 'ok'\n\n def update(self, query, commit=True):\n try:\n if query is not None:\n cur = self.connection.cursor()\n cur.execute(query)\n if commit:\n self.connection.commit()\n cur.close()\n return \"ok\"\n except Exception as ex:\n app_logger.error(ex)\n return str(ex)\n", "repo_name": "terry-flander/forms-working", "sub_path": "app/lib/update_db.py", "file_name": "update_db.py", "file_ext": "py", "file_size_in_byte": 1389, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "app.lib.util.setup_logger", "line_number": 8, "usage_type": "call"}, {"api_name": "logging.DEBUG", "line_number": 8, "usage_type": "attribute"}, {"api_name": "app.lib.util.setup_logger", "line_number": 9, "usage_type": "call"}, {"api_name": "logging.INFO", "line_number": 9, "usage_type": "attribute"}, {"api_name": "psycopg2.connect", "line_number": 23, "usage_type": "call"}]} +{"seq_id": "37335199124", "text": "import pandas as pd\r\nimport numpy as np\r\nimport ast\r\nfrom sklearn.feature_extraction.text import CountVectorizer\r\nfrom nltk.stem.porter import PorterStemmer\r\nfrom sklearn.metrics.pairwise import cosine_similarity\r\nimport streamlit as st\r\nimport requests\r\n\r\n\r\nst.set_page_config(\r\n page_title=\"Movie Recommendation System\",\r\n page_icon=\":movie_camera:\",\r\n layout=\"wide\",\r\n initial_sidebar_state=\"collapsed\",\r\n)\r\n@st.cache(suppress_st_warning=True)\r\ndef set_custom_style():\r\n st.markdown(\r\n \"\"\"\r\n \r\n \"\"\",\r\n unsafe_allow_html=True\r\n )\r\n\r\n\r\nmovies = pd.read_csv('tmdb_5000_movies.csv')\r\ncredits=pd.read_csv('tmdb_5000_credits.csv')\r\n\r\nmovies = movies.merge(credits)\r\n\r\nmovies =movies[['movie_id','title','overview','genres','keywords','cast','crew']]\r\n\r\nmovies.dropna(inplace=True)\r\n#print(movies.duplicated().sum)\r\n#print(movies.iloc[0].genres)\r\n\r\ndef convert(obj):\r\n L=[]\r\n for i in ast.literal_eval(obj):\r\n L.append(i['name'])\r\n return L\r\n\r\ndef convert3(obj):\r\n L=[]\r\n counter=0\r\n for i in ast.literal_eval(obj):\r\n if counter!=3:\r\n L.append(i['name'])\r\n counter+=1\r\n else:\r\n break\r\n return L\r\n\r\n\r\ndef fetch_director(obj):\r\n L=[]\r\n for i in ast.literal_eval(obj):\r\n if i['job'] =='Director':\r\n L.append(i['name'])\r\n break\r\n return L\r\n\r\nmovies['genres'] =movies['genres'].apply(convert)\r\nmovies['keywords'] =movies['keywords'].apply(convert)\r\nmovies['cast'] =movies['cast'].apply(convert3)\r\nmovies['crew'] =movies['crew'].apply(fetch_director)\r\n\r\nmovies['overview']=movies['overview'].apply(lambda x:x.split())\r\n\r\nmovies['genres']=movies['genres'].apply(lambda x:[i.replace(\" \",\"\") for i in x])\r\nmovies['cast']=movies['cast'].apply(lambda x:[i.replace(\" \",\"\") for i in x])\r\nmovies['crew']=movies['crew'].apply(lambda x:[i.replace(\" \",\"\") for i in x])\r\nmovies['keywords']=movies['keywords'].apply(lambda x:[i.replace(\" \",\"\") for i in x])\r\n\r\n\r\nmovies['tags']= movies['overview']+movies['genres']+movies['cast']+movies['crew']\r\n\r\nnewdf= movies[['movie_id','title','tags']]\r\n\r\nnewdf['tags'] =newdf['tags'].apply(lambda x:\" \".join(x))\r\nnewdf['tags'] =newdf['tags'].apply(lambda x:x.lower())\r\ncv=CountVectorizer(max_features=5000,stop_words='english')\r\nvectors= cv.fit_transform(newdf['tags']).toarray()\r\n\r\nps= PorterStemmer()\r\ndef stem(text):\r\n y=[];\r\n for i in text.split():\r\n y.append(ps.stem(i))\r\n return \" \".join(y)\r\n\r\nnewdf[\"tags\"]=newdf['tags'].apply(stem)\r\n\r\nsimilarty= cosine_similarity(vectors)\r\n\r\ndef recommend(movie):\r\n movieIndex= newdf[newdf['title'] == movie].index[0]\r\n distances=similarty[movieIndex]\r\n movieList=sorted(list(enumerate(distances)),reverse=True,key=lambda x:x[1])[1:6]\r\n\r\n for i in movieList:\r\n print(newdf.iloc[i[0]].title)\r\n\r\ndef recommender(movie):\r\n recommendedMovies = []\r\n recommendedMoviesPosters = []\r\n movieIndex = newdf[newdf['title'] == movie].index[0]\r\n distances = similarty[movieIndex]\r\n\r\n movieList = sorted(list(enumerate(distances)), reverse=True, key=lambda x: x[1])[1:6]\r\n\r\n for i in movieList:\r\n movieID = movies.iloc[i[0]].movie_id\r\n recommendedMovie = newdf.iloc[i[0]].title\r\n poster = fetchposter(movieID)\r\n if poster:\r\n recommendedMovies.append(recommendedMovie)\r\n recommendedMoviesPosters.append(poster)\r\n\r\n return recommendedMovies, recommendedMoviesPosters\r\n\r\ndef fetchposter(movieID):\r\n response = requests.get('https://api.themoviedb.org/3/movie/{}?api_key=3758d25981c51d1e42e96b57e9b02e82&language=en-US'.format(movieID))\r\n data = response.json()\r\n if 'poster_path' in data and data['poster_path']:\r\n full_path = \"https://image.tmdb.org/t/p/w500/\" + data['poster_path']\r\n return full_path\r\n else:\r\n return None\r\n\r\n\r\nst.title('Movie Recommendation System')\r\nSelectedMovieName = st.selectbox('What would you like to watch?', newdf['title'].values)\r\n\r\nif st.button('Find Similar Movies'):\r\n columns = st.columns(5)\r\n names, posters = recommender(SelectedMovieName)\r\n\r\n if len(names) >= 5 and len(posters) >= 5:\r\n with columns[0]:\r\n st.text(names[0])\r\n st.image(posters[0], width=200)\r\n with columns[1]:\r\n st.text(names[1])\r\n st.image(posters[1], width=200)\r\n with columns[2]:\r\n st.text(names[2])\r\n st.image(posters[2], width=200)\r\n with columns[3]:\r\n st.text(names[3])\r\n st.image(posters[3], width=200)\r\n with columns[4]:\r\n st.text(names[4])\r\n st.image(posters[4], width=200)\r\n else:\r\n st.warning(\"Not enough similar movies found.\")", "repo_name": "AinabKazi/Codesoft", "sub_path": "main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 4839, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "streamlit.set_page_config", "line_number": 11, "usage_type": "call"}, {"api_name": "streamlit.markdown", "line_number": 19, "usage_type": "call"}, {"api_name": "streamlit.cache", "line_number": 17, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 32, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 33, "usage_type": "call"}, {"api_name": "ast.literal_eval", "line_number": 45, "usage_type": "call"}, {"api_name": "ast.literal_eval", "line_number": 52, "usage_type": "call"}, {"api_name": "ast.literal_eval", "line_number": 63, "usage_type": "call"}, {"api_name": "sklearn.feature_extraction.text.CountVectorizer", "line_number": 88, "usage_type": "call"}, {"api_name": "nltk.stem.porter.PorterStemmer", "line_number": 91, "usage_type": "call"}, {"api_name": "sklearn.metrics.pairwise.cosine_similarity", "line_number": 100, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 129, "usage_type": "call"}, {"api_name": "streamlit.title", "line_number": 138, "usage_type": "call"}, {"api_name": "streamlit.selectbox", "line_number": 139, "usage_type": "call"}, {"api_name": "streamlit.button", "line_number": 141, "usage_type": "call"}, {"api_name": "streamlit.columns", "line_number": 142, "usage_type": "call"}, {"api_name": "streamlit.text", "line_number": 147, "usage_type": "call"}, {"api_name": "streamlit.image", "line_number": 148, "usage_type": "call"}, {"api_name": "streamlit.text", "line_number": 150, "usage_type": "call"}, {"api_name": "streamlit.image", "line_number": 151, "usage_type": "call"}, {"api_name": "streamlit.text", "line_number": 153, "usage_type": "call"}, {"api_name": "streamlit.image", "line_number": 154, "usage_type": "call"}, {"api_name": "streamlit.text", "line_number": 156, "usage_type": "call"}, {"api_name": "streamlit.image", "line_number": 157, "usage_type": "call"}, {"api_name": "streamlit.text", "line_number": 159, "usage_type": "call"}, {"api_name": "streamlit.image", "line_number": 160, "usage_type": "call"}, {"api_name": "streamlit.warning", "line_number": 162, "usage_type": "call"}]} +{"seq_id": "1855624264", "text": "import cv2\nimport math\n\nimg = cv2.imread('angle1.png')\nimg_gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\npointlist=[]\n\ndef mouse_clicks(event,x,y,flags,params):\n if event == cv2.EVENT_LBUTTONDBLCLK:\n cv2.circle(img,(x,y),2,(255,0,0),3)\n pointlist.append([x,y])\n print(pointlist)\n if len(pointlist)%3==0:\n print(\"HELLO \")\n getAngle()\ndef getAngle():\n a = pointlist[-1]\n b = pointlist[-2]\n c = pointlist[-3]\n try : \n m1 = (b[1]-a[1])/(b[0]-a[0])\n m2 = (c[1]-b[1])/(c[0]-b[0])\n \n m12 = (m1-m2)/(1+m1*m2)\n angle = round(math.degrees(math.atan(m12)),1)\n if angle < 0 :\n angle = 180+angle\n except Exception as e :\n print(e)\n angle = \"undefined\"\n cv2.line(img,(a[0],a[1]),(b[0],b[1]),(255,0,0),4)\n cv2.line(img,(c[0],c[1]),(b[0],b[1]),(255,0,0),4)\n cv2.putText(img,str(angle)+\" degree\",(b[0]+20,b[1]-7),cv2.FONT_HERSHEY_COMPLEX,1,(0,255,0),2)\ndef absoluteValue(i):\n if i < 0 :\n return -i\n return i\nwhile True:\n cv2.imshow(\"Image\",img)\n cv2.setMouseCallback(\"Image\",mouse_clicks)\n k = cv2.waitKey(1) & 0xFF\n if k == 27 :\n break\n if cv2.waitKey(1) & 0xFF == ord('q'):\n pointlist=[]\n img = cv2.imread('angle1.png') \ncv2.destroyAllWindows()", "repo_name": "tanmoysrt/Opencv-Projects", "sub_path": "angle.py", "file_name": "angle.py", "file_ext": "py", "file_size_in_byte": 1320, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "21", "api": [{"api_name": "cv2.imread", "line_number": 4, "usage_type": "call"}, {"api_name": "cv2.cvtColor", "line_number": 5, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2GRAY", "line_number": 5, "usage_type": "attribute"}, {"api_name": "cv2.EVENT_LBUTTONDBLCLK", "line_number": 9, "usage_type": "attribute"}, {"api_name": "cv2.circle", "line_number": 10, "usage_type": "call"}, {"api_name": "math.degrees", "line_number": 25, "usage_type": "call"}, {"api_name": "math.atan", "line_number": 25, "usage_type": "call"}, {"api_name": "cv2.line", "line_number": 31, "usage_type": "call"}, {"api_name": "cv2.line", "line_number": 32, "usage_type": "call"}, {"api_name": "cv2.putText", "line_number": 33, "usage_type": "call"}, {"api_name": "cv2.FONT_HERSHEY_COMPLEX", "line_number": 33, "usage_type": "attribute"}, {"api_name": "cv2.imshow", "line_number": 39, "usage_type": "call"}, {"api_name": "cv2.setMouseCallback", "line_number": 40, "usage_type": "call"}, {"api_name": "cv2.waitKey", "line_number": 41, "usage_type": "call"}, {"api_name": "cv2.waitKey", "line_number": 44, "usage_type": "call"}, {"api_name": "cv2.imread", "line_number": 46, "usage_type": "call"}, {"api_name": "cv2.destroyAllWindows", "line_number": 47, "usage_type": "call"}]} +{"seq_id": "71605304373", "text": "from flet import *\nimport flet as ft\n\n\n# def main(page: Page):\n# \"\"\"Page Route\"\"\"\n# page.add(Text(f\"Inital route: {page.route}\"))\n\n# def route_change(route):\n# page.add(Text(f\"New route: {route}\"))\n\n# page.on_route_change = route_change\n# page.update()\n\n\"\"\"Route can be changed programmatically, by updating page.route property:\"\"\"\n#\n# def main(page: Page):\n# page.add(Text(f\"Initial route: {page.route}\"))\n\n# def route_change(route):\n# page.add(Text(f\"New route: {route}\"))\n\n# def go_store(e):\n# page.route = \"/store\"\n# page.update()\n\n# page.on_route_change = route_change\n# page.add(ElevatedButton(\"Go to store\", on_click=go_store))\n\n\n\"\"\"Building views on route change\"\"\"\n#\ndef main(page: Page):\n page.title = \"Route Example\"\n\n def route_change(route):\n page.views.clear()\n page.views.append(\n View(\n \"/\",\n [\n AppBar(title=Text(\"Flet app\"), bgcolor=colors.SURFACE_VARIANT),\n ElevatedButton(\"Visit Sotre\", on_click=lambda _: page.go(\"/store\")),\n ],\n )\n )\n if page.route == \"/store\":\n page.views.append(\n View(\n \"/store\",\n [\n AppBar(title=Text(\"Store\"), bgcolor=colors.SURFACE_VARIANT),\n ElevatedButton(\"Go Gome\", on_click=lambda _: page.go(\"/\")),\n ],\n )\n )\n page.update()\n\n def view_pop(view):\n page.views.pop()\n top_view = page.views[-1]\n page.go(top_view.route)\n\n page.on_route_change = route_change\n page.on_view_pop = view_pop\n page.go(page.route)\n # troute = TemplateRoute(page.route)\n\n # if troute.match(\"/books/:id\"):\n # print(\"Book view ID:\", troute.id)\n # elif troute.match(\"/account/:account_id/orders/:order_id\"):\n # print(\"Account:\", troute.account_id, \"Order:\", troute.order_id)\n # else:\n # print(\"Unknown route\")\n\n\nft.app(target=main, view=WEB_BROWSER)\n", "repo_name": "ariefendi992/flet-tutorial", "sub_path": "navigation_and_route.py", "file_name": "navigation_and_route.py", "file_ext": "py", "file_size_in_byte": 2107, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "flet.app", "line_number": 77, "usage_type": "call"}]} +{"seq_id": "31783604025", "text": "import logging\n\nfrom homeassistant.components.alarm_control_panel import (\n SUPPORT_ALARM_ARM_AWAY,\n SUPPORT_ALARM_ARM_HOME,\n SUPPORT_ALARM_ARM_NIGHT,\n AlarmControlPanelEntity,\n)\nfrom homeassistant.const import (\n STATE_ALARM_ARMED_AWAY,\n STATE_ALARM_ARMED_HOME,\n STATE_ALARM_ARMED_NIGHT,\n STATE_ALARM_DISARMED,\n)\n\nfrom . import Gateway3Device\nfrom .core.gateway3 import Gateway3\nfrom .core.utils import DOMAIN\n\n_LOGGER = logging.getLogger(__name__)\n\nALARM_STATES = [STATE_ALARM_DISARMED, STATE_ALARM_ARMED_HOME,\n STATE_ALARM_ARMED_AWAY, STATE_ALARM_ARMED_NIGHT]\n\n\nasync def async_setup_entry(hass, config_entry, async_add_entities):\n def setup(gateway: Gateway3, device: dict, attr: str):\n async_add_entities([Gateway3Alarm(gateway, device, attr)], True)\n\n gw: Gateway3 = hass.data[DOMAIN][config_entry.entry_id]\n gw.add_setup('alarm_control_panel', setup)\n\n\nasync def async_unload_entry(hass, entry):\n return True\n\n\nclass Gateway3Alarm(Gateway3Device, AlarmControlPanelEntity):\n @property\n def miio_did(self):\n return self.device['init']['alarm_did']\n\n @property\n def should_poll(self):\n return True\n\n @property\n def state(self):\n return self._state\n\n @property\n def icon(self):\n return \"mdi:shield-home\"\n\n @property\n def supported_features(self):\n return (SUPPORT_ALARM_ARM_HOME | SUPPORT_ALARM_ARM_AWAY |\n SUPPORT_ALARM_ARM_NIGHT)\n\n @property\n def code_arm_required(self):\n return False\n\n async def async_added_to_hass(self):\n pass\n\n async def async_will_remove_from_hass(self) -> None:\n pass\n\n def alarm_disarm(self, code=None):\n self.gw.miio.send('set_properties', [{\n 'did': self.miio_did, 'siid': 3, 'piid': 1, 'value': 0\n }])\n\n def alarm_arm_home(self, code=None):\n self.gw.miio.send('set_properties', [{\n 'did': self.miio_did, 'siid': 3, 'piid': 1, 'value': 1\n }])\n\n def alarm_arm_away(self, code=None):\n self.gw.miio.send('set_properties', [{\n 'did': self.miio_did, 'siid': 3, 'piid': 1, 'value': 2\n }])\n\n def alarm_arm_night(self, code=None):\n self.gw.miio.send('set_properties', [{\n 'did': self.miio_did, 'siid': 3, 'piid': 1, 'value': 3\n }])\n\n def update(self, *args):\n try:\n resp = self.gw.miio.send('get_properties', [{\n 'did': self.miio_did, 'siid': 3, 'piid': 1\n }])\n state = resp[0]['value']\n self._state = ALARM_STATES[state]\n except:\n pass\n", "repo_name": "kvazis/homeassistant", "sub_path": "custom_components/xiaomi_gateway3/alarm_control_panel.py", "file_name": "alarm_control_panel.py", "file_ext": "py", "file_size_in_byte": 2631, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 259, "dataset": "github-code", "pt": "21", "api": [{"api_name": "logging.getLogger", "line_number": 20, "usage_type": "call"}, {"api_name": "homeassistant.const.STATE_ALARM_DISARMED", "line_number": 22, "usage_type": "name"}, {"api_name": "homeassistant.const.STATE_ALARM_ARMED_HOME", "line_number": 22, "usage_type": "name"}, {"api_name": "homeassistant.const.STATE_ALARM_ARMED_AWAY", "line_number": 23, "usage_type": "name"}, {"api_name": "homeassistant.const.STATE_ALARM_ARMED_NIGHT", "line_number": 23, "usage_type": "name"}, {"api_name": "core.gateway3.Gateway3", "line_number": 27, "usage_type": "name"}, {"api_name": "core.gateway3.Gateway3", "line_number": 30, "usage_type": "name"}, {"api_name": "core.utils.DOMAIN", "line_number": 30, "usage_type": "name"}, {"api_name": "homeassistant.components.alarm_control_panel.AlarmControlPanelEntity", "line_number": 38, "usage_type": "name"}, {"api_name": "homeassistant.components.alarm_control_panel.SUPPORT_ALARM_ARM_HOME", "line_number": 57, "usage_type": "name"}, {"api_name": "homeassistant.components.alarm_control_panel.SUPPORT_ALARM_ARM_AWAY", "line_number": 57, "usage_type": "name"}, {"api_name": "homeassistant.components.alarm_control_panel.SUPPORT_ALARM_ARM_NIGHT", "line_number": 58, "usage_type": "name"}]} +{"seq_id": "10176552849", "text": "from django.shortcuts import redirect, render\nfrom django.utils.crypto import get_random_string\n\ndef index(request):\n return render(request, \"index.html\")\n\ndef random(request):\n word = get_random_string(length=14) # call imported method to assign variable\n\n if \"counter\" not in request.session: # if the request.session is empty, then set that \"key\" to 0\n request.session[\"counter\"] = 0\n\n request.session[\"counter\"] +=1 # bump the value +=1 each time method is called\n\n if \"word_list\" not in request.session: # if the request.session is empty, then create list\n request.session[\"word_list\"] = []\n\n request.session['random_word'] = word # assign the variable into the session\n request.session[\"word_list\"].append(word) # append the variable into the list\n\n\n return redirect(\"/\") # send the user on to the root route\n\ndef reset(request):\n request.session.flush() # flush the session variables on reset\n\n return redirect('/')\n\n\n# Create your views here.\n", "repo_name": "RianGirard/django_random_word", "sub_path": "rand_wordapp/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 1079, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "django.shortcuts.render", "line_number": 5, "usage_type": "call"}, {"api_name": "django.utils.crypto.get_random_string", "line_number": 8, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 22, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 27, "usage_type": "call"}]} +{"seq_id": "70186377332", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nimport rospy\nimport serial.tools.list_ports\nimport serial\nimport time\nimport math\n#import threading\nimport struct\nfrom binascii import unhexlify\n#from crcmod import mkCrcFun\nimport binascii\nimport crcmod\n#crcmod.pash.append(\"/usr/local/lib/python3.6/site-packages\")\n\nmotor_speed_mode = b'\\x01\\x2F\\x60\\x60\\x00\\x03\\x00\\x00\\x00\\x0D'\n#motor_status = b'\\x01\\x43\\x50\\x00\\x51\\x00\\x68\\x95'\nmotor_start = b'\\x01\\x44\\x21\\x00\\x31\\x00\\x00\\x01\\x00\\x01\\x75\\x34'\nmotor_stop = b'\\x01\\x44\\x21\\x00\\x31\\x00\\x00\\x00\\x00\\x00\\xE5\\x34' # AB轴失能\n\n\ndef check_code(byte0, byte1, speed_vel, speed_ang):\n '计算校验码时需要输入的字节'\n read = byte0+byte1+speed_vel+speed_ang #解析校验码要输入的前几位\n read=(str(binascii.b2a_hex(read))[2:-1])\n #print (read)\n return(read)\n\ndef crc16_modbus(read):\n '输出的控制电机指令字节码'\n crc16 =crcmod.mkCrcFun(0x18005, rev=True, initCrc=0xFFFF, xorOut=0x0000)\n data = read.replace(\" \",\"\")\n #print (data)\n readcrcout=hex(crc16(unhexlify(data))).upper()\n str_list = list(readcrcout)\n if len(str_list) < 6:\n str_list.insert(2, '0'*(6-len(str_list))) # 位数不足补0\n crc_data = \"\".join(str_list)\n #print(crc_data)\n read = read.strip()+crc_data[4:]+crc_data[2:4]\n read = bytes.fromhex(read)\n #print(read)\n return (read)\n\ndef motor_speed_vel(speed_v):\n '计算小车线速度speed_v'\n DEC1 = (speed_v )\n byte2 =(struct.pack(\"i\",DEC1)[-4:-3])#线速度\n byte3 =(struct.pack(\"i\",DEC1)[-3:-2])#线速度\n speed_vel = byte2 + byte3\n return (speed_vel)\ndef motor_speed_ang(speed_a):\n '小车角速度speed_a'\n DEC2 = (speed_a)\n byte4 = (struct.pack(\"i\",DEC2)[-4:-3]) #角速度两个字节\n byte5 = (struct.pack(\"i\",DEC2)[-3:-2])\n speed_ang = byte4+byte5\n return (speed_ang)\n#motor_speed_vel(200,20)\n\nclass SpeedMotor:\n def __init__(self, device, speed_v, speed_a):\n # 真实速度\n self.rel_speed = 0\n # 设置的速度\n self.set_speed1 = (speed_v)\n # 设置角速度\n self.set_speed2 = (speed_a)\n # 运行状态\n self.run = False\n # 故障状态\n self.fault = None\n # 电机电压\n self.voltage = 0\n # 电机电流\n self.current = 0\n # 设置串口通讯\n self.serial = serial.Serial(device, 115200)\n self.serial.timeout = 0\n # 设置为速度模式\n self.serial.write(motor_speed_mode)\n time.sleep(0.1)\n # 设置加减速度\n # self.serial.write(b'\\x0A\\x14\\x14\\x32')\n # time.sleep(0.1)\n\n def motor_speed_set(self):\n '速度设置'\n byte0 = b'\\x01'\n byte1 = b'\\xEA'\n speed_vel = motor_speed_vel(self.set_speed1)\n speed_ang = motor_speed_ang(self.set_speed2) \n read = check_code(byte0, byte1, speed_vel, speed_ang)\n read = crc16_modbus(read)\n speed_code = read\n self.serial.write(speed_code)\n\n def motor_start(self):\n '启动'\n self.serial.write(motor_start)\n self.run = True\n def motor_stop(self):\n '停止'\n self.run = False\n self.serial.write(motor_stop)\n\n#m = SpeedMotor('COM5', 0.4, 0.2) #这里要改成nano对应的USB2口,如果插电脑测试就是COM3\nm = SpeedMotor('/dev/ttyS0', 100, 20)\nm.motor_start()\nmotor_speed_vel(100)\nmotor_speed_ang(20)\nm.motor_speed_set()\ntime.sleep(5)\nm.motor_stop()\n\n\n", "repo_name": "XieWup/test_robot_ros_package", "sub_path": "motor-ctrl/scripts/motor001.py", "file_name": "motor001.py", "file_ext": "py", "file_size_in_byte": 3506, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "21", "api": [{"api_name": "binascii.b2a_hex", "line_number": 25, "usage_type": "call"}, {"api_name": "crcmod.mkCrcFun", "line_number": 31, "usage_type": "call"}, {"api_name": "binascii.unhexlify", "line_number": 34, "usage_type": "call"}, {"api_name": "struct.pack", "line_number": 48, "usage_type": "call"}, {"api_name": "struct.pack", "line_number": 49, "usage_type": "call"}, {"api_name": "struct.pack", "line_number": 55, "usage_type": "call"}, {"api_name": "struct.pack", "line_number": 56, "usage_type": "call"}, {"api_name": "serial.Serial", "line_number": 78, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 82, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 113, "usage_type": "call"}]} +{"seq_id": "17979459967", "text": "import PyPDF2\nimport re\n\ndef extract_pdf(pdf_file: str) -> [str]:\n try:\n with open(pdf_file, 'rb') as pdf:\n reader = PyPDF2.PdfReader(pdf, strict=False)\n pdf_text = []\n\n for page in reader.pages:\n content = page.extract_text()\n pdf_text.append(content)\n\n return pdf_text\n except FileNotFoundError:\n print(f\"Error: The file '{pdf_file}' was not found.\")\n except Exception as e:\n print(f\"An error occurred: {str(e)}\")\n\ndef print_words_starting_with_specific_words(text):\n pattern = r'(\\d{3})\\s+(SE111\\w*|SE112\\w*|AOL\\w*|MAT\\w*)'\n matches = re.findall(pattern, text, flags=re.IGNORECASE)\n\n if matches:\n for match in matches:\n number, word = match\n print(f\"Class:{number}, Sub:{word}\")\n\nif __name__ == '__main__':\n extracted = extract_pdf('target.pdf')\n if extracted:\n for text in extracted:\n print_words_starting_with_specific_words(text)\n", "repo_name": "imransihab0/pdf_extracting_diu", "sub_path": "main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 1002, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "21", "api": [{"api_name": "PyPDF2.PdfReader", "line_number": 7, "usage_type": "call"}, {"api_name": "re.findall", "line_number": 22, "usage_type": "call"}, {"api_name": "re.IGNORECASE", "line_number": 22, "usage_type": "attribute"}]} +{"seq_id": "70711907252", "text": "#!/usr/bin/env python\nimport ast\nimport datetime\nimport os\nimport time\nfrom abc import ABC, abstractmethod\nfrom itertools import combinations, product\nfrom string import digits\n\nfrom neo4j import GraphDatabase\nfrom py_stringmatching import Cosine\nfrom tqdm import tqdm\n\nuri = 'bolt://localhost:7687'\nuser = 'neo4j'\npw = os.environ['NEO4JPW']\n\ncosine_sim = Cosine().get_sim_score\n\n# attributes that need to be converted from strings\nkey_to_type = {\n 'id': int,\n 'price': int,\n 'size': int,\n 'bed': float,\n 'bath': float, # zillow doesn't seem to use 'half' bathrooms but we allow it.\n}\n\n\n# for debugging purposes\ndef getobj(iterable, input_id):\n try:\n for obj in iterable:\n if obj.id == input_id:\n return obj\n except:\n pass\n return None\n\n\n# Returns a value from 0 to 1 depending on how similar the numeric inputs\n# are to each other.\n#\n# Note that this is designed so that num_sim(a,b,c) == num_sim(b,a,c)\n#\n# Take the example where:\n# ratio = .3\n# base_val = 100,000\n#\n# Then if \"comp_val\" has a price within 70,000 and 130,000, a value > 0 will be\n# returned. 100,000 would be a perfect match and would return 1.\n#\ndef num_sim(base_val, comp_val, ratio):\n diff = min(abs(base_val - comp_val) / ((base_val + comp_val) / 2), ratio)\n return (ratio - diff) / ratio\n\n\nclass PropertyContainer(ABC):\n def __init__(self, info):\n self.print_keys = []\n\n for k, v in info.items():\n # Convert neo4j string to something we want to use ex: 'p.price' -> 'price'\n actual_key = k.split('.')[1] if '.' in k else k\n self.print_keys.append(actual_key)\n\n if actual_key in key_to_type:\n if v is None:\n self[actual_key] = None\n else:\n self[actual_key] = key_to_type[actual_key](v)\n elif actual_key == 'neighborhood' and isinstance(v, str):\n # ex: \"['San Diego']\"\n self[actual_key] = ast.literal_eval(v)\n else:\n self[actual_key] = v\n\n # Convert neighborhood to set\n try:\n self.neighborhood_set = set(self.neighborhood)\n except TypeError:\n self.neighborhood_set = set()\n\n def __str__(self):\n return f'{dict(((k, self[k]) for k in self.print_keys))}'\n\n def __getitem__(self, key):\n return self.__getattribute__(key)\n\n def __setitem__(self, key, value):\n return self.__setattr__(key, value)\n\n @abstractmethod\n def compare(self, other):\n pass\n\n\n# zillow property from graph\nclass ZPFG(PropertyContainer):\n data_source = 'zillow'\n node_name = 'Property'\n\n def __init__(self, info):\n super().__init__(info)\n\n # Remove digits from street\n self.stripped_street = self.street.translate({ord(d): None for d in digits})\n\n def compare(self, other):\n if isinstance(other, ZPFG):\n return self.zillowCompare(other)\n else:\n return self.airbnbCompare(other)\n\n # This is called in an NxN fashion but only ~half of the of calls will do\n # anything since comparisons are symmetric.\n def zillowCompare(self, other):\n score = 0\n\n # Price is most important factor; it sums up other attributes.\n if all((self.price, other.price)):\n score += 0.5 * num_sim(self.price, other.price, 0.3)\n\n # Comparing addresses is the most costly comparison and is therefore\n # currently designed for simplicity and speed.\n #\n # Possible modifications could be done here given more time:\n # - Since street names aren't unique, we could validate using gps coordinates\n # - Use an edit distance metric to compare street names in a more robust fashion\n # - Make the comparison aware of abbreviations such as 'street' -> 'st' or\n # 'avenue' -> 'ave'.\n if self.stripped_street == other.stripped_street:\n score += 0.2\n\n # Compare beds and baths\n if all((self.bed, other.bed)):\n score += 0.1 * num_sim(self.bed, other.bed, 0.5)\n\n if all((self.bath, other.bath)):\n score += 0.1 * num_sim(self.bath, other.bath, 0.5)\n\n # Compare square footage\n if all((self.size, other.size)):\n score += 0.1 * num_sim(self.size, other.size, 0.3)\n\n return score\n\n def airbnbCompare(self, other):\n score = 0\n\n # Compare beds and baths\n if all((self.bed, other.bed)):\n score += 1 / 3 * num_sim(self.bed, other.bed, 0.5)\n\n if all((self.bath, other.bath)):\n score += 1 / 3 * num_sim(self.bath, other.bath, 0.5)\n\n # Compare neighborhoods or city\n if len(self.neighborhood_set) > 0 and len(other.neighborhood_set) > 0:\n score += 1 / 3 * cosine_sim(self.neighborhood_set, other.neighborhood_set)\n elif self.city == other.city:\n score += 1 / 3\n\n return score\n\n\n# Container for airbnb data\nclass APFG(PropertyContainer):\n data_source = 'airbnb'\n node_name = 'Rental'\n\n def compare(self, other):\n if isinstance(other, APFG):\n return self.airbnbCompare(other)\n else:\n return other.airbnbCompare(self)\n\n def airbnbCompare(self, other):\n score = 0\n\n # Compare beds and baths\n if all((self.bed, other.bed)):\n score += 0.25 * num_sim(self.bed, other.bed, 0.5)\n\n if all((self.bath, other.bath)):\n score += 0.25 * num_sim(self.bath, other.bath, 0.5)\n\n # Compare neighborhoods or city\n if len(self.neighborhood_set) > 0 and len(other.neighborhood_set) > 0:\n score += 0.3 * cosine_sim(self.neighborhood_set, other.neighborhood_set)\n elif self.city == other.city:\n score += 0.3\n\n # Compare property type\n if self.type_id == other.type_id:\n score += 0.1\n\n # Compare amenity IDs\n score += 0.05 * cosine_sim(self.amenity_ids, other.amenity_ids)\n\n # Compare amenity names (subset of amenity IDs)\n score += 0.05 * cosine_sim(self.amenity_names, other.amenity_names)\n\n return score\n\n\n# Link similar properties together in the db.\n#\n# Note that Neo4j does not support creating undirected edges. Therefore we\n# end up creating both incoming and outgoing (directed) relationships between\n# \"similar\" nodes.\ndef connect_nodes(driver, pairs, threshold):\n pairs = list(pairs)\n relation = f'{pairs[0][0].data_source} <--> {pairs[0][1].data_source} relationships'\n count = 0\n\n print(f'Creating {relation}')\n\n with driver.session() as session:\n for p1, p2 in tqdm(pairs):\n score = p1.compare(p2) # compare properties\n\n # create relationship\n if score >= threshold:\n is_similar = f'[:Is_Similar {{score: {score}}}]'\n query = f'''MATCH (n1:{p1.node_name}), (n2:{p2.node_name})\n WHERE n1.id = {p1.id} AND n2.id = {p2.id}\n CREATE (n1)-{is_similar}->(n2), (n2)-{is_similar}->(n1)'''\n _ = session.run(query)\n count += 2\n\n total = len(pairs)\n pct = count / total * 100\n print(f'{count} new {relation} (total={total}, {pct:.2f}%)')\n\n\ndef zillowZillowConnect(driver):\n # Get data from db\n print('Fetching zillow data')\n\n with driver.session() as session:\n query = '''\n MATCH (p:Property)-[:Located_In]->(c:City)\n OPTIONAL MATCH (p)-[:Located_In]->(n:Neighborhood)\n RETURN p.id, p.price, p.street, p.size, p.bed, p.bath,\n c.name AS city,\n collect(n.name) AS neighborhood\n '''\n results = session.run(query)\n zillow_props = [ZPFG(r) for r in results]\n\n # Do all comparisons and add relationships\n threshold = 0.7\n connect_nodes(driver, combinations(zillow_props, 2), threshold)\n\n return zillow_props\n\n\ndef zillowAirbnbConnect(driver, zillow_props):\n # Get data from db\n print('Fetching airbnb data')\n\n with driver.session() as session:\n query = '''\n MATCH (r:Rental)-[:Located_In]->(c:City)\n OPTIONAL MATCH (r)-[:Located_In]->(n:Neighborhood)\n RETURN r.id, r.bed, r.bath, r.type_id, r.amenity_ids, r.amenity_names,\n c.name AS city,\n collect(n.name) AS neighborhood\n '''\n results = session.run(query)\n airbnb_props = [APFG(r) for r in results]\n\n # Do all airbnb comparisons and add relationships\n threshold = 0.98\n connect_nodes(driver, combinations(airbnb_props, 2), threshold)\n\n # Do all zillow comparisons and add relationships\n threshold = 0.95\n connect_nodes(driver, product(zillow_props, airbnb_props), threshold)\n\n return airbnb_props\n\n\nif __name__ == '__main__':\n start = time.time()\n driver = GraphDatabase.driver(uri, auth=(user, pw))\n\n # This could be removed if MERGE is used instead of CREATE, but I believe that\n # would be slower.\n with driver.session() as session:\n query = 'MATCH ()-[r:Is_Similar]-() DELETE r;'\n _ = session.run(query)\n\n zillow_props = zillowZillowConnect(driver)\n airbnb_props = zillowAirbnbConnect(driver, zillow_props)\n\n print(f'\\nElapsed time: {datetime.timedelta(seconds=time.time()-start)}')\n", "repo_name": "jloganucsd/203_final", "sub_path": "data_sources/zillow/simScore.py", "file_name": "simScore.py", "file_ext": "py", "file_size_in_byte": 9383, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "os.environ", "line_number": 16, "usage_type": "attribute"}, {"api_name": "py_stringmatching.Cosine", "line_number": 18, "usage_type": "call"}, {"api_name": "abc.ABC", "line_number": 58, "usage_type": "name"}, {"api_name": "ast.literal_eval", "line_number": 74, "usage_type": "call"}, {"api_name": "abc.abstractmethod", "line_number": 93, "usage_type": "name"}, {"api_name": "string.digits", "line_number": 107, "usage_type": "name"}, {"api_name": "tqdm.tqdm", "line_number": 220, "usage_type": "call"}, {"api_name": "itertools.combinations", "line_number": 254, "usage_type": "call"}, {"api_name": "itertools.combinations", "line_number": 276, "usage_type": "call"}, {"api_name": "itertools.product", "line_number": 280, "usage_type": "call"}, {"api_name": "time.time", "line_number": 286, "usage_type": "call"}, {"api_name": "neo4j.GraphDatabase.driver", "line_number": 287, "usage_type": "call"}, {"api_name": "neo4j.GraphDatabase", "line_number": 287, "usage_type": "name"}, {"api_name": "datetime.timedelta", "line_number": 298, "usage_type": "call"}, {"api_name": "time.time", "line_number": 298, "usage_type": "call"}]} +{"seq_id": "32716969288", "text": "'''\nroommanger to optimize user room mapping\n'''\n\nfrom models.roommap import Roommap\nimport datetime\n\n\nclass RoomManager():\n def __init__(self, database, sensorManager):\n print(\"init Roommanger\")\n self.DB = database\n self.sensorManager = sensorManager\n\n def checkRoomManagerEntrys(self):\n \"\"\"\n returns all Room User Mapping entry in the next 30 days\n\n Returns\n -------\n mongodb.cursors\n containing all room user mapping entrys in the next 30 days\n \"\"\"\n roommaps = self.DB.getRoomMapsByDatum(datetime.datetime.now().strftime(\"%Y-%m-%d\"),\n (datetime.datetime.now() + datetime.timedelta(days=30)).strftime(\"%Y-%m-%d\"))\n return roommaps\n\n def optimizeRoomMaps(self):\n \"\"\"\n starts the room user mapping optimization.\n Directly updates the Database and sets the Room leds\n \"\"\"\n relevantDates = [(datetime.datetime.now(\n ) + datetime.timedelta(days=i)).strftime(\"%Y-%m-%d\") for i in range(31)]\n\n for date in relevantDates:\n relevantUsers = [\n user for user in self.DB.getAllUsers() if date not in user['workplan']]\n for room in self.DB.getAllRooms():\n roomUsers = []\n currentUserCount = 0\n while currentUserCount < room['maxStaff']:\n if len(relevantUsers) == 0:\n break\n roomUsers.append(relevantUsers.pop(0)['key'])\n currentUserCount += 1\n if len(roomUsers) == 0:\n state = False\n else:\n state = True\n self.DB.updateRoomMap(\n Roommap(datum=date, room=room['key'], users=roomUsers, active=state).getDict())\n if date == (datetime.datetime.now()+datetime.timedelta(days=self.DB.dayoffset)).strftime('%Y-%m-%d'):\n self.sensorManager.publisher.publish(\n 'actuator/stateled', {'room': room['key'], 'state': int(state)})\n", "repo_name": "niklaskleinhans/smaroomans-webserver", "sub_path": "utilities/roommanger.py", "file_name": "roommanger.py", "file_ext": "py", "file_size_in_byte": 2118, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "datetime.datetime.now", "line_number": 24, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 24, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 25, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 25, "usage_type": "attribute"}, {"api_name": "datetime.timedelta", "line_number": 25, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 33, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 33, "usage_type": "attribute"}, {"api_name": "datetime.timedelta", "line_number": 34, "usage_type": "call"}, {"api_name": "models.roommap.Roommap", "line_number": 52, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 53, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 53, "usage_type": "attribute"}, {"api_name": "datetime.timedelta", "line_number": 53, "usage_type": "call"}]} +{"seq_id": "33641724043", "text": "# test\n# python3 ./profile_function.py --min-users 1 --max-users 2 --user-step 1 --exp-time 60s --profile-users 1 --profile-time 60s --warmup-time 30s --function mobilenet \n# python3 ./profile_function.py --min-users 5 --max-users 30 --user-step 5 --profile-users 10 --function mobilenet\n\n# assume docker version >= 1.13\nimport sys\nimport os\nimport time\nimport numpy as np\nimport json\nimport math\nimport random\nimport argparse\nimport logging\nimport subprocess\nfrom pathlib import Path\nimport copy\nimport shutil\nimport csv\n\nfrom pathlib import Path\nsys.path.append(str(Path.cwd() / 'util'))\nfrom db_activation import *\nfrom cpu_util import *\n\n# from socket import SOCK_STREAM, socket, AF_INET, SOL_SOCKET, SO_REUSEADDR\n\nrandom.seed(time.time())\n# -----------------------------------------------------------------------\n# miscs\n# -----------------------------------------------------------------------\nlogging.basicConfig(level=logging.INFO,\n\t\t\t\t\tformat='%(asctime)s %(levelname)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S')\n\nparser = argparse.ArgumentParser()\n# parser.add_argument('--cpus', dest='cpus', type=int, required=True)\n# parser.add_argument('--stack-name', dest='stack_name', type=str, required=True)\nparser.add_argument('--function', dest='function', type=str, required=True)\nparser.add_argument('--min-users', dest='min_users', type=int, required=True)\nparser.add_argument('--max-users', dest='max_users', type=int, required=True)\nparser.add_argument('--user-step', dest='user_step', type=int, required=True)\nparser.add_argument('--exp-time', dest='exp_time', type=str, default='5m')\nparser.add_argument('--warmup-time', dest='warmup_time', type=str, default='1m')\nparser.add_argument('--profile-users', dest='profile_users', type=int, required=True)\nparser.add_argument('--profile-time', dest='profile_time', type=str, default='10m')\nparser.add_argument('--iat', dest='iat', type=int, required=True)\nargs = parser.parse_args()\n\nfunction = args.function\nmin_users = args.min_users\nmax_users = args.max_users\nuser_step = args.user_step\nexp_time = args.exp_time\nwarmup_time = args.warmup_time\nprofile_users = args.profile_users\nprofile_time = args.profile_time\niat = args.iat\n\ndata_dir = Path.cwd() / 'data'\ndistr_data_dir = Path.cwd() / 'data' / 'distr'\nlocust_stats_dir = Path.home() / 'openwhisk_locust_log'\n\n# openwhisk\nopenwhisk_controller_log = Path('/tmp/wsklogs/controller0/controller0_logs.log')\n\nif not os.path.isdir(str(data_dir)):\n\tos.makedirs(str(data_dir))\n\nif not os.path.isdir(str(distr_data_dir)):\n\tos.makedirs(str(distr_data_dir))\n\nscript = Path.cwd() / 'scripts' / ('test_action_iat_' + str(iat) + '.sh')\nassert os.path.isfile(str(script))\n\ntested_users = range(min_users, max_users+1, user_step)\nprint('users')\nprint(tested_users)\n\ndef change_time(time_str):\n\tif 'm' in time_str:\n\t\treturn int(time_str.replace('m', '')) * 60\n\telif 's' in time_str:\n\t\treturn int(time_str.replace('s', ''))\n\telse:\n\t\treturn int(time_str)\n\ndef run_mpstat(test_time, file_handle):\n\tcmd = 'mpstat -P ALL 1 ' + str(change_time(test_time))\n\tprint(cmd)\n\tp = subprocess.Popen(cmd, shell=True, stdout=file_handle)\n\treturn p\n\ndef run_exp(test_time, user, quiet=False):\n\tcmd = str(script) + ' ' + str(test_time) + ' ' + str(user) + ' ' + function\n\tif not quiet:\n\t\tp = subprocess.Popen(cmd, shell=True)\n\telse:\n\t\tp = subprocess.Popen(cmd, shell=True, \n\t\t\tstdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)\n\treturn p\n\ndef copy_locust_stats(dir_name):\n\tfull_path = data_dir / dir_name\n\tif os.path.isdir(str(full_path)):\n\t\tshutil.rmtree(str(full_path))\n\tshutil.copytree(str(locust_stats_dir), str(full_path))\n\ndef get_activation_ids():\n\tfull_path = locust_stats_dir / 'locust_openwhisk_log.txt'\n\taids = {}\t# indexed by function name\n\twith open(str(full_path), 'r') as f:\n\t\tlines = f.readlines()\n\t\tfor line in lines:\n\t\t\tif 'aid--' in line:\n\t\t\t\t# print(line)\n\t\t\t\tdata = line.split('aid--')[-1]\n\t\t\t\taction, aid = data.split(':')\n\t\t\t\taid = aid.replace('\\n', '').strip()\n\t\t\t\tif action not in aids:\n\t\t\t\t\taids[action] = []\n\t\t\t\taids[action].append(aid)\n\t\t\t\t# print(aid)\n\t\t\t\t# print('')\n\treturn aids\n\ndef clear_locust_state():\n\tfor fn in os.listdir(str(locust_stats_dir)):\n\t\tfull_path = locust_stats_dir / fn\n\t\tos.remove(str(full_path))\n\ndef controller_log_length():\n\tl = 0\n\twith open(str(openwhisk_controller_log), 'r') as f:\n\t\tlines = f.readlines()\n\t\tl = len(lines)\n\treturn l\n\ndef grep_function_distr(tail_len, distr_file):\n\tchosen = []\n\twith open(str(openwhisk_controller_log), 'r') as f:\n\t\tlines = f.readlines()[-tail_len:]\n\t\tfor line in lines:\n\t\t\tif 'exe time' in line:\n\t\t\t\tchosen.append(line)\n\n\tdistr_file_path = str(distr_data_dir / distr_file)\n\twith open(distr_file_path, 'w+') as f:\n\t\tfor l in chosen:\n\t\t\tf.write(l + '\\n')\n\n# check log\nlog_init_length = controller_log_length()\nprint('log_init_length = %d' %log_init_length)\n# profile function distr\np = run_exp(test_time=profile_time, user=profile_users)\np.wait()\ntime.sleep(30)\nlog_length = controller_log_length()\nprint('log_length = %d' %log_length)\n\ndistr_file = function + '_distr.txt'\ngrep_function_distr(tail_len=log_length-log_init_length, distr_file=distr_file)\n\nclear_locust_state()\ntime.sleep(10)\n# stress test\nfor u in tested_users:\n\t# warumup\n\tp = run_exp(test_time=warmup_time, user=u)\n\tp.wait()\n\ttime.sleep(30)\n\t# time.sleep(10)\n\t# real exp\n\tmpstat_file = str(data_dir / ('mpstat_' + function + '_user_' + str(u) + '.txt'))\n\tf = open(mpstat_file, 'w+')\n\tpm = run_mpstat(test_time=exp_time, file_handle=f)\n\tpl = run_exp(test_time=exp_time, user=u)\n\n\tpl.wait()\n\tpm.wait()\n\tf.flush()\n\tf.close()\n\n\t# read activation data from db\n\taids = get_activation_ids()\n\n\taction_records = {}\n\n\tfor action in aids:\n\t\tprint('action %s' %action)\n\t\taction_records[action] = []\n\t\tfor aid in aids[action]:\n\t\t\tprint(aid)\n\t\t\ttime_out = 0\n\t\t\twhile True:\n\t\t\t\trecord = get_activation_by_id(aid)\n\t\t\t\tif record == None:\n\t\t\t\t\tprint('wait for couchdb...')\n\t\t\t\t\ttime.sleep(10)\n\t\t\t\t\ttime_out += 1\n\t\t\t\t\tif time_out == 3:\n\t\t\t\t\t\tprint('activation lost in couchdb')\n\t\t\t\t\t\tbreak\n\t\t\t\telse:\n\t\t\t\t\tduration = record['duration']\n\t\t\t\t\twait = 0\n\t\t\t\t\tfor d in record['annotations']:\n\t\t\t\t\t\tif d['key'] == 'waitTime':\n\t\t\t\t\t\t\twait = d['value']\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\taction_records[action].append([duration+wait, duration, wait])\n\t\t\t\t\tbreak\n\n\tdir_name = 'locust_' + function + '_user_' + str(u)\n\tcopy_locust_stats(dir_name)\n\tclear_locust_state()\n\tcsv_dir = data_dir / dir_name\n\tfor action in action_records:\n\t\twith open(str(csv_dir / ('latency_' + action + '.csv')), 'w+') as f:\n\t\t\tlat_writer = csv.writer(f, delimiter=',')\n\t\t\tlat_writer.writerow(['total', 'execution', 'wait'])\n\t\t\tfor t in action_records[action]:\n\t\t\t\tlat_writer.writerow(t)\n\n\t# time.sleep(10)\n\tconsecutive_low_use = 0\n\tprint('waiting for system to cool down...')\n\tprev_idle = 0\n\tprev_total = 0\n\twhile consecutive_low_use < 5:\n\t\ttime.sleep(1)\n\t\ttotal, idle = check_proc_stat()\n\t\tutil = compute_cpu_util(prev_idle, prev_total, idle, total)\n\t\tif util <= 0.1:\n\t\t\tconsecutive_low_use += 1\n\t\telse:\n\t\t\tconsecutive_low_use = 0\n\t\tprev_idle = idle\n\t\tprev_total = total\n\tprint('system cooled down\\n')\n\n", "repo_name": "zyqCSL/openwhisk_workloads", "sub_path": "openwhisk_locust/profile_function.py", "file_name": "profile_function.py", "file_ext": "py", "file_size_in_byte": 7070, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "21", "api": [{"api_name": "sys.path.append", "line_number": 22, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 22, "usage_type": "attribute"}, {"api_name": "pathlib.Path.cwd", "line_number": 22, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 22, "usage_type": "name"}, {"api_name": "random.seed", "line_number": 28, "usage_type": "call"}, {"api_name": "time.time", "line_number": 28, "usage_type": "call"}, {"api_name": "logging.basicConfig", "line_number": 32, "usage_type": "call"}, {"api_name": "logging.INFO", "line_number": 32, "usage_type": "attribute"}, {"api_name": "argparse.ArgumentParser", "line_number": 35, "usage_type": "call"}, {"api_name": "pathlib.Path.cwd", "line_number": 59, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 59, "usage_type": "name"}, {"api_name": "pathlib.Path.cwd", "line_number": 60, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 60, "usage_type": "name"}, {"api_name": "pathlib.Path.home", "line_number": 61, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 61, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 64, "usage_type": "call"}, {"api_name": "os.path.isdir", "line_number": 66, "usage_type": "call"}, {"api_name": "os.path", "line_number": 66, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 67, "usage_type": "call"}, {"api_name": "os.path.isdir", "line_number": 69, "usage_type": "call"}, {"api_name": "os.path", "line_number": 69, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 70, "usage_type": "call"}, {"api_name": "pathlib.Path.cwd", "line_number": 72, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 72, "usage_type": "name"}, {"api_name": "os.path.isfile", "line_number": 73, "usage_type": "call"}, {"api_name": "os.path", "line_number": 73, "usage_type": "attribute"}, {"api_name": "subprocess.Popen", "line_number": 90, "usage_type": "call"}, {"api_name": "subprocess.Popen", "line_number": 96, "usage_type": "call"}, {"api_name": "subprocess.Popen", "line_number": 98, "usage_type": "call"}, {"api_name": "subprocess.DEVNULL", "line_number": 99, "usage_type": "attribute"}, {"api_name": "os.path.isdir", "line_number": 104, "usage_type": "call"}, {"api_name": "os.path", "line_number": 104, "usage_type": "attribute"}, {"api_name": "shutil.rmtree", "line_number": 105, "usage_type": "call"}, {"api_name": "shutil.copytree", "line_number": 106, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 127, "usage_type": "call"}, {"api_name": "os.remove", "line_number": 129, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 157, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 165, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 171, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 199, "usage_type": "call"}, {"api_name": "csv.writer", "line_number": 220, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 231, "usage_type": "call"}]} +{"seq_id": "24307908327", "text": "import peewee\n\nfrom flask import request, jsonify\nfrom flask_restplus import Namespace, Resource\n\nfrom models import User\n\napi = Namespace(\n name='Validation',\n description='Returns registration validation result',\n path='/validation'\n)\n\n\n@api.route('/validate_user')\nclass UserValidation(Resource):\n @api.response(200, 'Success')\n def post(self):\n data = request.get_json()\n try:\n User.get(User.username == data)\n return jsonify({\"message\": \"username is already in use\"})\n except peewee.DoesNotExist:\n return jsonify({\"message\": \"username is available\"})\n\n\n@api.route('/validate_email')\nclass EmailValidation(Resource):\n @api.response(200, 'Success')\n def post(self):\n data = request.get_json()\n try:\n User.get(User.email == data)\n return jsonify({\"message\": \"email is already in use\"})\n except peewee.DoesNotExist:\n return jsonify({\"message\": \"email is available\"})\n", "repo_name": "rustam-python/Questioner-Server", "sub_path": "web_server_quiz/web_server_quiz/web/namespaces/validation.py", "file_name": "validation.py", "file_ext": "py", "file_size_in_byte": 997, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "flask_restplus.Namespace", "line_number": 8, "usage_type": "call"}, {"api_name": "flask_restplus.Resource", "line_number": 16, "usage_type": "name"}, {"api_name": "flask.request.get_json", "line_number": 19, "usage_type": "call"}, {"api_name": "flask.request", "line_number": 19, "usage_type": "name"}, {"api_name": "models.User.get", "line_number": 21, "usage_type": "call"}, {"api_name": "models.User", "line_number": 21, "usage_type": "name"}, {"api_name": "models.User.username", "line_number": 21, "usage_type": "attribute"}, {"api_name": "flask.jsonify", "line_number": 22, "usage_type": "call"}, {"api_name": "peewee.DoesNotExist", "line_number": 23, "usage_type": "attribute"}, {"api_name": "flask.jsonify", "line_number": 24, "usage_type": "call"}, {"api_name": "flask_restplus.Resource", "line_number": 28, "usage_type": "name"}, {"api_name": "flask.request.get_json", "line_number": 31, "usage_type": "call"}, {"api_name": "flask.request", "line_number": 31, "usage_type": "name"}, {"api_name": "models.User.get", "line_number": 33, "usage_type": "call"}, {"api_name": "models.User", "line_number": 33, "usage_type": "name"}, {"api_name": "models.User.email", "line_number": 33, "usage_type": "attribute"}, {"api_name": "flask.jsonify", "line_number": 34, "usage_type": "call"}, {"api_name": "peewee.DoesNotExist", "line_number": 35, "usage_type": "attribute"}, {"api_name": "flask.jsonify", "line_number": 36, "usage_type": "call"}]} +{"seq_id": "34191993127", "text": "from PyQt6 import uic\nfrom PyQt6.QtCore import Qt, pyqtSignal\n\nimport cfclient\nfrom cfclient.ui.tab_toolbox import TabToolbox\n\nimport logging\n\nfrom PyQt6.QtWidgets import QApplication, QStyledItemDelegate\nfrom PyQt6.QtWidgets import QAbstractItemView, QStyleOptionButton, QStyle\nfrom PyQt6.QtCore import QAbstractItemModel, QModelIndex\n\nfrom cfclient.utils.logdatawriter import LogWriter\n\n__author__ = 'Bitcraze AB'\n__all__ = ['LogBlockTab']\n\nlogblock_tab_class = uic.loadUiType(cfclient.module_path + \"/ui/tabs/logBlockTab.ui\")[0]\n\nlogger = logging.getLogger(__name__)\n\n\nclass LogBlockChildItem(object):\n \"\"\"Class that acts as a child in the tree and represents one variable in\n a log block\"\"\"\n\n def __init__(self, parent, name):\n \"\"\"Initialize the node\"\"\"\n self.parent = parent\n self.name = name\n\n def child_count(self):\n \"\"\"Return the number of children this node has\"\"\"\n return 0\n\n\nclass LogBlockItem(object):\n \"\"\"Class that acts as a parent in the tree view and represents a complete\n log block\"\"\"\n\n def __init__(self, block, model, connected_ts):\n \"\"\"Initialize the parent node\"\"\"\n super(LogBlockItem, self).__init__()\n self._block = block\n self.parent = None\n self.children = []\n self.name = block.name\n self.id = block.id\n self.period = block.period_in_ms\n self._model = model\n self._log_file_writer = LogWriter(block, connected_ts)\n\n self._block.started_cb.add_callback(self._set_started)\n self._block.added_cb.add_callback(self._set_added)\n self._block.error_cb.add_callback(self._log_error)\n\n self._var_list = \"\"\n\n for b in block.variables:\n self.children.append(LogBlockChildItem(self, b.name))\n self._var_list += \"%s/\" % b.name\n self._var_list = self._var_list[:-1]\n\n self._block_started = False\n self._doing_transaction = False\n\n def _log_error(self, logconfig, msg):\n \"\"\"\n Callback when there's an error starting the block in the Crazyflie\n \"\"\"\n # Do nothing here, a pop-up will notify the user that the\n # starting failed\n self._doing_transaction = False\n\n def _set_started(self, conf, started):\n \"\"\"Callback when a block has been started in the Crazyflie\"\"\"\n logger.debug(\"%s started: %s\", self.name, started)\n if started:\n self._block_started = True\n else:\n self._block_started = False\n self._doing_transaction = False\n self._model.refresh()\n\n def logging_started(self):\n \"\"\"Return True if the block has been started, otherwise False\"\"\"\n return self._block_started\n\n def writing_to_file(self):\n \"\"\"Return True if the block is being logged to file, otherwise False\"\"\"\n return self._log_file_writer.writing()\n\n def start_writing_to_file(self):\n \"\"\"Start logging to file for this block\"\"\"\n self._log_file_writer.start()\n\n def stop_writing_to_file(self):\n \"\"\"Stop logging to file for this block\"\"\"\n self._log_file_writer.stop()\n\n def start(self):\n \"\"\"Start the logging of this block\"\"\"\n self._doing_transaction = True\n self._block.start()\n\n def stop(self):\n \"\"\"Stop the logging of this block\"\"\"\n self._doing_transaction = True\n self._block.delete()\n\n def doing_transaction(self):\n \"\"\"Return True if a block is being added or started, False when it's\n been added/started/failed\"\"\"\n return self._doing_transaction\n\n def _set_added(self, conf, started):\n \"\"\"Callback when a block has been added to the Crazyflie\"\"\"\n logger.debug(\"%s added: %s\", self.name, started)\n\n def var_list(self):\n \"\"\"Return a string containing all the variable names of the children\"\"\"\n return self._var_list\n\n def child_count(self):\n \"\"\"Return the number of children this node has\"\"\"\n return len(self.children)\n\n def get_child(self, index):\n return self.children[index]\n\n\nclass LogBlockModel(QAbstractItemModel):\n\n def __init__(self, view, parent=None):\n super(LogBlockModel, self).__init__(parent)\n self._nodes = []\n self._column_headers = ['Id', 'Name', 'Period (ms)', 'Start',\n 'Write to file', 'Contents']\n self._view = view\n self._nodes_written_to_file = []\n\n def add_block(self, block, connected_ts):\n self._nodes.append(LogBlockItem(block, self, connected_ts))\n self.layoutChanged.emit()\n self._nodes.sort(key=lambda conf: conf.name.lower())\n\n def refresh(self):\n \"\"\"Force a refresh of the view though the model\"\"\"\n self.layoutChanged.emit()\n\n def clicked(self, index):\n \"\"\"\n Callback when a cell has been clicked (mouse down/up on same cell)\n \"\"\"\n node = index.internalPointer()\n if not node.parent and index.column() == 3:\n if node.logging_started():\n node.stop()\n else:\n node.start()\n if not node.parent and index.column() == 4:\n if node.writing_to_file():\n node.stop_writing_to_file()\n else:\n node.start_writing_to_file()\n self.layoutChanged.emit()\n\n def parent(self, index):\n \"\"\"Re-implemented method to get the parent of the given index\"\"\"\n if not index.isValid():\n return QModelIndex()\n\n node = index.internalPointer()\n if node.parent is None:\n return QModelIndex()\n else:\n return self.createIndex(self._nodes.index(node.parent), 0,\n node.parent)\n\n def remove_block(self, block):\n \"\"\"Remove a block from the view\"\"\"\n raise NotImplementedError()\n\n def columnCount(self, parent):\n \"\"\"Re-implemented method to get the number of columns\"\"\"\n return len(self._column_headers)\n\n def headerData(self, section, orientation, role):\n \"\"\"Re-implemented method to get the headers\"\"\"\n if role == Qt.ItemDataRole.DisplayRole:\n return self._column_headers[section]\n\n def rowCount(self, parent):\n \"\"\"Re-implemented method to get the number of rows for a given index\"\"\"\n parent_item = parent.internalPointer()\n if parent.isValid():\n parent_item = parent.internalPointer()\n return parent_item.child_count()\n else:\n return len(self._nodes)\n\n def index(self, row, column, parent):\n \"\"\"Re-implemented method to get the index for a specified\n row/column/parent combination\"\"\"\n if not self._nodes:\n return QModelIndex()\n node = parent.internalPointer()\n if not node:\n index = self.createIndex(row, column, self._nodes[row])\n self._nodes[row].index = index\n return index\n else:\n return self.createIndex(row, column, node.get_child(row))\n\n def data(self, index, role):\n \"\"\"Re-implemented method to get the data for a given index and role\"\"\"\n node = index.internalPointer()\n parent = node.parent\n if parent:\n if role == Qt.ItemDataRole.DisplayRole and index.column() == 5:\n return node.name\n elif not parent and role == Qt.ItemDataRole.DisplayRole and index.column() == 5:\n return node.var_list()\n elif not parent and role == Qt.ItemDataRole.DisplayRole:\n if index.column() == 0:\n return node.id\n if index.column() == 1:\n return node.name\n if index.column() == 2:\n return str(node.period)\n if role == Qt.ItemDataRole.TextAlignmentRole and \\\n (index.column() == 4 or index.column() == 3):\n return Qt.AlignmentFlag.AlignHCenter | Qt.AlignmentFlag.AlignVCenter\n\n return None\n\n def reset(self):\n \"\"\"Reset the model\"\"\"\n # Stop the logging to file\n for node in self._nodes:\n if node.writing_to_file():\n node.stop_writing_to_file()\n self._nodes = []\n self.layoutChanged.emit()\n\n\nclass CheckboxDelegate(QStyledItemDelegate):\n \"\"\"Custom delegate for rending checkboxes in the table\"\"\"\n\n def paint(self, painter, option, index):\n \"\"\"Re-implemented paint method\"\"\"\n item = index.internalPointer()\n col = index.column()\n if not item.parent and (col == 3 or col == 4):\n s = QStyleOptionButton()\n checkbox_rect = QApplication.style().subElementRect(QStyle.SubElement.SE_CheckBoxIndicator, option)\n s.rect = option.rect\n center_offset = int(s.rect.width() / 2 - checkbox_rect.width() / 2)\n s.rect.adjust(center_offset, 0, 0, 0)\n\n if col == 3:\n if not item.doing_transaction():\n s.state = QStyle.StateFlag.State_Enabled\n if item.logging_started():\n s.state |= QStyle.StateFlag.State_On\n\n if col == 4:\n s.state = QStyle.StateFlag.State_Enabled\n if item.writing_to_file():\n s.state |= QStyle.StateFlag.State_On\n\n self._paint_checkbox(s, painter)\n else:\n super(CheckboxDelegate, self).paint(painter, option, index)\n\n def _paint_checkbox(self, style, painter):\n QApplication.style().drawControl(QStyle.ControlElement.CE_CheckBox, style, painter)\n\n def _paint_checkbox_osx_workaround(self, style, painter):\n painter.save()\n painter.translate(style.rect.topLeft())\n QApplication.style().drawControl(QStyle.ControlElement.CE_CheckBox, style, painter)\n painter.restore()\n\n\nclass LogBlockTab(TabToolbox, logblock_tab_class):\n \"\"\"\n Used to show debug-information about logblock status.\n \"\"\"\n\n _blocks_updated_signal = pyqtSignal(bool)\n _disconnected_signal = pyqtSignal(str)\n\n def __init__(self, helper):\n \"\"\"Initialize the tab\"\"\"\n super(LogBlockTab, self).__init__(helper, 'Log Blocks')\n self.setupUi(self)\n\n self._helper.cf.log.block_added_cb.add_callback(self._block_added)\n self._disconnected_signal.connect(self._disconnected)\n self._helper.cf.disconnected.add_callback(\n self._disconnected_signal.emit)\n\n self._model = LogBlockModel(self._block_tree)\n self._block_tree.setModel(self._model)\n self._block_tree.clicked.connect(self._model.clicked)\n self._block_tree.setItemDelegate(CheckboxDelegate())\n self._block_tree.setSelectionMode(QAbstractItemView.SelectionMode.NoSelection)\n\n def _block_added(self, block):\n \"\"\"Callback from logging layer when a new block is added\"\"\"\n self._model.add_block(block, self._helper.cf.connected_ts)\n\n def _disconnected(self, link_uri):\n \"\"\"Callback when the Crazyflie is disconnected\"\"\"\n self._model.beginResetModel()\n self._model.reset()\n self._model.endResetModel()\n", "repo_name": "bitcraze/crazyflie-clients-python", "sub_path": "src/cfclient/ui/tabs/LogBlockTab.py", "file_name": "LogBlockTab.py", "file_ext": "py", "file_size_in_byte": 11087, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 287, "dataset": "github-code", "pt": "21", "api": [{"api_name": "PyQt6.uic.loadUiType", "line_number": 18, "usage_type": "call"}, {"api_name": "PyQt6.uic", "line_number": 18, "usage_type": "name"}, {"api_name": "cfclient.module_path", "line_number": 18, "usage_type": "attribute"}, {"api_name": "logging.getLogger", "line_number": 20, "usage_type": "call"}, {"api_name": "cfclient.utils.logdatawriter.LogWriter", "line_number": 51, "usage_type": "call"}, {"api_name": "PyQt6.QtCore.QAbstractItemModel", "line_number": 132, "usage_type": "name"}, {"api_name": "PyQt6.QtCore.QModelIndex", "line_number": 171, "usage_type": "call"}, {"api_name": "PyQt6.QtCore.QModelIndex", "line_number": 175, "usage_type": "call"}, {"api_name": "PyQt6.QtCore.Qt.ItemDataRole", "line_number": 190, "usage_type": "attribute"}, {"api_name": "PyQt6.QtCore.Qt", "line_number": 190, "usage_type": "name"}, {"api_name": "PyQt6.QtCore.QModelIndex", "line_number": 206, "usage_type": "call"}, {"api_name": "PyQt6.QtCore.Qt.ItemDataRole", "line_number": 220, "usage_type": "attribute"}, {"api_name": "PyQt6.QtCore.Qt", "line_number": 220, "usage_type": "name"}, {"api_name": "PyQt6.QtCore.Qt.ItemDataRole", "line_number": 222, "usage_type": "attribute"}, {"api_name": "PyQt6.QtCore.Qt", "line_number": 222, "usage_type": "name"}, {"api_name": "PyQt6.QtCore.Qt.ItemDataRole", "line_number": 224, "usage_type": "attribute"}, {"api_name": "PyQt6.QtCore.Qt", "line_number": 224, "usage_type": "name"}, {"api_name": "PyQt6.QtCore.Qt.ItemDataRole", "line_number": 231, "usage_type": "attribute"}, {"api_name": "PyQt6.QtCore.Qt", "line_number": 231, "usage_type": "name"}, {"api_name": "PyQt6.QtCore.Qt.AlignmentFlag", "line_number": 233, "usage_type": "attribute"}, {"api_name": "PyQt6.QtCore.Qt", "line_number": 233, "usage_type": "name"}, {"api_name": "PyQt6.QtWidgets.QStyledItemDelegate", "line_number": 247, "usage_type": "name"}, {"api_name": "PyQt6.QtWidgets.QStyleOptionButton", "line_number": 255, "usage_type": "call"}, {"api_name": "PyQt6.QtWidgets.QApplication.style", "line_number": 256, "usage_type": "call"}, {"api_name": "PyQt6.QtWidgets.QApplication", "line_number": 256, "usage_type": "name"}, {"api_name": "PyQt6.QtWidgets.QStyle.SubElement", "line_number": 256, "usage_type": "attribute"}, {"api_name": "PyQt6.QtWidgets.QStyle", "line_number": 256, "usage_type": "name"}, {"api_name": "PyQt6.QtWidgets.QStyle.StateFlag", "line_number": 263, "usage_type": "attribute"}, {"api_name": "PyQt6.QtWidgets.QStyle", "line_number": 263, "usage_type": "name"}, {"api_name": "PyQt6.QtWidgets.QStyle.StateFlag", "line_number": 265, "usage_type": "attribute"}, {"api_name": "PyQt6.QtWidgets.QStyle", "line_number": 265, "usage_type": "name"}, {"api_name": "PyQt6.QtWidgets.QStyle.StateFlag", "line_number": 268, "usage_type": "attribute"}, {"api_name": "PyQt6.QtWidgets.QStyle", "line_number": 268, "usage_type": "name"}, {"api_name": "PyQt6.QtWidgets.QStyle.StateFlag", "line_number": 270, "usage_type": "attribute"}, {"api_name": "PyQt6.QtWidgets.QStyle", "line_number": 270, "usage_type": "name"}, {"api_name": "PyQt6.QtWidgets.QApplication.style", "line_number": 277, "usage_type": "call"}, {"api_name": "PyQt6.QtWidgets.QApplication", "line_number": 277, "usage_type": "name"}, {"api_name": "PyQt6.QtWidgets.QStyle.ControlElement", "line_number": 277, "usage_type": "attribute"}, {"api_name": "PyQt6.QtWidgets.QStyle", "line_number": 277, "usage_type": "name"}, {"api_name": "PyQt6.QtWidgets.QApplication.style", "line_number": 282, "usage_type": "call"}, {"api_name": "PyQt6.QtWidgets.QApplication", "line_number": 282, "usage_type": "name"}, {"api_name": "PyQt6.QtWidgets.QStyle.ControlElement", "line_number": 282, "usage_type": "attribute"}, {"api_name": "PyQt6.QtWidgets.QStyle", "line_number": 282, "usage_type": "name"}, {"api_name": "cfclient.ui.tab_toolbox.TabToolbox", "line_number": 286, "usage_type": "name"}, {"api_name": "PyQt6.QtCore.pyqtSignal", "line_number": 291, "usage_type": "call"}, {"api_name": "PyQt6.QtCore.pyqtSignal", "line_number": 292, "usage_type": "call"}, {"api_name": "PyQt6.QtWidgets.QAbstractItemView.SelectionMode", "line_number": 308, "usage_type": "attribute"}, {"api_name": "PyQt6.QtWidgets.QAbstractItemView", "line_number": 308, "usage_type": "name"}]} +{"seq_id": "38766682530", "text": "import bs4 as bs\nimport json\nfrom openpyxl import Workbook\nfrom openpyxl.styles import Font\n \n \nprint(\"start\")\n\n\n\ndef BannerToExcel(subject: str, semesters: tuple):\n workbook = Workbook()\n\n for semester in semesters:\n with open(subject + \" \" + semester + \".json\", \"r\") as file:\n # turn json file into big string\n content = file.read()\n # make replacements to content string\n clean = content.replace(\"'\", \"\\'\")\n clean = clean.replace(\"&\", \"AAA\")\n #clean = clean.replace(\"amp;\", \"\")\n # turn string into json formatted dictonary\n data = json.loads(clean)[\"data\"]\n \n courseData = tuple(((data[i][\"courseTitle\"],\n data[i][\"subjectDescription\"],\n int(data[i][\"courseNumber\"]),\n int(data[i][\"sequenceNumber\"]),\n int(data[i][\"creditHourLow\"]),\n semester,\n int(data[i][\"faculty\"][0][\"courseReferenceNumber\"]),\n data[i][\"faculty\"][0][\"displayName\"],\n data[i][\"campusDescription\"],\n max(0,int(data[i][\"seatsAvailable\"])),\n int(data[i][\"maximumEnrollment\"])) for i in range(0,len(data))))\n \n \n # Initialize Excel Workbook\n sheet = workbook.create_sheet(semester)\n sheet.title = semester\n \n \n \n sheet.append((\"Title\", \n \"Subject\",\n \"Course #\",\n \"Section #\",\n \"Hours\",\n \"CRN\",\n \"Term\",\n \"Instructor\",\n \"Campus\", \n \"Status - remaining seats\",\n \"Status - total seats\"))\n # Make first row bold\n for item in sheet[1]:\n item.font = Font(bold=True)\n \n # Add rows of data into the worksheet\n for row in courseData:\n # for item in row:\n # if type(item) == str:\n # item = item.replace(\"Finance\", \"YYYY\")\n # print(item)\n sheet.append(row)\n\n\n # Save Excel Sheet\n workbook.save(filename=\"RA Bart \" + subject + \".xlsx\")\n\n\ndef main():\n semesters = (\"Fall 2015\",\n \"Spring 2016\",\n \"Fall 2016\",\n \"Spring 2017\",\n \"Fall 2017\",\n \"Spring 2018\",\n \"Fall 2018\",\n \"Spring 2019\",\n \"Fall 2019\",\n \"Spring 2020\",\n \"Fall 2020\", \n \"Spring 2021\")\n BannerToExcel(subject=\"Finance & Insurance\", semesters=semesters)\n\nmain()", "repo_name": "Mtortolani/NEU-Banner-Scraper", "sub_path": "[old] Banner Runner.py", "file_name": "[old] Banner Runner.py", "file_ext": "py", "file_size_in_byte": 2831, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "openpyxl.Workbook", "line_number": 12, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 23, "usage_type": "call"}, {"api_name": "openpyxl.styles.Font", "line_number": 57, "usage_type": "call"}]} +{"seq_id": "3235252727", "text": "import pygame\nfrom collections import namedtuple\n\n\nLIMIT_X = 600\nLIMIT_Y = 800\n\nclass Entity(pygame.sprite.Sprite):\n def __init__(self, color, size):\n pygame.sprite.Sprite.__init__(self)\n self.color = color\n self.size = namedtuple('size', 'width height')(*size)\n self.image = pygame.Surface([self.size.width, self.size.height])\n self.image.fill(color)\n self.rect = self.image.get_rect()\n '''This bit [velocity] is hard coded; idk why'''\n self.velocity = 2 \n\n ###\n # This definitely isn't the best movement scheme\n # We're probably trying to go for something more along the lines of\n # 'fire boy and water girl' or 'hollow night'-ish\n # I can probably figure out jumping, and set up a crouching scheme\n # I don't know how to do collisions though\n # I can set up the whole arena-ish area, like make a blocking diagram\n # or a map of platforms the character can jump on\n # Could you do the staying on the platforms when the \n # character jumps on them bit? I'm not sure what that'd entail,\n # but if you need something to happen before you can do that,\n # please tell me and I'll do it :)\n ###\n def move(self, keys_pressed):\n if keys_pressed[pygame.K_a] and self.rect.x - self.velocity > 0: # move left spaceshit to the left; a pressed\n self.rect.x -= self.velocity\n if keys_pressed[pygame.K_d] and self.rect.x + self.velocity < LIMIT_X - self.size.width: # move left spaceshit to the right; d pressed\n self.rect.x += self.velocity\n if keys_pressed[pygame.K_w] and self.rect.y - self.velocity > 0: # move left spaceshit up; w pressed\n self.rect.y -= self.velocity\n if keys_pressed[pygame.K_s] and self.rect.y + self.velocity < LIMIT_Y - self.size.height: # move left spaceshit down; s pressed\n self.rect.y += self.velocity\n", "repo_name": "RitikShah/gamecop", "sub_path": "entity.py", "file_name": "entity.py", "file_ext": "py", "file_size_in_byte": 1898, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "21", "api": [{"api_name": "pygame.sprite", "line_number": 8, "usage_type": "attribute"}, {"api_name": "pygame.sprite.Sprite.__init__", "line_number": 10, "usage_type": "call"}, {"api_name": "pygame.sprite", "line_number": 10, "usage_type": "attribute"}, {"api_name": "collections.namedtuple", "line_number": 12, "usage_type": "call"}, {"api_name": "pygame.Surface", "line_number": 13, "usage_type": "call"}, {"api_name": "pygame.K_a", "line_number": 33, "usage_type": "attribute"}, {"api_name": "pygame.K_d", "line_number": 35, "usage_type": "attribute"}, {"api_name": "pygame.K_w", "line_number": 37, "usage_type": "attribute"}, {"api_name": "pygame.K_s", "line_number": 39, "usage_type": "attribute"}]} +{"seq_id": "39666708112", "text": "import codecs\nimport urllib\nimport pandas\nfrom bs4 import BeautifulSoup\nimport csv\n\nhtml_1 = urllib.urlopen('http://nomadicsamuel.com/top100travelblogs').read()\nsoup = BeautifulSoup(html_1, 'html.parser')\n\nnomad_dict_list = []\nfor row in soup.find_all('tr'):\n row_batch = dict()\n span_ct = 0\n for datum in row.find_all('span'):\n if span_ct == 0:\n try:\n row_batch['nomadicsamuel_Rank'] = int(datum.get_text())\n except ValueError:\n row_batch['nomadicsamuel_Rank'] = 0\n elif span_ct == 1:\n row_batch['blog_name'] = datum.get_text().encode('utf-8').strip()\n td_parent = datum.parent\n try:\n nomad_subhtml = urllib.urlopen(td_parent['href']).read()\n nomad_sub_soup = BeautifulSoup(nomad_subhtml,'html.parser')\n for para in nomad_sub_soup.find_all('p'):\n if para.get_text()[:6] == 'Follow':\n try:\n row_batch['blog_canon_link'] = para.a.get('href').encode('utf-8').strip()\n except AttributeError:\n row_batch['blog_canon_link'] = ''\n except KeyError:\n row_batch['blog_canon_link'] = ''\n elif span_ct == 2:\n try:\n row_batch['nomadicsamuel_Score'] = float(datum.get_text())\n except ValueError:\n row_batch['nomadicsamuel_Score'] = 0.\n span_ct += 1\n nomad_dict_list.append(row_batch)\n\nkeys = nomad_dict_list[0].keys()\nwith open(r'/run/media/jtl/OtherMind/_Neura/1. Upwork/2017.02.21 Travel Blog Scrapes/nomadic_samuel_files/blog_master.csv', 'wb') as output_file:\n dict_writer = csv.DictWriter(output_file, keys)\n dict_writer.writeheader()\n dict_writer.writerows(nomad_dict_list)\n", "repo_name": "rakmial/BeautifulSoup-MultiBlog-Scrape", "sub_path": "2017.02.21_travel_blog_scraper.py", "file_name": "2017.02.21_travel_blog_scraper.py", "file_ext": "py", "file_size_in_byte": 1843, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "urllib.urlopen", "line_number": 7, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 8, "usage_type": "call"}, {"api_name": "urllib.urlopen", "line_number": 24, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 25, "usage_type": "call"}, {"api_name": "csv.DictWriter", "line_number": 44, "usage_type": "call"}]} +{"seq_id": "30497719287", "text": "import numpy as np\nimport matplotlib.pyplot as plt\n\n\n\"\"\" === Non-linear Least-squares ===\nEstimate the 2D rigid transform between two sets of points\n=> The cost function is not a quadratic function.\n=> The cost function has local minima.\n=> No closed-form solution exists.\n\"\"\"\n\ndef rot_mat(angle):\n return np.array([[np.cos(angle), -np.sin(angle)],\n [np.sin(angle), np.cos(angle)]])\n\ndef f(X, angle, t):\n return (rot_mat(angle) @ X.T + t.reshape((-1, 1))).T\n\nX = np.array([[0.0, 0.0],\n [1.0, 0.0],\n [1.0, 1.0],\n [0.0, 1.0]])\n\nangle = np.deg2rad(55);\nR = rot_mat(angle)\n\nt = np.array([2.34, 1.43])\n\nnoise = np.random.randn(4, 2) * 0.1\nY = f(X, angle, t) + noise\n\n\nplt.scatter(X[:, 0], X[:, 1], c=\"red\")\nplt.scatter(Y[:, 0], Y[:, 1], c=\"blue\")\nplt.xlim([-2, 8])\nplt.ylim([-2, 8])\nplt.gca().set_aspect(1)\n\n\nM = 100\na_ests = np.linspace(-np.pi, np.pi, M)\ncosts = []\nfor a_est in a_ests:\n cost = np.sum((f(X, a_est, t) - Y)**2)\n costs.append(cost)\n\n\nplt.figure(\"Cost wrt. angle\")\nplt.scatter(a_ests, costs, s=1)\n\nplt.figure(\"Cost wrt. angle and t[0]\")\nt0_ests = np.linspace(0, 10, M)\na_ests_2d, t0_ests_2d = np.meshgrid(a_ests, t0_ests)\n\ncosts_2d = []\nfor a_est, t0_est in np.vstack((a_ests_2d.flatten(), t0_ests_2d.flatten())).T:\n cost = np.sum((f(X, a_est, np.array([t0_est, t[1]])) - Y)**2)\n costs_2d.append(cost)\n\ncosts_2d = np.asarray(costs_2d).reshape((M, M))\n\nplt.imshow(costs_2d, cmap=\"jet\")\n\nfig = plt.figure()\nax = fig.gca(projection='3d')\nax.plot_surface(a_ests_2d, t0_ests_2d, costs_2d, cmap=(\"jet\"))\n\n#%% Estimation by exhaustive search (not efficient)\nbest_index = np.argmin(costs_2d.flatten())\na_est = a_ests_2d.flatten()[best_index]\nt_est = np.array([t0_ests_2d.flatten()[best_index], t[1]])\nY_filt = f(X, a_est, t_est)\n\nplt.figure(\"Estimation\")\nplt.scatter(X[:, 0], X[:, 1], c=\"red\")\nplt.scatter(Y[:, 0], Y[:, 1], c=\"blue\")\nplt.scatter(Y_filt[:, 0], Y_filt[:, 1], c=\"green\")\nplt.xlim([-2, 8])\nplt.ylim([-2, 8])\nplt.gca().set_aspect(1)", "repo_name": "zinsmatt/3D-Vision", "sub_path": "Numerical_Optimization/non-linear_least_squares_2.py", "file_name": "non-linear_least_squares_2.py", "file_ext": "py", "file_size_in_byte": 2023, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 9, "dataset": "github-code", "pt": "21", "api": [{"api_name": "numpy.array", "line_number": 13, "usage_type": "call"}, {"api_name": "numpy.cos", "line_number": 13, "usage_type": "call"}, {"api_name": "numpy.sin", "line_number": 13, "usage_type": "call"}, {"api_name": "numpy.sin", "line_number": 14, "usage_type": "call"}, {"api_name": "numpy.cos", "line_number": 14, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 19, "usage_type": "call"}, {"api_name": "numpy.deg2rad", "line_number": 24, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 27, "usage_type": "call"}, {"api_name": "numpy.random.randn", "line_number": 29, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 29, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 33, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 33, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 34, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 34, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlim", "line_number": 35, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 35, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylim", "line_number": 36, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 36, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.gca", "line_number": 37, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 37, "usage_type": "name"}, {"api_name": "numpy.linspace", "line_number": 41, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 41, "usage_type": "attribute"}, {"api_name": "numpy.sum", "line_number": 44, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 48, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 48, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 49, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 49, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 51, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 51, "usage_type": "name"}, {"api_name": "numpy.linspace", "line_number": 52, "usage_type": "call"}, {"api_name": "numpy.meshgrid", "line_number": 53, "usage_type": "call"}, {"api_name": "numpy.vstack", "line_number": 56, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 57, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 57, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 60, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 62, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 62, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 64, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 64, "usage_type": "name"}, {"api_name": "numpy.argmin", "line_number": 69, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 71, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 74, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 74, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 75, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 75, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 76, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 76, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 77, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 77, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlim", "line_number": 78, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 78, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylim", "line_number": 79, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 79, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.gca", "line_number": 80, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 80, "usage_type": "name"}]} +{"seq_id": "11630153613", "text": "from datetime import date\n\nfields = {'field_1': {'type': 'label',\n 'valid_options': ['value_1', 'value_2'],\n 'reg_ex': '[azAZ]@[azAZ].com',\n 'lenght': None,\n 'type': 'label',\n 'triggers': [('screen', 'screen_name'), ('field', 'field_name')]\n },\n 'field_1': {\n 'valid_values': ['value_1', 'value_2'],\n 'reg_ex': '[azAZ]@[azAZ].com',\n 'lenght': 80,\n 'type': 'label',\n 'triggers': [('screen', 'screen_name'), ('field', 'field_name')],\n 'replaces': 'field_1',\n },\n 'case_info_lblStatus': {\n 'screen': 'CASE_INFORMATION',\n 'type': 'label',\n 'id': 'lblStatus',\n 'name': None,\n 'text': 'Started',\n 'valid_values': ['Started',],\n },\n 'case_info_lblDateModified': {\n 'screen': 'CASE_INFORMATION',\n 'type': 'label',\n 'id': 'lblDateModified',\n 'name': None,\n 'text': date.today().strftime(\"%m/%d/%y\"),\n },\n\n 'case_info_btnContinue':{\n 'screen': 'CASE_INFORMATION',\n 'type': 'button',\n 'id': 'btnContinue',\n 'name': 'btnContinue',\n 'text': 'Save Changes'\n },\n 'case_info_btnFindAvailableProducts':{\n 'screen': 'CASE_INFORMATION',\n 'type': 'button',\n 'id': 'btnFindAvailableProducts',\n 'name': 'btnFindAvailableProducts',\n 'text': 'Find Available Products'\n },\n }\n\ntabs = {\n 'CASE_INFORMATION': {'actions': ['action_1'],\n 'expected_butons': ['button_1', 'button_2'],\n 'fields': {'basic': ['field_1', 'field_2'],\n 'state_specific': {'al': ['al_field_1'],\n }\n },\n },\n}\n\nscreens = {\n 'CASE_INFORMATION': {'actions': ['action_1'],\n 'expected_butons': ['button_1', 'button_2'],\n 'fields': {'basic': ['field_1', 'field_2'],\n 'state_specific': {'al': ['al_field_1'],\n }\n },\n 'next_screen': 'DEFINITION_OF_REPLACEMENT',\n 'prev_screen': None},\n 'PRELIMINARY_INFORMATION_SHEET': {'actions': ['action_1'],\n 'expected_butons': ['button_1', 'button_2'],\n 'fields': {'al': ['al_field_1'],\n 'basic': ['field_1', 'field_2']\n },\n 'next_screen': 'DEFINITION_OF_REPLACEMENT',\n 'prev_screen': None},\n 'DEFINITION_OF_REPLACEMENT': {'actions': ['action_1'],\n 'expected_butons': ['button_1', 'button_2'],\n 'fields': {'al': ['al_field_1'],\n 'basic': ['field_1', 'field_2']\n },\n 'next_screen': 'NEW_YORK_VERIFICATION',\n 'prev_screen': 'PRELIMINARY_INFORMATION_SHEET'},\n 'NEW_YORK_VERIFICATION': {'actions': ['action_1'],\n 'expected_butons': ['button_1', 'button_2'],\n 'fields': {'al': ['al_field_1'],\n 'basic': ['field_1', 'field_2']\n },\n 'next_screen': 'PROPOSED_INSURED',\n 'prev_screen': 'DEFINITION_OF_REPLACEMENT'},\n 'PROPOSED_INSURED': {'actions': ['action_1'],\n 'expected_butons': ['button_1', 'button_2'],\n 'fields': {'al': ['al_field_1'],\n 'basic': ['field_1', 'field_2']\n },\n 'next_screen': 'PROPOSED_INSURED_CONT',\n 'prev_screen': 'NEW_YORK_VERIFICATION'},\n}\n\nplans = {\n '19E': {'full_name': 'ClearVantage UL (19E)',\n 'file_name': '19E',\n 'screens': {'basic_screens': ['pi', 'basic_information'],\n 'al': ['specific_screen_1', 'specific_screen_2']\n },\n 'restricted_states': ['NY', 'PR']\n },\n '20E': {'full_name': 'TurningPoint UL (20E)',\n 'file_name': '20E',\n 'screens': {'basic_screens': ['pi', 'basic_information'],\n 'NY': ['PRELIMINARY_INFORMATION_SHEET', 'DEFINITION_OF_REPLACEMENT']\n },\n 'restricted_states': ['PR']\n },\n '14X': {'full_name': 'Innovative Life (14X)',\n 'file_name': '20E',\n 'screens': {'basic_screens': ['pi', 'basic_information'],\n 'al': ['specific_screen_1', 'specific_screen_2']\n },\n 'restricted_states': ['IA', 'NH', 'NY', 'PR'],\n },\n 'L-5Z1': {'full_name': 'ReliaTerm (L-5Z1)',\n 'file_name': '20E',\n 'screens': {'basic_screens': ['pi', 'basic_information'],\n 'al': ['specific_screen_1', 'specific_screen_2']\n },\n 'restricted_states': ['NY', 'PR'],\n },\n '10S': {'full_name': 'SecureView (10 Series)',\n 'file_name': '20E',\n 'screens': {'basic_screens': ['pi', 'basic_information'],\n 'al': ['specific_screen_1', 'specific_screen_2']\n },\n 'restricted_states': ['PR'],\n },\n '14V': {'full_name': 'Innovative Life (14V)',\n 'file_name': '20E',\n 'screens': {'basic_screens': ['pi', 'basic_information'],\n 'al': ['specific_screen_1', 'specific_screen_2']\n },\n 'restricted_states': ['AL', 'AK', 'AZ', 'AR', 'CA', 'CO', 'CT',\n 'DE', 'DC', 'FL', 'GA', 'HI', 'ID', 'IL',\n 'IN', 'KS', 'KY', 'LA', 'ME', 'MD', 'MA',\n 'MI', 'MN', 'MS', 'MO', 'MT', 'NE', 'NV',\n 'NJ', 'NM', 'NY', 'NC', 'ND', 'OH', 'OK',\n 'OR', 'PA', 'PR', 'RI', 'SC', 'SD', 'TN',\n 'TX', 'UT', 'VT', 'VA', 'WA', 'WV', 'WI',\n 'WY'],\n }\n}\n\nbrd = [fields, screens, plans]\n", "repo_name": "efgallegos/testscript", "sub_path": "carriers/bankers/fuwl/fuwl_brd.py", "file_name": "fuwl_brd.py", "file_ext": "py", "file_size_in_byte": 7228, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "datetime.date.today", "line_number": 31, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 31, "usage_type": "name"}]} +{"seq_id": "19023898280", "text": "import pytest\nimport sys, os\nimport cellconstructor as CC, cellconstructor.Phonons\nimport cellconstructor.ForceTensor\n\nimport numpy as np\n\n# Perform the test with the following parameters\nTEST_DYN = [(\"../TestSymmetriesSupercell/SnSe.dyn.2x2x2\", 3),\n (\"../TestSymmetriesSupercell/skydyn_\", 4),\n (\"dyn\", 4)]\n\n@pytest.mark.parametrize(\"dyn_name, nqirr\", TEST_DYN)\ndef test_interpolate_on_itself(dyn_name, nqirr, verbose = False):\n # Move in the directory of the script\n total_path = os.path.dirname(os.path.abspath(__file__))\n os.chdir(total_path)\n\n # Load the dynamical matrix\n dyn = CC.Phonons.Phonons(dyn_name, nqirr)\n dyn.Symmetrize()\n\n t2 = CC.ForceTensor.Tensor2(dyn.structure,\n dyn.structure.generate_supercell(dyn.GetSupercell()),\n dyn.GetSupercell())\n t2.SetupFromPhonons(dyn)\n t2.Center(Far = 3)\n #t2.Apply_ASR()\n\n m = dyn.structure.get_masses_array()\n m = np.tile(m, (3,1)).T.ravel()\n \n for iq, q in enumerate(dyn.q_tot):\n fc = t2.Interpolate(-q)\n dynq = fc / np.sqrt(np.outer(m, m))\n\n w_tensor = np.linalg.eigvalsh(dynq)\n w_tensor = np.sqrt(np.abs(w_tensor)) * np.sign(w_tensor)\n w, p = dyn.DyagDinQ(iq)\n\n w_tensor *= CC.Units.RY_TO_CM\n w *= CC.Units.RY_TO_CM\n\n if verbose:\n print(\"q = {}\".format(q))\n print(\"\\n\".join([\"{:4d}) {:8.3f} cm-1 | {:8.3f} cm-1\".format(k, w[k], w_tensor[k]) for k in range(dyn.structure.N_atoms *3)]))\n print()\n print()\n\n assert np.max(np.abs(w - w_tensor)) < 1e-2, \"Error on point q = {}\".format(q)\n\n \n\n\nif __name__ == \"__main__\":\n \n test_interpolate_on_itself(*TEST_DYN[-2], verbose = True)\n\n \n \n\n \n\n \n", "repo_name": "SSCHAcode/CellConstructor", "sub_path": "tests/TestInterpolateDynmat/test_tensor2_on_itself.py", "file_name": "test_tensor2_on_itself.py", "file_ext": "py", "file_size_in_byte": 1804, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 13, "dataset": "github-code", "pt": "21", "api": [{"api_name": "os.path.dirname", "line_number": 16, "usage_type": "call"}, {"api_name": "os.path", "line_number": 16, "usage_type": "attribute"}, {"api_name": "os.path.abspath", "line_number": 16, "usage_type": "call"}, {"api_name": "os.chdir", "line_number": 17, "usage_type": "call"}, {"api_name": "cellconstructor.Phonons.Phonons", "line_number": 20, "usage_type": "call"}, {"api_name": "cellconstructor.Phonons", "line_number": 20, "usage_type": "attribute"}, {"api_name": "cellconstructor.ForceTensor.Tensor2", "line_number": 23, "usage_type": "call"}, {"api_name": "cellconstructor.ForceTensor", "line_number": 23, "usage_type": "attribute"}, {"api_name": "numpy.tile", "line_number": 31, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 35, "usage_type": "call"}, {"api_name": "numpy.outer", "line_number": 35, "usage_type": "call"}, {"api_name": "numpy.linalg.eigvalsh", "line_number": 37, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 37, "usage_type": "attribute"}, {"api_name": "numpy.sqrt", "line_number": 38, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 38, "usage_type": "call"}, {"api_name": "numpy.sign", "line_number": 38, "usage_type": "call"}, {"api_name": "cellconstructor.Units", "line_number": 41, "usage_type": "attribute"}, {"api_name": "cellconstructor.Units", "line_number": 42, "usage_type": "attribute"}, {"api_name": "numpy.max", "line_number": 50, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 50, "usage_type": "call"}, {"api_name": "pytest.mark.parametrize", "line_number": 13, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 13, "usage_type": "attribute"}]} +{"seq_id": "41087681783", "text": "import matplotlib.pyplot as plt\n\nx_values = list(range(1, 1001))\ny_values = [x**2 for x in x_values]\n#关联参数edgecolors=None去除轮廓线\n#关联参数c='cyan'可以指定数据点的颜色,也可以用rgb颜色模式自定义颜色\n#关联参数cmap=plt.cm.Blues表示颜色映射,颜色渐变\nplt.scatter(x_values, y_values, cmap=plt.cm.Blues, edgecolors=None, c=None, s=40)\n\n#设置图表标题,并给坐标轴加上标签\nplt.title('Square Numbers', fontsize=24)\nplt.xlabel('Value', fontsize=14)\nplt.ylabel('Square of Value', fontsize=14)\n\n#设置刻度标记的大小\nplt.tick_params(axis='both', which='major', labelsize=14)\n\n#设置每个坐标的取值范围\nplt.axis([0, 1100, 0, 1100000])\n\nplt.show()\n#plt.savefig('square.png', bbox_inches='tight')", "repo_name": "zhugp125/PythonProject", "sub_path": "plot/scatter_squares.py", "file_name": "scatter_squares.py", "file_ext": "py", "file_size_in_byte": 771, "program_lang": "python", "lang": "zh", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "matplotlib.pyplot.scatter", "line_number": 8, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 8, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.cm", "line_number": 8, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.title", "line_number": 11, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 11, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 12, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 12, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 13, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 13, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.tick_params", "line_number": 16, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 16, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.axis", "line_number": 19, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 19, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 21, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 21, "usage_type": "name"}]} +{"seq_id": "39813001164", "text": "from flask import Blueprint, abort, render_template, request, flash, session, redirect, url_for\nfrom models import *\nimport math\nimport json\nfrom functions import loginRequired, uploadQuestions\n\n\n# Creating Blueprint to be accessed in app.py\nhomeBp = Blueprint('homeBp', __name__)\nquizBp = Blueprint('quizBp', __name__)\nquizAnswersOnSubmitBp = Blueprint('quizAnswersOnSubmitBp', __name__)\nadminLoginBp = Blueprint('adminLoginBp', __name__)\nadminLogoutBp = Blueprint('adminLogoutBp', __name__)\ndeleteQuestionsBp = Blueprint('deleteQuestionsBp', __name__)\nupdateAdminBp = Blueprint('updateAdminBp', __name__)\nadminPanelBp = Blueprint('adminPanelBp', __name__)\n\n\n# Home Page [Default] | Listing all Subject & Chapter\n@homeBp.route('/')\ndef home():\n subject_chapter_mapping = {}\n sub = Subject.query.all()\n for subject in sub:\n chapter = Chapter.query.filter_by(subject_id=subject.id).all()\n # chapter = subject.chapters\n subject_chapter_mapping[subject] = chapter\n\n context = {\n \"subject_chapter_mapping\": subject_chapter_mapping\n\n }\n return render_template(\"home.html\", context=context)\n\n\n# Quiz Page \n@quizBp.route('///quiz/', methods=['GET', 'POST'])\ndef quiz(subject_slug, chapter_slug):\n\n # we use first() here to get first value from returned list[]\n try:\n subject = Subject.query.filter_by(slug=subject_slug).first()\n # we use first() here to get first value from returned list[]\n chapter = Chapter.query.filter_by(\n slug=chapter_slug, subject_id=subject.id).first()\n questions = chapter.questions\n lengthOfQuestions = len(questions)\n except:\n abort(404)\n\n if lengthOfQuestions in range(15, 100):\n numberOfQuiz = math.ceil(lengthOfQuestions/10)\n questionsPerQuiz = 10\n\n elif lengthOfQuestions >= 100:\n numberOfQuiz = math.ceil(lengthOfQuestions/20)\n questionsPerQuiz = 20\n else:\n numberOfQuiz = 1\n questionsPerQuiz = 15\n\n # get quizNumber from GET request [default will be \"Quiz1\"] \n quizNumber = request.args.get(\"quizNumber\", \"Quiz1\")\n try:\n # convert to int form as value comes in string format\n quizNumber = int(quizNumber.strip(\"Quiz\"))\n except Exception:\n quizNumber = 1\n\n # display questions in multiple quizes\n endIndex = quizNumber*questionsPerQuiz\n startIndex = endIndex-questionsPerQuiz\n questions = questions[startIndex:endIndex]\n quizNumber = f\"?quizNumber={quizNumber}\"\n\n return render_template(\"quiz.html\", quizNumber=quizNumber, context=questions, subject_slug=subject_slug, chapter_slug=chapter_slug, numberOfQuiz=numberOfQuiz)\n\n\n# Display and Calculate Result on Quiz Submit\n@quizAnswersOnSubmitBp.route('///quiz/answer/', methods=['GET', 'POST'])\ndef quizAnswersOnSubmit(subject_slug, chapter_slug):\n try:\n subject = Subject.query.filter_by(slug=subject_slug).first()\n chapter = Chapter.query.filter_by(\n slug=chapter_slug, subject_id=subject.id).first()\n questions = chapter.questions\n lengthOfQuestions = len(questions)\n except:\n abort(404)\n\n if lengthOfQuestions in range(15, 100):\n questionsPerQuiz = 10\n\n elif lengthOfQuestions >= 100:\n questionsPerQuiz = 20\n else:\n questionsPerQuiz = 15\n\n quizNumber = request.args.get(\"quizNumber\", \"Quiz1\")\n try:\n quizNumber = int(quizNumber.strip(\"Quiz\"))\n except Exception as e:\n quizNumber = 1\n endIndex = quizNumber*questionsPerQuiz\n startIndex = endIndex-questionsPerQuiz\n questions = questions[startIndex:endIndex]\n\n form = request.form # form submitted all values in dict format\n\n usersChoicesId = [int(form[i]) for i in form] \n usersQuestionsId = [int(i) for i in form]\n allQuestionsId = [ques.id for ques in questions] \n unAttemptedQuestionsID = [\n i for i in allQuestionsId if i not in usersQuestionsId]\n\n rightAnswers = []\n questions = [ques for ques in questions]\n for question in questions:\n rightAnswers.append(question.getAnswer().id)\n\n score = 0\n for i in usersChoicesId:\n if i in rightAnswers:\n score += 1\n\n # data to plot pie chart\n data = [score, len(questions)-score -\n len(unAttemptedQuestionsID), len(unAttemptedQuestionsID)]\n\n context = {\n \"questions\": questions,\n \"usersChoicesId\": usersChoicesId,\n \"score\": f\"{score} / {len(questions)}\",\n \"data\": data,\n \"unAttemptedQuestionsID\": unAttemptedQuestionsID,\n \"usersQuestionsId\": usersQuestionsId,\n }\n\n return render_template(\"quizAnswersOnSubmit.html\", context=context)\n\n\n\n@adminPanelBp.route('/admin/', methods=['GET', 'POST'])\n@loginRequired # === loginRequired(adminPanel)\ndef adminPanel():\n if request.method == \"POST\":\n # getting json file from adminPanel\n jsonFile = request.files.get(\"jsonFile\")\n if jsonFile:\n jsonData = json.load(jsonFile)\n # calling uploadQuestions() in functions.py \n result = uploadQuestions(jsonData) \n flash(result)\n return render_template(\"adminPanel.html\", username=session[\"username\"])\n\n\n\n# Admin Login Page [with session]\n@adminLoginBp.route('/admin/login/', methods=['GET', 'POST'])\ndef adminLogin():\n # if admin already in session \n if \"username\" in session:\n return redirect('/admin/')\n else:\n # if admin trying to login\n if request.method == \"POST\":\n username = request.form.get(\"username\")\n password = request.form.get(\"password\")\n admin = Admin.query.filter_by(\n username=username, password=password).first()\n if admin:\n session['username'] = admin.username\n return redirect('/admin/')\n else:\n flash('Invalid username or password')\n return render_template(\"adminLogin.html\")\n else:\n return render_template(\"adminLogin.html\")\n\n\n\n# Admin Logout and clear Session\n@adminLogoutBp.route('/admin/logout/')\ndef adminLogout():\n session.clear()\n return redirect(url_for(\"adminLoginBp.adminLogin\"))\n\n\n\n# Delete Questions from database\n@deleteQuestionsBp.route('/admin/deleteQuestions/', methods=['GET', 'POST'])\n# login required implemented using Decorators [functions.py file]\n@loginRequired # === loginRequired(deleteQuestions)\ndef deleteQuestions():\n try:\n questions = Question.query.all()\n except:\n abort(404)\n\n if request.method == \"POST\":\n # get question id to be deleted\n questionId = int(request.form.get(\"questionId\"))\n question = Question.query.get(questionId)\n\n for choice in question.choices:\n db.session.delete(choice)\n db.session.commit()\n\n db.session.delete(question)\n db.session.commit()\n questions = Question.query.all()\n\n return render_template(\"deleteQuestions.html\", questions=questions)\n\n\n\n# Update Admin data [within session]\n@updateAdminBp.route('/admin/update/', methods=['GET', 'POST'])\ndef updateAdmin():\n try:\n username = session.get(\"username\")\n if username:\n if request.method == \"POST\":\n newUsername = request.form.get(\"username\")\n newPassword = request.form.get(\"newPassword\")\n confirmPassword = request.form.get(\"confirmPassword\")\n if newPassword == confirmPassword:\n admin = Admin.query.filter_by(username=username).first()\n admin.username = newUsername\n admin.password = confirmPassword\n session['username'] = admin.username\n db.session.commit()\n flash(\"Your Profile updated successfully\")\n return redirect(\"/admin/\")\n else:\n flash(\"Your password and confirm password does not match!\")\n return render_template(\"updateAdmin.html\", username=username)\n else:\n return redirect(\"/admin/\")\n except:\n return redirect(\"/admin/\")\n\n\n\n\n\n# About Us\n@adminLogoutBp.route('/aboutUs/')\ndef aboutUs():\n return render_template(\"aboutUs.html\")\n\n\n# Contact Us\n@adminLogoutBp.route('/contactUs/',methods=['GET', 'POST'])\ndef contactUs():\n\n if request.method==\"POST\":\n name = request.form.get(\"name\")\n email = request.form.get(\"email\")\n message = request.form.get(\"message\")\n\n contactUsForm = ContactUsForm()\n contactUsForm.name = name\n contactUsForm.email = email\n contactUsForm.message = message\n db.session.add(contactUsForm)\n db.session.commit()\n flash(\"Thank You! for contacting us.\")\n return redirect(\"/contactUs/\")\n\n\n\n return render_template(\"contactUs.html\")\n\n\n", "repo_name": "RohitKV1n0d/logoVerifier", "sub_path": "routes.py", "file_name": "routes.py", "file_ext": "py", "file_size_in_byte": 8895, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "flask.Blueprint", "line_number": 9, "usage_type": "call"}, {"api_name": "flask.Blueprint", "line_number": 10, "usage_type": "call"}, {"api_name": "flask.Blueprint", "line_number": 11, "usage_type": "call"}, {"api_name": "flask.Blueprint", "line_number": 12, "usage_type": "call"}, {"api_name": "flask.Blueprint", "line_number": 13, "usage_type": "call"}, {"api_name": "flask.Blueprint", "line_number": 14, "usage_type": "call"}, {"api_name": "flask.Blueprint", "line_number": 15, "usage_type": "call"}, {"api_name": "flask.Blueprint", "line_number": 16, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 33, "usage_type": "call"}, {"api_name": "flask.abort", "line_number": 49, "usage_type": "call"}, {"api_name": "math.ceil", "line_number": 52, "usage_type": "call"}, {"api_name": "math.ceil", "line_number": 56, "usage_type": "call"}, {"api_name": "flask.request.args.get", "line_number": 63, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 63, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 63, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 76, "usage_type": "call"}, {"api_name": "flask.abort", "line_number": 89, "usage_type": "call"}, {"api_name": "flask.request.args.get", "line_number": 99, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 99, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 99, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 108, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 108, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 139, "usage_type": "call"}, {"api_name": "flask.request.method", "line_number": 146, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 146, "usage_type": "name"}, {"api_name": "flask.request.files.get", "line_number": 148, "usage_type": "call"}, {"api_name": "flask.request.files", "line_number": 148, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 148, "usage_type": "name"}, {"api_name": "json.load", "line_number": 150, "usage_type": "call"}, {"api_name": "functions.uploadQuestions", "line_number": 152, "usage_type": "call"}, {"api_name": "flask.flash", "line_number": 153, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 154, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 154, "usage_type": "name"}, {"api_name": "functions.loginRequired", "line_number": 144, "usage_type": "name"}, {"api_name": "flask.session", "line_number": 162, "usage_type": "name"}, {"api_name": "flask.redirect", "line_number": 163, "usage_type": "call"}, {"api_name": "flask.request.method", "line_number": 166, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 166, "usage_type": "name"}, {"api_name": "flask.request.form.get", "line_number": 167, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 167, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 167, "usage_type": "name"}, {"api_name": "flask.request.form.get", "line_number": 168, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 168, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 168, "usage_type": "name"}, {"api_name": "flask.session", "line_number": 172, "usage_type": "name"}, {"api_name": "flask.redirect", "line_number": 173, "usage_type": "call"}, {"api_name": "flask.flash", "line_number": 175, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 176, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 178, "usage_type": "call"}, {"api_name": "flask.session.clear", "line_number": 185, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 185, "usage_type": "name"}, {"api_name": "flask.redirect", "line_number": 186, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 186, "usage_type": "call"}, {"api_name": "flask.abort", "line_number": 198, "usage_type": "call"}, {"api_name": "flask.request.method", "line_number": 200, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 200, "usage_type": "name"}, {"api_name": "flask.request.form.get", "line_number": 202, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 202, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 202, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 213, "usage_type": "call"}, {"api_name": "functions.loginRequired", "line_number": 193, "usage_type": "name"}, {"api_name": "flask.session.get", "line_number": 221, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 221, "usage_type": "name"}, {"api_name": "flask.request.method", "line_number": 223, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 223, "usage_type": "name"}, {"api_name": "flask.request.form.get", "line_number": 224, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 224, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 224, "usage_type": "name"}, {"api_name": "flask.request.form.get", "line_number": 225, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 225, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 225, "usage_type": "name"}, {"api_name": "flask.request.form.get", "line_number": 226, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 226, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 226, "usage_type": "name"}, {"api_name": "flask.session", "line_number": 231, "usage_type": "name"}, {"api_name": "flask.flash", "line_number": 233, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 234, "usage_type": "call"}, {"api_name": "flask.flash", "line_number": 236, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 237, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 239, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 241, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 250, "usage_type": "call"}, {"api_name": "flask.request.method", "line_number": 257, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 257, "usage_type": "name"}, {"api_name": "flask.request.form.get", "line_number": 258, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 258, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 258, "usage_type": "name"}, {"api_name": "flask.request.form.get", "line_number": 259, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 259, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 259, "usage_type": "name"}, {"api_name": "flask.request.form.get", "line_number": 260, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 260, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 260, "usage_type": "name"}, {"api_name": "flask.flash", "line_number": 268, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 269, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 273, "usage_type": "call"}]} +{"seq_id": "16838093143", "text": "\nfrom kfp import dsl\nfrom mlrun import mount_v3io\nimport yaml\n\nwith open(\"config.yaml\") as f:\n config = yaml.safe_load(f)\n\nfuncs = {}\n\n# Configure function resources\ndef init_functions(functions: dict, project=None, secrets=None):\n # Mount V3IO data layer to pipeline components\n for f in functions.values():\n f.apply(mount_v3io())\n \n # Configuration for training function\n image = lambda gpu: 'mlrun/ml-models-gpu' if gpu else 'mlrun/ml-models' \n functions['trainer'].spec.image = image(config['trainer']['resources']['use_gpu'])\n functions['trainer'].with_requests(cpu=config['trainer']['resources']['requests']['cpu'],\n mem=config['trainer']['resources']['requests']['mem'])\n functions['trainer'].with_limits(cpu=config['trainer']['resources']['limits']['cpu'],\n mem=config['trainer']['resources']['limits']['mem'])\n functions['trainer'].spec.replicas = config['trainer']['resources']['replicas']\n if config['trainer']['resources']['use_gpu']:\n functions['trainer'].gpus(1)\n \n # Configuration for serving function\n functions['serving'].set_env('MODEL_CLASS', config['serving']['model_class'])\n functions['serving'].set_env('IMAGE_HEIGHT', config['serving']['image_height'])\n functions['serving'].set_env('IMAGE_WIDTH', config['serving']['image_width'])\n functions['serving'].set_env('ENABLE_EXPLAINER', config['serving']['enable_explainer'])\n functions[\"serving\"].spec.base_spec['spec']['loggerSinks'] = [{'level': 'info'}]\n functions['serving'].spec.min_replicas = config['serving']['replicas']\n functions['serving'].spec.max_replicas = config['serving']['replicas']\n\n# Create a Kubeflow Pipelines pipeline\n@dsl.pipeline(\n name='Image classification demo',\n description='Train an Image Classification TF Algorithm using MLRun'\n)\ndef kfpipeline():\n\n # step 1: download images\n open_archive = funcs['utils'].as_step(name='download',\n handler='open_archive',\n params={'target_path': config['utils']['images_dir']},\n inputs={'archive_url': config['utils']['image_archive']},\n outputs=['content'])\n\n # step 2: label images\n source_dir = str(open_archive.outputs['content']) + '/cats_n_dogs'\n label = funcs['utils'].as_step(name='label',\n handler='categories_map_builder',\n params={'source_dir': source_dir},\n outputs=['categories_map',\n 'file_categories'])\n\n # step 3: train the model\n params = config['trainer']['params']\n params['data_path'] = source_dir\n train = funcs['trainer'].as_step(name='train',\n params=params,\n inputs={\n 'categories_map': label.outputs['categories_map'],\n 'file_categories': label.outputs['file_categories']},\n outputs=['model'])\n\n # deploy the model using nuclio functions\n deploy = funcs['serving'].deploy_step(models={config['serving']['model_name']: train.outputs['model']})\n", "repo_name": "igz-us-sales/igz-platform-deployment", "sub_path": "horovod/project/workflow.py", "file_name": "workflow.py", "file_ext": "py", "file_size_in_byte": 3393, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "21", "api": [{"api_name": "yaml.safe_load", "line_number": 7, "usage_type": "call"}, {"api_name": "mlrun.mount_v3io", "line_number": 15, "usage_type": "call"}, {"api_name": "kfp.dsl.pipeline", "line_number": 38, "usage_type": "call"}, {"api_name": "kfp.dsl", "line_number": 38, "usage_type": "name"}]} +{"seq_id": "17050390636", "text": "from datetime import date\nfrom rest_framework import serializers\nfrom rest_framework.exceptions import ValidationError\nfrom booking_rooms.models import BookingRoom, Room, RoomAvailability\n\n\nclass RoomSerializer(serializers.ModelSerializer):\n class Meta:\n model = Room\n fields = ('id', 'name', 'type', 'capacity')\n\n\nclass RoomAvailabilitySerializer(serializers.ModelSerializer):\n room = RoomSerializer(write_only=True)\n id = serializers.IntegerField(write_only=True)\n\n class Meta:\n model = RoomAvailability\n fields = ('start', 'end')\n\n\nclass BookingRoomSerializer(serializers.ModelSerializer):\n resident = serializers.DictField(\n child=serializers.CharField())\n start = serializers.DateTimeField()\n end = serializers.DateTimeField()\n\n class Meta:\n model = BookingRoom\n fields = (\"resident\", 'start', 'end')\n\n def validate(self, data):\n start = data.get('start')\n end = data.get('end')\n start_time = start.time()\n end_time = end.time()\n start_date = start.date()\n end_date = end.date()\n today = date.today()\n if start_date != end_date:\n raise ValidationError(\n {\n \"error\": \"start va end ga kiritayotgan kunlari bir xil bo'lishi kerak\"\n }\n )\n\n if start_date < today or end_date < today:\n data = {\n \"error\": \"Iltimos bugundan avvalgi kunni kiritmang\"\n }\n raise ValidationError(data)\n\n if start_time > end_time:\n raise ValidationError(\n {\n \"error\": \"start ning vaqti endning vaqtidan kichik bo'lishi kerak\"\n }\n )\n\n return data\n\n", "repo_name": "Mirxojiddin/YBKY42Backend", "sub_path": "booking_rooms/serializers.py", "file_name": "serializers.py", "file_ext": "py", "file_size_in_byte": 1767, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "rest_framework.serializers.ModelSerializer", "line_number": 7, "usage_type": "attribute"}, {"api_name": "rest_framework.serializers", "line_number": 7, "usage_type": "name"}, {"api_name": "booking_rooms.models.Room", "line_number": 9, "usage_type": "name"}, {"api_name": "rest_framework.serializers.ModelSerializer", "line_number": 13, "usage_type": "attribute"}, {"api_name": "rest_framework.serializers", "line_number": 13, "usage_type": "name"}, {"api_name": "rest_framework.serializers.IntegerField", "line_number": 15, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 15, "usage_type": "name"}, {"api_name": "booking_rooms.models.RoomAvailability", "line_number": 18, "usage_type": "name"}, {"api_name": "rest_framework.serializers.ModelSerializer", "line_number": 22, "usage_type": "attribute"}, {"api_name": "rest_framework.serializers", "line_number": 22, "usage_type": "name"}, {"api_name": "rest_framework.serializers.DictField", "line_number": 23, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 23, "usage_type": "name"}, {"api_name": "rest_framework.serializers.CharField", "line_number": 24, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 24, "usage_type": "name"}, {"api_name": "rest_framework.serializers.DateTimeField", "line_number": 25, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 25, "usage_type": "name"}, {"api_name": "rest_framework.serializers.DateTimeField", "line_number": 26, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 26, "usage_type": "name"}, {"api_name": "booking_rooms.models.BookingRoom", "line_number": 29, "usage_type": "name"}, {"api_name": "datetime.date.today", "line_number": 39, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 39, "usage_type": "name"}, {"api_name": "rest_framework.exceptions.ValidationError", "line_number": 41, "usage_type": "call"}, {"api_name": "rest_framework.exceptions.ValidationError", "line_number": 51, "usage_type": "call"}, {"api_name": "rest_framework.exceptions.ValidationError", "line_number": 54, "usage_type": "call"}]} +{"seq_id": "73771927091", "text": "from itertools import accumulate\nfrom typing import List\n\nclass Solution:\n def getModifiedArray(self, length: int, updates: List[List[int]]) -> List[int]:\n delta = [0] * length\n for start, end, inc in updates:\n delta[start] += inc\n if end + 1 < length:\n delta[end + 1] -= inc\n print(delta)\n return list(accumulate(delta))\n\n\nl = 5\nupdates = [[1,3,2],[2,4,3],[0,2,-2]]\nsol = Solution()\nprint(sol.getModifiedArray(l, updates))", "repo_name": "jacky1107/leetcode", "sub_path": "medium/370_range_addition.py", "file_name": "370_range_addition.py", "file_ext": "py", "file_size_in_byte": 491, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "typing.List", "line_number": 5, "usage_type": "name"}, {"api_name": "itertools.accumulate", "line_number": 12, "usage_type": "call"}]} +{"seq_id": "73253637491", "text": "import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom scipy.stats import norm\n\n\nplt.rcParams.update({\n \"figure.autolayout\": True})\n\n\nclass ElevatorStateSimulation:\n\n def __init__(self, max_lowering, max_days):\n self.x_min = 0\n self.x_max = max_days\n self.y_min = 0\n self.y_max = max_lowering\n\n std = 3\n\n n = 20\n xs = np.linspace(self.x_min, self.x_max, n)\n ys = np.linspace(self.y_min, self.y_max, n)\n self.vs = np.zeros((n, n))\n for i in range(n):\n # The mean should change from \"max lowering\" to 0 from day 0 to \"max day\".\n mean = self.y_max - ys[i]\n v = norm.pdf(ys, mean, std)\n v = np.interp(v, (v.min(), v.max()), (0, 1))\n self.vs[i] = v\n\n self.xmg, self.ymg = np.meshgrid(xs, ys)\n\n def plot(self):\n elev = 55\n azim = 100\n\n fig = plt.figure(figsize=(30, 10))\n ax = fig.add_subplot(1, 1, 1, projection='3d')\n ax.view_init(elev, azim)\n ax.plot_surface(self.xmg, self.ymg, self.vs, cmap=cm.jet)\n ax.set_xlabel('day')\n ax.set_ylabel('elevation')\n ax.set_zlabel('reward')\n ax.set_title(\"elevator reward\")\n plt.show()\n\n\nif __name__ == \"__main__\":\n reward = ElevatorStateSimulation(10, 90)\n reward.plot()\n", "repo_name": "pwierzgala/evaa", "sub_path": "source_code/master/rl/simulations/elevator.py", "file_name": "elevator.py", "file_ext": "py", "file_size_in_byte": 1396, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "matplotlib.pyplot.rcParams.update", "line_number": 8, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.rcParams", "line_number": 8, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot", "line_number": 8, "usage_type": "name"}, {"api_name": "numpy.linspace", "line_number": 23, "usage_type": "call"}, {"api_name": "numpy.linspace", "line_number": 24, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 25, "usage_type": "call"}, {"api_name": "scipy.stats.norm.pdf", "line_number": 29, "usage_type": "call"}, {"api_name": "scipy.stats.norm", "line_number": 29, "usage_type": "name"}, {"api_name": "numpy.interp", "line_number": 30, "usage_type": "call"}, {"api_name": "numpy.meshgrid", "line_number": 33, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 39, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 39, "usage_type": "name"}, {"api_name": "matplotlib.cm.jet", "line_number": 42, "usage_type": "attribute"}, {"api_name": "matplotlib.cm", "line_number": 42, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 47, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 47, "usage_type": "name"}]} +{"seq_id": "13415608835", "text": "\"\"\"CLI application entry point.\"\"\"\nimport os\nimport subprocess\n\nimport click\nfrom getch import pause\n\nfrom vigorish.app import Vigorish\nfrom vigorish.cli.click_params import DataSetName, DateString, FileTypeName, JobName, MlbSeason\nfrom vigorish.cli.components import print_message, validate_scrape_dates\nfrom vigorish.cli.main_menu import MainMenu\nfrom vigorish.config.project_paths import VIG_FOLDER\nfrom vigorish.enums import DataSet, StatusReport, SyncDirection\nfrom vigorish.scrape.job_runner import JobRunner\nfrom vigorish.status.report_status import (\n report_date_range_status,\n report_season_status,\n report_status_single_date,\n)\nfrom vigorish.tasks import SyncDataNoPromptsTask\nfrom vigorish.util.datetime_util import current_year, today_str\nfrom vigorish.util.result import Result\nfrom vigorish.util.string_helpers import flatten_list2d\nfrom vigorish.util.sys_helpers import run_command\n\n\n@click.group(context_settings={\"help_option_names\": [\"-h\", \"--help\"]})\n@click.pass_context\ndef cli(ctx):\n \"\"\"\n Vigorish scrapes various websites for MLB data.\n\n Please visit https://aaronluna.dev/projects/vigorish for user guides and project documentation.\n \"\"\"\n if os.environ.get(\"ENV\") != \"TEST\": # pragma: no cover\n if not VIG_FOLDER.exists():\n VIG_FOLDER.mkdir()\n ctx.obj = Vigorish()\n\n\n@cli.command(context_settings={\"help_option_names\": [\"-h\", \"--help\"]})\n@click.pass_obj\ndef ui(app): # pragma: no cover\n \"\"\"Menu-driven UI powered by Bullet.\"\"\"\n try:\n result = MainMenu(app).launch()\n return exit_app(app, result)\n except Exception as e:\n return exit_app(app, Result.Fail(f\"Error: {repr(e)}\"))\n\n\n@cli.command(context_settings={\"help_option_names\": [\"-h\", \"--help\"]})\n@click.confirmation_option(prompt=\"Are you sure you want to delete all existing data?\")\n@click.pass_obj\ndef setup(app): # pragma: no cover\n \"\"\"Populate database with initial player, team and season data.\n\n WARNING! Before the setup process begins, all existing data will be deleted. This cannot be undone.\n \"\"\"\n print() # place an empty line between the command and the progress bars\n result = app.initialize_database()\n return exit_app(app, result, \"Successfully populated database with initial data.\")\n\n\n@cli.command(context_settings={\"help_option_names\": [\"-h\", \"--help\"]})\n@click.option(\n \"--data-set\",\n type=DataSetName(),\n multiple=True,\n default=[str(DataSet.ALL)],\n show_default=True,\n help=\"Data set(s) to scrape, multiple values can be provided.\",\n)\n@click.option(\n \"--start\",\n type=DateString(),\n prompt=True,\n help=(\"Date to start scraping data, string can be in any format that is recognized by dateutil.parser.\"),\n)\n@click.option(\n \"--end\",\n type=DateString(),\n prompt=True,\n help=(\"Date to stop scraping data, string can be in any format that is recognized by dateutil.parser.\"),\n)\n@click.option(\n \"--job-name\",\n type=JobName(),\n default=\"\",\n help=\"A name to help identify this job.\",\n prompt=(\"(Optional) Enter a name for this job (ONLY letters, numbers, underscore, and/or hyphen characters)\"),\n)\n@click.pass_obj\ndef scrape(app, data_set, start, end, job_name):\n \"\"\"Scrape MLB data from websites.\"\"\"\n result = validate_scrape_dates(app.db_session, start, end)\n if result.failure:\n return exit_app(app, result)\n new_scrape_job = app.create_scrape_job(data_set, start, end, job_name).value\n job_runner = JobRunner(app=app, db_job=new_scrape_job)\n result = job_runner.execute()\n return exit_app(app, result)\n\n\n@cli.group(context_settings={\"help_option_names\": [\"-h\", \"--help\"]})\n@click.pass_obj\ndef status(app):\n \"\"\"Report progress of scraped data, by date or MLB season.\"\"\"\n pass\n\n\n@status.command(\"date\", context_settings={\"help_option_names\": [\"-h\", \"--help\"]})\n@click.argument(\"game_date\", type=DateString(), default=today_str)\n@click.option(\n \"-v\",\n \"verbosity\",\n count=True,\n default=1,\n help=(\n \"Specify the level of detail to report:\\n\"\n \" -v: report the combined scrape progress for all games on the specified date.\\n\"\n \" -vv: report combined and individual scrape progress for each game on the specified date\\n\"\n \" -vvv: report combined/individual game scrape progress and pitch appearance scrape progress\\n\"\n ),\n)\n@click.pass_obj\ndef status_date(app, game_date, verbosity):\n \"\"\"Report status for a single date.\n\n Dates can be provided in any format that is recognized by dateutil.parser.\n For example, all of the following strings are valid ways to represent the same date:\n \"2018-5-13\" -or- \"05/13/2018\" -or- \"May 13 2018\"\n \"\"\"\n report_type = StatusReport.NONE\n if verbosity <= 0:\n error = f\"Invalid value for verbosity: {verbosity}. Value must be greater than zero.\"\n return exit_app(app, Result.Fail(error))\n elif verbosity == 1:\n report_type = StatusReport.DATE_DETAIL_ALL_DATES\n elif verbosity == 2:\n report_type = StatusReport.DATE_DETAIL_MISSING_PITCHFX\n else:\n report_type = StatusReport.SINGLE_DATE_WITH_GAME_STATUS\n result = report_status_single_date(app.db_session, game_date, report_type)\n if result.success:\n report_viewer = result.value\n report_viewer.launch()\n return exit_app(app, result)\n\n\n@status.command(\"range\", context_settings={\"help_option_names\": [\"-h\", \"--help\"]})\n@click.option(\"--start\", type=DateString(), prompt=True, help=\"First date to report status.\")\n@click.option(\"--end\", type=DateString(), prompt=True, help=\"Last date to report status.\")\n@click.option(\n \"-v\",\n \"verbosity\",\n count=True,\n default=1,\n help=(\n \"Specify the level of detail to report:\\n\"\n \" -v: summary report of only dates missing data\\n\"\n \" -vv: summary report of all dates\\n\"\n \" -vvv: detailed report of only dates missing data\\n\"\n \" -vvvv: detailed report of all dates\\n\"\n \"-vvvvv: detailed report of all dates with missing pitch_app_ids\"\n ),\n)\n@click.pass_obj\ndef status_date_range(app, start, end, verbosity):\n \"\"\"Report status for each date in a specified range.\n\n Dates can be provided in any format that is recognized by dateutil.parser.\n For example, all of the following strings are valid ways to represent the same date:\n \"2018-5-13\" -or- \"05/13/2018\" -or- \"May 13 2018\"\n \"\"\"\n report_type = StatusReport.NONE\n if verbosity <= 0:\n error = f\"Invalid value for verbosity: {verbosity}. Value must be greater than zero.\"\n return exit_app(app, Result.Fail(error))\n elif verbosity == 1:\n report_type = StatusReport.DATE_SUMMARY_MISSING_DATA\n elif verbosity == 2:\n report_type = StatusReport.DATE_SUMMARY_ALL_DATES\n elif verbosity == 3:\n report_type = StatusReport.DATE_DETAIL_MISSING_DATA\n elif verbosity == 4:\n report_type = StatusReport.DATE_DETAIL_ALL_DATES\n else:\n report_type = StatusReport.DATE_DETAIL_MISSING_PITCHFX\n result = report_date_range_status(app.db_session, start, end, report_type)\n if result.success:\n report_viewer = result.value\n report_viewer.launch()\n return exit_app(app, result)\n\n\n@status.command(\"season\", context_settings={\"help_option_names\": [\"-h\", \"--help\"]})\n@click.argument(\"year\", type=MlbSeason(), default=current_year)\n@click.option(\n \"-v\",\n \"verbosity\",\n count=True,\n default=1,\n help=(\n \"Specify the level of detail to report:\"\n \" -v: overall metrics for entire season\"\n \" -vv: summary report of dates in season that are missing data\"\n \" -vvv: summary report of all dates in season\"\n \" -vvvv: detailed report of dates in season that are missing data\"\n \" -vvvv: detailed report of all dates in season\"\n \"-vvvvvv: detailed report of all dates in season with missing pitch_app_ids\"\n ),\n)\n@click.pass_obj\ndef status_season(app, year, verbosity):\n \"\"\"Report status for a single MLB season.\"\"\"\n report_type = StatusReport.NONE\n if verbosity <= 0:\n error = f\"Invalid value for verbosity: {verbosity}. Value must be greater than zero.\"\n return exit_app(app, Result.Fail(error))\n elif verbosity == 1:\n report_type = StatusReport.SEASON_SUMMARY\n elif verbosity == 2:\n report_type = StatusReport.DATE_SUMMARY_MISSING_DATA\n elif verbosity == 3:\n report_type = StatusReport.DATE_SUMMARY_ALL_DATES\n elif verbosity == 4:\n report_type = StatusReport.DATE_DETAIL_MISSING_DATA\n elif verbosity == 5:\n report_type = StatusReport.DATE_DETAIL_ALL_DATES\n else:\n report_type = StatusReport.DATE_DETAIL_MISSING_PITCHFX\n result = report_season_status(app.db_session, year, report_type)\n if result.success:\n report_viewer = result.value\n report_viewer.launch()\n return exit_app(app, result)\n\n\n@cli.group(context_settings={\"help_option_names\": [\"-h\", \"--help\"]})\n@click.pass_obj\ndef sync(app):\n \"\"\"Synchronize scraped data to/from S3 bucket.\"\"\"\n pass\n\n\n@sync.command(\"up\", context_settings={\"help_option_names\": [\"-h\", \"--help\"]})\n@click.argument(\"year\", type=MlbSeason(), default=current_year)\n@click.option(\n \"--file-type\",\n type=FileTypeName(),\n help=\"Type of file to sync, must provide only one value.\",\n prompt=True,\n)\n@click.option(\n \"--data-set\",\n type=DataSetName(),\n multiple=True,\n default=[str(DataSet.ALL)],\n show_default=True,\n help=\"Data set(s) to sync, multiple values can be provided.\",\n)\n@click.pass_obj\ndef sync_up_to_s3(app, year, file_type, data_set):\n \"\"\"Sync files from local folder to S3 bucket.\"\"\"\n data_sets_int = sum(int(ds) for ds in flatten_list2d(data_set))\n result_dict = SyncDataNoPromptsTask(app).execute(\n sync_direction=SyncDirection.UP_TO_S3,\n year=year,\n file_type=file_type,\n data_sets_int=data_sets_int,\n )\n result = Result.Combine(list(result_dict.values()))\n if os.environ.get(\"ENV\") != \"TEST\": # pragma: no cover\n pause(message=\"\\nPress any key to continue...\")\n return exit_app(app, result)\n\n\n@sync.command(\"down\", context_settings={\"help_option_names\": [\"-h\", \"--help\"]})\n@click.argument(\"year\", type=MlbSeason(), default=current_year)\n@click.option(\n \"--file-type\",\n type=FileTypeName(),\n help=\"Type of file to sync, must provide only one value.\",\n prompt=True,\n)\n@click.option(\n \"--data-set\",\n type=DataSetName(),\n multiple=True,\n default=[str(DataSet.ALL)],\n show_default=True,\n help=\"Data set(s) to sync, multiple values can be provided.\",\n)\n@click.pass_obj\ndef sync_down_to_local(app, year, file_type, data_set):\n \"\"\"Sync files from S3 bucket to local folder.\"\"\"\n data_sets_int = sum(int(ds) for ds in flatten_list2d(data_set))\n result_dict = SyncDataNoPromptsTask(app).execute(\n sync_direction=SyncDirection.DOWN_TO_LOCAL,\n year=year,\n file_type=file_type,\n data_sets_int=data_sets_int,\n )\n result = Result.Combine(list(result_dict.values()))\n if os.environ.get(\"ENV\") != \"TEST\": # pragma: no cover\n pause(message=\"\\nPress any key to continue...\")\n return exit_app(app, result)\n\n\ndef exit_app(app, result, message=None):\n app.db_session.close()\n subprocess.run([\"clear\"])\n print()\n exit_code = exit_app_success(message) if result.success else exit_app_error(result.error)\n print()\n return exit_code\n\n\ndef exit_app_success(message=None):\n if message:\n print_message(message, fg=\"bright_green\", bold=True)\n return 0\n\n\ndef exit_app_error(message):\n if message:\n if isinstance(message, list):\n for m in message:\n print_message(m, fg=\"bright_red\", bold=True)\n else:\n print_message(message, fg=\"bright_red\", bold=True)\n return 1\n\n\nif __name__ == '__main__':\n run_command('vig ui')\n", "repo_name": "a-luna/vigorish", "sub_path": "src/vigorish/cli/vig.py", "file_name": "vig.py", "file_ext": "py", "file_size_in_byte": 11893, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "21", "api": [{"api_name": "os.environ.get", "line_number": 35, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 35, "usage_type": "attribute"}, {"api_name": "vigorish.config.project_paths.VIG_FOLDER.exists", "line_number": 36, "usage_type": "call"}, {"api_name": "vigorish.config.project_paths.VIG_FOLDER", "line_number": 36, "usage_type": "name"}, {"api_name": "vigorish.config.project_paths.VIG_FOLDER.mkdir", "line_number": 37, "usage_type": "call"}, {"api_name": "vigorish.config.project_paths.VIG_FOLDER", "line_number": 37, "usage_type": "name"}, {"api_name": "vigorish.app.Vigorish", "line_number": 38, "usage_type": "call"}, {"api_name": "click.group", "line_number": 27, "usage_type": "call"}, {"api_name": "click.pass_context", "line_number": 28, "usage_type": "attribute"}, {"api_name": "vigorish.cli.main_menu.MainMenu", "line_number": 46, "usage_type": "call"}, {"api_name": "vigorish.util.result.Result.Fail", "line_number": 49, "usage_type": "call"}, {"api_name": "vigorish.util.result.Result", "line_number": 49, "usage_type": "name"}, {"api_name": "click.pass_obj", "line_number": 42, "usage_type": "attribute"}, {"api_name": "click.confirmation_option", "line_number": 53, "usage_type": "call"}, {"api_name": "click.pass_obj", "line_number": 54, "usage_type": "attribute"}, {"api_name": "vigorish.cli.components.validate_scrape_dates", "line_number": 96, "usage_type": "call"}, {"api_name": "vigorish.scrape.job_runner.JobRunner", "line_number": 100, "usage_type": "call"}, {"api_name": "click.option", "line_number": 66, "usage_type": "call"}, {"api_name": "vigorish.cli.click_params.DataSetName", "line_number": 68, "usage_type": "call"}, {"api_name": "vigorish.enums.DataSet.ALL", "line_number": 70, "usage_type": "attribute"}, {"api_name": "vigorish.enums.DataSet", "line_number": 70, "usage_type": "name"}, {"api_name": "click.option", "line_number": 74, "usage_type": "call"}, {"api_name": "vigorish.cli.click_params.DateString", "line_number": 76, "usage_type": "call"}, {"api_name": "click.option", "line_number": 80, "usage_type": "call"}, {"api_name": "vigorish.cli.click_params.DateString", "line_number": 82, "usage_type": "call"}, {"api_name": "click.option", "line_number": 86, "usage_type": "call"}, {"api_name": "vigorish.cli.click_params.JobName", "line_number": 88, "usage_type": "call"}, {"api_name": "click.pass_obj", "line_number": 93, "usage_type": "attribute"}, {"api_name": "click.pass_obj", "line_number": 106, "usage_type": "attribute"}, {"api_name": "vigorish.enums.StatusReport.NONE", "line_number": 134, "usage_type": "attribute"}, {"api_name": "vigorish.enums.StatusReport", "line_number": 134, "usage_type": "name"}, {"api_name": "vigorish.util.result.Result.Fail", "line_number": 137, "usage_type": "call"}, {"api_name": "vigorish.util.result.Result", "line_number": 137, "usage_type": "name"}, {"api_name": "vigorish.enums.StatusReport.DATE_DETAIL_ALL_DATES", "line_number": 139, "usage_type": "attribute"}, {"api_name": "vigorish.enums.StatusReport", "line_number": 139, "usage_type": "name"}, {"api_name": "vigorish.enums.StatusReport.DATE_DETAIL_MISSING_PITCHFX", "line_number": 141, "usage_type": "attribute"}, {"api_name": "vigorish.enums.StatusReport", "line_number": 141, "usage_type": "name"}, {"api_name": "vigorish.enums.StatusReport.SINGLE_DATE_WITH_GAME_STATUS", "line_number": 143, "usage_type": "attribute"}, {"api_name": "vigorish.enums.StatusReport", "line_number": 143, "usage_type": "name"}, {"api_name": "vigorish.status.report_status.report_status_single_date", "line_number": 144, "usage_type": "call"}, {"api_name": "click.argument", "line_number": 113, "usage_type": "call"}, {"api_name": "vigorish.cli.click_params.DateString", "line_number": 113, "usage_type": "call"}, {"api_name": "vigorish.util.datetime_util.today_str", "line_number": 113, "usage_type": "name"}, {"api_name": "click.option", "line_number": 114, "usage_type": "call"}, {"api_name": "click.pass_obj", "line_number": 126, "usage_type": "attribute"}, {"api_name": "vigorish.enums.StatusReport.NONE", "line_number": 176, "usage_type": "attribute"}, {"api_name": "vigorish.enums.StatusReport", "line_number": 176, "usage_type": "name"}, {"api_name": "vigorish.util.result.Result.Fail", "line_number": 179, "usage_type": "call"}, {"api_name": "vigorish.util.result.Result", "line_number": 179, "usage_type": "name"}, {"api_name": "vigorish.enums.StatusReport.DATE_SUMMARY_MISSING_DATA", "line_number": 181, "usage_type": "attribute"}, {"api_name": "vigorish.enums.StatusReport", "line_number": 181, "usage_type": "name"}, {"api_name": "vigorish.enums.StatusReport.DATE_SUMMARY_ALL_DATES", "line_number": 183, "usage_type": "attribute"}, {"api_name": "vigorish.enums.StatusReport", "line_number": 183, "usage_type": "name"}, {"api_name": "vigorish.enums.StatusReport.DATE_DETAIL_MISSING_DATA", "line_number": 185, "usage_type": "attribute"}, {"api_name": "vigorish.enums.StatusReport", "line_number": 185, "usage_type": "name"}, {"api_name": "vigorish.enums.StatusReport.DATE_DETAIL_ALL_DATES", "line_number": 187, "usage_type": "attribute"}, {"api_name": "vigorish.enums.StatusReport", "line_number": 187, "usage_type": "name"}, {"api_name": "vigorish.enums.StatusReport.DATE_DETAIL_MISSING_PITCHFX", "line_number": 189, "usage_type": "attribute"}, {"api_name": "vigorish.enums.StatusReport", "line_number": 189, "usage_type": "name"}, {"api_name": "vigorish.status.report_status.report_date_range_status", "line_number": 190, "usage_type": "call"}, {"api_name": "click.option", "line_number": 152, "usage_type": "call"}, {"api_name": "vigorish.cli.click_params.DateString", "line_number": 152, "usage_type": "call"}, {"api_name": "click.option", "line_number": 153, "usage_type": "call"}, {"api_name": "vigorish.cli.click_params.DateString", "line_number": 153, "usage_type": "call"}, {"api_name": "click.option", "line_number": 154, "usage_type": "call"}, {"api_name": "click.pass_obj", "line_number": 168, "usage_type": "attribute"}, {"api_name": "vigorish.enums.StatusReport.NONE", "line_number": 217, "usage_type": "attribute"}, {"api_name": "vigorish.enums.StatusReport", "line_number": 217, "usage_type": "name"}, {"api_name": "vigorish.util.result.Result.Fail", "line_number": 220, "usage_type": "call"}, {"api_name": "vigorish.util.result.Result", "line_number": 220, "usage_type": "name"}, {"api_name": "vigorish.enums.StatusReport.SEASON_SUMMARY", "line_number": 222, "usage_type": "attribute"}, {"api_name": "vigorish.enums.StatusReport", "line_number": 222, "usage_type": "name"}, {"api_name": "vigorish.enums.StatusReport.DATE_SUMMARY_MISSING_DATA", "line_number": 224, "usage_type": "attribute"}, {"api_name": "vigorish.enums.StatusReport", "line_number": 224, "usage_type": "name"}, {"api_name": "vigorish.enums.StatusReport.DATE_SUMMARY_ALL_DATES", "line_number": 226, "usage_type": "attribute"}, {"api_name": "vigorish.enums.StatusReport", "line_number": 226, "usage_type": "name"}, {"api_name": "vigorish.enums.StatusReport.DATE_DETAIL_MISSING_DATA", "line_number": 228, "usage_type": "attribute"}, {"api_name": "vigorish.enums.StatusReport", "line_number": 228, "usage_type": "name"}, {"api_name": "vigorish.enums.StatusReport.DATE_DETAIL_ALL_DATES", "line_number": 230, "usage_type": "attribute"}, {"api_name": "vigorish.enums.StatusReport", "line_number": 230, "usage_type": "name"}, {"api_name": "vigorish.enums.StatusReport.DATE_DETAIL_MISSING_PITCHFX", "line_number": 232, "usage_type": "attribute"}, {"api_name": "vigorish.enums.StatusReport", "line_number": 232, "usage_type": "name"}, {"api_name": "vigorish.status.report_status.report_season_status", "line_number": 233, "usage_type": "call"}, {"api_name": "click.argument", "line_number": 198, "usage_type": "call"}, {"api_name": "vigorish.cli.click_params.MlbSeason", "line_number": 198, "usage_type": "call"}, {"api_name": "vigorish.util.datetime_util.current_year", "line_number": 198, "usage_type": "name"}, {"api_name": "click.option", "line_number": 199, "usage_type": "call"}, {"api_name": "click.pass_obj", "line_number": 214, "usage_type": "attribute"}, {"api_name": "click.pass_obj", "line_number": 241, "usage_type": "attribute"}, {"api_name": "vigorish.util.string_helpers.flatten_list2d", "line_number": 266, "usage_type": "call"}, {"api_name": "vigorish.tasks.SyncDataNoPromptsTask", "line_number": 267, "usage_type": "call"}, {"api_name": "vigorish.enums.SyncDirection.UP_TO_S3", "line_number": 268, "usage_type": "attribute"}, {"api_name": "vigorish.enums.SyncDirection", "line_number": 268, "usage_type": "name"}, {"api_name": "vigorish.util.result.Result.Combine", "line_number": 273, "usage_type": "call"}, {"api_name": "vigorish.util.result.Result", "line_number": 273, "usage_type": "name"}, {"api_name": "os.environ.get", "line_number": 274, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 274, "usage_type": "attribute"}, {"api_name": "getch.pause", "line_number": 275, "usage_type": "call"}, {"api_name": "click.argument", "line_number": 248, "usage_type": "call"}, {"api_name": "vigorish.cli.click_params.MlbSeason", "line_number": 248, "usage_type": "call"}, {"api_name": "vigorish.util.datetime_util.current_year", "line_number": 248, "usage_type": "name"}, {"api_name": "click.option", "line_number": 249, "usage_type": "call"}, {"api_name": "vigorish.cli.click_params.FileTypeName", "line_number": 251, "usage_type": "call"}, {"api_name": "click.option", "line_number": 255, "usage_type": "call"}, {"api_name": "vigorish.cli.click_params.DataSetName", "line_number": 257, "usage_type": "call"}, {"api_name": "vigorish.enums.DataSet.ALL", "line_number": 259, "usage_type": "attribute"}, {"api_name": "vigorish.enums.DataSet", "line_number": 259, "usage_type": "name"}, {"api_name": "click.pass_obj", "line_number": 263, "usage_type": "attribute"}, {"api_name": "vigorish.util.string_helpers.flatten_list2d", "line_number": 298, "usage_type": "call"}, {"api_name": "vigorish.tasks.SyncDataNoPromptsTask", "line_number": 299, "usage_type": "call"}, {"api_name": "vigorish.enums.SyncDirection.DOWN_TO_LOCAL", "line_number": 300, "usage_type": "attribute"}, {"api_name": "vigorish.enums.SyncDirection", "line_number": 300, "usage_type": "name"}, {"api_name": "vigorish.util.result.Result.Combine", "line_number": 305, "usage_type": "call"}, {"api_name": "vigorish.util.result.Result", "line_number": 305, "usage_type": "name"}, {"api_name": "os.environ.get", "line_number": 306, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 306, "usage_type": "attribute"}, {"api_name": "getch.pause", "line_number": 307, "usage_type": "call"}, {"api_name": "click.argument", "line_number": 280, "usage_type": "call"}, {"api_name": "vigorish.cli.click_params.MlbSeason", "line_number": 280, "usage_type": "call"}, {"api_name": "vigorish.util.datetime_util.current_year", "line_number": 280, "usage_type": "name"}, {"api_name": "click.option", "line_number": 281, "usage_type": "call"}, {"api_name": "vigorish.cli.click_params.FileTypeName", "line_number": 283, "usage_type": "call"}, {"api_name": "click.option", "line_number": 287, "usage_type": "call"}, {"api_name": "vigorish.cli.click_params.DataSetName", "line_number": 289, "usage_type": "call"}, {"api_name": "vigorish.enums.DataSet.ALL", "line_number": 291, "usage_type": "attribute"}, {"api_name": "vigorish.enums.DataSet", "line_number": 291, "usage_type": "name"}, {"api_name": "click.pass_obj", "line_number": 295, "usage_type": "attribute"}, {"api_name": "subprocess.run", "line_number": 313, "usage_type": "call"}, {"api_name": "vigorish.cli.components.print_message", "line_number": 322, "usage_type": "call"}, {"api_name": "vigorish.cli.components.print_message", "line_number": 330, "usage_type": "call"}, {"api_name": "vigorish.cli.components.print_message", "line_number": 332, "usage_type": "call"}, {"api_name": "vigorish.util.sys_helpers.run_command", "line_number": 337, "usage_type": "call"}]} +{"seq_id": "28276798803", "text": "from pathlib import Path\nfrom pybo import *\n\n\nclass AdjustSeg:\n\n def __init__(self, path, volumes):\n self.win_sz = 2\n self.path = path\n self.volumes = volumes\n self.token_corpus = []\n self.ambiguous = None\n self.c_ambiguous = None\n self.nonambiguous = None\n self.c_nonambiguous = None\n self._build_token_list()\n self._classify_ambiguity()\n\n\n def _build_token_list(self):\n for volume in self.volumes:\n with open(self.path/volume) as f:\n _tokens = f.read().split()\n\n # remove all the tokens which are not word\n non_words = ['#', '¥', 'n', '༄༅', '-', '+', '།']\n for token in _tokens:\n is_word = True\n for char in token:\n if char in non_words:\n is_word = False\n if is_word:\n self.token_corpus.append(token)\n\n\n def _classify_ambiguity(self):\n\n def __to_words(corrected_tokens):\n token_words = []\n for tk in corrected_tokens:\n if '+' in tk:\n token_words.append('{}{}'.format(*tk.split('+')))\n else:\n token_words.append('{}{}'.format(*tk.split('-')))\n return token_words\n\n amb, nonamb = [], []\n hist_tokens = [None]*self.win_sz\n for volume in self.volumes:\n with open(self.path/volume) as f:\n tokens = f.read().split()\n for token in tokens:\n if '+' in token:\n first_tk, second_tk = token.split('+')\n if f'{first_tk}{second_tk}' in self.token_corpus:\n amb.append(token)\n else:\n nonamb.append(token)\n elif '-' in token:\n s = [token]\n for i in range(self.win_sz):\n if hist_tokens[-1]:\n prev_token = hist_tokens[-(i+1)]\n s.insert(0, prev_token)\n if '-' not in prev_token: break\n nonamb.pop()\n\n nonamb.append(''.join(s))\n\n # store the prev two token\n if hist_tokens[-1] is not None:\n hist_tokens[-2] = hist_tokens[-1]\n hist_tokens[-1] = token\n\n self.c_ambiguous, self.c_nonambiguous = list(set(amb)), list(set(nonamb))\n\n self.ambiguous = __to_words(self.c_ambiguous)\n self.nonambiguous = __to_words(self.c_nonambiguous)\n\n\n def stats(self):\n print(\"# of words:\", len(self.token_corpus))\n print(\"# of Ambiguous:\", len(self.c_ambiguous))\n print(\"# of Nonambiguos:\", len(self.c_nonambiguous))\n\n print()\n print(\"Ambiguous types:\")\n print(*self.c_ambiguous, sep='\\n')\n\n print()\n print(\"Non ambiguous types:\")\n print(*self.c_nonambiguous[:20], sep='\\n')\n\n\n def _split_token(self, token, split_idx):\n\n def __get_syls_split_idx(token, split_idx):\n for i, syl in enumerate(token.syls):\n if syl[-1] >= split_idx:\n return i\n\n def __init_syls(syls):\n start_idx = syls[0][0]\n for syl in syls:\n for i in range(len(syl)):\n syl[i] -= start_idx\n return syls\n\n def __create_char_groups(char_groups, keys, split_idx=0):\n new_char_groups = {}\n for key in keys:\n new_char_groups[key] = char_groups[key + split_idx]\n return new_char_groups\n\n def __split_char_groups(token, split_idx):\n keys = list(token.char_groups.keys())\n first_keys = keys[:split_idx]\n second_keys = [k-split_idx for k in keys[split_idx:]]\n\n first_token_char_groups = __create_char_groups(token.char_groups,\n first_keys)\n second_token_char_groups = __create_char_groups(token.char_groups,\n second_keys,\n split_idx)\n\n return first_token_char_groups, second_token_char_groups\n\n # create an empty tokens\n first_token = Token()\n second_token = Token()\n\n # split content, syls, char_types and char_groups\n first_token_content = token.content[:split_idx]\n second_token_content = token.content[split_idx:]\n\n syls_split_idx = __get_syls_split_idx(token, split_idx)\n first_token_syls = token.syls[:syls_split_idx]\n second_token_syls = __init_syls(token.syls[syls_split_idx:])\n\n first_token_char_types = token.char_types[:split_idx]\n second_token_char_types = token.char_types[split_idx:]\n\n s = __split_char_groups(token, split_idx)\n first_token_char_groups, second_token_char_groups = s\n\n # create splited tokens\n first_token.content = first_token_content\n first_token.type = token.type\n first_token.char_groups = first_token_char_groups\n first_token.syls = first_token_syls\n first_token.len = len(first_token_char_groups)\n first_token.start = token.start\n\n second_token.content = second_token_content\n second_token.type = token.type\n second_token.char_groups = second_token_char_groups\n second_token.syls = second_token_syls\n second_token.len = len(second_token.content)\n second_token.start = token.start + split_idx\n\n return [first_token, second_token]\n\n\n def adjust(self, token_list):\n adjusted_token = []\n for token in token_list:\n # frist adjust all the non ambiguous segmentation\n if token.content in self.nonambiguous or token.content+'་' in self.nonambiguous:\n if not token.content.endswith('་'):\n matched_idx = self.nonambiguous.index(token.content+'་')\n else:\n matched_idx = self.nonambiguous.index(token.content)\n if '+' in self.c_nonambiguous[matched_idx]:\n split_idx = self.c_nonambiguous[matched_idx].index('+')\n s = self._split_token(token, split_idx)\n adjusted_token.extend(s)\n break\n else:\n adjusted_token.append(token)\n else:\n adjusted_token.append(token)\n\n return adjusted_token\n\n\nif __name__ == \"__main__\":\n\n path = Path('../kt-no-tantra')\n\n volumes = [\n '100 དབུ་མ། ཞ_cleaned_cleaned_cleaned.txt',\n '001_cleaned_cleaned_cleaned.txt',\n '044_cleaned_cleaned_cleaned.txt'\n ]\n\n tok = BoTokenizer('POS')\n adj = AdjustSeg(path, volumes)\n\n string = 'སྒྲུབ་པའི་ཆོས་དང་མི་མཐུན་པའི་ཕྱོགས་ཀྱི་དཔེ་ཡིན་པ་ར་གོ་རིམས་བཞིན་དུ་སྦྱར་རོ་།།'\n token_list = tok.tokenize(string, split_affixes=True)\n\n print(\"Before seg adjustment\")\n print(*[tk.content for tk in token_list], sep='\\n')\n\n print(\"After seg adjustment\")\n adjusted_tokens = adj.adjust(token_list)\n print(*[tk.content for tk in adjusted_tokens], sep='\\n')\n", "repo_name": "Esukhia/canonsegmentation", "sub_path": "adjustment/adjustseg.py", "file_name": "adjustseg.py", "file_ext": "py", "file_size_in_byte": 7501, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "pathlib.Path", "line_number": 188, "usage_type": "call"}]} +{"seq_id": "23386161082", "text": "# pyttsx3 is a module that allows us to speak text in a voice format like Microsoft Speech Recognition API (MSRAPI) or Google Speech Recognition API (GSRAPI) or Amazon Speech Recognition API (ASRAPI).\nimport pyttsx3\n# datetime is a module that allows us to get the current time.\nimport datetime\n\n# take command from user function.\nimport speech_recognition as sr\n\n# wikipedia function to search for a query in wikipedia.\nimport wikipedia\n\n# sapi5 is the name of the voice that is used in the speak function above.\n\nengine = pyttsx3.init('sapi5')\nvoices = engine.getProperty('voices')\n\n# this print is just for check which type voice i have in my computer.\n# print(voices[0].id)\n# This function will take the voice that is selected in the computer and will speak the text that is passed to it.\nengine.setProperty('voice', voices[0].id)\n\n\n# Speak function\ndef speak(audio):\n engine.say(audio)\n engine.runAndWait()\n\n# wish me function\n# This function will greet the user with the name of the user.\ndef wishMe():\n hour = int(datetime.datetime.now().hour)\n if hour >= 0 and hour < 12:\n speak(\"Good Morning!\")\n elif hour >= 12 and hour < 18:\n speak(\"Good Afternoon!\")\n else:\n speak(\"Good Evening!\")\n speak(\"I am Jarvis. Please tell me how may I help you\") \n \n# It takes microphone input from the user and returns string output. \ndef takeCommand():\n \n r = sr.Recognizer()\n with sr.Microphone() as source:\n print(\"Listening...\")\n r.pause_threshold = 1\n audio = r.listen(source)\n try:\n print(\"Recognizing...\")\n query = r.recognize_google(audio, language='en-in')\n print(f\"User said: {query}\\n\")\n except Exception as e:\n # print(e)\n print(\"Say that again please...\")\n return \"None\"\n return query\n\n\n\nif __name__==\"__main__\":\n # speak(\"Aniket is very powerful\")\n wishMe()\n while True:\n query = takeCommand().lower()\n # Logic for executing tasks based on query \n if 'wikipeadia' in query:\n speak('Searching Wikipedia...')\n query = query.replace(\"wikipedia\", \"\")\n results = wikipedia.summary(query, sentences=2)\n speak(\"According to Wikipedia\")\n print(results)\n speak(results)\n # elif 'open youtube' in query:\n # webbrowser.open(\"youtube.com\")\n # elif 'open google' in query:\n # webbrowser.open(\"google.com\")\n # elif 'open stackoverflow' in query:\n # webbrowser.open(\"stackoverflow.com\")\n # # elif 'play music' in query:\n # # music_dir = 'D:\\\\Non Critical\\\\songs\\\\Favorite Songs2'\n # # songs = os.listdir(music_dir)\n # # print(songs)\n # # os.startfile(os.path.join(music_dir, songs[0]))\n\n\n", "repo_name": "aniket-tiwari15/JARVIS", "sub_path": "Jarvis.py", "file_name": "Jarvis.py", "file_ext": "py", "file_size_in_byte": 2800, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "pyttsx3.init", "line_number": 14, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 31, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 31, "usage_type": "attribute"}, {"api_name": "speech_recognition.Recognizer", "line_number": 43, "usage_type": "call"}, {"api_name": "speech_recognition.Microphone", "line_number": 44, "usage_type": "call"}, {"api_name": "wikipedia.summary", "line_number": 69, "usage_type": "call"}]} +{"seq_id": "27470734917", "text": "from fastapi import APIRouter, Depends, Request, Query, Path\nfrom depends import get_crypt_course, get_usd_course, get_user, User, get_authorized, get_db, Session\nfrom main import render_template\nfrom utils import format_int\nfrom fastapi.responses import RedirectResponse, HTMLResponse\nfrom models.crud import UserCRUD, LogEntryCRUD\nrouter = APIRouter(tags=['Render'])\n\n@router.get(\"/\", response_class=HTMLResponse, summary='Отображение главной страницы')\nasync def index(\n request: Request,\n user: User | None = Depends(get_user),\n course: tuple[float, float] = Depends(get_crypt_course),\n usd_course: float = Depends(get_usd_course)):\n return render_template('index.html', course=course, request=request, usd=usd_course, format_int=format_int, user=user)\n\n@router.get(\"/register\", response_class=HTMLResponse, summary='Отображение страницы регистрации')\nasync def register(request: Request):\n return render_template('register.html', request=request)\n\n@router.get(\"/admin\", response_class=HTMLResponse, summary='Отображение страницы администратора')\nasync def admin_index(request: Request, user: User = Depends(get_authorized),\n db: Session = Depends(get_db)):\n if not user.is_admin:\n return RedirectResponse(url='/')\n return render_template('admin.html', users=UserCRUD.get_all(db), user=user, request=request)\n\n@router.get('/admin/history/{user_id}', response_class=HTMLResponse, summary='Отображение истории запросов пользователя')\nasync def admin_history(request: Request, user: User = Depends(get_authorized),\n db: Session = Depends(get_db),\n user_id: int = Path(..., description='ID пользователя'),\n page: int = Query(1, description='Номер страницы')):\n if page < 1:\n page = 1\n if not user.is_admin:\n return RedirectResponse(url='/')\n return render_template('admin_history.html',\n user=user,\n request=request,\n logs=LogEntryCRUD.get_history(db, user_id, (page - 1) * 10, 10, False),\n page=page)\n\n@router.get('/admin/search/{block_id}', response_class=HTMLResponse, summary='Отображение страницы поиска блока')\nasync def admin_search(request: Request, user: User = Depends(get_authorized), block_id: int = Path(..., description='ID блока')):\n if not user.is_admin:\n return RedirectResponse(url='/')\n return render_template('admin_search.html', user=user, request=request, block_id=block_id)\n\n@router.get(\"/logout\", response_class=RedirectResponse, summary='Выход из аккаунта')\nasync def logout():\n resp = RedirectResponse(url='/')\n resp.delete_cookie(key='token')\n return resp\n\n@router.get('/search/{block_id}', response_class=HTMLResponse, summary='Отображение результата поиска')\nasync def search(request: Request,\n user: User | None = Depends(get_authorized),\n block_id: int = Path(..., description='ID блока в сети BTC')):\n return render_template('search.html', request=request, user=user, block_id=block_id)\n\n@router.get('/history', response_class=HTMLResponse, summary='Отображение истории поиска')\nasync def history(request: Request,\n user: User | None = Depends(get_authorized),\n db: Session = Depends(get_db),\n page: int = Query(1, description='Номер страницы')):\n if page < 1:\n page = 1\n logs = LogEntryCRUD.get_history(db, user.id, (page - 1) * 10, 10)\n return render_template('history.html', request=request, user=user, logs=logs, page=page)\n", "repo_name": "feysuff/pljoncoin", "sub_path": "api/routes/render.py", "file_name": "render.py", "file_ext": "py", "file_size_in_byte": 3924, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "fastapi.APIRouter", "line_number": 7, "usage_type": "call"}, {"api_name": "fastapi.Request", "line_number": 11, "usage_type": "name"}, {"api_name": "depends.User", "line_number": 12, "usage_type": "name"}, {"api_name": "fastapi.Depends", "line_number": 12, "usage_type": "call"}, {"api_name": "depends.get_user", "line_number": 12, "usage_type": "argument"}, {"api_name": "fastapi.Depends", "line_number": 13, "usage_type": "call"}, {"api_name": "depends.get_crypt_course", "line_number": 13, "usage_type": "argument"}, {"api_name": "fastapi.Depends", "line_number": 14, "usage_type": "call"}, {"api_name": "depends.get_usd_course", "line_number": 14, "usage_type": "argument"}, {"api_name": "main.render_template", "line_number": 15, "usage_type": "call"}, {"api_name": "utils.format_int", "line_number": 15, "usage_type": "name"}, {"api_name": "fastapi.responses.HTMLResponse", "line_number": 9, "usage_type": "name"}, {"api_name": "fastapi.Request", "line_number": 18, "usage_type": "name"}, {"api_name": "main.render_template", "line_number": 19, "usage_type": "call"}, {"api_name": "fastapi.responses.HTMLResponse", "line_number": 17, "usage_type": "name"}, {"api_name": "fastapi.Request", "line_number": 22, "usage_type": "name"}, {"api_name": "depends.User", "line_number": 22, "usage_type": "name"}, {"api_name": "depends.Session", "line_number": 23, "usage_type": "name"}, {"api_name": "fastapi.Depends", "line_number": 22, "usage_type": "call"}, {"api_name": "depends.get_authorized", "line_number": 22, "usage_type": "argument"}, {"api_name": "fastapi.Depends", "line_number": 23, "usage_type": "call"}, {"api_name": "depends.get_db", "line_number": 23, "usage_type": "argument"}, {"api_name": "fastapi.responses.RedirectResponse", "line_number": 25, "usage_type": "call"}, {"api_name": "main.render_template", "line_number": 26, "usage_type": "call"}, {"api_name": "models.crud.UserCRUD.get_all", "line_number": 26, "usage_type": "call"}, {"api_name": "models.crud.UserCRUD", "line_number": 26, "usage_type": "name"}, {"api_name": "fastapi.responses.HTMLResponse", "line_number": 21, "usage_type": "name"}, {"api_name": "fastapi.Request", "line_number": 29, "usage_type": "name"}, {"api_name": "depends.User", "line_number": 29, "usage_type": "name"}, {"api_name": "depends.Session", "line_number": 30, "usage_type": "name"}, {"api_name": "fastapi.Depends", "line_number": 29, "usage_type": "call"}, {"api_name": "depends.get_authorized", "line_number": 29, "usage_type": "argument"}, {"api_name": "fastapi.Depends", "line_number": 30, "usage_type": "call"}, {"api_name": "depends.get_db", "line_number": 30, "usage_type": "argument"}, {"api_name": "fastapi.Path", "line_number": 31, "usage_type": "call"}, {"api_name": "fastapi.Query", "line_number": 32, "usage_type": "call"}, {"api_name": "fastapi.responses.RedirectResponse", "line_number": 36, "usage_type": "call"}, {"api_name": "main.render_template", "line_number": 37, "usage_type": "call"}, {"api_name": "models.crud.LogEntryCRUD.get_history", "line_number": 40, "usage_type": "call"}, {"api_name": "models.crud.LogEntryCRUD", "line_number": 40, "usage_type": "name"}, {"api_name": "fastapi.responses.HTMLResponse", "line_number": 28, "usage_type": "name"}, {"api_name": "fastapi.Request", "line_number": 44, "usage_type": "name"}, {"api_name": "depends.User", "line_number": 44, "usage_type": "name"}, {"api_name": "fastapi.Depends", "line_number": 44, "usage_type": "call"}, {"api_name": "depends.get_authorized", "line_number": 44, "usage_type": "argument"}, {"api_name": "fastapi.Path", "line_number": 44, "usage_type": "call"}, {"api_name": "fastapi.responses.RedirectResponse", "line_number": 46, "usage_type": "call"}, {"api_name": "main.render_template", "line_number": 47, "usage_type": "call"}, {"api_name": "fastapi.responses.HTMLResponse", "line_number": 43, "usage_type": "name"}, {"api_name": "fastapi.responses.RedirectResponse", "line_number": 51, "usage_type": "call"}, {"api_name": "fastapi.responses.RedirectResponse", "line_number": 49, "usage_type": "name"}, {"api_name": "fastapi.Request", "line_number": 56, "usage_type": "name"}, {"api_name": "depends.User", "line_number": 57, "usage_type": "name"}, {"api_name": "fastapi.Depends", "line_number": 57, "usage_type": "call"}, {"api_name": "depends.get_authorized", "line_number": 57, "usage_type": "argument"}, {"api_name": "fastapi.Path", "line_number": 58, "usage_type": "call"}, {"api_name": "main.render_template", "line_number": 59, "usage_type": "call"}, {"api_name": "fastapi.responses.HTMLResponse", "line_number": 55, "usage_type": "name"}, {"api_name": "fastapi.Request", "line_number": 62, "usage_type": "name"}, {"api_name": "depends.User", "line_number": 63, "usage_type": "name"}, {"api_name": "depends.Session", "line_number": 64, "usage_type": "name"}, {"api_name": "fastapi.Depends", "line_number": 63, "usage_type": "call"}, {"api_name": "depends.get_authorized", "line_number": 63, "usage_type": "argument"}, {"api_name": "fastapi.Depends", "line_number": 64, "usage_type": "call"}, {"api_name": "depends.get_db", "line_number": 64, "usage_type": "argument"}, {"api_name": "fastapi.Query", "line_number": 65, "usage_type": "call"}, {"api_name": "models.crud.LogEntryCRUD.get_history", "line_number": 68, "usage_type": "call"}, {"api_name": "models.crud.LogEntryCRUD", "line_number": 68, "usage_type": "name"}, {"api_name": "main.render_template", "line_number": 69, "usage_type": "call"}, {"api_name": "fastapi.responses.HTMLResponse", "line_number": 61, "usage_type": "name"}]} +{"seq_id": "3941240357", "text": "import json\nimport boto3\nfrom decimal import Decimal\nimport pandas as pd\n\nfile_path = \"textract_output.json\"\n\ndef read_json_data(file_path):\n data = []\n with open(file_path) as f:\n data = json.loads(f.read())\n print(type(data))\n print(len(data))\n return data[:300]\n\nif __name__ == \"__main__\":\n data = read_json_data(file_path=file_path)\n df = pd.json_normalize(data)\n print(df)\n", "repo_name": "bengogd/jsonpandas", "sub_path": "json2dframe.py", "file_name": "json2dframe.py", "file_ext": "py", "file_size_in_byte": 417, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "json.loads", "line_number": 11, "usage_type": "call"}, {"api_name": "pandas.json_normalize", "line_number": 18, "usage_type": "call"}]} +{"seq_id": "6502155330", "text": "from threading import Thread\nimport logging\nfrom typing import Optional, Any, cast\n\nlog = logging.getLogger(__name__)\n\n\nclass ThreadWithReturnValue(Thread):\n def __init__(self, *args: Any, **kwargs: Any):\n Thread.__init__(self, *args, **kwargs)\n self._return: Optional[Any] = None\n self._exception: Optional[Exception] = None\n\n def run(self) -> None:\n if self._target is not None:\n try:\n # save return valie\n self._return = self._target(*self._args, **self._kwargs)\n except Exception as e:\n # save exception, if one was caught\n self._exception = e\n\n def join(self, timeout: Optional[float] = None) -> Any:\n if timeout is None:\n log.warning(\"Joining thread with timeout of 0s. Is this correct?\")\n # join thread\n Thread.join(self, timeout=timeout)\n # raise exception, if one was raised\n if self._exception is not None:\n raise self._exception\n # otherwise return value\n return self._return\n\n\n__all__ = [\"ThreadWithReturnValue\"]\n", "repo_name": "pyobs/pyobs-core", "sub_path": "pyobs/utils/threads/threadwithreturnvalue.py", "file_name": "threadwithreturnvalue.py", "file_ext": "py", "file_size_in_byte": 1115, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 8, "dataset": "github-code", "pt": "21", "api": [{"api_name": "logging.getLogger", "line_number": 5, "usage_type": "call"}, {"api_name": "threading.Thread", "line_number": 8, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 9, "usage_type": "name"}, {"api_name": "threading.Thread.__init__", "line_number": 10, "usage_type": "call"}, {"api_name": "threading.Thread", "line_number": 10, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 11, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 11, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 12, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 23, "usage_type": "name"}, {"api_name": "threading.Thread.join", "line_number": 27, "usage_type": "call"}, {"api_name": "threading.Thread", "line_number": 27, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 23, "usage_type": "name"}]} +{"seq_id": "75009352691", "text": "from tensorflow import keras\nfrom nltk_utils import *\nimport json\nimport random\n\n\nmodel = keras.models.load_model('chatbot_model.h5')\n\nwith open('content.json','r') as f:\n intents = json.load(f)\n\nall_words = []\ntags = []\npatterns_tags = []\n\nfor intent in intents['intents']:\n tag = intent['tag']\n tags.append(tag)\n for pattern in intent['patterns']:\n w = tokenize(pattern)\n all_words.extend(w)\n patterns_tags.append((w, tag))\n \n \nignore_words = ['?', '!', '.', ',']\nall_words = [stem(w) for w in all_words if w not in ignore_words]\nall_words = sorted(set(all_words))\n\ndef preprocess_sentences(sentence):\n token_sentence = tokenize(sentence)\n bag = bag_of_words(token_sentence, all_words)\n return bag\n\ndef get_user_typed():\n return input('Enter: ')\n\ndef predict_tag(sentence):\n X_predict = np.array([preprocess_sentences(sentence)], dtype=np.float32)\n idx = np.argmax(model.predict(X_predict[0:1]))\n return tags[idx]\n\ndef response(tag):\n for intent in intents['intents']:\n if intent['tag'] == tag:\n return random.choice(intent['responses'])\n\ndef chatbot(user_input):\n pred_tag = predict_tag(user_input)\n pred_res = response(pred_tag)\n return pred_res\n\nif __name__ == '__main__':\n for i in range(5):\n typed = get_user_typed()\n pred_tag = predict_tag(typed)\n pred_res = response(pred_tag)\n print('Responce: ', pred_res)", "repo_name": "HaiDangAI/AI-Virtual-Assistant", "sub_path": "chatbot.py", "file_name": "chatbot.py", "file_ext": "py", "file_size_in_byte": 1445, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "tensorflow.keras.models.load_model", "line_number": 7, "usage_type": "call"}, {"api_name": "tensorflow.keras.models", "line_number": 7, "usage_type": "attribute"}, {"api_name": "tensorflow.keras", "line_number": 7, "usage_type": "name"}, {"api_name": "json.load", "line_number": 10, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 45, "usage_type": "call"}]} +{"seq_id": "10640166191", "text": "import pymongo\n\nDB_NAME = \"MalwareWeb\"\n\n\ndef createDB(dbname):\n connection = pymongo.Connection()\n db = connection[dbname]\n collection = db[\"temp_collection\"]\n return db\n\n\ndef getDBInstance():\n client = pymongo.MongoClient()\n if DB_NAME not in client.database_names():\n instance = createDB(DB_NAME)\n return getattr(client, DB_NAME)\n", "repo_name": "praveen97uma/MalwareWebMap", "sub_path": "crawler/db_utils.py", "file_name": "db_utils.py", "file_ext": "py", "file_size_in_byte": 360, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "pymongo.Connection", "line_number": 7, "usage_type": "call"}, {"api_name": "pymongo.MongoClient", "line_number": 14, "usage_type": "call"}]} +{"seq_id": "37409214302", "text": "#!/usr/bin/env python3\r\n# -*- coding: utf-8 -*-\r\n# (c) @AlbertEinsteinTG\r\n\r\nfrom pyrogram import filters, Client\r\nfrom pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup, CallbackQuery\r\nfrom bot import Translation, LOGGER # pylint: disable=import-error\r\nfrom bot.database import Database # pylint: disable=import-error\r\n\r\ndb = Database()\r\n\r\n@Client.on_message(filters.command([\"start\"]) & filters.private, group=1)\r\nasync def start(bot, update):\r\n \r\n try:\r\n file_uid = update.command[1]\r\n except IndexError:\r\n file_uid = False\r\n \r\n if file_uid:\r\n file_id, file_name, file_caption, file_type = await db.get_file(file_uid)\r\n \r\n if (file_id or file_type) == None:\r\n return\r\n \r\n caption = file_caption if file_caption != (\"\" or None) else (\"\" + file_name + \"\")\r\n try:\r\n await update.reply_cached_media(\r\n file_id,\r\n quote=True,\r\n caption = f\"{file_name} \\n \\n ⚜️പുതിയ സിനിമകൾ ഇറങ്ങുമ്പോൾ തന്നെ ലഭിക്കാൻ ചാനെലിൽ ജോയിൻ ചെയ്യൂ.. \\n \\n 🌟⊰᯽⊱┈──╌❊╌──┈⊰᯽⊱🌟 \\n @NEW_MLM_HD_MOVES \\n @mlm_movies_update\",\r\n parse_mode=\"html\",\r\n reply_markup=InlineKeyboardMarkup(\r\n [\r\n [\r\n InlineKeyboardButton\r\n (\r\n '🔰 UPDATE CHANNEL 🔰', url=\"https://t.me/mlm_movies_update\"\r\n )\r\n ]\r\n ]\r\n )\r\n )\r\n except Exception as e:\r\n await update.reply_text(f\"Error:\\n{e}\", True, parse_mode=\"html\")\r\n LOGGER(__name__).error(e)\r\n return\r\n\r\n buttons = [[\r\n InlineKeyboardButton('🔰 MOVIE REQESTING GROUP 🔰', url='https://t.me/NEW_MLM_HD_MOVES'),\r\n ],[\r\n InlineKeyboardButton('🔰 UPDATE CHANNEL 🔰', url='https://t.me/mlm_movies_update'),\r\n ],[\r\n InlineKeyboardButton('OWNER 👨‍✈️', url='https://t.me/mrplantozz_bot'),\r\n InlineKeyboardButton('Help ⚙', callback_data=\"help\"),\r\n ],[\r\n InlineKeyboardButton('CLOSE 🔒', callback_data='close')\r\n ]]\r\n \r\n reply_markup = InlineKeyboardMarkup(buttons)\r\n \r\n await bot.send_message(\r\n chat_id=update.chat.id,\r\n text=Translation.START_TEXT.format(\r\n update.from_user.first_name),\r\n reply_markup=reply_markup,\r\n parse_mode=\"html\",\r\n reply_to_message_id=update.message_id\r\n )\r\n\r\n\r\n@Client.on_message(filters.command([\"help\"]) & filters.private, group=1)\r\nasync def help(bot, update):\r\n buttons = [[\r\n InlineKeyboardButton('HOME ⚓', callback_data='start'),\r\n InlineKeyboardButton('ABOUT ⭕', callback_data='about')\r\n ],[\r\n InlineKeyboardButton('CLOSE 🔒', callback_data='close')\r\n ]]\r\n \r\n reply_markup = InlineKeyboardMarkup(buttons)\r\n \r\n await bot.send_message(\r\n chat_id=update.chat.id,\r\n text=Translation.HELP_TEXT,\r\n reply_markup=reply_markup,\r\n parse_mode=\"html\",\r\n reply_to_message_id=update.message_id\r\n )\r\n\r\n\r\n@Client.on_message(filters.command([\"about\"]) & filters.private, group=1)\r\nasync def about(bot, update):\r\n \r\n buttons = [[\r\n InlineKeyboardButton('Home ⚓', callback_data='start'),\r\n InlineKeyboardButton('Close 🔒', callback_data='close')\r\n ]]\r\n reply_markup = InlineKeyboardMarkup(buttons)\r\n \r\n await bot.send_message(\r\n chat_id=update.chat.id,\r\n text=Translation.ABOUT_TEXT,\r\n reply_markup=reply_markup,\r\n disable_web_page_preview=True,\r\n parse_mode=\"html\",\r\n reply_to_message_id=update.message_id\r\n )\r\n", "repo_name": "movie-sender-Rbot-v5/new_filter_bot_v1_for_mlm", "sub_path": "bot/plugins/commands.py", "file_name": "commands.py", "file_ext": "py", "file_size_in_byte": 3988, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "bot.database.Database", "line_number": 10, "usage_type": "call"}, {"api_name": "pyrogram.types.InlineKeyboardMarkup", "line_number": 33, "usage_type": "call"}, {"api_name": "pyrogram.types.InlineKeyboardButton", "line_number": 36, "usage_type": "call"}, {"api_name": "bot.LOGGER", "line_number": 46, "usage_type": "call"}, {"api_name": "pyrogram.types.InlineKeyboardButton", "line_number": 50, "usage_type": "call"}, {"api_name": "pyrogram.types.InlineKeyboardButton", "line_number": 52, "usage_type": "call"}, {"api_name": "pyrogram.types.InlineKeyboardButton", "line_number": 54, "usage_type": "call"}, {"api_name": "pyrogram.types.InlineKeyboardButton", "line_number": 55, "usage_type": "call"}, {"api_name": "pyrogram.types.InlineKeyboardButton", "line_number": 57, "usage_type": "call"}, {"api_name": "pyrogram.types.InlineKeyboardMarkup", "line_number": 60, "usage_type": "call"}, {"api_name": "bot.send_message", "line_number": 62, "usage_type": "call"}, {"api_name": "bot.Translation.START_TEXT.format", "line_number": 64, "usage_type": "call"}, {"api_name": "bot.Translation.START_TEXT", "line_number": 64, "usage_type": "attribute"}, {"api_name": "bot.Translation", "line_number": 64, "usage_type": "name"}, {"api_name": "pyrogram.Client.on_message", "line_number": 12, "usage_type": "call"}, {"api_name": "pyrogram.Client", "line_number": 12, "usage_type": "name"}, {"api_name": "pyrogram.filters.command", "line_number": 12, "usage_type": "call"}, {"api_name": "pyrogram.filters", "line_number": 12, "usage_type": "name"}, {"api_name": "pyrogram.filters.private", "line_number": 12, "usage_type": "attribute"}, {"api_name": "pyrogram.types.InlineKeyboardButton", "line_number": 75, "usage_type": "call"}, {"api_name": "pyrogram.types.InlineKeyboardButton", "line_number": 76, "usage_type": "call"}, {"api_name": "pyrogram.types.InlineKeyboardButton", "line_number": 78, "usage_type": "call"}, {"api_name": "pyrogram.types.InlineKeyboardMarkup", "line_number": 81, "usage_type": "call"}, {"api_name": "bot.send_message", "line_number": 83, "usage_type": "call"}, {"api_name": "bot.Translation.HELP_TEXT", "line_number": 85, "usage_type": "attribute"}, {"api_name": "bot.Translation", "line_number": 85, "usage_type": "name"}, {"api_name": "pyrogram.Client.on_message", "line_number": 72, "usage_type": "call"}, {"api_name": "pyrogram.Client", "line_number": 72, "usage_type": "name"}, {"api_name": "pyrogram.filters.command", "line_number": 72, "usage_type": "call"}, {"api_name": "pyrogram.filters", "line_number": 72, "usage_type": "name"}, {"api_name": "pyrogram.filters.private", "line_number": 72, "usage_type": "attribute"}, {"api_name": "pyrogram.types.InlineKeyboardButton", "line_number": 96, "usage_type": "call"}, {"api_name": "pyrogram.types.InlineKeyboardButton", "line_number": 97, "usage_type": "call"}, {"api_name": "pyrogram.types.InlineKeyboardMarkup", "line_number": 99, "usage_type": "call"}, {"api_name": "bot.send_message", "line_number": 101, "usage_type": "call"}, {"api_name": "bot.Translation.ABOUT_TEXT", "line_number": 103, "usage_type": "attribute"}, {"api_name": "bot.Translation", "line_number": 103, "usage_type": "name"}, {"api_name": "pyrogram.Client.on_message", "line_number": 92, "usage_type": "call"}, {"api_name": "pyrogram.Client", "line_number": 92, "usage_type": "name"}, {"api_name": "pyrogram.filters.command", "line_number": 92, "usage_type": "call"}, {"api_name": "pyrogram.filters", "line_number": 92, "usage_type": "name"}, {"api_name": "pyrogram.filters.private", "line_number": 92, "usage_type": "attribute"}]} +{"seq_id": "4850914973", "text": "from copy import deepcopy\nimport sys\nfrom itertools import permutations\n\n\ndef rotateFunc(c,r,s, arr):\n startx = r - s - 1\n starty = c - s - 1\n index = 1\n while True:\n if startx == r-1 and starty == c - 1:\n break\n\n temp = arr[starty][startx]\n\n for nowy in range(starty, c+s-index):\n arr[nowy][startx] = arr[nowy+1][startx]\n\n for nowx in range(startx, r+s-index):\n arr[c+s-index][nowx] = arr[c+s-index][nowx+1]\n\n for nowy in range(c+s-index, starty, -1):\n arr[nowy][r+s-index] = arr[nowy-1][r+s-index]\n\n for nowx in range(r+s-index, startx,-1):\n arr[starty][nowx] = arr[starty][nowx-1]\n\n arr[starty][startx+1] = temp\n\n startx += 1\n starty += 1\n index += 1\n\ninput = sys.stdin.readline\n\nn,m,k = map(int, input().rstrip().split(' '))\n\nanswer = 10**5\n\narr = []\nrotate = []\nrotatearr = [i for i in range(k)]\n\nfor _ in range(n):\n arr.append(list(map(int,input().rstrip().split(' '))))\n\n\nfor _ in range(k):\n rotate.append(list(map(int,input().rstrip().split(' '))))\n\nrotatePerm = list(permutations(rotatearr,k))\n\nfor nowRotate in rotatePerm:\n nowArr = deepcopy(arr)\n for rotateIndex in nowRotate:\n nowR, nowC, nowS = rotate[rotateIndex]\n rotateFunc(nowR, nowC, nowS, nowArr)\n answer = min(answer, min([sum(nowArr[i]) for i in range(n)]))\n\nprint(answer)\n", "repo_name": "JiyoungMa/Algorithm", "sub_path": "백준/17406 배열 돌리기 4.py", "file_name": "17406 배열 돌리기 4.py", "file_ext": "py", "file_size_in_byte": 1410, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "sys.stdin", "line_number": 34, "usage_type": "attribute"}, {"api_name": "itertools.permutations", "line_number": 51, "usage_type": "call"}, {"api_name": "copy.deepcopy", "line_number": 54, "usage_type": "call"}]} +{"seq_id": "72236126132", "text": "import torch\nfrom nmt.model.seq2seq_rnn import RNNSeq2Seq\nfrom nmt.model.seq2seq_luong import LuongSeq2Seq\nfrom nmt.model.seq2seq_bahdanau import BahdanauSeq2Seq\nfrom nmt.model.seq2seq_transformer import TransformerSeq2Seq\n\nMODELS = {\n 'rnn': RNNSeq2Seq,\n 'luong': LuongSeq2Seq,\n 'bahdanau': BahdanauSeq2Seq,\n 'transformer': TransformerSeq2Seq,\n}\n\ndef create_model(enc_vocab, dec_vocab, **kw):\n model_type = kw.get('type', None)\n model_params = kw.get('params', None)\n if not model_type or not model_params:\n raise KeyError('invalid model configure')\n\n Seq2Seq = MODELS.get(model_type, None)\n if not Seq2Seq:\n raise KeyError('invalid model type')\n params = model_params.get(model_type, None)\n if not params:\n raise KeyError('invalid model params')\n\n seq2seq = Seq2Seq(enc_vocab, dec_vocab, **params)\n seq2seq.apply(init_weights)\n return seq2seq\n\ndef init_weights(m):\n if type(m) == torch.nn.Linear:\n torch.nn.init.xavier_uniform_(m.weight)\n else:\n for name, param in m.named_parameters():\n if 'weight' in name and param.dim() > 1:\n torch.nn.init.xavier_uniform_(param.data)\n\ndef load_ckpt(model_dir, model, optimizer=None, mode='last'):\n checkpoint = torch.load(model_dir.rfile(f'checkpoint-{mode}.pt'))\n model.load_state_dict(checkpoint['model'])\n if optimizer is not None:\n optimizer.load_state_dict(checkpoint['optim'])\n\ndef save_ckpt(model_dir, model, optimizer=None, mode='last'):\n checkpoint = {}\n checkpoint['model'] = model.state_dict()\n if optimizer is not None:\n checkpoint['optim'] = optimizer.state_dict()\n torch.save(checkpoint, model_dir.file(f'checkpoint-{mode}.pt'))\n", "repo_name": "chengui/torch-nmt", "sub_path": "nmt/model/__init__.py", "file_name": "__init__.py", "file_ext": "py", "file_size_in_byte": 1744, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "21", "api": [{"api_name": "nmt.model.seq2seq_rnn.RNNSeq2Seq", "line_number": 8, "usage_type": "name"}, {"api_name": "nmt.model.seq2seq_luong.LuongSeq2Seq", "line_number": 9, "usage_type": "name"}, {"api_name": "nmt.model.seq2seq_bahdanau.BahdanauSeq2Seq", "line_number": 10, "usage_type": "name"}, {"api_name": "nmt.model.seq2seq_transformer.TransformerSeq2Seq", "line_number": 11, "usage_type": "name"}, {"api_name": "torch.nn", "line_number": 32, "usage_type": "attribute"}, {"api_name": "torch.nn.init.xavier_uniform_", "line_number": 33, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 33, "usage_type": "attribute"}, {"api_name": "torch.nn.init.xavier_uniform_", "line_number": 37, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 37, "usage_type": "attribute"}, {"api_name": "torch.load", "line_number": 40, "usage_type": "call"}, {"api_name": "torch.save", "line_number": 50, "usage_type": "call"}]} +{"seq_id": "5664599797", "text": "from time import sleep\nfrom turtle import pos\nfrom bot2 import Insta_Bot\nfrom selenium import webdriver\nimport sqlite3\nimport datetime as dt\n\nstatrt = dt.datetime.now()\nbrowser = webdriver.Firefox(executable_path=\"geckodriver\")\nbrowser.get('https://www.instagram.com/')\nbrowser.add_cookie({\"name\" : \"sessionid\" ,\"domain\" : \".instagram.com\", \"value\" : \"17129991155%3ALfzxCcWImYn9rz%3A16\",\"httponly\" : True ,\"secure\" : True})\n\nbot_insta = Insta_Bot(browser)\n\n# 17129991155\npkfollowings = bot_insta.get_followings_pks(17129991155)\n\n\ndef get_like_word():\n conn = sqlite3.connect('AlphA.db')\n c = conn.cursor()\n c.execute(\"SELECT username,pk FROM User Where (bio like '%photo%' or bio like '%عکاس%' or username like '%photo%' or work like '%photo%') and following > 500 and followers < 1500\")\n b = set(c.fetchall())\n x = []\n for i in b:\n x.append([i[0],i[1]]) \n # c.execute(\"SELECT username FROM User Where bio like '%%'\")\n print(len(x))\n return x\n\n# print(get_like_word())\n\n\nusers2 = []\nusers = get_like_word()\n\nfor i in users:\n if i[1] in pkfollowings:\n print('l')\n continue\n users2.append(i[0])\n\n\nlenusers = len(users2)\nj = 0 \nfor i in users2:\n sleep(5)\n try:\n username = i[0]\n bot_insta.follow_user(username)\n # sleep(18)\n posts = bot_insta.get_all_post(username)\n postlen = len(posts)\n sleep(10)\n jj = 0\n for i in posts:\n try:\n bot_insta.like_post(i)\n except:\n pass\n print(f\"like posts of {username} : {jj}/{postlen}\")\n jj += 1\n sleep(10)\n \n except:\n pass\n \n print(f\"users : {j}/{lenusers}\")\n j += 1\n fin0 = dt.datetime.now()\n print(f\"time : {fin0 - statrt}\")\n\n sleep(180)\n\n\nfinish = dt.datetime.now()\nprint(f\"full time = {finish - statrt}\")\n\n\n\n", "repo_name": "awmxr/Insta-Bot", "sub_path": "03.py", "file_name": "03.py", "file_ext": "py", "file_size_in_byte": 1886, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "datetime.datetime.now", "line_number": 8, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 8, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.Firefox", "line_number": 9, "usage_type": "call"}, {"api_name": "selenium.webdriver", "line_number": 9, "usage_type": "name"}, {"api_name": "bot2.Insta_Bot", "line_number": 13, "usage_type": "call"}, {"api_name": "sqlite3.connect", "line_number": 20, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 47, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 54, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 63, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 70, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 70, "usage_type": "attribute"}, {"api_name": "time.sleep", "line_number": 73, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 76, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 76, "usage_type": "attribute"}]} +{"seq_id": "3114178344", "text": "'''\nCreated on Jul. 17, 2021\n\n@author: zollen\n@score: \nlag features for the prediction.xsd - output: 1.03740\nitem_cnt_month_lag1,2,3\ndate_item_avg_cnt_lag1,2,3\ndate_shop_item_avg_cnt_lag1,2,3\ndate_shop_subtype_avg_cnt_lag1,2,3\ndelta_reveune_lag2\ndelta_price_lag1,2,3\ndate_itemtype_avg_cnt_lag1\ndate_itemcat_avg_cnt_lag1,2,3\ndate_name3_avg_cnt_lag2\n'''\n\nimport pandas as pd\nimport numpy as np\nimport time\nfrom xgboost import XGBRegressor\nimport futuresales_kaggle.lib.future_lib as ft\nimport warnings\n\n\nwarnings.filterwarnings('ignore')\n\npd.set_option('max_columns', None)\npd.set_option('max_rows', None)\npd.set_option('display.width', 1000)\n\nnp.random.seed(0)\n\ntarget = 'item_price'\nlabel = 'item_cnt_month'\nkeys = ['shop_id', 'item_id']\nbase_features = ['date_block_num', 'shop_id', 'item_id', \n 'shop_category', 'shop_city', \n 'item_category_id', 'name2', \n 'name3', 'item_type', 'item_subtype']\n\nlag_features = []\n \n\nfeatures = base_features + ['item_price_lag1', \n 'item_price_lag2', \n 'item_price_lag3',\n 'item_price_lag4',\n 'item_price_lag5'] + lag_features\n\ntrain = pd.read_csv('../data/monthly_train.csv')\nraw = pd.read_csv('../data/sales_train.csv')\ntest = pd.read_csv('../data/monthly_test.csv')\nitems = pd.read_csv('../data/monthly_items.csv')\ncats = pd.read_csv('../data/monthly_cats.csv')\nshops = pd.read_csv('../data/monthly_shops.csv')\npreds = pd.read_csv('../data/prediction.csv')\n\n\n'''\nmerge cats, shops and items\n'''\nitems_cats = pd.merge(items, cats, how='left', on='item_category_id')\ntrain_item_cats = pd.merge(train, items_cats, how='left', on='item_id')\nraw_item_cats = pd.merge(raw, items_cats, how='left', on='item_id')\ntest_item_cats = pd.merge(test, items_cats, how='left', on='item_id')\ntrain_item_cats_shops = pd.merge(train_item_cats, shops, how='left', on='shop_id')\ntest_item_cats_shops = pd.merge(test_item_cats, shops, how='left', on='shop_id')\ntest_item_cats_shops[label] = preds[label]\ntest_item_cats_shops[label] = test_item_cats_shops[label].clip(0, 20)\ntrain_item_cats_shops[label] = train_item_cats_shops[label].clip(0, 20)\n\n\n\nall_df = pd.concat([train_item_cats_shops, test_item_cats_shops])\nall_df.drop(columns=['ID'], inplace=True)\n\npp = ft.add_lag_features(all_df, 5, keys, ['item_price' ] + lag_features)\n\npp.drop(columns=lag_features, inplace = True)\n\n\n\nt1 = pp[pp['date_block_num'] < 34]\nt3 = pp[pp['date_block_num'] == 34]\n\n\nprint(\"TOTAL: \", len(test))\nprint(t1.head())\n\nstart_ts = time.time()\n\nmodel = XGBRegressor()\nmodel.fit(t1[features], t1[target])\n\n\nt3[target] = model.predict(t3[features])\n\ntest.drop(columns=[target], inplace = True)\ntest = test.merge(t3[['shop_id', 'item_id', 'item_price']], on=['shop_id', 'item_id'], how='left')\ntest.fillna(0, inplace=True)\n\n'''\nselect rows that exists only in test, but not in train\n'''\nk = test.merge(train[['shop_id', 'item_id']], \n on=['shop_id', 'item_id'], how='outer', indicator=True).loc[lambda x : x['_merge'] == 'left_only']\n\ntest = test.set_index(['shop_id', 'item_id'])\nk = k.set_index(['shop_id', 'item_id'])\n\ntest.loc[test.index.isin(k.index), 'item_price'] = 0\n\ntest = test.reset_index()\nk = k.reset_index()\n\nend_ts = time.time() \n\n\nprint(\"TOTAL: \", len(test))\nprint(\"TIME: \", end_ts - start_ts)\n\ntest.to_csv('../data/monthly_test2.csv', index = False)\nprint(\"Done\")\n", "repo_name": "zollen/Python-ML", "sub_path": "futuresales_kaggle/work1/prices.py", "file_name": "prices.py", "file_ext": "py", "file_size_in_byte": 3437, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "warnings.filterwarnings", "line_number": 26, "usage_type": "call"}, {"api_name": "pandas.set_option", "line_number": 28, "usage_type": "call"}, {"api_name": "pandas.set_option", "line_number": 29, "usage_type": "call"}, {"api_name": "pandas.set_option", "line_number": 30, "usage_type": "call"}, {"api_name": "numpy.random.seed", "line_number": 32, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 32, "usage_type": "attribute"}, {"api_name": "pandas.read_csv", "line_number": 51, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 52, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 53, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 54, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 55, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 56, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 57, "usage_type": "call"}, {"api_name": "pandas.merge", "line_number": 63, "usage_type": "call"}, {"api_name": "pandas.merge", "line_number": 64, "usage_type": "call"}, {"api_name": "pandas.merge", "line_number": 65, "usage_type": "call"}, {"api_name": "pandas.merge", "line_number": 66, "usage_type": "call"}, {"api_name": "pandas.merge", "line_number": 67, "usage_type": "call"}, {"api_name": "pandas.merge", "line_number": 68, "usage_type": "call"}, {"api_name": "pandas.concat", "line_number": 75, "usage_type": "call"}, {"api_name": "futuresales_kaggle.lib.future_lib.add_lag_features", "line_number": 78, "usage_type": "call"}, {"api_name": "futuresales_kaggle.lib.future_lib", "line_number": 78, "usage_type": "name"}, {"api_name": "time.time", "line_number": 91, "usage_type": "call"}, {"api_name": "xgboost.XGBRegressor", "line_number": 93, "usage_type": "call"}, {"api_name": "time.time", "line_number": 117, "usage_type": "call"}]} +{"seq_id": "73636092212", "text": "import time\nimport pyautogui\nimport os\nimport sys\nimport keyboard\nfrom Log import write_log_entry, increment_stat\nfrom Wrapper import timer\nfrom SettingsAndWindow import update_settings, get_idle_slayer_window\n\nbase_dir = os.path.dirname(os.path.abspath(sys.argv[0]))\nlogs_dir = os.path.join(base_dir, \"AutoSlayerLogs\")\n\n@timer\ndef bonus_stage(skip_bonus_stage_state):\n update_settings(\"paused\")\n \n write_log_entry(\"Start of BonusStage\")\n while True:\n slider()\n time.sleep(0.5)\n if not pyautogui.pixelMatchesColor(660, 254, (255, 231, 55)):\n break\n time.sleep(3.9)\n if skip_bonus_stage_state:\n bonus_stage_do_nothing()\n else:\n if not pyautogui.pixelMatchesColor(454, 91, (225, 224, 226)): # if Spirit Boost, do nothing until close appears\n bonus_stage_nsp()\n else:\n bonus_stage_nsp()\n\n@timer\ndef bonus_stage_do_nothing():\n write_log_entry(\"Do nothing BonusStage Active\")\n while not bonus_stage_fail():\n time.sleep(0.2)\n \n update_settings(\"paused\")\n\n@timer\ndef bonus_stage_fail():\n window = get_idle_slayer_window()\n print(\"Checking for exit button\")\n if pyautogui.pixelMatchesColor(window.left + 775, window.top + 600, (180, 0, 0), tolerance=10):\n pyautogui.leftClick(window.left + 721, window.top + 577)\n print(\"Exit button found\")\n \n write_log_entry(\"BonusStage Failed\")\n increment_stat(\"Failed/Skipped Bonus Stages\")\n \n update_settings(\"paused\")\n \n return True\n return False\n\ndef c_send(press_delay, post_press_delay=0, key=\"w\"):\n keyboard.press(key)\n time.sleep((press_delay / 1000))\n keyboard.release(key)\n time.sleep((post_press_delay / 1000))\n\n@timer\ndef slider():\n window = get_idle_slayer_window()\n # Define the positions\n positions = [\n {\"x\": 443, \"y\": 560, \"name\": \"Top Left\"},\n {\"x\": 443, \"y\": 620, \"name\": \"Bottom Left\"},\n {\"x\": 850, \"y\": 560, \"name\": \"Top Right\"},\n {\"x\": 850, \"y\": 620, \"name\": \"Bottom Right\"},\n ]\n \n for pos in positions:\n if pyautogui.pixelMatchesColor(window.left + pos[\"x\"], window.top + pos[\"y\"], (0, 126, 0)):\n perform_slider_operation(window, pos[\"x\"], pos[\"y\"], pos[\"name\"])\n return\n\ndef perform_slider_operation(window, x, y, name):\n start_x = window.left + 450 if name.endswith(\"Right\") else window.left + 840\n end_x = window.left + 840 if name.endswith(\"Right\") else window.left + 450\n pyautogui.moveTo(start_x, window.top + y)\n pyautogui.click(start_x, window.top + y)\n pyautogui.dragTo(end_x, window.top + y, button='left', duration=0.5)\n print(name)\n\n@timer\ndef find_pixel_until_found(x1, y1, x2, y2, color):\n window = get_idle_slayer_window()\n if x1 == x2 and y1 == y2:\n a_pos = None\n while True:\n a_pos = pyautogui.pixelMatchesColor(window.left + x1, window.top + y1, color)\n if a_pos is not False:\n print(a_pos)\n return a_pos\n else:\n a_pos = None\n while True:\n for x in range(x1, x2):\n for y in range(y1, y2):\n a_pos = pyautogui.pixelMatchesColor(window.left + x, window.top + y, color)\n if a_pos is not False:\n print(a_pos)\n return a_pos\n else:\n print(\"No match found\")\n\n@timer\ndef bonus_stage_sp():\n write_log_entry(\"BonusStageSpiritBoost\")\n\n # Section 1 sync\n find_pixel_until_found(220, 465, 220, 465(160, 147, 142))\n time.sleep(0.2)\n\n # Section 1 start\n c_send(162, 1177) #1\n c_send(73, 2452) #2\n c_send(66, 1688) #3\n c_send(84, 867) #4\n c_send(85, 2576) #5\n c_send(80, 740) #1\n c_send(90, 781) #2\n c_send(108, 2899) #3\n c_send(57, 722) #4\n c_send(83, 717) #5\n c_send(94, 5000) #1\n\n\n if bonus_stage_fail():\n return\n\n # Section 1 Collection\n c_send(40, 2500)\n for _ in range(19):\n pyautogui.press(\"w\")\n time.sleep(0.4)\n\n if bonus_stage_fail():\n return\n\n write_log_entry(\"BonusStageSpiritBoost Section 1 Complete\")\n\n # Section 2 sync\n find_pixel_until_found(780, 536, 780, 536, (187, 38, 223))\n\n # Section 2 start\n c_send(156, 719) #1\n c_send(47, 687) #2\n c_send(360, 1390) #3\n c_send(485, 344) #4\n c_send(406, 859) #5\n c_send(78, 600) #6\n c_send(94, 900) #7\n c_send(109, 954) #8\n c_send(31, 672) #9\n c_send(515, 1344) #10\n c_send(484, 297) #11\n c_send(406, 859) #12\n c_send(78, 600) #13\n c_send(94, 900) #14\n c_send(109, 954) #15\n c_send(31, 672) #16\n c_send(515, 1344) #17\n c_send(469, 219) #18\n c_send(297, 1000) #19\n c_send(156, 500) #20\n c_send(110, 3000) #21\n c_send(360, 2984) #22\n c_send(531, 2313) #23\n\n\n if bonus_stage_fail():\n return\n\n # Section 2 Collection\n c_send(350, 1000)\n for _ in range(20):\n pyautogui.press(\"w\")\n time.sleep(0.4)\n\n if bonus_stage_fail():\n return\n\n write_log_entry(\"BonusStageSpiritBoost Section 2 Complete\")\n\n # Stage 3 sync\n find_pixel_until_found(220, 465, 220, 465, (160, 147, 142))\n\n # Section 3 Start\n c_send(109, 1203) #1\n c_send(31, 641) #2\n c_send(47, 1200) #3\n c_send(1, 3100) #4\n #repeat\n c_send(109, 1203) #5\n c_send(31, 641) #6\n c_send(47, 1200) #7\n c_send(1, 3100) #8\n #repeat\n c_send(109, 1203) #9\n c_send(31, 641) #10\n c_send(47, 1200) #11\n c_send(1, 3100) #12\n #repeat\n c_send(109, 1203) #13\n c_send(31, 641) #14\n c_send(47, 5125) #15\n\n\n if bonus_stage_fail():\n return\n\n # Section 3 Collection\n c_send(900, 200)\n for _ in range(20):\n pyautogui.press(\"w\")\n time.sleep(0.4)\n\n if bonus_stage_fail():\n return\n\n write_log_entry(\"BonusStageSpiritBoost Section 3 Complete\")\n\n # Section 4 sync\n find_pixel_until_found(250, 472, 100, 250, (13, 32, 48))\n time.sleep(0.2)\n\n # Section 4 Start\n c_send(32, 2800) #1\n c_send(31, 809) #2\n c_send(41, 1200) #3\n c_send(100, 900) #4\n c_send(641, 500) #5\n\n c_send(31, 850) #6\n c_send(41, 770) #7\n c_send(641, 400) #8\n\n c_send(31, 850) #9\n c_send(41, 870) #10\n c_send(641, 300) #11\n\n c_send(31, 850) #12\n c_send(41, 790) #13\n c_send(641, 400) #14\n\n c_send(31, 850) #15\n c_send(41, 840) #16\n c_send(641, 300) #17\n\n c_send(31, 850) #18\n c_send(41, 840) #19\n c_send(641, 300) #20\n\n # Section 4 Collection\n for _ in range(23):\n pyautogui.press(\"w\")\n time.sleep(0.4)\n\n if bonus_stage_fail():\n return\n\n update_settings(\"paused\")\n\n write_log_entry(\"BonusStageSpiritBoost Section 4 Complete\")\n\n@timer\ndef bonus_stage_nsp():\n write_log_entry(\"BonusStage\")\n # Section 1 sync\n find_pixel_until_found(220, 465, 220, 465, (160, 147, 142))\n time.sleep(0.2)\n\n # Section 1 start\n c_send(94, 1640) #1\n c_send(32, 1218) #2\n c_send(94, 600) #3\n c_send(109, 1828) #4\n c_send(63, 640) #5\n c_send(47, 688) #6\n c_send(78, 1906) #7\n c_send(141, 1625) #8\n c_send(47, 3187) #9\n c_send(47, 734) #10\n c_send(47, 750) #11\n c_send(78, 1203) #12\n c_send(110, 5000) #13\n\n if bonus_stage_fail():\n return\n\n # Section 1 Collection\n c_send(40, 5000)\n for _ in range(17):\n pyautogui.press(\"w\")\n time.sleep(0.4)\n if bonus_stage_fail():\n return\n else:\n increment_stat(\"Stage 2 Section 1 Completed\")\n write_log_entry(\"BonusStage Section 1 Complete\")\n\n # Section 2 sync\n find_pixel_until_found(780, 536, 780, 536, (187, 38, 223))\n\n # Section 2 start\n c_send(156, 719) #1\n c_send(47, 687) #2\n c_send(360, 1390) #3\n c_send(485, 344) #4\n c_send(406, 859) #5\n c_send(78, 600) #6\n c_send(94, 900) #7\n c_send(109, 954) #8\n c_send(31, 672) #9\n c_send(515, 1344) #10\n c_send(484, 297) #11\n c_send(406, 859) #12\n c_send(78, 600) #13\n c_send(94, 900) #14\n c_send(109, 954) #15\n c_send(31, 672) #16\n c_send(515, 1344) #17\n c_send(469, 219) #18\n c_send(297, 1000) #19\n c_send(156, 500) #20\n c_send(110, 3000) #21\n c_send(360, 2984) #22\n c_send(531, 2313) #23\n\n if bonus_stage_fail():\n return\n\n # Section 2 Collection\n c_send(350, 1000)\n for _ in range(20):\n pyautogui.press(\"w\")\n time.sleep(0.4)\n if bonus_stage_fail():\n return\n else:\n increment_stat(\"Stage 2 Section 2 Completed\")\n write_log_entry(\"BonusStage Section 2 Complete\")\n\n # Stage 3 sync\n find_pixel_until_found(220, 465, 220, 465, (160, 147, 142))\n\n # Section 3 Start\n c_send(109, 1203) #1\n c_send(31, 641) #2\n c_send(47, 1578) #3\n c_send(47, 2437) #4\n #repeat\n c_send(109, 1203) #5\n c_send(31, 641) #6\n c_send(47, 1578) #7\n c_send(47, 2437) #8\n #repeat\n c_send(109, 1203) #9\n c_send(31, 641) #10\n c_send(47, 1578) #11\n c_send(47, 2437) #12\n #repeat\n c_send(109, 1203) #13\n c_send(31, 641) #14\n c_send(47, 5125) #15\n if bonus_stage_fail():\n return\n\n # Section 3 Collection\n c_send(900, 200)\n for _ in range(20):\n pyautogui.press(\"w\")\n time.sleep(0.4)\n if bonus_stage_fail():\n return\n else:\n increment_stat(\"Stage 2 Section 3 Completed\")\n write_log_entry(\"BonusStage Section 3 Complete\")\n\n # Section 4 sync\n find_pixel_until_found(100, 250, 250, 472, (13, 32, 48))\n time.sleep(0.2)\n\n # Section 4 Start\n c_send(32, 1375) #1\n c_send(641, 690) #2\n c_send(41, 1375) #3\n c_send(41, 1374) #4\n c_send(641, 690) #5\n c_send(41, 1373) #6\n c_send(41, 2500) #7\n c_send(31, 809) #8\n c_send(41, 1375) #9\n c_send(41, 1374) #10\n c_send(641, 690) #11\n c_send(41, 1373) #12\n c_send(41, 1372) #13\n c_send(641, 690) #14\n c_send(41, 1371) #15\n # extra jump just in case\n c_send(41) #16\n\n # Section 4 Collection\n for _ in range(23):\n pyautogui.press(\"w\")\n time.sleep(0.4)\n if bonus_stage_fail():\n return\n else:\n increment_stat(\"Stage 2 Section 4 Completed\")\n write_log_entry(\"BonusStage Section 4 Complete\")\n increment_stat(\"Bonus Stages\")\n\n update_settings(\"paused\")", "repo_name": "RLAlpha49/Idle-Slayer-Script", "sub_path": "BonusStage.py", "file_name": "BonusStage.py", "file_ext": "py", "file_size_in_byte": 10361, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "21", "api": [{"api_name": "os.path.dirname", "line_number": 10, "usage_type": "call"}, {"api_name": "os.path", "line_number": 10, "usage_type": "attribute"}, {"api_name": "os.path.abspath", "line_number": 10, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 10, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 11, "usage_type": "call"}, {"api_name": "os.path", "line_number": 11, "usage_type": "attribute"}, {"api_name": "SettingsAndWindow.update_settings", "line_number": 15, "usage_type": "call"}, {"api_name": "Log.write_log_entry", "line_number": 17, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 20, "usage_type": "call"}, {"api_name": "pyautogui.pixelMatchesColor", "line_number": 21, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 23, "usage_type": "call"}, {"api_name": "pyautogui.pixelMatchesColor", "line_number": 27, "usage_type": "call"}, {"api_name": "Wrapper.timer", "line_number": 13, "usage_type": "name"}, {"api_name": "Log.write_log_entry", "line_number": 34, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 36, "usage_type": "call"}, {"api_name": "SettingsAndWindow.update_settings", "line_number": 38, "usage_type": "call"}, {"api_name": "Wrapper.timer", "line_number": 32, "usage_type": "name"}, {"api_name": "SettingsAndWindow.get_idle_slayer_window", "line_number": 42, "usage_type": "call"}, {"api_name": "pyautogui.pixelMatchesColor", "line_number": 44, "usage_type": "call"}, {"api_name": "pyautogui.leftClick", "line_number": 45, "usage_type": "call"}, {"api_name": "Log.write_log_entry", "line_number": 48, "usage_type": "call"}, {"api_name": "Log.increment_stat", "line_number": 49, "usage_type": "call"}, {"api_name": "SettingsAndWindow.update_settings", "line_number": 51, "usage_type": "call"}, {"api_name": "Wrapper.timer", "line_number": 40, "usage_type": "name"}, {"api_name": "keyboard.press", "line_number": 57, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 58, "usage_type": "call"}, {"api_name": "keyboard.release", "line_number": 59, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 60, "usage_type": "call"}, {"api_name": "SettingsAndWindow.get_idle_slayer_window", "line_number": 64, "usage_type": "call"}, {"api_name": "pyautogui.pixelMatchesColor", "line_number": 74, "usage_type": "call"}, {"api_name": "Wrapper.timer", "line_number": 62, "usage_type": "name"}, {"api_name": "pyautogui.moveTo", "line_number": 81, "usage_type": "call"}, {"api_name": "pyautogui.click", "line_number": 82, "usage_type": "call"}, {"api_name": "pyautogui.dragTo", "line_number": 83, "usage_type": "call"}, {"api_name": "SettingsAndWindow.get_idle_slayer_window", "line_number": 88, "usage_type": "call"}, {"api_name": "pyautogui.pixelMatchesColor", "line_number": 92, "usage_type": "call"}, {"api_name": "pyautogui.pixelMatchesColor", "line_number": 101, "usage_type": "call"}, {"api_name": "Wrapper.timer", "line_number": 86, "usage_type": "name"}, {"api_name": "Log.write_log_entry", "line_number": 110, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 114, "usage_type": "call"}, {"api_name": "pyautogui.press", "line_number": 136, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 137, "usage_type": "call"}, {"api_name": "Log.write_log_entry", "line_number": 142, "usage_type": "call"}, {"api_name": "pyautogui.press", "line_number": 179, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 180, "usage_type": "call"}, {"api_name": "Log.write_log_entry", "line_number": 185, "usage_type": "call"}, {"api_name": "pyautogui.press", "line_number": 217, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 218, "usage_type": "call"}, {"api_name": "Log.write_log_entry", "line_number": 223, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 227, "usage_type": "call"}, {"api_name": "pyautogui.press", "line_number": 258, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 259, "usage_type": "call"}, {"api_name": "SettingsAndWindow.update_settings", "line_number": 264, "usage_type": "call"}, {"api_name": "Log.write_log_entry", "line_number": 266, "usage_type": "call"}, {"api_name": "Wrapper.timer", "line_number": 108, "usage_type": "name"}, {"api_name": "Log.write_log_entry", "line_number": 270, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 273, "usage_type": "call"}, {"api_name": "pyautogui.press", "line_number": 296, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 297, "usage_type": "call"}, {"api_name": "Log.increment_stat", "line_number": 301, "usage_type": "call"}, {"api_name": "Log.write_log_entry", "line_number": 302, "usage_type": "call"}, {"api_name": "pyautogui.press", "line_number": 338, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 339, "usage_type": "call"}, {"api_name": "Log.increment_stat", "line_number": 343, "usage_type": "call"}, {"api_name": "Log.write_log_entry", "line_number": 344, "usage_type": "call"}, {"api_name": "pyautogui.press", "line_number": 374, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 375, "usage_type": "call"}, {"api_name": "Log.increment_stat", "line_number": 379, "usage_type": "call"}, {"api_name": "Log.write_log_entry", "line_number": 380, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 384, "usage_type": "call"}, {"api_name": "pyautogui.press", "line_number": 407, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 408, "usage_type": "call"}, {"api_name": "Log.increment_stat", "line_number": 412, "usage_type": "call"}, {"api_name": "Log.write_log_entry", "line_number": 413, "usage_type": "call"}, {"api_name": "Log.increment_stat", "line_number": 414, "usage_type": "call"}, {"api_name": "SettingsAndWindow.update_settings", "line_number": 416, "usage_type": "call"}, {"api_name": "Wrapper.timer", "line_number": 268, "usage_type": "name"}]} +{"seq_id": "20595737829", "text": "from fourparts import Notes\nimport pytest\n\n\ndef test_cases():\n return [\n (\"C\", 0),\n (\"C#/Db\", 1),\n (\"D\", 2),\n (\"D#/Eb\", 3),\n (\"E\", 4),\n (\"F\", 5),\n (\"F#/Gb\", 6),\n (\"G\", 7),\n (\"G#/Ab\", 8),\n (\"A\", 9),\n (\"A#/Bb\", 10),\n (\"B\", 11),\n ]\n\n\n@pytest.mark.parametrize(\"note, expected\", test_cases())\ndef test_eval(note, expected):\n assert Notes.get_note_index(note) == expected\n\n\ndef exception_cases():\n return [(\"not a note\", pytest.raises(KeyError))]\n\n\n@pytest.mark.parametrize(\"note, exception\", exception_cases())\ndef test_exception(note, exception):\n with exception:\n assert Notes.get_note_index(note) is not None\n", "repo_name": "ruixuantan/FourParts", "sub_path": "tests/test_structures/test_notes/test_Notes/test_get_note_index.py", "file_name": "test_get_note_index.py", "file_ext": "py", "file_size_in_byte": 713, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "fourparts.Notes.get_note_index", "line_number": 24, "usage_type": "call"}, {"api_name": "fourparts.Notes", "line_number": 24, "usage_type": "name"}, {"api_name": "pytest.mark.parametrize", "line_number": 22, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 22, "usage_type": "attribute"}, {"api_name": "pytest.raises", "line_number": 28, "usage_type": "call"}, {"api_name": "fourparts.Notes.get_note_index", "line_number": 34, "usage_type": "call"}, {"api_name": "fourparts.Notes", "line_number": 34, "usage_type": "name"}, {"api_name": "pytest.mark.parametrize", "line_number": 31, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 31, "usage_type": "attribute"}]} +{"seq_id": "36718486942", "text": "import torch\r\nimport cv2\r\nimport numpy as np\r\nimport PIL.ImageFile\r\nimport PIL.Image as Image\r\n\r\n\r\nclass Convert2:\r\n def __init__(self, im):\r\n if isinstance(im, torch.Tensor):\r\n im = im.detach().cpu()\r\n self.im = np.array(im)\r\n\r\n def convert2(self, c):\r\n if c in ['Torch', 'torch', 'Tensor', 'tensor', 'pytorch', 'Pytorch']:\r\n self.im = torch.from_numpy(self.im)\r\n elif c in ['PIL', 'Image']:\r\n self.im = Image.fromarray(self.im)\r\n return self.im\r\n\r\n def float(self):\r\n self.im = self.im.astype(np.float32)\r\n\r\n def uint8(self):\r\n self.im = self.im.astype(np.uint8)\r\n\r\n # 应该只压缩维度\r\n def set_dim(self, dim):\r\n self.im = np.squeeze(self.im)\r\n for _ in range(dim - self.im.ndim):\r\n self.im = self.im[np.newaxis, :]\r\n\r\n def alpha(self, alpha):\r\n self.im = self.im * alpha\r\n\r\n\r\ndef Any2Torch(im, dim=4):\r\n if isinstance(im, torch.Tensor):\r\n return im\r\n c = Convert2(im)\r\n if isinstance(im, PIL.ImageFile.ImageFile):\r\n c.float()\r\n c.alpha(1 / 255.)\r\n elif c.im.dtype == np.uint8:\r\n c.float()\r\n c.alpha(1 / 255.)\r\n c.set_dim(dim)\r\n if dim is 4:\r\n if c.im.shape[-1] is 3:\r\n c.im = c.im.transpose([0, 3, 1, 2])\r\n else:\r\n if c.im.shape[-1] is 3:\r\n c.im = c.im.transpose([2, 0, 1])\r\n return c.convert2('Torch')\r\n\r\n\r\ndef Any2PIL(im):\r\n if isinstance(im, PIL.ImageFile.ImageFile):\r\n return im\r\n c = Convert2(im)\r\n if isinstance(im, torch.Tensor):\r\n c.alpha(255.)\r\n c.uint8()\r\n c.set_dim(2)\r\n if c.im.ndim is 3 and c.im.shape[0] == 3:\r\n c.im = c.im.transpose([1, 2, 0])\r\n return c.convert2('PIL')\r\n\r\n\r\ndef Any2np(im):\r\n c = Convert2(im)\r\n return c.convert2('np')\r\n\r\n\r\ndef kpl2lst(kpl):\r\n \"\"\"\r\n 将cv2的KeyPoint list转换成[Nx2]的numpy\r\n :param kpl:KeyPoint list\r\n :return:\r\n \"\"\"\r\n if isinstance(kpl, list):\r\n return np.array([pt.pt for pt in kpl]).astype(np.float32)\r\n else:\r\n return kpl.squeeze()\r\n\r\n\r\ndef lst2kpl(lst):\r\n \"\"\"\r\n 将numpy表示的点转回KeyPoint list\r\n :param lst:\r\n :return: list\r\n \"\"\"\r\n return [cv2.KeyPoint(float(pt[0]), float(pt[1]), 32) for pt in lst]\r\n\r\n\r\n# --------------------------------------------------------------------------\r\n# 转换仿射矩阵\r\n# --------------------------------------------------------------------------\r\ndef get_N(W, H):\r\n \"\"\"N that maps from unnormalized to normalized coordinates\"\"\"\r\n N = np.zeros((3, 3), dtype=np.float64)\r\n N[0, 0] = 2.0 / W\r\n N[0, 1] = 0\r\n N[1, 1] = 2.0 / H\r\n N[1, 0] = 0\r\n N[0, -1] = -1.0\r\n N[1, -1] = -1.0\r\n N[-1, -1] = 1.0\r\n return N\r\n\r\n\r\ndef get_N_inv(W, H):\r\n \"\"\"N that maps from normalized to unnormalized coordinates\"\"\"\r\n N = get_N(W, H)\r\n return np.linalg.inv(N)\r\n\r\n\r\ndef cv_m2theta(M, w, h):\r\n \"\"\"convert affine warp matrix `M` compatible with `opencv.warpAffine` to `theta` matrix\r\n compatible with `torch.F.affine_grid`\r\n\r\n Parameters\r\n ----------\r\n M : np.ndarray\r\n affine warp matrix shaped [2, 3]\r\n w : int\r\n width of image\r\n h : int\r\n height of image\r\n\r\n Returns\r\n -------\r\n np.ndarray\r\n theta tensor for `torch.F.affine_grid`, shaped [2, 3]\r\n \"\"\"\r\n M_aug = np.concatenate([M, np.zeros((1, 3))], axis=0)\r\n M_aug[-1, -1] = 1.0\r\n N = get_N(w, h)\r\n N_inv = get_N_inv(w, h)\r\n theta = N @ M_aug @ N_inv\r\n theta = np.linalg.inv(theta)\r\n return theta[:2, :]\r\n\r\n\r\ndef theta2cv_m(theta, w, h, return_inv=False):\r\n \"\"\"convert theta matrix compatible with `torch.F.affine_grid` to affine warp matrix `M`\r\n compatible with `opencv.warpAffine`.\r\n\r\n Note:\r\n M works with `opencv.warpAffine`.\r\n To transform a set of bounding box corner points using `opencv.perspectiveTransform`, M^-1 is required\r\n\r\n Parameters\r\n ----------\r\n theta : np.ndarray\r\n theta tensor for `torch.F.affine_grid`, shaped [2, 3]\r\n w : int\r\n width of image\r\n h : int\r\n height of image\r\n return_inv : False\r\n return M^-1 instead of M.\r\n\r\n Returns\r\n -------\r\n np.ndarray\r\n affine warp matrix `M` shaped [2, 3]\r\n \"\"\"\r\n theta_aug = np.concatenate([theta, np.zeros((1, 3))], axis=0)\r\n theta_aug[-1, -1] = 1.0\r\n N = get_N(w, h)\r\n N_inv = get_N_inv(w, h)\r\n M = np.linalg.inv(theta_aug)\r\n M = N_inv @ M @ N\r\n if return_inv:\r\n M_inv = np.linalg.inv(M)\r\n return M_inv[:2, :]\r\n return M[:2, :]\r\n", "repo_name": "TongXin-CASIA/Excepted_Affine", "sub_path": "utils/convert.py", "file_name": "convert.py", "file_ext": "py", "file_size_in_byte": 4615, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 4, "dataset": "github-code", "pt": "21", "api": [{"api_name": "torch.Tensor", "line_number": 10, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 12, "usage_type": "call"}, {"api_name": "torch.from_numpy", "line_number": 16, "usage_type": "call"}, {"api_name": "PIL.Image.fromarray", "line_number": 18, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 18, "usage_type": "name"}, {"api_name": "numpy.float32", "line_number": 22, "usage_type": "attribute"}, {"api_name": "numpy.uint8", "line_number": 25, "usage_type": "attribute"}, {"api_name": "numpy.squeeze", "line_number": 29, "usage_type": "call"}, {"api_name": "numpy.newaxis", "line_number": 31, "usage_type": "attribute"}, {"api_name": "torch.Tensor", "line_number": 38, "usage_type": "attribute"}, {"api_name": "PIL.ImageFile.ImageFile", "line_number": 41, "usage_type": "attribute"}, {"api_name": "PIL.ImageFile", "line_number": 41, "usage_type": "name"}, {"api_name": "numpy.uint8", "line_number": 44, "usage_type": "attribute"}, {"api_name": "PIL.ImageFile.ImageFile", "line_number": 58, "usage_type": "attribute"}, {"api_name": "PIL.ImageFile", "line_number": 58, "usage_type": "name"}, {"api_name": "torch.Tensor", "line_number": 61, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 82, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 82, "usage_type": "attribute"}, {"api_name": "cv2.KeyPoint", "line_number": 93, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 101, "usage_type": "call"}, {"api_name": "numpy.float64", "line_number": 101, "usage_type": "attribute"}, {"api_name": "numpy.linalg.inv", "line_number": 115, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 115, "usage_type": "attribute"}, {"api_name": "numpy.concatenate", "line_number": 136, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 136, "usage_type": "call"}, {"api_name": "numpy.linalg.inv", "line_number": 141, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 141, "usage_type": "attribute"}, {"api_name": "numpy.concatenate", "line_number": 169, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 169, "usage_type": "call"}, {"api_name": "numpy.linalg.inv", "line_number": 173, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 173, "usage_type": "attribute"}, {"api_name": "numpy.linalg.inv", "line_number": 176, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 176, "usage_type": "attribute"}]} +{"seq_id": "2129208021", "text": "import os\n\n# core workflow imports\nfrom workflows.ne.sub_directories.core_sub_directories import core_sub_directories\nfrom workflows.ne.output_files.ne_matrix_IDs import ne_matrix_IDs\nfrom workflows.ne.output_files.ne_matrix_annotated import ne_matrix_annotated\nfrom workflows.ne.output_files.ne_matrix_symbols import ne_matrix_symbols\nfrom workflows.ne.output_files.ne_gene_IDs import ne_gene_IDs\nfrom workflows.ne.output_files.ne_gene_symbols import ne_gene_symbols\n\n# plot imports\nfrom plots.start_plots import start_plots\nfrom plots.add_plot import add_plot\nfrom plots.end_plots import end_plots\nfrom plots.run_r import run_r\n\n# report imports\nfrom reports.start_report import start_report\nfrom reports.add_header_section_to_report import add_header_section_to_report\nfrom reports.add_plot_section_to_report import add_plot_section_to_report\nfrom reports.add_text_section_to_report import add_text_section_to_report\nfrom reports.end_report import end_report\n\n\n# runs the workflow\ndef run_ne_workflow(global_variables, biotype):\n\n print(\"-\" * len(list(biotype)))\n print(biotype)\n print(\"-\" * len(list(biotype)))\n print()\n\n # gets the config for the workflow\n config = global_variables[\"config\"][\"NE\"]\n\n # gets the outpath for the workflow - as we use this a lot\n out_path = os.path.join(global_variables[\"out_path\"], biotype, \"ne_workflow\")\n\n for element in config:\n\n element_name, element_active, element_type, element_subtype, element_path = element\n\n if check_element_prerequisites(element_active, element_type, element_subtype, element_path, global_variables):\n\n # methods for the core workflow\n if element_name == \"ne_sub_directories_core\" and element_type == \"core\":\n core_sub_directories(global_variables, out_path)\n elif element_name == \"ne_file_matrix_annotated\" and element_type == \"core\":\n ne_matrix_annotated(global_variables, out_path, biotype)\n elif element_name == \"ne_file_matrix_IDs\" and element_type == \"core\":\n ne_matrix_IDs(global_variables, out_path, biotype)\n elif element_name == \"ne_file_matrix_symbols\" and element_type == \"core\":\n ne_matrix_symbols(global_variables, out_path, biotype)\n elif element_name == \"ne_file_gene_IDs\" and element_type == \"core\":\n ne_gene_IDs(global_variables, out_path, biotype)\n elif element_name == \"ne_file_gene_symbols\" and element_type == \"core\":\n ne_gene_symbols(global_variables, out_path, biotype)\n\n # methods for statistical analysis\n\n # methods for the plots\n elif element_name == \"ne_start_plots\" and element_type == \"plot_core\":\n pr_dictionary = start_plots(global_variables, out_path, \"ne\", None)\n elif element_type == \"plot\":\n add_plot(element_path, pr_dictionary)\n elif element_name == \"ne_end_plots\" and element_type == \"plot_core\":\n end_plots(pr_dictionary)\n elif element_name == \"ne_run_r\" and element_type == \"plot_core\":\n run_r(pr_dictionary, global_variables)\n\n # methods for the report\n elif element_name == \"ne_start_report\" and element_type == \"report_core\":\n start_report(global_variables, pr_dictionary, element_path)\n elif element_type == \"report_title\":\n add_header_section_to_report(element_path, pr_dictionary)\n elif element_type == \"report_text\":\n add_text_section_to_report(element_path, pr_dictionary, global_variables)\n elif element_type == \"report_plot\":\n add_plot_section_to_report(element_path, pr_dictionary, global_variables)\n elif element_name == \"ne_end_report\" and element_type == \"report_core\":\n end_report(pr_dictionary)\n print(\"done with: \" + element_name.replace(\"_\", \" \"))\n\n print()\n\n\n# checks that prerequisites have been met for running an elements command\ndef check_element_prerequisites(element_active, element_type, element_subtype, element_path, global_variables):\n\n if element_active == \"FALSE\":\n return False\n elif element_subtype == \"ora\" and global_variables[\"ora_flag\"] == False:\n return False\n elif element_subtype == \"ura\" and global_variables[\"ura_flag\"] == False:\n return False\n elif element_type == \"plot\" and element_path.upper() == \"NONE\":\n return False\n else:\n return True", "repo_name": "Searchlight2/Searchlight2", "sub_path": "software/workflows/ne/run_ne_workflow.py", "file_name": "run_ne_workflow.py", "file_ext": "py", "file_size_in_byte": 4532, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 18, "dataset": "github-code", "pt": "21", "api": [{"api_name": "os.path.join", "line_number": 37, "usage_type": "call"}, {"api_name": "os.path", "line_number": 37, "usage_type": "attribute"}, {"api_name": "workflows.ne.sub_directories.core_sub_directories.core_sub_directories", "line_number": 47, "usage_type": "call"}, {"api_name": "workflows.ne.output_files.ne_matrix_annotated.ne_matrix_annotated", "line_number": 49, "usage_type": "call"}, {"api_name": "workflows.ne.output_files.ne_matrix_IDs.ne_matrix_IDs", "line_number": 51, "usage_type": "call"}, {"api_name": "workflows.ne.output_files.ne_matrix_symbols.ne_matrix_symbols", "line_number": 53, "usage_type": "call"}, {"api_name": "workflows.ne.output_files.ne_gene_IDs.ne_gene_IDs", "line_number": 55, "usage_type": "call"}, {"api_name": "workflows.ne.output_files.ne_gene_symbols.ne_gene_symbols", "line_number": 57, "usage_type": "call"}, {"api_name": "plots.start_plots.start_plots", "line_number": 63, "usage_type": "call"}, {"api_name": "plots.add_plot.add_plot", "line_number": 65, "usage_type": "call"}, {"api_name": "plots.end_plots.end_plots", "line_number": 67, "usage_type": "call"}, {"api_name": "plots.run_r.run_r", "line_number": 69, "usage_type": "call"}, {"api_name": "reports.start_report.start_report", "line_number": 73, "usage_type": "call"}, {"api_name": "reports.add_header_section_to_report.add_header_section_to_report", "line_number": 75, "usage_type": "call"}, {"api_name": "reports.add_text_section_to_report.add_text_section_to_report", "line_number": 77, "usage_type": "call"}, {"api_name": "reports.add_plot_section_to_report.add_plot_section_to_report", "line_number": 79, "usage_type": "call"}, {"api_name": "reports.end_report.end_report", "line_number": 81, "usage_type": "call"}]} +{"seq_id": "41194313384", "text": "\nimport tqdm\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport numpy as np\nimport tensorflow as tf\nimport tensorflow_probability as tfp\nfrom collections import namedtuple\nfrom pipeline import ensemble_predict\ntfd = tfp.distributions\n\nPI_bound = namedtuple(\n 'PI_bound', ['ensembleAverage', 'lowerBound', 'upperBound', 'mean', 'std'])\nCI95_metrics = namedtuple(\"CI95_metrics\", [\"PI_2p5\", \"PI_97p5\", \"PI_median\"])\n\n# create an universal metric to compare the performance of different models\nacc_metrics = namedtuple('acc_metrics', ['mae', 'mape'])\n\n\nclass EnsemblePredict():\n\n def __init__(self, ensemble_size, test_features, test_labels):\n self.ensemble_size = ensemble_size\n self.test_features = test_features\n self.gt = test_labels\n\n def mc_predict_test_set(self, model):\n\n self.enPred_WholeTestSet = ensemble_predict(\n model=model,\n test_data=self.test_features,\n ensemble_size=self.ensemble_size)\n\n def pl_epistemic(self, val_x_axis):\n \"\"\" plot epistemic uncertainty of the whole test set \"\"\"\n\n pl_preds_uncertainty(\n x_axis=val_x_axis,\n predictions=self.enPred_WholeTestSet,\n ground_truth=self.gt,\n option='CI95')\n\n def pl_residual_B(self, low=2, limit=4):\n\n mean = np.mean(self.enPred_WholeTestSet, axis=0)\n\n fig, ax = plt.subplots()\n ax.scatter(mean, self.gt, color='blue', alpha=0.5)\n\n ax.plot(np.arange(low, limit, 0.01), np.arange(\n low, limit, 0.01), color='gray', ls='--')\n\n error = np.std(self.enPred_WholeTestSet, axis=0)\n ax.errorbar(mean, self.gt, xerr=error,\n fmt='none', ecolor='blue', alpha=0.5)\n ax.set_xlabel('Predicted revenue in million')\n ax.set_ylabel('Ground truth revenue in million')\n\n def cp_ensemble_metrics(self,):\n \"\"\" compute the uncertainty metrics for val data set\"\"\"\n\n # compute the MAE\n MAEs = tf.keras.metrics.mean_absolute_error(\n y_true=self.gt, y_pred=self.enPred_WholeTestSet)\n\n MAPEs = tf.keras.metrics.mean_absolute_percentage_error(\n y_true=self.gt,\n y_pred=self.enPred_WholeTestSet)\n\n mae = np.mean(MAEs)\n mape = np.mean(MAPEs)\n return acc_metrics(mae=mae, mape=mape)\n\n def pl_epistemic_ts(self, dataset):\n \"\"\" plot epistemic uncertainty of the whole test set \"\"\"\n\n fig, ax = plt.subplots(figsize=(12, 4))\n\n # plot the full train and val [revenue] series\n ax.plot(dataset.revenue, marker='+')\n\n # boundry between train and val\n ax.axvline(x=200, ymin=0, ymax=1, color='purple', linestyle='--')\n\n # plot the val results\n val_x_axis = np.arange(200, 208)\n\n # add the ground truth\n ax.scatter(val_x_axis, self.gt, color='r', marker='o', )\n\n CI95_metric = CI95_interval(self.enPred_WholeTestSet)\n\n # the ensemble median\n # ax.plot(val_x_axis, CI95_metric.PI_median, color='red', label='ensemble median')\n\n ax.fill_between(val_x_axis,\n CI95_metric.PI_2p5,\n CI95_metric.PI_97p5,\n color='coral',\n alpha=0.2,\n label=r'95\\%' ' credible interval')\n ax.legend(loc='best')\n ax.grid(linestyle=':')\n ax.set_ylabel('Revenue in million')\n ax.set_title('Epistemic uncertainty')\n ax.set_xlim([160, 208])\n\n def mixed_uncertainty_PI(self, dataset, PI_dp_bounds_all_list, val_x_axis):\n \"\"\" plot epistemic uncertainty of the whole test set \"\"\"\n\n fig, ax = plt.subplots(figsize=(12, 4))\n\n # plot the full train and val [revenue] series\n ax.plot(dataset.revenue, marker='+')\n\n # boundry between train and val\n ax.axvline(x=200, ymin=0, ymax=1, color='purple', linestyle='--')\n\n # add the ground truth\n ax.scatter(val_x_axis, self.gt, color='r', marker='o', )\n\n mean_curve = np.array([x.mean[0] for x in PI_dp_bounds_all_list])\n lb_curve = np.array([x.lowerBound[0] for x in PI_dp_bounds_all_list])\n ub_curve = np.array([x.upperBound[0] for x in PI_dp_bounds_all_list])\n\n # the ensemble median\n ax.plot(val_x_axis, mean_curve, color='red', label='ensemble mean')\n\n ax.fill_between(val_x_axis,\n lb_curve,\n ub_curve,\n color='coral',\n alpha=0.2,\n label=r'95\\%' ' credible interval')\n ax.legend(loc='best')\n ax.grid(linestyle=':')\n ax.set_title('Mixed uncertainty - both aleatoric and epistemic')\n ax.set_xlim([160, 208])\n\n def cp_ensemble_testset(self, model):\n \"\"\" compute the tfd distribution objects (with mean and stddev) for all the data points\n \"\"\"\n container = []\n # compute the ensemble dist for all data points\n for i in tqdm.tqdm(range(len(self.gt))):\n dp_dist_result = cp_ensemble_dp(\n model=model,\n input_dp=self.test_features[i][np.newaxis],\n ensemble_size=self.ensemble_size)\n container.append(dp_dist_result)\n self._dist_obj_testset = container\n\n def get_PI_bounds_testset(self, style='gmm'):\n \"\"\" choose a PI bound style and get these bounds for the whole test set \n ! the current entry point \n\n Parameters\n ----------\n style : str,\n two choices: 'gmm' and 'envelop'\n \"\"\"\n\n # if not hasattr(self, '_dist_obj_testset'):\n # self.cp_ensemble_testset()\n\n PI_dp_bounds_all_list = [cp_dp_PI_bound(\n ensemble_dp_dist, style=style) for ensemble_dp_dist in self._dist_obj_testset]\n return PI_dp_bounds_all_list\n\n def cp_d_metrics(self,):\n \"\"\" compute the deterministic metrics for val data set\"\"\"\n\n # compute the MAE\n MAEs = tf.keras.metrics.mean_absolute_error(\n y_true=self.gt, y_pred=self.enPred_WholeTestSet)\n\n mape = tf.keras.metrics.mean_absolute_percentage_error(\n y_true=self.gt,\n y_pred=self.enPred_WholeTestSet)\n\n mae = np.mean(MAEs)\n mape = np.mean(mape)\n return mae, mape\n\n\nclass AleatoricPredict:\n \"\"\" for aleatoric model \"\"\"\n\n def __init__(self, test_features, test_labels):\n self.test_features = test_features\n self.test_labels = test_labels\n\n\n def predict_dist(self, model, data=None):\n \"\"\" predict the distribution object \"\"\"\n\n if data is None:\n data = self.test_features\n \n # compute the mean of the conditional distribution objects\n self.conditional_means = model(data).mean()\n\n # compute the variance of the dist objects\n self.conditional_stds = model(data).stddev()\n\n\n @property\n def lower_bound(self):\n return self.conditional_means - 2 * self.conditional_means\n\n\n @property\n def upper_bound(self):\n return self.conditional_means + 2 * self.conditional_means\n \n\n def cp_metrics(self,):\n \"\"\" currently we compute mae and mape \"\"\"\n\n mae = tf.keras.metrics.mean_absolute_error(\n y_true=self.test_labels, y_pred=np.squeeze(self.conditional_means))\n \n mape = tf.keras.metrics.mean_absolute_percentage_error(\n y_true=self.test_labels, \n y_pred=np.squeeze(self.conditional_means))\n\n return acc_metrics(mae=mae, mape=mape)\n\n\n def pl_aleatoric_uncertainty(self, val_x_axis):\n \"\"\" plot the aleatoric uncertainty in the residual plot \"\"\"\n\n # val range only\n fig, ax = plt.subplots()\n\n # ground truth\n ax.scatter(val_x_axis, self.test_labels, marker='o', alpha=0.4, label='ground truth')\n\n # mean prediction\n ax.plot(val_x_axis, self.conditional_means, color='blue', label='conditional mean')\n ax.plot(val_x_axis, self.lower_bound, 'g--', label='95 aleatoric interval')\n ax.plot(val_x_axis, self.upper_bound, 'g--')\n ax.legend()\n\n ax.set_ylabel('Revenue') \n ax.set_xlabel('validation')\n ax.set_title('Aleatoric uncertainy')\n # ax.set_ylim([0, 6])\n\n\ndef show_dist(model):\n dummy_input = np.array([[0]])\n model_prior = model.layers[0]._prior(dummy_input)\n model_posterior = model.layers[0]._posterior(dummy_input)\n print('prior mean:', model_prior.mean().numpy())\n print('prior variacnce', model_prior.variance().numpy())\n print('posterior mean:', model_posterior.mean().numpy())\n # print('posterior covariance', model_posterior.covariance().numpy()[0])\n # print('', model_posterior.covariance().numpy()[1])\n\n\ndef pl_preds_uncertainty(x_axis, predictions, ground_truth, option):\n \"\"\" plot uncertainty of preds on a data point \"\"\"\n\n fig, ax = plt.subplots()\n\n if option == 'meanNstd':\n\n mean = np.mean(predictions, axis=0)\n # median = np.median(predictions, axis=0)\n std = np.std(predictions, axis=0)\n\n # the ensemble average curve\n ax.plot(x_axis, mean, 'r:', label='ensemble average')\n # ax.plot(x_axis, median, 'r:', label='ensemble median')\n ax.fill_between(x_axis,\n mean + 2 * std,\n mean - 2 * std,\n color='salmon',\n alpha=0.3,\n label='mean +- 2 sigma')\n # 3 * sigma\n ax.fill_between(x_axis,\n mean + 3 * std,\n mean - 3 * std,\n color='salmon',\n alpha=0.15,\n label='median +- 3 sigma')\n elif option == 'CI95':\n CI95_metric = CI95_interval(predictions)\n\n # the ensemble median\n ax.plot(x_axis, CI95_metric.PI_median,\n color='red', label='ensemble median')\n ax.fill_between(x_axis,\n CI95_metric.PI_2p5,\n CI95_metric.PI_97p5,\n color='coral',\n alpha=0.2,\n label=r'95\\%' ' credible interval')\n elif option == 'multi':\n for c, row in enumerate(predictions):\n if c == 0:\n ax.plot(x_axis, row, 'gray', alpha=0.1,\n zorder=0, label='prediction')\n else:\n ax.plot(x_axis, row, 'gray', alpha=0.1, zorder=0)\n\n # plot ground truth\n ax.scatter(x_axis, ground_truth, color='b', label='target', zorder=1)\n\n ax.set_title('Epistemic uncertainty')\n ax.set_xlabel('Validation')\n ax.set_ylabel('Revenue')\n # ax.set_ylim([0, 10])\n\n ax.legend(frameon=False, loc='upper left', fontsize='small')\n ax.grid(ls=':')\n\n\ndef plot_history_info(history_obj, title=''):\n \"\"\" given a tf history object, display the learning curve of loss and metric \"\"\"\n\n fig, ax = plt.subplots(nrows=1, ncols=3, figsize=(10, 4))\n\n a, b, c, d, e, f = history_obj.history.keys()\n\n ax[0].plot(history_obj.epoch, history_obj.history[a], label=a)\n ax[0].plot(history_obj.epoch, history_obj.history[d], label=d)\n ax[0].set_ylabel(a)\n ax[0].set_xlabel('epochs')\n ax[0].legend()\n\n ax[1].plot(history_obj.epoch, history_obj.history[b], label=b)\n ax[1].plot(history_obj.epoch, history_obj.history[e], label=e)\n ax[1].set_ylabel(b)\n ax[1].set_xlabel('epochs')\n ax[1].legend()\n\n ax[2].plot(history_obj.epoch, history_obj.history[c], label=c)\n ax[2].plot(history_obj.epoch, history_obj.history[f], label=f)\n ax[2].set_ylabel(c)\n ax[2].set_xlabel('epochs')\n ax[2].legend()\n\n fig.suptitle(title)\n\n\ndef CI95_interval(ensemble_predictions):\n \"\"\" compute the 95 credible interval \n\n Parameters\n ----------\n ensemble_predictions : array\n 2D, e.g. (100*8), matrix of ensemble predictions of the test set\n \"\"\"\n\n PI_2p5 = np.percentile(a=ensemble_predictions, q=2.5, axis=0)\n PI_97p5 = np.percentile(a=ensemble_predictions, q=97.5, axis=0)\n PI_median = np.median(ensemble_predictions, axis=0)\n\n return CI95_metrics(PI_2p5, PI_97p5, PI_median)\n\n\ndef cp_ensemble_dp(model, input_dp, ensemble_size):\n \"\"\" Possibly a even more low-level computation of an ensemble of means and stds (for all frequencies), respectively,\n for epistemic uncertainty and aleatory uncertainty.\n\n ! the computation part of the above function `pl_mixed_uncertainty_PI`\n\n Parameters\n ----------\n input_dp : array in shape (33,)\n the input data point from, say, the test set (in np.arrar)\n groundTruth: array\n the corresponding ground truth from the test set\n option : str,\n Two options, either output the plot only, or return the uncertainty metrics, PI width and PICP\n\n Ruturn\n ------\n An ensemble of `mean` and `std` of tfp.distribution objects for each data point;\n \"\"\"\n\n dist_objs = [model(input_dp) for _ in range(ensemble_size)]\n means = [np.squeeze(dist_obj.mean()) for dist_obj in dist_objs]\n stds = [np.squeeze(dist_obj.stddev()) for dist_obj in dist_objs]\n\n # each dict element is a `ensembles_size` length of list of arrays, each array in (, 33)\n return {'ensemble_means': means, 'ensemble_stds': stds}\n\n\ndef cp_dp_PI_bound(ensemble_dp_dist, style='envelop', k=2):\n \"\"\" the **envelop** style method for computing the PI bounds for a data point \n ! the computation part of the above function `pl_mixed_uncertainty_PI`\n\n Parameters\n ----------\n input_dp : array in shape (33,)\n the input data point from, say, the test set (in np.arrar)\n groundTruth: array\n the corresponding ground truth from the test set\n k : int \n confidence level, normally 2 or 3\n style : str,\n Two style of computing the PI bounds from the same ensemble distribution results.\n\n Ruturn\n ------\n the uncertainty width metric for a certain data point\n \"\"\"\n\n means = ensemble_dp_dist['ensemble_means']\n stds = ensemble_dp_dist['ensemble_stds']\n\n if style == 'envelop':\n # one way to yield the PI ([lb, ub]) - envelop style\n lb = [mean - k * std for mean, std in zip(means, stds)]\n ub = [mean + k * std for mean, std in zip(means, stds)]\n\n lower_bound_curve = np.amin(np.vstack(lb), axis=0)\n upper_bound_curve = np.amax(np.vstack(ub), axis=0)\n mean_curve = np.mean(np.vstack(means), axis=0)\n\n elif style == 'gmm':\n ensemble_means = np.vstack(means)\n ensemble_stds = np.vstack(stds)\n gmm_lists_dp = []\n # of each frequency, cretea a uniform mixure-of-Gaussians\n for col in range(ensemble_means.shape[1]):\n gm_f = tfd.MixtureSameFamily(\n mixture_distribution=tfd.Categorical(\n probs=[1 / ensemble_means.shape[0]] * ensemble_means.shape[0]),\n components_distribution=tfd.Normal(\n loc=ensemble_means[:, col],\n scale=ensemble_stds[:, col],\n )\n )\n gmm_lists_dp.append(gm_f)\n\n mean_curve = np.array([gmm.mean().numpy() for gmm in gmm_lists_dp])\n std_gmm = np.array([gmm.stddev().numpy() for gmm in gmm_lists_dp])\n lower_bound_curve = mean_curve - 2 * std_gmm\n upper_bound_curve = mean_curve + 2 * std_gmm\n\n return PI_bound(ensembleAverage=mean_curve, lowerBound=lower_bound_curve, upperBound=upper_bound_curve, mean=mean_curve, std=std_gmm)\n\n\ndef pl_priorNposterior(trace, parameter, prior_obj, low=-2, high=2):\n \"\"\" plot both the prior and posterior distribution of a parameter \n \n parameters\n ----------\n trace : pymc3 trace object\n the trace from which to get posterior samples\n parameter : str\n which parameter to plot\n prior_obj : tfp distribution object\n Tensorflow probability distribution object as prior with given parameters and type\n low : float\n lower bound of the parameter on the x-axis\n high : float\n upper bound of the parameter on the x-axis\n \"\"\"\n\n # get the posterior of a parameter (i.e. samples in np array)\n pos_dist = trace.posterior[parameter].to_numpy()[0]\n\n # manually create and plot the prior distribution\n\n # the posterior \n fig, ax = plt.subplots()\n dummy_xaxis = np.linspace(low, high, 100)\n ax.plot(dummy_xaxis, prior_obj.prob(dummy_xaxis), color='green', label='prior')\n sns.histplot(x=pos_dist, bins=10, kde=True, stat='density', label='posterior', ax=ax)\n ax.legend()\n ax.set_xlabel(f'{parameter}')", "repo_name": "leslieDLcy/KTP_Croud", "sub_path": "src/modelling/modules.py", "file_name": "modules.py", "file_ext": "py", "file_size_in_byte": 16609, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "tensorflow_probability.distributions", "line_number": 10, "usage_type": "attribute"}, {"api_name": "collections.namedtuple", "line_number": 12, "usage_type": "call"}, {"api_name": "collections.namedtuple", "line_number": 14, "usage_type": "call"}, {"api_name": "collections.namedtuple", "line_number": 17, "usage_type": "call"}, {"api_name": "pipeline.ensemble_predict", "line_number": 29, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 45, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 47, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 47, "usage_type": "name"}, {"api_name": "numpy.arange", "line_number": 50, "usage_type": "call"}, {"api_name": "numpy.std", "line_number": 53, "usage_type": "call"}, {"api_name": "tensorflow.keras.metrics.mean_absolute_error", "line_number": 63, "usage_type": "call"}, {"api_name": "tensorflow.keras", "line_number": 63, "usage_type": "attribute"}, {"api_name": "tensorflow.keras.metrics.mean_absolute_percentage_error", "line_number": 66, "usage_type": "call"}, {"api_name": "tensorflow.keras", "line_number": 66, "usage_type": "attribute"}, {"api_name": "numpy.mean", "line_number": 70, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 71, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 77, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 77, "usage_type": "name"}, {"api_name": "numpy.arange", "line_number": 86, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 111, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 111, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 122, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 123, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 124, "usage_type": "call"}, {"api_name": "tqdm.tqdm", "line_number": 145, "usage_type": "call"}, {"api_name": "numpy.newaxis", "line_number": 148, "usage_type": "attribute"}, {"api_name": "tensorflow.keras.metrics.mean_absolute_error", "line_number": 174, "usage_type": "call"}, {"api_name": "tensorflow.keras", "line_number": 174, "usage_type": "attribute"}, {"api_name": "tensorflow.keras.metrics.mean_absolute_percentage_error", "line_number": 177, "usage_type": "call"}, {"api_name": "tensorflow.keras", "line_number": 177, "usage_type": "attribute"}, {"api_name": "numpy.mean", "line_number": 181, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 182, "usage_type": "call"}, {"api_name": "tensorflow.keras.metrics.mean_absolute_error", "line_number": 220, "usage_type": "call"}, {"api_name": "tensorflow.keras", "line_number": 220, "usage_type": "attribute"}, {"api_name": "numpy.squeeze", "line_number": 221, "usage_type": "call"}, {"api_name": "tensorflow.keras.metrics.mean_absolute_percentage_error", "line_number": 223, "usage_type": "call"}, {"api_name": "tensorflow.keras", "line_number": 223, "usage_type": "attribute"}, {"api_name": "numpy.squeeze", "line_number": 225, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 234, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 234, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 252, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 265, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 265, "usage_type": "name"}, {"api_name": "numpy.mean", "line_number": 269, "usage_type": "call"}, {"api_name": "numpy.std", "line_number": 271, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 324, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 324, "usage_type": "name"}, {"api_name": "numpy.percentile", "line_number": 358, "usage_type": "call"}, {"api_name": "numpy.percentile", "line_number": 359, "usage_type": "call"}, {"api_name": "numpy.median", "line_number": 360, "usage_type": "call"}, {"api_name": "numpy.squeeze", "line_number": 386, "usage_type": "call"}, {"api_name": "numpy.squeeze", "line_number": 387, "usage_type": "call"}, {"api_name": "numpy.amin", "line_number": 421, "usage_type": "call"}, {"api_name": "numpy.vstack", "line_number": 421, "usage_type": "call"}, {"api_name": "numpy.amax", "line_number": 422, "usage_type": "call"}, {"api_name": "numpy.vstack", "line_number": 422, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 423, "usage_type": "call"}, {"api_name": "numpy.vstack", "line_number": 423, "usage_type": "call"}, {"api_name": "numpy.vstack", "line_number": 426, "usage_type": "call"}, {"api_name": "numpy.vstack", "line_number": 427, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 441, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 442, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 472, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 472, "usage_type": "name"}, {"api_name": "numpy.linspace", "line_number": 473, "usage_type": "call"}, {"api_name": "seaborn.histplot", "line_number": 475, "usage_type": "call"}]} +{"seq_id": "69798407734", "text": "from django.conf import settings\nfrom tastypie.authorization import Authorization\nfrom tastypie.bundle import Bundle\nfrom tastypie.constants import ALL_WITH_RELATIONS\nfrom tastypie.fields import ToManyField, CharField, ToOneField\nfrom tastypie.resources import ModelResource, Resource\nfrom cinema.models import Genre, Movie, Rating, UniqueForm # Old Stuff = Student, Class, StudentProject\n\n\nclass BareMovieResource(ModelResource):\n class Meta:\n queryset = Movie.objects.all()\n resource_name = \"bare_movie\"\n\n\nclass GenreResource(ModelResource):\n movies = ToManyField(BareMovieResource, 'movies', full=True, null=True)\n\n class Meta:\n allowed_methods = ['get']\n queryset = Genre.objects.all()\n resource_name = \"genre\"\n authorization = Authorization()\n always_return_date = True\n\nclass MovieResource(ModelResource):\n genre = ToOneField(GenreResource, 'genre', full=True)\n\n class Meta:\n allowed_methods = ['get']\n queryset = Movie.objects.all()\n resource_name = \"movie\"\n authorization = Authorization()\n always_return_date = True\n filtering = {\n \"genre\": ALL_WITH_RELATIONS\n }\n\n\nclass RatingResource(ModelResource):\n movies = ToManyField(MovieResource, 'movies', full=True, null=True)\n\n class Meta:\n allowed_methods = ['get', 'post']\n always_return_data = True\n queryset = Movie.objects.all()\n resource_name = \"class\"\n authorization = Authorization()\n filtering = {\n 'users': ALL_WITH_RELATIONS,\n 'title': ['contains', 'icontains'],\n 'start_date': ['gt',]\n }\n\n\n######################\n# Non-Model Resource #\n######################\n\nclass Version(object):\n def __init__(self, identifier=None):\n self.identifier = identifier\n\n\nclass VersionResource(Resource):\n identifier = CharField(attribute='identifier')\n\n class Meta:\n resource_name = 'version'\n allowed_methods = ['get']\n object_class = Version\n include_resource_uri = False\n\n def detail_uri_kwargs(self, bundle_or_obj):\n kwargs = {}\n\n if isinstance(bundle_or_obj, Bundle):\n kwargs['pk'] = bundle_or_obj.obj.identifier\n else:\n kwargs['pk'] = bundle_or_obj['identifier']\n\n return kwargs\n\n def get_object_list(self, bundle, **kwargs):\n return [Version(identifier=settings.VERSION)]\n\n def obj_get_list(self, bundle, **kwargs):\n return self.get_object_list(bundle, **kwargs)", "repo_name": "gffbss/dev-project", "sub_path": "cinema/api/resources.py", "file_name": "resources.py", "file_ext": "py", "file_size_in_byte": 2546, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 2, "dataset": "github-code", "pt": "21", "api": [{"api_name": "tastypie.resources.ModelResource", "line_number": 10, "usage_type": "name"}, {"api_name": "cinema.models.Movie.objects.all", "line_number": 12, "usage_type": "call"}, {"api_name": "cinema.models.Movie.objects", "line_number": 12, "usage_type": "attribute"}, {"api_name": "cinema.models.Movie", "line_number": 12, "usage_type": "name"}, {"api_name": "tastypie.resources.ModelResource", "line_number": 16, "usage_type": "name"}, {"api_name": "tastypie.fields.ToManyField", "line_number": 17, "usage_type": "call"}, {"api_name": "cinema.models.Genre.objects.all", "line_number": 21, "usage_type": "call"}, {"api_name": "cinema.models.Genre.objects", "line_number": 21, "usage_type": "attribute"}, {"api_name": "cinema.models.Genre", "line_number": 21, "usage_type": "name"}, {"api_name": "tastypie.authorization.Authorization", "line_number": 23, "usage_type": "call"}, {"api_name": "tastypie.resources.ModelResource", "line_number": 26, "usage_type": "name"}, {"api_name": "tastypie.fields.ToOneField", "line_number": 27, "usage_type": "call"}, {"api_name": "cinema.models.Movie.objects.all", "line_number": 31, "usage_type": "call"}, {"api_name": "cinema.models.Movie.objects", "line_number": 31, "usage_type": "attribute"}, {"api_name": "cinema.models.Movie", "line_number": 31, "usage_type": "name"}, {"api_name": "tastypie.authorization.Authorization", "line_number": 33, "usage_type": "call"}, {"api_name": "tastypie.constants.ALL_WITH_RELATIONS", "line_number": 36, "usage_type": "name"}, {"api_name": "tastypie.resources.ModelResource", "line_number": 40, "usage_type": "name"}, {"api_name": "tastypie.fields.ToManyField", "line_number": 41, "usage_type": "call"}, {"api_name": "cinema.models.Movie.objects.all", "line_number": 46, "usage_type": "call"}, {"api_name": "cinema.models.Movie.objects", "line_number": 46, "usage_type": "attribute"}, {"api_name": "cinema.models.Movie", "line_number": 46, "usage_type": "name"}, {"api_name": "tastypie.authorization.Authorization", "line_number": 48, "usage_type": "call"}, {"api_name": "tastypie.constants.ALL_WITH_RELATIONS", "line_number": 50, "usage_type": "name"}, {"api_name": "tastypie.resources.Resource", "line_number": 65, "usage_type": "name"}, {"api_name": "tastypie.fields.CharField", "line_number": 66, "usage_type": "call"}, {"api_name": "tastypie.bundle.Bundle", "line_number": 77, "usage_type": "argument"}, {"api_name": "django.conf.settings.VERSION", "line_number": 85, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 85, "usage_type": "name"}]} +{"seq_id": "1338611648", "text": "import pandas as pd\r\nfrom sklearn.cluster import KMeans\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn import preprocessing\r\nplt.style.use('ggplot')\r\ncolors = ['C0', 'C1', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7', 'C8', 'C9']*100\r\n\r\ndf = pd.read_csv('csv/noName - more.csv')\r\n##df = pd.read_csv('csv/noName - faker.csv')\r\n##df = pd.read_csv('csv/noName.csv')\r\nx = np.array(df[['work','ot']])\r\nx = preprocessing.scale(x)\r\n\r\nf = np.array([[7,44]])\r\n\r\nclf = KMeans(n_clusters=10)\r\nclf.fit(x)\r\nlabels = clf.predict(x)\r\n\r\nplt.scatter(x[:,0],x[:,1], c='black')\r\nplt.ylabel('Main work\\'s amounts')\r\nplt.xlabel('Over Time hours')\r\nplt.show()\r\n", "repo_name": "moonblood2/opencv", "sub_path": "dadProject/plotting data.py", "file_name": "plotting data.py", "file_ext": "py", "file_size_in_byte": 649, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "matplotlib.pyplot.style.use", "line_number": 6, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.style", "line_number": 6, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot", "line_number": 6, "usage_type": "name"}, {"api_name": "pandas.read_csv", "line_number": 9, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 12, "usage_type": "call"}, {"api_name": "sklearn.preprocessing.scale", "line_number": 13, "usage_type": "call"}, {"api_name": "sklearn.preprocessing", "line_number": 13, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 15, "usage_type": "call"}, {"api_name": "sklearn.cluster.KMeans", "line_number": 17, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 21, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 21, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 22, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 22, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 23, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 23, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 24, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 24, "usage_type": "name"}]} +{"seq_id": "10721920670", "text": "import pytest\nfrom tests.settings import DATABASE_URL\n\nimport edgy\nfrom edgy.core.db.querysets.clauses import not_\n\ndatabase = edgy.Database(url=DATABASE_URL)\nmodels = edgy.Registry(database=database)\n\npytestmark = pytest.mark.anyio\n\n\nclass User(edgy.Model):\n name = edgy.CharField(max_length=100)\n language = edgy.CharField(max_length=200, null=True)\n email = edgy.EmailField(null=True, max_length=255)\n\n class Meta:\n registry = models\n\n\n@pytest.fixture(autouse=True, scope=\"function\")\nasync def create_test_database():\n await models.create_all()\n yield\n await models.drop_all()\n\n\n@pytest.fixture(autouse=True)\nasync def rollback_connections():\n with database.force_rollback():\n async with database:\n yield\n\n\nasync def test_filter_with_not():\n await User.query.create(name=\"Adam\", language=\"EN\")\n\n results = await User.query.filter(not_(User.columns.name == \"Adam\"))\n\n assert len(results) == 0\n\n\nasync def test_filter_with_not_two():\n await User.query.create(name=\"Adam\")\n await User.query.create(name=\"Edgy\")\n user = await User.query.create(name=\"Esmerald\")\n\n results = await User.query.filter(not_(User.columns.name == \"Edgy\")).filter(\n not_(User.columns.name == \"Adam\")\n )\n\n assert len(results) == 1\n assert results[0].pk == user.pk\n\n\nasync def test_filter_with_not_style():\n await User.query.create(name=\"Adam\")\n await User.query.create(name=\"Edgy\")\n user = await User.query.create(name=\"Esmerald\")\n\n results = await User.query.not_(name=\"Edgy\").not_(name=\"Adam\")\n\n assert len(results) == 1\n assert results[0].pk == user.pk\n", "repo_name": "tarsil/edgy", "sub_path": "tests/clauses/test_not_clauses.py", "file_name": "test_not_clauses.py", "file_ext": "py", "file_size_in_byte": 1633, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 33, "dataset": "github-code", "pt": "21", "api": [{"api_name": "edgy.Database", "line_number": 7, "usage_type": "call"}, {"api_name": "tests.settings.DATABASE_URL", "line_number": 7, "usage_type": "name"}, {"api_name": "edgy.Registry", "line_number": 8, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 10, "usage_type": "attribute"}, {"api_name": "edgy.Model", "line_number": 13, "usage_type": "attribute"}, {"api_name": "edgy.CharField", "line_number": 14, "usage_type": "call"}, {"api_name": "edgy.CharField", "line_number": 15, "usage_type": "call"}, {"api_name": "edgy.EmailField", "line_number": 16, "usage_type": "call"}, {"api_name": "pytest.fixture", "line_number": 22, "usage_type": "call"}, {"api_name": "pytest.fixture", "line_number": 29, "usage_type": "call"}, {"api_name": "edgy.core.db.querysets.clauses.not_", "line_number": 39, "usage_type": "call"}, {"api_name": "edgy.core.db.querysets.clauses.not_", "line_number": 49, "usage_type": "call"}, {"api_name": "edgy.core.db.querysets.clauses.not_", "line_number": 50, "usage_type": "call"}]} +{"seq_id": "21605800721", "text": "import os, datetime, re, difflib\r\n\r\nLSPCI_OUTPUT_FOLDER = 'lspci-outputs'\r\nMAILTO = '' # user@domain\r\nMAILFROM = 'Unnamed Linux Server'\r\nSUBJECT = 'PCI Differences Detected'\r\n\r\nif (LSPCI_OUTPUT_FOLDER not in os.listdir('.')):\r\n os.mkdir(LSPCI_OUTPUT_FOLDER)\r\n\r\ncurrentTime = datetime.datetime.utcnow().isoformat().replace(':', '_') # replaces the hour/minute/second colons with underscores to make it filename safe\r\n\r\nos.system('lspci -nn > {}/{}.lspcilog'.format(\r\n LSPCI_OUTPUT_FOLDER,\r\n currentTime\r\n)) == 0\r\n\r\nlspciPreviousOutputs = sorted(os.listdir(LSPCI_OUTPUT_FOLDER))\r\n\r\nif (len(lspciPreviousOutputs) >= 2):\r\n lspciPreviousOutput = str(open('{}/{}'.format(\r\n LSPCI_OUTPUT_FOLDER,\r\n lspciPreviousOutputs[-2]\r\n )).read())\r\n lspciCurrentOutput = str(open('{}/{}'.format(\r\n LSPCI_OUTPUT_FOLDER,\r\n lspciPreviousOutputs[-1]\r\n )).read())\r\n \r\n differenceBetweenTwoFiles = difflib.ndiff(lspciPreviousOutput, lspciCurrentOutput)\r\n\r\n lines = []\r\n line = ['', ''] # [character, difference, actual line]\r\n for characterDiffPair in differenceBetweenTwoFiles:\r\n line[0] += characterDiffPair[-1]\r\n line[1] += characterDiffPair[0]\r\n if (characterDiffPair[-1] == '\\n'):\r\n lines.append(line)\r\n line = ['', '']\r\n \r\n differences = ''\r\n\r\n for difference in lines:\r\n\r\n # i wrote these regex by hand so if they arent working for you, please raise an issue on the repo, as i am not too good with regex\r\n lastIndexOfIommuGroup = re.search('[0-9a-fA-F]{1,9}:[0-9a-fA-F]{1,9}.[0-9a-fA-F]{1,9} ', difference[0]).span()[1]\r\n indexOfBothEndsOfDeviceVendorIDPair = re.search(' \\[[0-9a-fA-F]{4,8}:[0-9a-fA-F]{4,8}\\]', difference[0]).span()\r\n\r\n name = difference[0][lastIndexOfIommuGroup:indexOfBothEndsOfDeviceVendorIDPair[0]]\r\n nameDifference = difference[1][lastIndexOfIommuGroup:indexOfBothEndsOfDeviceVendorIDPair[0]]\r\n\r\n vendorDeviceID = difference[0][indexOfBothEndsOfDeviceVendorIDPair[0]:indexOfBothEndsOfDeviceVendorIDPair[1]][1:] # [1:] since the regex returns a space at the beginning of the line, so this gets rid of it\r\n vendorDeviceIdDifference = difference[1][indexOfBothEndsOfDeviceVendorIDPair[0]:indexOfBothEndsOfDeviceVendorIDPair[1]][1:]\r\n\r\n vendorDeviceIdPairs = vendorDeviceID.split('[')[1].split(']')[0].split(':') #[1234:5678] but in a list form like ['1234', '5678']\r\n\r\n actualDeviceName = name + ' ' + '[{}:{}]'.format(\r\n vendorDeviceIdPairs[0][:4],\r\n vendorDeviceIdPairs[1][:4]\r\n ) + '\\n'\r\n\r\n # if the name difference is equal to a string of pluses that is equal to the length of the name, then this is a new device\r\n # ex:\r\n # name = \"ijkhasfgdldkjhdsfg\"\r\n # nameDifference = \"++++++++++++++++++\"\r\n # this would mean that name is new since the entire phrase was added\r\n if (nameDifference == '+' * len(name)):\r\n differences += ('NEW DEVICE: ' + actualDeviceName)\r\n \r\n # if the name difference is equal to a string of minuses that is equal to the length of the name, then this device was removed\r\n # this follows the same logic as the new device comparison, only with minuses instead of pluses\r\n elif (nameDifference == '-' * len(name)):\r\n differences += ('MISSING DEVICE: ' + actualDeviceName)\r\n \r\n # since the vendor device ids are 4 characters long, its safe to assume that a vendor device id that has a length of greater than 4 has a new id\r\n # this is because it would contain the old id \"1234\" plus the new id \"5678\" thus forming the string \"12345678\" together\r\n elif (len(vendorDeviceIdPairs[0]) > 4 or len(vendorDeviceIdPairs[1]) > 4):\r\n differences += ('SAME DEVICE BUT DIFFERENT ID: ' + actualDeviceName)\r\n\r\n if (len(differences) > 0):\r\n differences = 'To: {}\\nFrom: {}\\nSubject: {}\\nFound {} PCI differences:\\n'.format(\r\n MAILTO,\r\n MAILFROM,\r\n SUBJECT,\r\n len(differences.split('\\n')) - 1\r\n ) + differences\r\n file = open('lastdiff.txt', 'w')\r\n file.write(differences)\r\n file.close()\r\n\r\n print(differences)\r\n \r\n os.system('cat ./lastdiff.txt | ssmtp {}'.format(MAILTO))", "repo_name": "renamedquery/pcichk", "sub_path": "pcichk.py", "file_name": "pcichk.py", "file_ext": "py", "file_size_in_byte": 4323, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "os.listdir", "line_number": 8, "usage_type": "call"}, {"api_name": "os.mkdir", "line_number": 9, "usage_type": "call"}, {"api_name": "datetime.datetime.utcnow", "line_number": 11, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 11, "usage_type": "attribute"}, {"api_name": "os.system", "line_number": 13, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 18, "usage_type": "call"}, {"api_name": "difflib.ndiff", "line_number": 30, "usage_type": "call"}, {"api_name": "re.search", "line_number": 46, "usage_type": "call"}, {"api_name": "re.search", "line_number": 47, "usage_type": "call"}, {"api_name": "os.system", "line_number": 93, "usage_type": "call"}]} +{"seq_id": "40166964724", "text": "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport torchvision\nfrom torchvision import datasets, transforms\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# hyperparameters\nbatch_size = 64\nnum_epochs = 5\nlearning_rate = 0.01\nmomentum = 0.9\ncuda = False\n\n# use_cuda = torch.cuda.is_available()\n# device = torch.device('cuda' if use_cuda else 'cpu')\ndevice = torch.device('cpu')\n\nno_filter1 = 20\nno_filter2 = 50\nno_neurons = 500\n\n\n# MNIST\ntrain_dataset = torchvision.datasets.MNIST(\n root='./data', train=True, transform=transforms.ToTensor(), download=True)\n\ntest_dataset = torchvision.datasets.MNIST(\n root='./data', train=False, transform=transforms.ToTensor())\n\ntrain_loader = torch.utils.data.DataLoader(\n dataset=train_dataset, batch_size=batch_size, shuffle=True)\n\ntest_loader = torch.utils.data.DataLoader(\n dataset=train_dataset, batch_size=batch_size, shuffle=True)\n\n\nclass CNN(nn.Module):\n def __init__(self):\n super(CNN, self).__init__()\n self.conv1 = nn.Conv2d(1, no_filter1, 5, 1)\n self.conv2 = nn.Conv2d(no_filter1, no_filter2, 5, 1)\n self.fc1 = nn.Linear(4 * 4 * no_filter2, no_neurons)\n self.fc2 = nn.Linear(no_neurons, 10)\n self.pool = nn.MaxPool2d(2, 2)\n\n def forward(self, x):\n x = self.pool(F.relu(self.conv1(x)))\n x = self.pool(F.relu(self.conv2(x)))\n x = x.view(-1, 4 * 4 * no_filter2)\n x = F.relu(self.fc1(x))\n x = self.fc2(x)\n\n return F.log_softmax(x, dim=1)\n\n\ndef train_model(model, train_loader, optimizer, epoch):\n model.train()\n all_losses = []\n for batch_idx, (data, target) in enumerate(train_loader):\n data, target = data.to(device), target.to(device)\n optimizer.zero_grad()\n\n output = model(data)\n\n loss = F.nll_loss(output, target)\n all_losses.append(loss.detach().cpu().numpy())\n\n loss.backward()\n\n optimizer.step()\n\n if batch_idx % 100 == 0:\n print(f'Epoch: {epoch}, Loss: {loss.item()}')\n\n return np.array(all_losses).mean()\n\n\ndef test_model(model, test_loader):\n model.eval()\n test_loss = 0\n correct = 0\n\n with torch.no_grad():\n num_iter = 0\n for data, target in test_loader:\n data, target = data.to(device), target.to(device)\n\n output = model(data)\n\n test_loss += F.nll_loss(output, target)\n pred = output.argmax(dim=1, keepdim=True)\n correct += pred.eq(target.view_as(pred)).float().mean().item()\n num_iter += 1\n test_loss /= num_iter\n test_accuracy = 100.0 * correct / num_iter\n\n print(f'\\nAverage loss: {test_loss:.4f}, Accuracy: {test_accuracy:.0f}%\\n')\n return test_loss, test_accuracy\n\n\ndef plot_loss(loss, label, color='red'):\n plt.plot(loss, label=label, color=color)\n plt.legend()\n\n\nmodel = CNN().to(device)\n\noptimizer = optim.SGD(model.parameters(), lr=learning_rate, momentum=momentum)\n\nlosses_train = []\nlosses_test = []\naccuracy_test = []\n\nfor epoch in range(num_epochs):\n train_loss = train_model(\n model=model, train_loader=train_loader, optimizer=optimizer, epoch=epoch)\n test_loss, test_accuracy = test_model(model=model, test_loader=test_loader)\n losses_train.append(train_loss)\n losses_test.append(test_loss)\n accuracy_test.append(test_accuracy)\n\nplt.figure(1)\nplot_loss(losses_train, 'train_loss', 'red')\nplot_loss(losses_test, 'test_loss', 'blue')\nplt.show()\n\nplt.figure(2)\nplot_loss(accuracy_test, 'test_accuracy')\nplt.show()\n\nprint('test', losses_test, losses_train)\n\ntorch.save(model.state_dict(), 'mnist_cnn.pt')\n", "repo_name": "radu-catalin/Assignment2-MNIST_COUNTING", "sub_path": "mnist_classification.py", "file_name": "mnist_classification.py", "file_ext": "py", "file_size_in_byte": 3644, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "torch.device", "line_number": 19, "usage_type": "call"}, {"api_name": "torchvision.datasets.MNIST", "line_number": 27, "usage_type": "call"}, {"api_name": "torchvision.datasets", "line_number": 27, "usage_type": "attribute"}, {"api_name": "torchvision.transforms.ToTensor", "line_number": 28, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 28, "usage_type": "name"}, {"api_name": "torchvision.datasets.MNIST", "line_number": 30, "usage_type": "call"}, {"api_name": "torchvision.datasets", "line_number": 30, "usage_type": "attribute"}, {"api_name": "torchvision.transforms.ToTensor", "line_number": 31, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 31, "usage_type": "name"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 33, "usage_type": "call"}, {"api_name": "torch.utils", "line_number": 33, "usage_type": "attribute"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 36, "usage_type": "call"}, {"api_name": "torch.utils", "line_number": 36, "usage_type": "attribute"}, {"api_name": "torch.nn.Module", "line_number": 40, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 40, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 43, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 43, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 44, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 44, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 45, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 45, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 46, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 46, "usage_type": "name"}, {"api_name": "torch.nn.MaxPool2d", "line_number": 47, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 47, "usage_type": "name"}, {"api_name": "torch.nn.functional.relu", "line_number": 50, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 50, "usage_type": "name"}, {"api_name": "torch.nn.functional.relu", "line_number": 51, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 51, "usage_type": "name"}, {"api_name": "torch.nn.functional.relu", "line_number": 53, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 53, "usage_type": "name"}, {"api_name": "torch.nn.functional.log_softmax", "line_number": 56, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 56, "usage_type": "name"}, {"api_name": "torch.nn.functional.nll_loss", "line_number": 68, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 68, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 78, "usage_type": "call"}, {"api_name": "torch.no_grad", "line_number": 86, "usage_type": "call"}, {"api_name": "torch.nn.functional.nll_loss", "line_number": 93, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 93, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 105, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 105, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 106, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 106, "usage_type": "name"}, {"api_name": "torch.optim.SGD", "line_number": 111, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 111, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 125, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 125, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 128, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 128, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 130, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 130, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 132, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 132, "usage_type": "name"}, {"api_name": "torch.save", "line_number": 136, "usage_type": "call"}]} +{"seq_id": "27877492596", "text": "import attr\nfrom .Board import Board\nimport numpy\n\n\n@attr.s(auto_attribs=True)\nclass Checker:\n board: Board\n\n def _valid(self, slice):\n isvalid = True\n flat = slice.flatten()\n uniq = numpy.unique(flat)\n if 0 in slice:\n isvalid = False\n if len(uniq) < len(slice):\n isvalid = False\n return isvalid\n \n def _sections(self):\n centers = [\n (1, 1), (1, 4), (1, 7),\n (4, 1), (4, 4), (4, 7),\n (7, 1), (7, 4), (7, 7),\n ]\n return [self.board.section(loc) for loc in centers]\n\n def is_solved(self):\n if numpy.any(self.board.cells == 0):\n return False\n elif not any([self._valid(self.board[row, ]) for row in range(0, 9)]):\n return False\n elif not any([self._valid(self.board[:, col]) for col in range(0, 9)]):\n return False\n elif not any([self._valid(section) for section in self._sections()]):\n return False\n else:\n return True\n", "repo_name": "kevdougful/sudokusolver", "sub_path": "src/sudokusolver/Checker.py", "file_name": "Checker.py", "file_ext": "py", "file_size_in_byte": 1040, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "Board.Board", "line_number": 8, "usage_type": "name"}, {"api_name": "numpy.unique", "line_number": 13, "usage_type": "call"}, {"api_name": "numpy.any", "line_number": 29, "usage_type": "call"}, {"api_name": "attr.s", "line_number": 6, "usage_type": "call"}]} +{"seq_id": "2496810068", "text": "from django.db import models\nfrom user.models import UserProfile, User, Address\nfrom django.urls import reverse\nfrom PIL import Image\n\n\n\nclass Property(models.Model):\n thumbnail = models.ImageField(upload_to='property_images', null=True, blank=True)\n property_description = models.TextField(null=True)\n posted_by = models.ForeignKey(UserProfile, null=True, on_delete=models.CASCADE)\n address = models.ForeignKey(Address, on_delete=models.CASCADE)\n price_per_day = models.IntegerField(null=True)\n\n def __str__(self):\n return self.address.street_address\n\n\n def get_absolute_url(self):\n return reverse('prop-details', kwargs={'pk': self.pk})\n\n def u_save(self):\n super().save() # saving image first\n\n if self.thumbnail:\n img = Image.open(self.thumbnail.path) # Open image using self\n if img.height > 300 or img.width > 300:\n new_img = (300, 300)\n img.thumbnail(new_img)\n img.save(self.thumbnail.path) # saving image at the same path\n\n else:\n self.thumbnail = 'property_images/default.png'\n\n\n def x_save(self):\n super().save() # saving image first\n\n\n def save(self, force_insert=False, force_update=False, using=None,\n update_fields=None):\n super().save() # saving image first\n\n if self.thumbnail:\n img = Image.open(self.thumbnail.path) # Open image using self\n if img.height > 300 or img.width > 300:\n new_img = (300, 300)\n img.thumbnail(new_img)\n img.save(self.thumbnail.path) # saving image at the same path\n\n else:\n self.thumbnail = 'property_images/default.png'\n\n\n\n\nclass Reservation(models.Model):\n renter = models.ForeignKey(User, on_delete=models.CASCADE, null=True)\n property = models.ForeignKey(Property, on_delete=models.CASCADE, null=True)\n start_date = models.DateField(null=True, help_text=\"YYYY-MM-DD.\")\n end_date = models.DateField(null=True, help_text=\"YYYY-MM-DD.\")\n\n def __str__(self):\n return f'rented {self.property.address.street_address} from {self.start_date} until {self.end_date}'\n\n\nclass Feedback(models.Model):\n rating = models.IntegerField(choices=[(i, i) for i in range(11)], null=True)\n comment = models.TextField(null=True)\n reservation = models.OneToOneField(Reservation, on_delete=models.CASCADE, null=True)\n\n", "repo_name": "George-Strauch/Software-Engineering-Project", "sub_path": "rentals/models.py", "file_name": "models.py", "file_ext": "py", "file_size_in_byte": 2456, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "django.db.models.Model", "line_number": 8, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 8, "usage_type": "name"}, {"api_name": "django.db.models.ImageField", "line_number": 9, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 9, "usage_type": "name"}, {"api_name": "django.db.models.TextField", "line_number": 10, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 10, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 11, "usage_type": "call"}, {"api_name": "user.models.UserProfile", "line_number": 11, "usage_type": "argument"}, {"api_name": "django.db.models", "line_number": 11, "usage_type": "name"}, {"api_name": "django.db.models.CASCADE", "line_number": 11, "usage_type": "attribute"}, {"api_name": "django.db.models.ForeignKey", "line_number": 12, "usage_type": "call"}, {"api_name": "user.models.Address", "line_number": 12, "usage_type": "argument"}, {"api_name": "django.db.models", "line_number": 12, "usage_type": "name"}, {"api_name": "django.db.models.CASCADE", "line_number": 12, "usage_type": "attribute"}, {"api_name": "django.db.models.IntegerField", "line_number": 13, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 13, "usage_type": "name"}, {"api_name": "django.urls.reverse", "line_number": 20, "usage_type": "call"}, {"api_name": "PIL.Image.open", "line_number": 26, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 26, "usage_type": "name"}, {"api_name": "PIL.Image.open", "line_number": 45, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 45, "usage_type": "name"}, {"api_name": "django.db.models.Model", "line_number": 57, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 57, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 58, "usage_type": "call"}, {"api_name": "user.models.User", "line_number": 58, "usage_type": "argument"}, {"api_name": "django.db.models", "line_number": 58, "usage_type": "name"}, {"api_name": "django.db.models.CASCADE", "line_number": 58, "usage_type": "attribute"}, {"api_name": "django.db.models.ForeignKey", "line_number": 59, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 59, "usage_type": "name"}, {"api_name": "django.db.models.CASCADE", "line_number": 59, "usage_type": "attribute"}, {"api_name": "django.db.models.DateField", "line_number": 60, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 60, "usage_type": "name"}, {"api_name": "django.db.models.DateField", "line_number": 61, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 61, "usage_type": "name"}, {"api_name": "django.db.models.Model", "line_number": 67, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 67, "usage_type": "name"}, {"api_name": "django.db.models.IntegerField", "line_number": 68, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 68, "usage_type": "name"}, {"api_name": "django.db.models.TextField", "line_number": 69, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 69, "usage_type": "name"}, {"api_name": "django.db.models.OneToOneField", "line_number": 70, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 70, "usage_type": "name"}, {"api_name": "django.db.models.CASCADE", "line_number": 70, "usage_type": "attribute"}]} +{"seq_id": "40368978344", "text": "# _*_ coding: utf-8\nfrom odoo import models, fields, api,_\nfrom odoo.http import content_disposition, request\nfrom odoo.modules.module import get_resource_path\nimport random as rand\n\nfrom datetime import datetime\ntry:\n from odoo.addons.report_xlsx.report.report_xlsx import ReportXlsx\n from xlsxwriter.utility import xl_rowcol_to_cell\nexcept ImportError:\n ReportXlsx = object\n\nDATE_DICT = {\n '%m/%d/%Y' : 'mm/dd/yyyy',\n '%Y/%m/%d' : 'yyyy/mm/dd',\n '%m/%d/%y' : 'mm/dd/yy',\n '%d/%m/%Y' : 'dd/mm/yyyy',\n '%d/%m/%y' : 'dd/mm/yy',\n '%d-%m-%Y' : 'dd-mm-yyyy',\n '%d-%m-%y' : 'dd-mm-yy',\n '%m-%d-%Y' : 'mm-dd-yyyy',\n '%m-%d-%y' : 'mm-dd-yy',\n '%Y-%m-%d' : 'yyyy-mm-dd',\n '%f/%e/%Y' : 'm/d/yyyy',\n '%f/%e/%y' : 'm/d/yy',\n '%e/%f/%Y' : 'd/m/yyyy',\n '%e/%f/%y' : 'd/m/yy',\n '%f-%e-%Y' : 'm-d-yyyy',\n '%f-%e-%y' : 'm-d-yy',\n '%e-%f-%Y' : 'd-m-yyyy',\n '%e-%f-%y' : 'd-m-yy'\n}\n\nclass InsTrialBalanceXlsx(models.AbstractModel):\n _name = 'report.dynamic_xlsx.ins_trial_balance_xlsx'\n _inherit = 'report.report_xlsx.abstract'\n\n def _define_formats(self, workbook):\n \"\"\" Add cell formats to current workbook.\n Available formats:\n * format_title\n * format_header\n \"\"\"\n self.format_title = workbook.add_format({\n 'bold': True,\n 'align': 'center',\n 'font_size': 12,\n 'font': 'Arial',\n })\n self.format_title2 = workbook.add_format({\n 'bold': True,\n 'align': 'center',\n 'font_size': 24,\n 'font': 'Arial',\n 'font_color': 'red',\n 'valign': 'vcenter',\n })\n self.format_header = workbook.add_format({\n 'bold': True,\n 'font_size': 10,\n 'font': 'Arial',\n #'border': True\n })\n self.format_merged_header = workbook.add_format({\n 'bold': True,\n 'font_size': 10,\n 'align': 'center',\n 'right': True,\n 'left': True,\n 'font': 'Arial',\n })\n self.format_merged_header_without_border = workbook.add_format({\n 'bold': True,\n 'font_size': 10,\n 'align': 'center',\n 'font': 'Arial',\n })\n self.content_header = workbook.add_format({\n 'bold': False,\n 'font_size': 10,\n 'font': 'Arial',\n })\n self.line_header = workbook.add_format({\n 'bold': True,\n 'font_size': 10,\n 'align': 'right',\n 'font': 'Arial',\n })\n self.line_header_total = workbook.add_format({\n 'bold': True,\n 'font_size': 10,\n 'align': 'right',\n 'font': 'Arial',\n 'top': True,\n 'bottom': True,\n })\n self.line_header_left = workbook.add_format({\n 'bold': True,\n 'font_size': 10,\n 'align': 'left',\n 'font': 'Arial',\n })\n self.line_header_left_total = workbook.add_format({\n 'bold': True,\n 'font_size': 10,\n 'align': 'left',\n 'font': 'Arial',\n 'top': True,\n 'bottom': True,\n })\n self.line_header_light = workbook.add_format({\n 'bold': False,\n 'font_size': 10,\n 'align': 'right',\n 'font': 'Arial',\n })\n self.line_header_light_total = workbook.add_format({\n 'bold': False,\n 'font_size': 10,\n 'align': 'right',\n 'font': 'Arial',\n 'top': True,\n 'bottom': True,\n })\n self.line_header_light_left = workbook.add_format({\n 'bold': False,\n 'font_size': 10,\n 'align': 'left',\n 'font': 'Arial',\n })\n self.line_header_highlight = workbook.add_format({\n 'bold': True,\n 'font_size': 10,\n 'align': 'right',\n 'font': 'Arial',\n })\n self.line_header_light_date = workbook.add_format({\n 'bold': False,\n 'font_size': 10,\n 'align': 'center',\n 'font': 'Arial',\n })\n\n def prepare_report_filters(self, data, filter, sheet_2,row_pos_2, language_id, format_header,line_header_light_date, content_header):\n \"\"\"It is writing under second page\"\"\"\n row_pos_2 += 2\n if filter:\n # Date from\n sheet_2.write_string(row_pos_2, 0, _('Date from'),\n format_header)\n sheet_2.write_datetime(row_pos_2, 1, self.convert_to_date(language_id,str(filter['date_from']) or ''),\n line_header_light_date)\n row_pos_2 += 1\n sheet_2.write_string(row_pos_2, 0, _('Date to'),\n format_header)\n sheet_2.write_datetime(row_pos_2, 1, self.convert_to_date(language_id,str(filter['date_to']) or ''),\n line_header_light_date)\n\n row_pos_2 += 1\n sheet_2.write_string(row_pos_2, 0, _('Display accounts'),\n format_header)\n sheet_2.write_string(row_pos_2, 1, filter['display_accounts'],\n content_header)\n\n # Journals\n row_pos_2 += 1\n sheet_2.write_string(row_pos_2, 0, _('Journals'),\n format_header)\n j_list = ', '.join([lt or '' for lt in filter.get('journals')])\n sheet_2.write_string(row_pos_2, 1, j_list,\n content_header)\n\n # Accounts\n row_pos_2 += 1\n sheet_2.write_string(row_pos_2, 0, _('Analytic Accounts'),\n format_header)\n a_list = ', '.join([lt or '' for lt in filter.get('analytics')])\n sheet_2.write_string(row_pos_2, 1, a_list,\n content_header)\n\n # Accounts\n # row_pos_2 += 1\n # sheet_2.write_string(row_pos_2, 0, _('Accounts'),\n # self.format_header)\n # a_list = ', '.join([lt or '' for lt in filter.get('accounts')])\n # sheet_2.write_string(row_pos_2, 1, a_list,\n # self.content_header)\n\n # Branches\n # row_pos_2 += 1\n # sheet_2.write_string(row_pos_2, 0, _('Branch'),\n # self.format_header)\n # a_list = ', '.join([lt or '' for lt in filter.get('operating_location_ids')])\n # sheet_2.write_string(row_pos_2, 1, a_list,\n # self.content_header)\n\n def prepare_report_contents(self, acc_lines, retained, subtotal, filter, sheet, row_pos, language_id, format_merged_header, format_merged_header_without_border,\n format_header, line_header_light_left, line_header_light, line_header_highlight,line_header_left_total, line_header_light_total, line_header_total):\n\n row_pos += 5\n sheet.merge_range(row_pos, 1, row_pos, 3, 'Initial Balance', format_merged_header)\n\n sheet.write_datetime(row_pos, 4, self.convert_to_date(language_id,filter.get('date_from')),\n format_merged_header_without_border)\n sheet.write_string(row_pos, 5, _(' To '),\n format_merged_header_without_border)\n sheet.write_datetime(row_pos, 6, self.convert_to_date(language_id,filter.get('date_to')),\n format_merged_header_without_border,)\n\n sheet.merge_range(row_pos, 7, row_pos, 9, 'Ending Balance', format_merged_header)\n\n row_pos += 2\n\n sheet.write_string(row_pos, 0, _('Account'),\n format_header)\n sheet.write_string(row_pos, 1, _('Debit'),\n format_header)\n sheet.write_string(row_pos, 2, _('Credit'),\n format_header)\n sheet.write_string(row_pos, 3, _('Balance'),\n format_header)\n sheet.write_string(row_pos, 4, _('Debit'),\n format_header)\n sheet.write_string(row_pos, 5, _('Credit'),\n format_header)\n sheet.write_string(row_pos, 6, _('Balance'),\n format_header)\n sheet.write_string(row_pos, 7, _('Debit'),\n format_header)\n sheet.write_string(row_pos, 8, _('Credit'),\n format_header)\n sheet.write_string(row_pos, 9, _('Balance'),\n format_header)\n\n if acc_lines:\n if not filter.get('show_hierarchy'):\n for line in acc_lines: # Normal lines\n row_pos += 1\n sheet.write_string(row_pos, 0, acc_lines[line].get('code') + ' ' +acc_lines[line].get('name'), line_header_light_left)\n sheet.write_number(row_pos, 1, float(acc_lines[line].get('initial_debit')), line_header_light)\n sheet.write_number(row_pos, 2, float(acc_lines[line].get('initial_credit')), line_header_light)\n sheet.write_number(row_pos, 3, float(acc_lines[line].get('initial_balance')), line_header_highlight)\n sheet.write_number(row_pos, 4, float(acc_lines[line].get('debit')), line_header_light)\n sheet.write_number(row_pos, 5, float(acc_lines[line].get('credit')), line_header_light)\n sheet.write_number(row_pos, 6, float(acc_lines[line].get('balance')), line_header_highlight)\n sheet.write_number(row_pos, 7, float(acc_lines[line].get('ending_debit')), line_header_light)\n sheet.write_number(row_pos, 8, float(acc_lines[line].get('ending_credit')), line_header_light)\n sheet.write_number(row_pos, 9, float(acc_lines[line].get('ending_balance')), line_header_highlight)\n else:\n for line in acc_lines: # Normal lines\n row_pos += 1\n blank_space = ' ' * len(line.get('indent_list'))\n if line.get('dummy'):\n sheet.write_string(row_pos, 0, blank_space + line.get('code'),\n line_header_light_left)\n else:\n sheet.write_string(row_pos, 0, blank_space + line.get('code') + ' ' + line.get('name'),\n line_header_light_left)\n sheet.write_number(row_pos, 1, float(line.get('initial_debit')), line_header_light)\n sheet.write_number(row_pos, 2, float(line.get('initial_credit')), line_header_light)\n sheet.write_number(row_pos, 3, float(line.get('initial_balance')), line_header_highlight)\n sheet.write_number(row_pos, 4, float(line.get('debit')), line_header_light)\n sheet.write_number(row_pos, 5, float(line.get('credit')), line_header_light)\n sheet.write_number(row_pos, 6, float(line.get('balance')), line_header_highlight)\n sheet.write_number(row_pos, 7, float(line.get('ending_debit')), line_header_light)\n sheet.write_number(row_pos, 8, float(line.get('ending_credit')), line_header_light)\n sheet.write_number(row_pos, 9, float(line.get('ending_balance')), line_header_highlight)\n\n\n if filter.get('strict_range'):\n # Retained Earnings line\n row_pos += 1\n sheet.write_string(row_pos, 0, ' ' + retained['RETAINED'].get('name'), line_header_light_left)\n sheet.write_number(row_pos, 1, float(retained['RETAINED'].get('initial_debit')), line_header_light)\n sheet.write_number(row_pos, 2, float(retained['RETAINED'].get('initial_credit')), line_header_light)\n sheet.write_number(row_pos, 3, float(retained['RETAINED'].get('initial_balance')), line_header_highlight)\n sheet.write_number(row_pos, 4, float(retained['RETAINED'].get('debit')), line_header_light)\n sheet.write_number(row_pos, 5, float(retained['RETAINED'].get('credit')), line_header_light)\n sheet.write_number(row_pos, 6, float(retained['RETAINED'].get('balance')), line_header_highlight)\n sheet.write_number(row_pos, 7, float(retained['RETAINED'].get('ending_debit')), line_header_light)\n sheet.write_number(row_pos, 8, float(retained['RETAINED'].get('ending_credit')), line_header_light)\n sheet.write_number(row_pos, 9, float(retained['RETAINED'].get('ending_balance')), line_header_highlight)\n # Sub total line\n row_pos += 2\n sheet.write_string(row_pos, 0, subtotal['SUBTOTAL'].get('code') + ' ' + subtotal['SUBTOTAL'].get('name'), line_header_left_total)\n sheet.write_number(row_pos, 1,float(subtotal['SUBTOTAL'].get('initial_debit')), line_header_light_total)\n sheet.write_number(row_pos, 2, float(subtotal['SUBTOTAL'].get('initial_credit')), line_header_light_total)\n sheet.write_number(row_pos, 3, float(subtotal['SUBTOTAL'].get('initial_balance')), line_header_total)\n sheet.write_number(row_pos, 4, float(subtotal['SUBTOTAL'].get('debit')), line_header_light_total)\n sheet.write_number(row_pos, 5, float(subtotal['SUBTOTAL'].get('credit')), line_header_light_total)\n sheet.write_number(row_pos, 6, float(subtotal['SUBTOTAL'].get('balance')), line_header_total)\n sheet.write_number(row_pos, 7, float(subtotal['SUBTOTAL'].get('ending_debit')), line_header_light_total)\n sheet.write_number(row_pos, 8, float(subtotal['SUBTOTAL'].get('ending_credit')), line_header_light_total)\n sheet.write_number(row_pos, 9, float(subtotal['SUBTOTAL'].get('ending_balance')), line_header_total)\n\n def _format_float_and_dates(self, currency_id, lang_id,line_header, line_header_light, line_header_highlight,line_header_light_date, format_merged_header_without_border):\n\n line_header.num_format = currency_id.excel_format\n\n line_header_light.num_format = currency_id.excel_format\n\n line_header_highlight.num_format = currency_id.excel_format\n\n line_header_light_date.num_format = DATE_DICT.get(lang_id.date_format, 'dd/mm/yyyy')\n format_merged_header_without_border.num_format = DATE_DICT.get(lang_id.date_format, 'dd/mm/yyyy')\n\n def convert_to_date(self, language_id, datestring=False):\n if datestring:\n datestring = fields.Date.from_string(datestring).strftime(language_id.date_format)\n return datetime.strptime(datestring, language_id.date_format)\n else:\n return False\n\n def generate_xlsx_report(self, workbook, data, record):\n format_title = workbook.add_format({\n 'bold': True,\n 'align': 'center',\n 'font_size': 12,\n 'font': 'Arial',\n })\n format_title2 = workbook.add_format({\n 'bold': True,\n 'align': 'center',\n 'font_size': 24,\n 'font': 'Arial',\n 'font_color': 'red',\n 'valign': 'vcenter',\n })\n format_header = workbook.add_format({\n 'bold': True,\n 'font_size': 10,\n 'font': 'Arial',\n #'border': True\n })\n format_merged_header = workbook.add_format({\n 'bold': True,\n 'font_size': 10,\n 'align': 'center',\n 'right': True,\n 'left': True,\n 'font': 'Arial',\n })\n format_merged_header_without_border = workbook.add_format({\n 'bold': True,\n 'font_size': 10,\n 'align': 'center',\n 'font': 'Arial',\n })\n content_header = workbook.add_format({\n 'bold': False,\n 'font_size': 10,\n 'font': 'Arial',\n })\n line_header = workbook.add_format({\n 'bold': True,\n 'font_size': 10,\n 'align': 'right',\n 'font': 'Arial',\n })\n line_header_total = workbook.add_format({\n 'bold': True,\n 'font_size': 10,\n 'align': 'right',\n 'font': 'Arial',\n 'top': True,\n 'bottom': True,\n })\n line_header_left = workbook.add_format({\n 'bold': True,\n 'font_size': 10,\n 'align': 'left',\n 'font': 'Arial',\n })\n line_header_left_total = workbook.add_format({\n 'bold': True,\n 'font_size': 10,\n 'align': 'left',\n 'font': 'Arial',\n 'top': True,\n 'bottom': True,\n })\n line_header_light = workbook.add_format({\n 'bold': False,\n 'font_size': 10,\n 'align': 'right',\n 'font': 'Arial',\n })\n line_header_light_total = workbook.add_format({\n 'bold': False,\n 'font_size': 10,\n 'align': 'right',\n 'font': 'Arial',\n 'top': True,\n 'bottom': True,\n })\n line_header_light_left = workbook.add_format({\n 'bold': False,\n 'font_size': 10,\n 'align': 'left',\n 'font': 'Arial',\n })\n line_header_highlight = workbook.add_format({\n 'bold': True,\n 'font_size': 10,\n 'align': 'right',\n 'font': 'Arial',\n })\n line_header_light_date = workbook.add_format({\n 'bold': False,\n 'font_size': 10,\n 'align': 'center',\n 'font': 'Arial',\n })\n row_pos = 0\n row_pos_2 = 0\n sheet = workbook.add_worksheet('Trial Balance')\n sheet_2 = workbook.add_worksheet('Filters')\n sheet.set_column(0, 0, 30)\n sheet.set_column(1, 1, 15)\n sheet.set_column(2, 2, 15)\n sheet.set_column(3, 3, 15)\n sheet.set_column(4, 4, 15)\n sheet.set_column(5, 5, 15)\n sheet.set_column(6, 6, 15)\n sheet.set_column(7, 7, 15)\n sheet.set_column(8, 8, 15)\n sheet.set_column(9, 9, 15)\n\n sheet_2.set_column(0, 0, 35)\n sheet_2.set_column(1, 1, 25)\n sheet_2.set_column(2, 2, 25)\n sheet_2.set_column(3, 3, 25)\n sheet_2.set_column(4, 4, 25)\n sheet_2.set_column(5, 5, 25)\n sheet_2.set_column(6, 6, 25)\n\n sheet.freeze_panes(5, 0)\n\n sheet.set_zoom(80)\n\n sheet.screen_gridlines = False\n sheet_2.screen_gridlines = False\n sheet_2.protect()\n\n row = 1\n image = get_resource_path('dynamic_xlsx', 'static/description', 'logo.png')\n sheet.insert_image(row, 0, image, {'x_scale': 0.2, 'y_scale': 0.2})\n\n # For Formating purpose\n lang = self.env.user.lang\n language_id = self.env['res.lang'].search([('code', '=', lang)])[0]\n self._format_float_and_dates(self.env.user.company_id.currency_id, language_id, line_header,line_header_light, line_header_highlight, line_header_light_date,format_merged_header_without_border)\n\n if record:\n\n data = record.read()\n date_from = record.date_from\n date_to = record.date_to\n x_month = date_to.strftime('%B')\n\n\n sheet.merge_range(0, 0, 0, 10, data[0]['company_id'][1], format_title)\n sheet.merge_range(1, 0, 2, 10, 'Trial Balance', format_title2) \n\n sheet.merge_range(3, 0, 3, 10, 'From %s %s' % (date_from.strftime('%d %B %Y'), date_to.strftime('%d %B %Y')), format_title)\n \n dateformat = self.env.user.lang\n filters, account_lines, retained, subtotal = record.get_report_datas()\n\n # Filter section\n self.prepare_report_filters(data, filters, sheet_2, row_pos_2, language_id, format_header, line_header_light_date, content_header)\n # Content section\n self.prepare_report_contents(account_lines, retained, subtotal, filters, sheet, row_pos, language_id, format_merged_header, format_merged_header_without_border,\n format_header, line_header_light_left, line_header_light, line_header_highlight,line_header_left_total, line_header_light_total, line_header_total)", "repo_name": "omikronkreatif/Kanjabungnew", "sub_path": "dynamic_xlsx/reports/report_trial_balance_xlsx.py", "file_name": "report_trial_balance_xlsx.py", "file_ext": "py", "file_size_in_byte": 20614, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "odoo.addons.report_xlsx.report.report_xlsx.ReportXlsx", "line_number": 12, "usage_type": "name"}, {"api_name": "odoo.models.AbstractModel", "line_number": 35, "usage_type": "attribute"}, {"api_name": "odoo.models", "line_number": 35, "usage_type": "name"}, {"api_name": "odoo._", "line_number": 150, "usage_type": "call"}, {"api_name": "odoo._", "line_number": 155, "usage_type": "call"}, {"api_name": "odoo._", "line_number": 161, "usage_type": "call"}, {"api_name": "odoo._", "line_number": 168, "usage_type": "call"}, {"api_name": "odoo._", "line_number": 176, "usage_type": "call"}, {"api_name": "odoo._", "line_number": 206, "usage_type": "call"}, {"api_name": "odoo._", "line_number": 215, "usage_type": "call"}, {"api_name": "odoo._", "line_number": 217, "usage_type": "call"}, {"api_name": "odoo._", "line_number": 219, "usage_type": "call"}, {"api_name": "odoo._", "line_number": 221, "usage_type": "call"}, {"api_name": "odoo._", "line_number": 223, "usage_type": "call"}, {"api_name": "odoo._", "line_number": 225, "usage_type": "call"}, {"api_name": "odoo._", "line_number": 227, "usage_type": "call"}, {"api_name": "odoo._", "line_number": 229, "usage_type": "call"}, {"api_name": "odoo._", "line_number": 231, "usage_type": "call"}, {"api_name": "odoo._", "line_number": 233, "usage_type": "call"}, {"api_name": "odoo.fields.Date.from_string", "line_number": 310, "usage_type": "call"}, {"api_name": "odoo.fields.Date", "line_number": 310, "usage_type": "attribute"}, {"api_name": "odoo.fields", "line_number": 310, "usage_type": "name"}, {"api_name": "datetime.datetime.strptime", "line_number": 311, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 311, "usage_type": "name"}, {"api_name": "odoo.modules.module.get_resource_path", "line_number": 447, "usage_type": "call"}]} +{"seq_id": "27851076795", "text": "\"\"\"Define the main routes and views.\"\"\"\nfrom datetime import timedelta\nfrom pathlib import Path\nfrom typing import Any\n\nfrom flask import (\n Blueprint,\n Flask,\n current_app,\n redirect,\n render_template,\n request,\n url_for,\n)\nfrom werkzeug.wrappers import Response\n\nfrom podcast_log.forms import (\n AddPodcastForm,\n EditEpisodeForm,\n EditPodcastForm,\n FileUploadForm,\n)\nfrom podcast_log.models import STATUS_CHOICES, Episode, Podcast, Status\nfrom podcast_log.pagination import Paginator\nfrom podcast_log.tables import AllEpisodesTable, PodcastEpisodesTable, StatisticsTable\nfrom podcast_log.tasks import (\n add_podcast_to_update_queue,\n create_new_podcast,\n migrate_csv_file,\n)\n\nbp = Blueprint(\"main\", __name__)\n\n\n@bp.route(\"/\")\ndef index() -> Response:\n \"\"\"Redirect to the podcast list.\"\"\"\n return redirect(url_for(\"main.podcast_list\"))\n\n\n@bp.route(\"/podcasts\")\ndef podcast_list() -> str:\n \"\"\"Display a list of podcasts.\"\"\"\n podcasts = Podcast.query.order_by(Podcast.title).all()\n return render_template(\"index.html\", podcasts=podcasts)\n\n\n@bp.route(\"/podcasts/update\")\ndef update_all() -> Response:\n \"\"\"Update all podcasts.\"\"\"\n for podcast in Podcast.query.all():\n add_podcast_to_update_queue(podcast.id)\n return redirect(url_for(\"main.podcast_list\"))\n\n\n@bp.route(\"/podcasts/add\", methods=(\"GET\", \"POST\"))\ndef add_podcast() -> Any:\n \"\"\"Add a new podcast.\"\"\"\n form = AddPodcastForm()\n if form.validate_on_submit():\n podcast = create_new_podcast(form.url.data, form.episode_number_pattern.data)\n return redirect(url_for(\"main.podcast_detail\", podcast_id=podcast.id))\n return render_template(\"add-podcast.html\", form=form)\n\n\n@bp.route(\"/podcast/\")\ndef podcast_detail(podcast_id: int) -> str:\n \"\"\"Show the details for a single podcast.\"\"\"\n page = request.args.get(\"page\", 1, type=int)\n status = request.args.get(\"status\")\n\n podcast = Podcast.query.get(podcast_id)\n query = podcast.episodes\n if status:\n query = query.filter_by(status=getattr(Status, status.upper()))\n\n paginator = Paginator(\n query, page=page, sort_column=Episode.publication_timestamp, reverse_sort=True\n )\n table = PodcastEpisodesTable(paginator.items)\n return render_template(\n \"podcast-detail.html\", podcast=podcast, paginator=paginator, table=table\n )\n\n\n@bp.route(\"/podcast//update\")\ndef update_podcast(podcast_id: int) -> Response:\n \"\"\"Force update a single podcast.\"\"\"\n add_podcast_to_update_queue(podcast_id, force=True)\n return redirect(url_for(\"main.podcast_detail\", podcast_id=podcast_id))\n\n\n@bp.route(\"/podcast//edit\", methods=(\"GET\", \"POST\"))\ndef edit_podcast(podcast_id: int) -> Any:\n \"\"\"Edit the details for a podcast.\"\"\"\n podcast = Podcast.query.get(podcast_id)\n form = EditPodcastForm(obj=podcast)\n if form.validate_on_submit():\n podcast = Podcast.query.get(podcast_id)\n form.populate_obj(podcast)\n podcast.save()\n return redirect(url_for(\"main.podcast_detail\", podcast_id=podcast.id))\n return render_template(\"edit-podcast.html\", podcast_id=podcast_id, form=form)\n\n\n@bp.route(\"/episodes\")\ndef episode_list() -> str:\n \"\"\"Show a list of the most recent episodes.\"\"\"\n page = request.args.get(\"page\", 1, type=int)\n status = request.args.get(\"status\")\n\n query = Episode.query\n if status:\n query = query.filter_by(status=getattr(Status, status.upper()))\n\n paginator = Paginator(\n query, page=page, sort_column=Episode.publication_timestamp, reverse_sort=True\n )\n table = AllEpisodesTable(paginator.items)\n return render_template(\"episode-list.html\", paginator=paginator, table=table)\n\n\n@bp.route(\"/episode//edit\", methods=(\"GET\", \"POST\"))\ndef edit_episode(episode_id: int) -> Any:\n \"\"\"Edit an episodes' details.\"\"\"\n episode = Episode.query.get(episode_id)\n form = EditEpisodeForm(obj=episode)\n if form.validate_on_submit():\n podcast_id = episode.podcast.id\n if \"episode_delete\" in request.form:\n episode.delete()\n else:\n form.populate_obj(episode)\n episode.save()\n return redirect(url_for(\"main.podcast_detail\", podcast_id=podcast_id))\n return render_template(\"edit-episode.html\", episode_id=episode_id, form=form)\n\n\n@bp.route(\"/episode//update-status\", methods=(\"POST\",))\ndef update_episode_status(episode_id: int) -> Response:\n \"\"\"Update the status of a specific episode.\"\"\"\n episode = Episode.query.get(episode_id)\n status = request.form[\"status\"]\n for key, value in STATUS_CHOICES.items():\n if value == status:\n episode.status = key\n episode.save()\n return redirect(request.referrer)\n\n\n@bp.route(\"/statistics\")\ndef statistics() -> str:\n \"\"\"Show the overall statistics for each podcast and the cumulative totals.\"\"\"\n podcasts = Podcast.query.order_by(Podcast.title).all()\n total_progress = \"\"\n total_time_listened = timedelta(seconds=0)\n for podcast in podcasts:\n total_time_listened += podcast.statistics.time_listened\n\n items = []\n for podcast in podcasts:\n items.append(\n {\n \"image_url\": podcast.image_url,\n \"title\": podcast.title,\n \"progress\": podcast.statistics.progress,\n \"time_listened\": podcast.statistics.time_listened,\n }\n )\n items.append(\n {\n \"image_url\": \"\",\n \"title\": \"Total\",\n \"progress\": total_progress,\n \"time_listened\": total_time_listened,\n }\n )\n table = StatisticsTable(items)\n return render_template(\"statistics.html\", table=table)\n\n\n@bp.route(\"/upload-tsv\", methods=[\"GET\", \"POST\"])\ndef upload_tsv_file() -> Any:\n \"\"\"Hidden form to upload podcast status from TSV file.\"\"\"\n form = FileUploadForm()\n if form.validate_on_submit():\n fp = form.file.data\n if Path(fp.filename).suffix == \".tsv\":\n upload_path = Path(current_app.instance_path, \"upload\")\n upload_path.mkdir(exist_ok=True)\n file_path = (upload_path / fp.filename).resolve()\n fp.save(str(file_path))\n migrate_csv_file(file_path)\n return redirect(url_for(\"main.statistics\"))\n form = FileUploadForm()\n return render_template(\"upload-file.html\", form=form)\n\n\ndef init_app(app: Flask) -> None:\n \"\"\"Initialize the application routes by registering the blueprint.\"\"\"\n app.register_blueprint(bp)\n", "repo_name": "mattkram/podcast-log", "sub_path": "podcast_log/routes.py", "file_name": "routes.py", "file_ext": "py", "file_size_in_byte": 6586, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "flask.Blueprint", "line_number": 32, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 38, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 38, "usage_type": "call"}, {"api_name": "werkzeug.wrappers.Response", "line_number": 36, "usage_type": "name"}, {"api_name": "podcast_log.models.Podcast.query.order_by", "line_number": 44, "usage_type": "call"}, {"api_name": "podcast_log.models.Podcast.query", "line_number": 44, "usage_type": "attribute"}, {"api_name": "podcast_log.models.Podcast", "line_number": 44, "usage_type": "name"}, {"api_name": "podcast_log.models.Podcast.title", "line_number": 44, "usage_type": "attribute"}, {"api_name": "flask.render_template", "line_number": 45, "usage_type": "call"}, {"api_name": "podcast_log.models.Podcast.query.all", "line_number": 51, "usage_type": "call"}, {"api_name": "podcast_log.models.Podcast.query", "line_number": 51, "usage_type": "attribute"}, {"api_name": "podcast_log.models.Podcast", "line_number": 51, "usage_type": "name"}, {"api_name": "podcast_log.tasks.add_podcast_to_update_queue", "line_number": 52, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 53, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 53, "usage_type": "call"}, {"api_name": "werkzeug.wrappers.Response", "line_number": 49, "usage_type": "name"}, {"api_name": "podcast_log.forms.AddPodcastForm", "line_number": 59, "usage_type": "call"}, {"api_name": "podcast_log.tasks.create_new_podcast", "line_number": 61, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 62, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 62, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 63, "usage_type": "call"}, {"api_name": "typing.Any", "line_number": 57, "usage_type": "name"}, {"api_name": "flask.request.args.get", "line_number": 69, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 69, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 69, "usage_type": "name"}, {"api_name": "flask.request.args.get", "line_number": 70, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 70, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 70, "usage_type": "name"}, {"api_name": "podcast_log.models.Podcast.query.get", "line_number": 72, "usage_type": "call"}, {"api_name": "podcast_log.models.Podcast.query", "line_number": 72, "usage_type": "attribute"}, {"api_name": "podcast_log.models.Podcast", "line_number": 72, "usage_type": "name"}, {"api_name": "podcast_log.models.Status", "line_number": 75, "usage_type": "argument"}, {"api_name": "podcast_log.pagination.Paginator", "line_number": 77, "usage_type": "call"}, {"api_name": "podcast_log.models.Episode.publication_timestamp", "line_number": 78, "usage_type": "attribute"}, {"api_name": "podcast_log.models.Episode", "line_number": 78, "usage_type": "name"}, {"api_name": "podcast_log.tables.PodcastEpisodesTable", "line_number": 80, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 81, "usage_type": "call"}, {"api_name": "podcast_log.tasks.add_podcast_to_update_queue", "line_number": 89, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 90, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 90, "usage_type": "call"}, {"api_name": "werkzeug.wrappers.Response", "line_number": 87, "usage_type": "name"}, {"api_name": "podcast_log.models.Podcast.query.get", "line_number": 96, "usage_type": "call"}, {"api_name": "podcast_log.models.Podcast.query", "line_number": 96, "usage_type": "attribute"}, {"api_name": "podcast_log.models.Podcast", "line_number": 96, "usage_type": "name"}, {"api_name": "podcast_log.forms.EditPodcastForm", "line_number": 97, "usage_type": "call"}, {"api_name": "podcast_log.models.Podcast.query.get", "line_number": 99, "usage_type": "call"}, {"api_name": "podcast_log.models.Podcast.query", "line_number": 99, "usage_type": "attribute"}, {"api_name": "podcast_log.models.Podcast", "line_number": 99, "usage_type": "name"}, {"api_name": "flask.redirect", "line_number": 102, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 102, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 103, "usage_type": "call"}, {"api_name": "typing.Any", "line_number": 94, "usage_type": "name"}, {"api_name": "flask.request.args.get", "line_number": 109, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 109, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 109, "usage_type": "name"}, {"api_name": "flask.request.args.get", "line_number": 110, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 110, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 110, "usage_type": "name"}, {"api_name": "podcast_log.models.Episode.query", "line_number": 112, "usage_type": "attribute"}, {"api_name": "podcast_log.models.Episode", "line_number": 112, "usage_type": "name"}, {"api_name": "podcast_log.models.Status", "line_number": 114, "usage_type": "argument"}, {"api_name": "podcast_log.pagination.Paginator", "line_number": 116, "usage_type": "call"}, {"api_name": "podcast_log.models.Episode.publication_timestamp", "line_number": 117, "usage_type": "attribute"}, {"api_name": "podcast_log.models.Episode", "line_number": 117, "usage_type": "name"}, {"api_name": "podcast_log.tables.AllEpisodesTable", "line_number": 119, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 120, "usage_type": "call"}, {"api_name": "podcast_log.models.Episode.query.get", "line_number": 126, "usage_type": "call"}, {"api_name": "podcast_log.models.Episode.query", "line_number": 126, "usage_type": "attribute"}, {"api_name": "podcast_log.models.Episode", "line_number": 126, "usage_type": "name"}, {"api_name": "podcast_log.forms.EditEpisodeForm", "line_number": 127, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 130, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 130, "usage_type": "name"}, {"api_name": "flask.redirect", "line_number": 135, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 135, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 136, "usage_type": "call"}, {"api_name": "typing.Any", "line_number": 124, "usage_type": "name"}, {"api_name": "podcast_log.models.Episode.query.get", "line_number": 142, "usage_type": "call"}, {"api_name": "podcast_log.models.Episode.query", "line_number": 142, "usage_type": "attribute"}, {"api_name": "podcast_log.models.Episode", "line_number": 142, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 143, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 143, "usage_type": "name"}, {"api_name": "podcast_log.models.STATUS_CHOICES.items", "line_number": 144, "usage_type": "call"}, {"api_name": "podcast_log.models.STATUS_CHOICES", "line_number": 144, "usage_type": "name"}, {"api_name": "flask.redirect", "line_number": 148, "usage_type": "call"}, {"api_name": "flask.request.referrer", "line_number": 148, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 148, "usage_type": "name"}, {"api_name": "werkzeug.wrappers.Response", "line_number": 140, "usage_type": "name"}, {"api_name": "podcast_log.models.Podcast.query.order_by", "line_number": 154, "usage_type": "call"}, {"api_name": "podcast_log.models.Podcast.query", "line_number": 154, "usage_type": "attribute"}, {"api_name": "podcast_log.models.Podcast", "line_number": 154, "usage_type": "name"}, {"api_name": "podcast_log.models.Podcast.title", "line_number": 154, "usage_type": "attribute"}, {"api_name": "datetime.timedelta", "line_number": 156, "usage_type": "call"}, {"api_name": "podcast_log.tables.StatisticsTable", "line_number": 178, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 179, "usage_type": "call"}, {"api_name": "podcast_log.forms.FileUploadForm", "line_number": 185, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 188, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 189, "usage_type": "call"}, {"api_name": "flask.current_app.instance_path", "line_number": 189, "usage_type": "attribute"}, {"api_name": "flask.current_app", "line_number": 189, "usage_type": "name"}, {"api_name": "podcast_log.tasks.migrate_csv_file", "line_number": 193, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 194, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 194, "usage_type": "call"}, {"api_name": "podcast_log.forms.FileUploadForm", "line_number": 195, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 196, "usage_type": "call"}, {"api_name": "typing.Any", "line_number": 183, "usage_type": "name"}, {"api_name": "flask.Flask", "line_number": 199, "usage_type": "name"}]} +{"seq_id": "18224483995", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport datetime\nfrom django.utils.timezone import utc\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('sito', '0001_initial'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='news',\n name='subtitle',\n field=models.CharField(max_length=255, null=True, verbose_name=b'Titolo', blank=True),\n ),\n migrations.AlterField(\n model_name='news',\n name='title',\n field=models.CharField(default=datetime.datetime(2015, 5, 7, 14, 7, 56, 517242, tzinfo=utc), max_length=255, verbose_name=b'Titolo'),\n preserve_default=False,\n ),\n ]\n", "repo_name": "arunkgupta/ristorantemotta", "sub_path": "sito/migrations/0002_auto_20150507_1407.py", "file_name": "0002_auto_20150507_1407.py", "file_ext": "py", "file_size_in_byte": 769, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "django.db.migrations.Migration", "line_number": 9, "usage_type": "attribute"}, {"api_name": "django.db.migrations", "line_number": 9, "usage_type": "name"}, {"api_name": "django.db.migrations.AddField", "line_number": 16, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 16, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 19, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 19, "usage_type": "name"}, {"api_name": "django.db.migrations.AlterField", "line_number": 21, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 21, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 24, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 24, "usage_type": "name"}, {"api_name": "datetime.datetime", "line_number": 24, "usage_type": "call"}, {"api_name": "django.utils.timezone.utc", "line_number": 24, "usage_type": "name"}]} +{"seq_id": "70910609973", "text": "from django.contrib import messages\nfrom django.shortcuts import render, redirect, get_object_or_404\nfrom django.contrib.auth.decorators import login_required\nfrom django.urls import reverse\nfrom django.http import JsonResponse, HttpResponseRedirect, HttpResponse, HttpResponseNotFound\nfrom property.models import Property, LandProperty\nfrom dashboard.forms import PropertyForm, PropertyLandForm, CarForm, CarImagesForm, BrandForm, TypeForm, SparePartForm, SparePartImagesForm, SchoolForm, SchoolImagesForm\nfrom cars.models import CarImage, Car, Brand, Type, School, SparePart, SparePartImage, School, SchoolImage\nfrom dashboard.decorators import check_admin\n\n\n# Create your views here.\ndef gen_asset_id(moduleName):\n moduleInstance = moduleName.objects.last()\n if moduleInstance is not None:\n return (moduleInstance.id + 1)\n return 1\n\n\n@login_required\n@check_admin\ndef PropertyAddPage(request):\n propertyForm = PropertyForm()\n propertyLandForm = PropertyLandForm()\n \n context = {\n \"dash_title\": 'Add Property',\n \"property_form\": propertyForm,\n \"propertyland_form\": propertyLandForm,\n }\n return render(request, \"dashboard/add-property.html\", context)\n\n\n\n\n@login_required\n@check_admin\ndef ajaxPropertyLandAdd(request):\n # request should be ajax and method should be POST.\n if request.is_ajax and request.method == \"POST\":\n # get the form data\n form = PropertyForm(request.POST, request.FILES)\n propland_form = PropertyLandForm(request.POST, request.FILES)\n if form.is_valid() and propland_form.is_valid():\n \n locality = propland_form.cleaned_data['locality']\n location = propland_form.cleaned_data['location']\n\n instance = form.save(request)\n prop = Property.objects.get(pk=instance.id)\n\n propland_obj = LandProperty.objects.create(\n property=prop,\n locality=locality, \n location=location, \n )\n\n propland_obj.save()\n return JsonResponse({'error': False, 'message': 'Uploaded Successfully'}, status=200)\n else:\n # some form errors occured.\n print(propland_form.errors)\n print(form.errors)\n return JsonResponse({'error': True, 'errors': form.errors}, status=400)\n\n # some error occured\n return JsonResponse({}, status=400)\n\n\n\n@login_required\n@check_admin\ndef CarPage(request):\n car_lists = Car.objects.order_by('-id')\n context = {\n 'dash_title': 'Cars',\n 'car_lists': car_lists\n }\n return render(request, 'dashboard/car.html', context)\n\n\n@login_required\n@check_admin\ndef CarAddPage(request):\n form = CarForm()\n image_form = CarImagesForm()\n if request.method == \"POST\":\n form = CarForm(request.POST, request.FILES)\n img_form = CarImagesForm(request.POST, request.FILES)\n files = request.FILES.getlist(\"images\")\n if form.is_valid() and img_form.is_valid():\n inst = form.save()\n for imagefile in files:\n file_instance = CarImage(car=inst, images=imagefile)\n file_instance.save()\n messages.success(request, 'Car been Added succesfully')\n return redirect('dashboard:car')\n else:\n print(form.errors)\n context = {\n \"dash_title\": 'Add Car',\n \"form\": form,\n \"image_form\": image_form\n }\n return render(request, \"dashboard/add-car.html\", context)\n\n\n\n\n\n@login_required\n@check_admin\ndef DeleteCar(request, *args, **kwargs):\n get_object_or_404(Car, pk=kwargs[\"id\"]).delete()\n messages.success(request, \"Car deleted successfully\")\n return redirect(reverse(\"dashboard:car\"))\n\n\n\n@login_required\n@check_admin\ndef CarEditPage(request, *args, **kwargs):\n car = get_object_or_404(Car, pk=kwargs[\"id\"])\n images = CarImage.objects.filter(car=car)\n form = CarForm(instance=car)\n image_form = CarImagesForm()\n if request.method == \"POST\":\n form = CarForm(request.POST, request.FILES, instance=car)\n img_form = CarImagesForm(request.POST, request.FILES)\n files = request.FILES.getlist(\"images\")\n if form.is_valid() and img_form.is_valid():\n inst = form.save()\n for imagefile in files:\n file_instance = CarImage(car=inst, images=imagefile)\n file_instance.save()\n messages.success(request, 'Car been updated succesfully')\n return redirect('dashboard:car')\n else:\n print(form.errors)\n context = {\n \"dash_title\": 'Edit Car',\n \"form\": form,\n \"image_form\": image_form,\n \"images\": images\n }\n return render(request, \"dashboard/edit-car.html\", context)\n\n@login_required\n@check_admin\ndef DeleteCarImage(request, *args, **kwargs):\n carimg = get_object_or_404(CarImage, pk=kwargs[\"id\"])\n car = carimg.car\n carimg.delete()\n messages.success(request, \"Image deleted successfully\")\n return redirect(\"dashboard:edit-car\", id=car.pk)\n\n\n@login_required\n@check_admin\ndef ViewCar(request, *args, **kwargs):\n car = get_object_or_404(Car, pk=kwargs[\"id\"])\n images = CarImage.objects.filter(car=car)\n context = {\n \"car\": car,\n \"images\": images\n }\n return render(request, \"dashboard/view-car.html\", context)\n\n\n\n@login_required\n@check_admin\ndef FeaturedCar(request, *args, **kwargs):\n car = get_object_or_404(Car, pk=kwargs[\"id\"])\n car_qs = Car.objects.filter(id=car.id)\n if car.featured == 1:\n car_qs.update(featured=0)\n else:\n car_qs.update(featured=1)\n messages.success(request, \"Updated successfully\")\n return redirect('dashboard:car')\n\n\n\n\n\n\n\n@login_required\n@check_admin\ndef BrandPage(request):\n brands = Brand.objects.order_by('-id')\n context = {\n 'dash_title': 'Brands',\n 'brands': brands\n }\n return render(request, 'dashboard/brands.html', context)\n\n\n\n@login_required\n@check_admin\ndef FeaturedBrand(request, *args, **kwargs):\n brand = get_object_or_404(Brand, pk=kwargs[\"id\"])\n brand_qs = Brand.objects.filter(id=brand.id)\n if brand.featured == 1:\n brand_qs.update(featured=0)\n else:\n brand_qs.update(featured=1)\n messages.success(request, \"updated successfully\")\n return redirect('dashboard:brands')\n\n\n@login_required\n@check_admin\ndef ViewBrand(request, *args, **kwargs):\n brand = get_object_or_404(Brand, pk=kwargs[\"id\"])\n context = {\n \"brand\": brand,\n }\n return render(request, \"dashboard/view-brand.html\", context)\n\n\n@login_required\n@check_admin\ndef DeleteBrand(request, *args, **kwargs):\n get_object_or_404(Brand, pk=kwargs[\"id\"]).delete()\n messages.success(request, \"Brand deleted successfully\")\n return redirect(reverse(\"dashboard:brands\"))\n\n\n\n@login_required\n@check_admin\ndef BrandEditPage(request, *args, **kwargs):\n brand = get_object_or_404(Brand, pk=kwargs[\"id\"])\n form = BrandForm(instance=brand)\n if request.method == \"POST\":\n form = BrandForm(request.POST, request.FILES, instance=brand)\n if form.is_valid():\n form.save()\n messages.success(request, 'brand been updated succesfully')\n return redirect('dashboard:brands')\n else:\n print(form.errors)\n context = {\n \"dash_title\": 'Edit Brand',\n \"form\": form,\n }\n return render(request, \"dashboard/edit-car.html\", context)\n\n\n\n\n\n\n@login_required\n@check_admin\ndef BrandAddPage(request):\n form = BrandForm()\n if request.method == \"POST\":\n form = BrandForm(request.POST, request.FILES)\n if form.is_valid():\n form.save()\n messages.success(request, 'Brand been Added succesfully')\n return redirect('dashboard:brands')\n else:\n print(form.errors)\n context = {\n \"dash_title\": 'Add Brand',\n \"form\": form,\n }\n return render(request, \"dashboard/add-brand.html\", context)\n\n\n\n@login_required\n@check_admin\ndef TypePage(request):\n types = Type.objects.order_by('-id')\n context = {\n 'dash_title': 'Car Types',\n 'types': types\n }\n return render(request, 'dashboard/types.html', context)\n\n\n\n\n@login_required\n@check_admin\ndef TypeAddPage(request):\n form = TypeForm()\n if request.method == \"POST\":\n form = TypeForm(request.POST)\n if form.is_valid():\n form.save()\n messages.success(request, 'Type been Added succesfully')\n return redirect('dashboard:types')\n else:\n print(form.errors)\n context = {\n \"dash_title\": 'Add Car Type',\n \"form\": form,\n }\n return render(request, \"dashboard/add-brand.html\", context)\n\n\n@login_required\n@check_admin\ndef TypeEditPage(request, *args, **kwargs):\n typ = get_object_or_404(Type, pk=kwargs[\"id\"])\n form = TypeForm(instance=typ)\n if request.method == \"POST\":\n form = TypeForm(request.POST, instance=typ)\n if form.is_valid():\n form.save()\n messages.success(request, 'Car type been updated succesfully')\n return redirect('dashboard:types')\n else:\n print(form.errors)\n context = {\n \"dash_title\": 'Edit Car type',\n \"form\": form,\n }\n return render(request, \"dashboard/edit-car.html\", context)\n\n\n@login_required\n@check_admin\ndef DeleteType(request, *args, **kwargs):\n get_object_or_404(Type, pk=kwargs[\"id\"]).delete()\n messages.success(request, \"Car Type deleted successfully\")\n return redirect(reverse(\"dashboard:types\"))\n\n\n\n\n\n\n@login_required\n@check_admin\ndef SparePartPage(request):\n spareparts = SparePart.objects.order_by('-id')\n context = {\n 'dash_title': 'Spare Part',\n 'spareparts': spareparts\n }\n return render(request, 'dashboard/spare-parts.html', context)\n\n\n\n\n@login_required\n@check_admin\ndef SparePartAddPage(request):\n form = SparePartForm()\n image_form = SparePartImagesForm()\n if request.method == \"POST\":\n form = SparePartForm(request.POST, request.FILES)\n img_form = SparePartImagesForm(request.POST, request.FILES)\n files = request.FILES.getlist(\"images\")\n if form.is_valid() and img_form.is_valid():\n inst = form.save()\n for imagefile in files:\n file_instance = SparePartImage(sparepart=inst, images=imagefile)\n file_instance.save()\n messages.success(request, 'Spare Part been Added succesfully')\n return redirect('dashboard:spare-parts')\n else:\n print(form.errors)\n context = {\n \"dash_title\": 'Add Spare Part',\n \"form\": form,\n \"image_form\": image_form\n }\n return render(request, \"dashboard/add-spare-part.html\", context)\n\n\n\n\n\n@login_required\n@check_admin\ndef SparePartEditPage(request, *args, **kwargs):\n sparepart = get_object_or_404(SparePart, pk=kwargs[\"id\"])\n images = sparepart.sparepartimages.order_by('-id')\n form = SparePartForm(instance=sparepart)\n image_form = SparePartImagesForm()\n if request.method == \"POST\":\n form = SparePartForm(request.POST, request.FILES, instance=sparepart)\n img_form = SparePartImagesForm(request.POST, request.FILES)\n files = request.FILES.getlist(\"images\")\n if form.is_valid() and img_form.is_valid():\n inst = form.save()\n for imagefile in files:\n file_instance = SparePartImage(sparepart=inst, images=imagefile)\n file_instance.save()\n messages.success(request, 'Spare Part been updated succesfully')\n return redirect('dashboard:spare-parts')\n else:\n print(form.errors)\n context = {\n \"dash_title\": 'Edit Spare Part',\n \"form\": form,\n \"image_form\": image_form,\n \"images\": images\n }\n return render(request, \"dashboard/edit-spare-part.html\", context)\n\n\n\n@login_required\n@check_admin\ndef FeaturedSparePart(request, *args, **kwargs):\n sparepart = get_object_or_404(SparePart, pk=kwargs[\"id\"])\n sparepart_qs = SparePart.objects.filter(id=sparepart.id)\n if sparepart.featured == 1:\n sparepart_qs.update(featured=0)\n else:\n sparepart_qs.update(featured=1)\n messages.success(request, \"updated successfully\")\n return redirect('dashboard:spare-parts')\n\n\n@login_required\n@check_admin\ndef ViewSparePart(request, *args, **kwargs):\n sparepart = get_object_or_404(SparePart, pk=kwargs[\"id\"])\n images = sparepart.sparepartimages.order_by('-id')\n context = {\n \"sparepart\": sparepart,\n \"images\": images\n }\n return render(request, \"dashboard/view-spare-part.html\", context)\n\n\n@login_required\n@check_admin\ndef DeleteSparePart(request, *args, **kwargs):\n get_object_or_404(SparePart, pk=kwargs[\"id\"]).delete()\n messages.success(request, \"Spare Part deleted successfully\")\n return redirect(reverse(\"dashboard:spare-parts\"))\n\n\n@login_required\n@check_admin\ndef DeleteSparePartImage(request, *args, **kwargs):\n spareimg = get_object_or_404(SparePartImage, pk=kwargs[\"id\"])\n sparepart = spareimg.sparepart\n spareimg.delete()\n messages.success(request, \"Image deleted successfully\")\n return redirect(\"dashboard:edit-spare-part\", id=sparepart.pk)\n\n\n@login_required\n@check_admin\ndef SchoolPage(request):\n schools = School.objects.order_by('-id')\n context = {\n 'dash_title': 'Driving Schools',\n 'schools': schools\n }\n return render(request, 'dashboard/schools.html', context)\n\n\n\n\n@login_required\n@check_admin\ndef SchoolAddPage(request):\n form = SchoolForm()\n image_form = SchoolImagesForm()\n if request.method == \"POST\":\n form = SchoolForm(request.POST, request.FILES)\n img_form = SchoolImagesForm(request.POST, request.FILES)\n files = request.FILES.getlist(\"images\")\n if form.is_valid() and img_form.is_valid():\n inst = form.save()\n for imagefile in files:\n file_instance = SchoolImage(school=inst, images=imagefile)\n file_instance.save()\n messages.success(request, 'Driving School been Added succesfully')\n return redirect('dashboard:schools')\n else:\n print(form.errors)\n context = {\n \"dash_title\": 'Add Driving School',\n \"form\": form,\n \"image_form\": image_form\n }\n return render(request, \"dashboard/add-school.html\", context)\n\n\n\n\n\n@login_required\n@check_admin\ndef SchoolEditPage(request, *args, **kwargs):\n school = get_object_or_404(School, pk=kwargs[\"id\"])\n images = school.schoolimage.order_by('-id')\n form = SchoolForm(instance=school)\n image_form = SchoolImagesForm()\n if request.method == \"POST\":\n form = SchoolForm(request.POST, request.FILES, instance=school)\n img_form = SchoolImagesForm(request.POST, request.FILES)\n files = request.FILES.getlist(\"images\")\n if form.is_valid() and img_form.is_valid():\n inst = form.save()\n for imagefile in files:\n file_instance = SchoolImage(school=inst, images=imagefile)\n file_instance.save()\n messages.success(request, 'Driving School been updated succesfully')\n return redirect('dashboard:schools')\n else:\n print(form.errors)\n context = {\n \"dash_title\": 'Edit Driving School',\n \"form\": form,\n \"image_form\": image_form,\n \"images\": images\n }\n return render(request, \"dashboard/edit-school.html\", context)\n\n\n\n@login_required\n@check_admin\ndef FeaturedSchool(request, *args, **kwargs):\n school = get_object_or_404(School, pk=kwargs[\"id\"])\n school_qs = School.objects.filter(id=school.id)\n if school.featured == 1:\n school_qs.update(featured=0)\n else:\n school_qs.update(featured=1)\n messages.success(request, \"Updated successfully\")\n return redirect('dashboard:schools')\n\n\n@login_required\n@check_admin\ndef ViewSchool(request, *args, **kwargs):\n school = get_object_or_404(School, pk=kwargs[\"id\"])\n images = school.schoolimage.order_by('-id')\n context = {\n \"school\": school,\n \"images\": images\n }\n return render(request, \"dashboard/view-school.html\", context)\n\n\n@login_required\n@check_admin\ndef DeleteSchool(request, *args, **kwargs):\n get_object_or_404(School, pk=kwargs[\"id\"]).delete()\n messages.success(request, \"Driving School deleted successfully\")\n return redirect(reverse(\"dashboard:schools\"))\n\n\n\n\n@login_required\n@check_admin\ndef DeleteSchoolImage(request, *args, **kwargs):\n schoolimg = get_object_or_404(SchoolImage, pk=kwargs[\"id\"])\n school = schoolimg.school\n schoolimg.delete()\n messages.success(request, \"Image deleted successfully\")\n return redirect(\"dashboard:edit-school\", id=school.pk)", "repo_name": "hamzaumar8/sandvet", "sub_path": "dashboard/views/cars.py", "file_name": "cars.py", "file_ext": "py", "file_size_in_byte": 16825, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "dashboard.forms.PropertyForm", "line_number": 23, "usage_type": "call"}, {"api_name": "dashboard.forms.PropertyLandForm", "line_number": 24, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 31, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 20, "usage_type": "name"}, {"api_name": "dashboard.decorators.check_admin", "line_number": 21, "usage_type": "name"}, {"api_name": "dashboard.forms.PropertyForm", "line_number": 42, "usage_type": "call"}, {"api_name": "dashboard.forms.PropertyLandForm", "line_number": 43, "usage_type": "call"}, {"api_name": "property.models.Property.objects.get", "line_number": 50, "usage_type": "call"}, {"api_name": "property.models.Property.objects", "line_number": 50, "usage_type": "attribute"}, {"api_name": "property.models.Property", "line_number": 50, "usage_type": "name"}, {"api_name": "property.models.LandProperty.objects.create", "line_number": 52, "usage_type": "call"}, {"api_name": "property.models.LandProperty.objects", "line_number": 52, "usage_type": "attribute"}, {"api_name": "property.models.LandProperty", "line_number": 52, "usage_type": "name"}, {"api_name": "django.http.JsonResponse", "line_number": 59, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 64, "usage_type": "call"}, {"api_name": "django.http.JsonResponse", "line_number": 67, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 36, "usage_type": "name"}, {"api_name": "dashboard.decorators.check_admin", "line_number": 37, "usage_type": "name"}, {"api_name": "cars.models.Car.objects.order_by", "line_number": 74, "usage_type": "call"}, {"api_name": "cars.models.Car.objects", "line_number": 74, "usage_type": "attribute"}, {"api_name": "cars.models.Car", "line_number": 74, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 79, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 71, "usage_type": "name"}, {"api_name": "dashboard.decorators.check_admin", "line_number": 72, "usage_type": "name"}, {"api_name": "dashboard.forms.CarForm", "line_number": 85, "usage_type": "call"}, {"api_name": "dashboard.forms.CarImagesForm", "line_number": 86, "usage_type": "call"}, {"api_name": "dashboard.forms.CarForm", "line_number": 88, "usage_type": "call"}, {"api_name": "dashboard.forms.CarImagesForm", "line_number": 89, "usage_type": "call"}, {"api_name": "cars.models.CarImage", "line_number": 94, "usage_type": "call"}, {"api_name": "django.contrib.messages.success", "line_number": 96, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 96, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 97, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 105, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 82, "usage_type": "name"}, {"api_name": "dashboard.decorators.check_admin", "line_number": 83, "usage_type": "name"}, {"api_name": "django.shortcuts.get_object_or_404", "line_number": 114, "usage_type": "call"}, {"api_name": "cars.models.Car", "line_number": 114, "usage_type": "argument"}, {"api_name": "django.contrib.messages.success", "line_number": 115, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 115, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 116, "usage_type": "call"}, {"api_name": "django.urls.reverse", "line_number": 116, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 111, "usage_type": "name"}, {"api_name": "dashboard.decorators.check_admin", "line_number": 112, "usage_type": "name"}, {"api_name": "django.shortcuts.get_object_or_404", "line_number": 123, "usage_type": "call"}, {"api_name": "cars.models.Car", "line_number": 123, "usage_type": "argument"}, {"api_name": "cars.models.CarImage.objects.filter", "line_number": 124, "usage_type": "call"}, {"api_name": "cars.models.CarImage.objects", "line_number": 124, "usage_type": "attribute"}, {"api_name": "cars.models.CarImage", "line_number": 124, "usage_type": "name"}, {"api_name": "dashboard.forms.CarForm", "line_number": 125, "usage_type": "call"}, {"api_name": "dashboard.forms.CarImagesForm", "line_number": 126, "usage_type": "call"}, {"api_name": "dashboard.forms.CarForm", "line_number": 128, "usage_type": "call"}, {"api_name": "dashboard.forms.CarImagesForm", "line_number": 129, "usage_type": "call"}, {"api_name": "cars.models.CarImage", "line_number": 134, "usage_type": "call"}, {"api_name": "django.contrib.messages.success", "line_number": 136, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 136, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 137, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 146, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 120, "usage_type": "name"}, {"api_name": "dashboard.decorators.check_admin", "line_number": 121, "usage_type": "name"}, {"api_name": "django.shortcuts.get_object_or_404", "line_number": 151, "usage_type": "call"}, {"api_name": "cars.models.CarImage", "line_number": 151, "usage_type": "argument"}, {"api_name": "django.contrib.messages.success", "line_number": 154, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 154, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 155, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 148, "usage_type": "name"}, {"api_name": "dashboard.decorators.check_admin", "line_number": 149, "usage_type": "name"}, {"api_name": "django.shortcuts.get_object_or_404", "line_number": 161, "usage_type": "call"}, {"api_name": "cars.models.Car", "line_number": 161, "usage_type": "argument"}, {"api_name": "cars.models.CarImage.objects.filter", "line_number": 162, "usage_type": "call"}, {"api_name": "cars.models.CarImage.objects", "line_number": 162, "usage_type": "attribute"}, {"api_name": "cars.models.CarImage", "line_number": 162, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 167, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 158, "usage_type": "name"}, {"api_name": "dashboard.decorators.check_admin", "line_number": 159, "usage_type": "name"}, {"api_name": "django.shortcuts.get_object_or_404", "line_number": 174, "usage_type": "call"}, {"api_name": "cars.models.Car", "line_number": 174, "usage_type": "argument"}, {"api_name": "cars.models.Car.objects.filter", "line_number": 175, "usage_type": "call"}, {"api_name": "cars.models.Car.objects", "line_number": 175, "usage_type": "attribute"}, {"api_name": "cars.models.Car", "line_number": 175, "usage_type": "name"}, {"api_name": "django.contrib.messages.success", "line_number": 180, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 180, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 181, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 171, "usage_type": "name"}, {"api_name": "dashboard.decorators.check_admin", "line_number": 172, "usage_type": "name"}, {"api_name": "cars.models.Brand.objects.order_by", "line_number": 192, "usage_type": "call"}, {"api_name": "cars.models.Brand.objects", "line_number": 192, "usage_type": "attribute"}, {"api_name": "cars.models.Brand", "line_number": 192, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 197, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 189, "usage_type": "name"}, {"api_name": "dashboard.decorators.check_admin", "line_number": 190, "usage_type": "name"}, {"api_name": "django.shortcuts.get_object_or_404", "line_number": 204, "usage_type": "call"}, {"api_name": "cars.models.Brand", "line_number": 204, "usage_type": "argument"}, {"api_name": "cars.models.Brand.objects.filter", "line_number": 205, "usage_type": "call"}, {"api_name": "cars.models.Brand.objects", "line_number": 205, "usage_type": "attribute"}, {"api_name": "cars.models.Brand", "line_number": 205, "usage_type": "name"}, {"api_name": "django.contrib.messages.success", "line_number": 210, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 210, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 211, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 201, "usage_type": "name"}, {"api_name": "dashboard.decorators.check_admin", "line_number": 202, "usage_type": "name"}, {"api_name": "django.shortcuts.get_object_or_404", "line_number": 217, "usage_type": "call"}, {"api_name": "cars.models.Brand", "line_number": 217, "usage_type": "argument"}, {"api_name": "django.shortcuts.render", "line_number": 221, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 214, "usage_type": "name"}, {"api_name": "dashboard.decorators.check_admin", "line_number": 215, "usage_type": "name"}, {"api_name": "django.shortcuts.get_object_or_404", "line_number": 227, "usage_type": "call"}, {"api_name": "cars.models.Brand", "line_number": 227, "usage_type": "argument"}, {"api_name": "django.contrib.messages.success", "line_number": 228, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 228, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 229, "usage_type": "call"}, {"api_name": "django.urls.reverse", "line_number": 229, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 224, "usage_type": "name"}, {"api_name": "dashboard.decorators.check_admin", "line_number": 225, "usage_type": "name"}, {"api_name": "django.shortcuts.get_object_or_404", "line_number": 236, "usage_type": "call"}, {"api_name": "cars.models.Brand", "line_number": 236, "usage_type": "argument"}, {"api_name": "dashboard.forms.BrandForm", "line_number": 237, "usage_type": "call"}, {"api_name": "dashboard.forms.BrandForm", "line_number": 239, "usage_type": "call"}, {"api_name": "django.contrib.messages.success", "line_number": 242, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 242, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 243, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 250, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 233, "usage_type": "name"}, {"api_name": "dashboard.decorators.check_admin", "line_number": 234, "usage_type": "name"}, {"api_name": "dashboard.forms.BrandForm", "line_number": 260, "usage_type": "call"}, {"api_name": "dashboard.forms.BrandForm", "line_number": 262, "usage_type": "call"}, {"api_name": "django.contrib.messages.success", "line_number": 265, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 265, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 266, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 273, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 257, "usage_type": "name"}, {"api_name": "dashboard.decorators.check_admin", "line_number": 258, "usage_type": "name"}, {"api_name": "cars.models.Type.objects.order_by", "line_number": 280, "usage_type": "call"}, {"api_name": "cars.models.Type.objects", "line_number": 280, "usage_type": "attribute"}, {"api_name": "cars.models.Type", "line_number": 280, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 285, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 277, "usage_type": "name"}, {"api_name": "dashboard.decorators.check_admin", "line_number": 278, "usage_type": "name"}, {"api_name": "dashboard.forms.TypeForm", "line_number": 293, "usage_type": "call"}, {"api_name": "dashboard.forms.TypeForm", "line_number": 295, "usage_type": "call"}, {"api_name": "django.contrib.messages.success", "line_number": 298, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 298, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 299, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 306, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 290, "usage_type": "name"}, {"api_name": "dashboard.decorators.check_admin", "line_number": 291, "usage_type": "name"}, {"api_name": "django.shortcuts.get_object_or_404", "line_number": 312, "usage_type": "call"}, {"api_name": "cars.models.Type", "line_number": 312, "usage_type": "argument"}, {"api_name": "dashboard.forms.TypeForm", "line_number": 313, "usage_type": "call"}, {"api_name": "dashboard.forms.TypeForm", "line_number": 315, "usage_type": "call"}, {"api_name": "django.contrib.messages.success", "line_number": 318, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 318, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 319, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 326, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 309, "usage_type": "name"}, {"api_name": "dashboard.decorators.check_admin", "line_number": 310, "usage_type": "name"}, {"api_name": "django.shortcuts.get_object_or_404", "line_number": 332, "usage_type": "call"}, {"api_name": "cars.models.Type", "line_number": 332, "usage_type": "argument"}, {"api_name": "django.contrib.messages.success", "line_number": 333, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 333, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 334, "usage_type": "call"}, {"api_name": "django.urls.reverse", "line_number": 334, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 329, "usage_type": "name"}, {"api_name": "dashboard.decorators.check_admin", "line_number": 330, "usage_type": "name"}, {"api_name": "cars.models.SparePart.objects.order_by", "line_number": 344, "usage_type": "call"}, {"api_name": "cars.models.SparePart.objects", "line_number": 344, "usage_type": "attribute"}, {"api_name": "cars.models.SparePart", "line_number": 344, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 349, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 341, "usage_type": "name"}, {"api_name": "dashboard.decorators.check_admin", "line_number": 342, "usage_type": "name"}, {"api_name": "dashboard.forms.SparePartForm", "line_number": 357, "usage_type": "call"}, {"api_name": "dashboard.forms.SparePartImagesForm", "line_number": 358, "usage_type": "call"}, {"api_name": "dashboard.forms.SparePartForm", "line_number": 360, "usage_type": "call"}, {"api_name": "dashboard.forms.SparePartImagesForm", "line_number": 361, "usage_type": "call"}, {"api_name": "cars.models.SparePartImage", "line_number": 366, "usage_type": "call"}, {"api_name": "django.contrib.messages.success", "line_number": 368, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 368, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 369, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 377, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 354, "usage_type": "name"}, {"api_name": "dashboard.decorators.check_admin", "line_number": 355, "usage_type": "name"}, {"api_name": "django.shortcuts.get_object_or_404", "line_number": 386, "usage_type": "call"}, {"api_name": "cars.models.SparePart", "line_number": 386, "usage_type": "argument"}, {"api_name": "dashboard.forms.SparePartForm", "line_number": 388, "usage_type": "call"}, {"api_name": "dashboard.forms.SparePartImagesForm", "line_number": 389, "usage_type": "call"}, {"api_name": "dashboard.forms.SparePartForm", "line_number": 391, "usage_type": "call"}, {"api_name": "dashboard.forms.SparePartImagesForm", "line_number": 392, "usage_type": "call"}, {"api_name": "cars.models.SparePartImage", "line_number": 397, "usage_type": "call"}, {"api_name": "django.contrib.messages.success", "line_number": 399, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 399, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 400, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 409, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 383, "usage_type": "name"}, {"api_name": "dashboard.decorators.check_admin", "line_number": 384, "usage_type": "name"}, {"api_name": "django.shortcuts.get_object_or_404", "line_number": 416, "usage_type": "call"}, {"api_name": "cars.models.SparePart", "line_number": 416, "usage_type": "argument"}, {"api_name": "cars.models.SparePart.objects.filter", "line_number": 417, "usage_type": "call"}, {"api_name": "cars.models.SparePart.objects", "line_number": 417, "usage_type": "attribute"}, {"api_name": "cars.models.SparePart", "line_number": 417, "usage_type": "name"}, {"api_name": "django.contrib.messages.success", "line_number": 422, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 422, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 423, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 413, "usage_type": "name"}, {"api_name": "dashboard.decorators.check_admin", "line_number": 414, "usage_type": "name"}, {"api_name": "django.shortcuts.get_object_or_404", "line_number": 429, "usage_type": "call"}, {"api_name": "cars.models.SparePart", "line_number": 429, "usage_type": "argument"}, {"api_name": "django.shortcuts.render", "line_number": 435, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 426, "usage_type": "name"}, {"api_name": "dashboard.decorators.check_admin", "line_number": 427, "usage_type": "name"}, {"api_name": "django.shortcuts.get_object_or_404", "line_number": 441, "usage_type": "call"}, {"api_name": "cars.models.SparePart", "line_number": 441, "usage_type": "argument"}, {"api_name": "django.contrib.messages.success", "line_number": 442, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 442, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 443, "usage_type": "call"}, {"api_name": "django.urls.reverse", "line_number": 443, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 438, "usage_type": "name"}, {"api_name": "dashboard.decorators.check_admin", "line_number": 439, "usage_type": "name"}, {"api_name": "django.shortcuts.get_object_or_404", "line_number": 449, "usage_type": "call"}, {"api_name": "cars.models.SparePartImage", "line_number": 449, "usage_type": "argument"}, {"api_name": "django.contrib.messages.success", "line_number": 452, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 452, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 453, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 446, "usage_type": "name"}, {"api_name": "dashboard.decorators.check_admin", "line_number": 447, "usage_type": "name"}, {"api_name": "cars.models.School.objects.order_by", "line_number": 459, "usage_type": "call"}, {"api_name": "cars.models.School.objects", "line_number": 459, "usage_type": "attribute"}, {"api_name": "cars.models.School", "line_number": 459, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 464, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 456, "usage_type": "name"}, {"api_name": "dashboard.decorators.check_admin", "line_number": 457, "usage_type": "name"}, {"api_name": "dashboard.forms.SchoolForm", "line_number": 472, "usage_type": "call"}, {"api_name": "dashboard.forms.SchoolImagesForm", "line_number": 473, "usage_type": "call"}, {"api_name": "dashboard.forms.SchoolForm", "line_number": 475, "usage_type": "call"}, {"api_name": "dashboard.forms.SchoolImagesForm", "line_number": 476, "usage_type": "call"}, {"api_name": "cars.models.SchoolImage", "line_number": 481, "usage_type": "call"}, {"api_name": "django.contrib.messages.success", "line_number": 483, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 483, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 484, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 492, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 469, "usage_type": "name"}, {"api_name": "dashboard.decorators.check_admin", "line_number": 470, "usage_type": "name"}, {"api_name": "django.shortcuts.get_object_or_404", "line_number": 501, "usage_type": "call"}, {"api_name": "cars.models.School", "line_number": 501, "usage_type": "argument"}, {"api_name": "dashboard.forms.SchoolForm", "line_number": 503, "usage_type": "call"}, {"api_name": "dashboard.forms.SchoolImagesForm", "line_number": 504, "usage_type": "call"}, {"api_name": "dashboard.forms.SchoolForm", "line_number": 506, "usage_type": "call"}, {"api_name": "dashboard.forms.SchoolImagesForm", "line_number": 507, "usage_type": "call"}, {"api_name": "cars.models.SchoolImage", "line_number": 512, "usage_type": "call"}, {"api_name": "django.contrib.messages.success", "line_number": 514, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 514, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 515, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 524, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 498, "usage_type": "name"}, {"api_name": "dashboard.decorators.check_admin", "line_number": 499, "usage_type": "name"}, {"api_name": "django.shortcuts.get_object_or_404", "line_number": 531, "usage_type": "call"}, {"api_name": "cars.models.School", "line_number": 531, "usage_type": "argument"}, {"api_name": "cars.models.School.objects.filter", "line_number": 532, "usage_type": "call"}, {"api_name": "cars.models.School.objects", "line_number": 532, "usage_type": "attribute"}, {"api_name": "cars.models.School", "line_number": 532, "usage_type": "name"}, {"api_name": "django.contrib.messages.success", "line_number": 537, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 537, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 538, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 528, "usage_type": "name"}, {"api_name": "dashboard.decorators.check_admin", "line_number": 529, "usage_type": "name"}, {"api_name": "django.shortcuts.get_object_or_404", "line_number": 544, "usage_type": "call"}, {"api_name": "cars.models.School", "line_number": 544, "usage_type": "argument"}, {"api_name": "django.shortcuts.render", "line_number": 550, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 541, "usage_type": "name"}, {"api_name": "dashboard.decorators.check_admin", "line_number": 542, "usage_type": "name"}, {"api_name": "django.shortcuts.get_object_or_404", "line_number": 556, "usage_type": "call"}, {"api_name": "cars.models.School", "line_number": 556, "usage_type": "argument"}, {"api_name": "django.contrib.messages.success", "line_number": 557, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 557, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 558, "usage_type": "call"}, {"api_name": "django.urls.reverse", "line_number": 558, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 553, "usage_type": "name"}, {"api_name": "dashboard.decorators.check_admin", "line_number": 554, "usage_type": "name"}, {"api_name": "django.shortcuts.get_object_or_404", "line_number": 566, "usage_type": "call"}, {"api_name": "cars.models.SchoolImage", "line_number": 566, "usage_type": "argument"}, {"api_name": "django.contrib.messages.success", "line_number": 569, "usage_type": "call"}, {"api_name": "django.contrib.messages", "line_number": 569, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 570, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 563, "usage_type": "name"}, {"api_name": "dashboard.decorators.check_admin", "line_number": 564, "usage_type": "name"}]} +{"seq_id": "34104982562", "text": "import os\nimport json\nimport torch\nimport csv\nimport numpy as np\nfrom torch.utils.data import Dataset, DataLoader\nfrom torchvision import transforms, utils\nimport time\nfrom PIL import Image\nimport glob\nimport sys\nfrom scipy import signal\nimport random\nimport ffmpeg\nfrom ffmpeg import Error\nimport pandas as pd\nfrom datetime import timedelta\n\nclass GetAudioVideoDataset(Dataset):\n\n def __init__(self, args, mode='train', transforms=None):\n \n self.fps = 24\n self.win_size = args.window_size\n self.stride = self.win_size\n self.rate = 16000\n self.seconds_per_snippet = self.win_size/self.fps\n \n self.mode = mode\n self.transforms = transforms\n\n # initialize audio transform\n self._init_atransform()\n # Retrieve list of audio and video files\n self.video_files = []\n self._set_video_files(os.path.join(args.paths_video))\n self.durations = {}\n self._set_video_duration(os.path.join(args.duration_csv))\n\n\n def _init_atransform(self):\n self.aid_transform = transforms.Compose([transforms.ToTensor()])\n\n def _set_video_files(self, paths_video):\n # paths_df = pd.read_csv(paths_csv)\n self.video_files = glob.glob(f'{paths_video}/*.mp4')\n print(f'# of audio files = {len(self.video_files):d}')\n\n def _set_video_duration(self, duration_csv):\n duration_df = pd.read_csv(duration_csv)\n self.durations = {row[1].videoid:int(row[1].duration) for row in duration_df.iterrows()}\n\n def __len__(self):\n return len(self.video_files) \n\n def extract_audio(self, filename): \n try:\n out, err = (\n ffmpeg\n .input(filename)\n .output('-', format='f32le', acodec='pcm_f32le', ac=1, ar=str(self.rate))\n .run(capture_stdout=True, capture_stderr=True)\n )\n except Error as err:\n print(err.stderr)\n return np.array([])\n \n return np.frombuffer(out, np.float32)\n\n\n def __getitem__(self, idx):\n mp4file = self.video_files[idx]\n video_name = os.path.splitext(os.path.basename(mp4file))[0]\n video_spectograms = []\n video_samples = []\n \n sample = self.extract_audio(mp4file)\n if not sample.any():\n return video_name, sample, mp4file\n duration = self.durations[video_name] #Limit the duration of the video\n sample = sample[0:duration*self.rate]\n padded_duration = int(duration + (self.win_size/self.fps - duration%(self.win_size/self.fps)))\n sound_stride = int((self.stride/self.fps)*self.rate)\n sound_win_size = (self.win_size/self.fps)*self.rate\n for i, time_stamp in enumerate(range(0, int(padded_duration*self.rate)-sound_stride, sound_stride)):\n this_start = int(time_stamp)\n this_end = int(this_start + sound_win_size)\n this_sample = sample[this_start:this_end].copy()\n # repeat in case audio is too short\n # if (sample.shape[0]-this_start) < sound_win_size:\n # num_to_pad = int(np.ceil(sound_win_size - (sample.shape[0]-this_start)))\n # this_sample = np.pad(this_sample, \n # [(0, num_to_pad)],\n # 'constant')\n if i>1 and not this_sample.shape[-1] == video_samples[-1].shape[-1]:\n \n num_to_pad = video_samples[-1].shape[-1] - this_sample.shape[-1]\n this_sample = np.pad(this_sample, \n [(0, num_to_pad)],\n 'constant')\n this_sample[this_sample > 1.] = 1.\n this_sample[this_sample < -1.] = -1.\n video_samples.append(this_sample)\n frequencies, times, spectrogram = signal.spectrogram(this_sample, self.rate, nperseg=512,noverlap=353)\n spectrogram = np.log(spectrogram+ 1e-7)\n\n mean = np.mean(spectrogram)\n std = np.std(spectrogram)\n spectrogram = np.divide(spectrogram-mean,std+1e-9)\n video_spectograms.append(spectrogram)\n spectogram = torch.tensor(np.array(video_spectograms))\n return video_name, spectogram, mp4file\n\n\n", "repo_name": "PardoAlejo/VGGSoundFeatures", "sub_path": "datasets/dataloader.py", "file_name": "dataloader.py", "file_ext": "py", "file_size_in_byte": 4296, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "torch.utils.data.Dataset", "line_number": 19, "usage_type": "name"}, {"api_name": "torchvision.transforms", "line_number": 30, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 36, "usage_type": "call"}, {"api_name": "os.path", "line_number": 36, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 38, "usage_type": "call"}, {"api_name": "os.path", "line_number": 38, "usage_type": "attribute"}, {"api_name": "torchvision.transforms.Compose", "line_number": 42, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 42, "usage_type": "name"}, {"api_name": "torchvision.transforms.ToTensor", "line_number": 42, "usage_type": "call"}, {"api_name": "glob.glob", "line_number": 46, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 50, "usage_type": "call"}, {"api_name": "ffmpeg.input", "line_number": 59, "usage_type": "call"}, {"api_name": "ffmpeg.Error", "line_number": 64, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 66, "usage_type": "call"}, {"api_name": "numpy.frombuffer", "line_number": 68, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 68, "usage_type": "attribute"}, {"api_name": "os.path.splitext", "line_number": 73, "usage_type": "call"}, {"api_name": "os.path", "line_number": 73, "usage_type": "attribute"}, {"api_name": "os.path.basename", "line_number": 73, "usage_type": "call"}, {"api_name": "numpy.pad", "line_number": 98, "usage_type": "call"}, {"api_name": "scipy.signal.spectrogram", "line_number": 104, "usage_type": "call"}, {"api_name": "scipy.signal", "line_number": 104, "usage_type": "name"}, {"api_name": "numpy.log", "line_number": 105, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 107, "usage_type": "call"}, {"api_name": "numpy.std", "line_number": 108, "usage_type": "call"}, {"api_name": "numpy.divide", "line_number": 109, "usage_type": "call"}, {"api_name": "torch.tensor", "line_number": 111, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 111, "usage_type": "call"}]} +{"seq_id": "73531689652", "text": "from django import forms\n\nfrom ..models import Image\n\nclass CreateImageForm(forms.ModelForm):\n\n class Meta:\n model = Image\n fields = ['private', 'image'] \n\nclass UpdateImageForm(forms.ModelForm):\n\n class Meta:\n model = Image\n fields = ['private', 'image']\n\n def save(self, commit=True):\n obj = self.instance\n obj.private = self.cleaned_data['private']\n\n if self.cleaned_data['image']:\n obj.image = self.cleaned_data['image']\n\n if commit:\n obj.save()\n return obj\n\n ", "repo_name": "LucasBellido/ShopifyImageRepo", "sub_path": "image_repository/api/forms/imageForm.py", "file_name": "imageForm.py", "file_ext": "py", "file_size_in_byte": 559, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "django.forms.ModelForm", "line_number": 5, "usage_type": "attribute"}, {"api_name": "django.forms", "line_number": 5, "usage_type": "name"}, {"api_name": "models.Image", "line_number": 8, "usage_type": "name"}, {"api_name": "django.forms.ModelForm", "line_number": 11, "usage_type": "attribute"}, {"api_name": "django.forms", "line_number": 11, "usage_type": "name"}, {"api_name": "models.Image", "line_number": 14, "usage_type": "name"}]} +{"seq_id": "42522242735", "text": "#!/usr/bin/env python3\nimport time\nfrom multiprocessing import Pool\n\n\nCOUNT = int(5e8)\n\ndef countdown(n: int) -> None:\n while n > 0:\n n -= 1\n\nif __name__ == '__main__':\n p_count = 4\n pool = Pool(processes=p_count)\n for n in range(1, p_count+1):\n pool.apply_async(countdown, [(COUNT//p_count) * n])\n pool.close()\n pool.join()\n", "repo_name": "pimiento/python_threads_examples", "sub_path": "multi_process.py", "file_name": "multi_process.py", "file_ext": "py", "file_size_in_byte": 357, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "21", "api": [{"api_name": "multiprocessing.Pool", "line_number": 14, "usage_type": "call"}]} +{"seq_id": "71706136374", "text": "# This Source Code Form is subject to the terms of the Mozilla Public\n# License, v. 2.0. If a copy of the MPL was not distributed with this\n# file, You can obtain one at http://mozilla.org/MPL/2.0/.\nfrom itertools import chain, product, repeat\nimport os\nfrom io import StringIO\nimport numpy as np # type: ignore\n\nfrom typing import ( # noqa\n List, Tuple, DefaultDict, Iterator, IO, Sized, Iterable, Union, Dict, Any,\n Optional\n)\n\nfrom . import geomlib\n\n\nspecie_data = geomlib.Atom.data\nbohr = geomlib.bohr\n\n\nVec = Tuple[float, float, float]\n\n\n_string_cache: Dict[Any, str] = {}\n\n\nclass Atom:\n def __init__(self, specie: str, coord: Vec, ghost: bool = False) -> None:\n self.specie = specie\n self.coord = coord\n self.ghost = ghost\n\n @property\n def mass(self) -> float:\n mass: float = specie_data[self.specie]['mass']\n return mass\n\n @property\n def number(self) -> int:\n return int(specie_data[self.specie]['number'])\n\n @property\n def covalent_radius(self) -> float:\n r: float = specie_data[self.specie]['covalent radius']\n return r\n\n def copy(self) -> 'Atom':\n return Atom(self.specie, self.coord, self.ghost)\n\n\nclass Molecule(Sized, Iterable):\n def __init__(self, atoms: List[Atom]) -> None:\n self._atoms = atoms\n\n @classmethod\n def from_coords(cls, species: List[str], coords: List[Vec]) -> 'Molecule':\n return cls([Atom(sp, coord) for sp, coord in zip(species, coords)])\n\n @property\n def species(self) -> List[str]:\n return [atom.specie for atom in self]\n\n @property\n def numbers(self) -> List[int]:\n return [atom.number for atom in self]\n\n @property\n def mass(self) -> float:\n return sum(atom.mass for atom in self)\n\n @property\n def cms(self) -> np.ndarray:\n masses = np.array([atom.mass for atom in self])\n return (masses[:, None]*self.xyz).sum(0)/self.mass\n\n @property\n def coords(self) -> List[Vec]:\n return [atom.coord for atom in self]\n\n def __repr__(self) -> str:\n return \"<{} '{}'>\".format(self.__class__.__name__, self.formula)\n\n @property\n def xyz(self) -> np.ndarray:\n return np.array(self.coords)\n\n @property\n def formula(self) -> str:\n counter = DefaultDict[str, int](int)\n for specie in self.species:\n counter[specie] += 1\n return ''.join(\n f'{sp}{n if n > 1 else \"\"}' for sp, n in sorted(counter.items())\n )\n\n def bondmatrix(self, scale: float) -> np.ndarray:\n xyz = self.xyz\n Rs = np.array([atom.covalent_radius for atom in self])\n dmatrix = np.sqrt(np.sum((xyz[None, :]-xyz[:, None])**2, 2))\n thrmatrix = scale*(Rs[None, :]+Rs[:, None])\n return dmatrix < thrmatrix\n\n def get_fragments(self, scale: float = 1.3) -> List['Molecule']:\n bond = self.bondmatrix(scale)\n ifragments = geomlib.getfragments(bond)\n fragments = [\n Molecule([self._atoms[i].copy() for i in fragment])\n for fragment in ifragments\n ]\n return fragments\n\n def shifted(self, delta: Union[Vec, np.ndarray]) -> 'Molecule':\n m = self.copy()\n for atom in m:\n c = atom.coord\n atom.coord = (c[0]+delta[0], c[1]+delta[1], c[2]+delta[2])\n return m\n\n def __add__(self, other: object) -> 'Molecule':\n if not isinstance(other, Molecule):\n return NotImplemented # type:ignore\n return Molecule(self._atoms + other._atoms)\n\n @property\n def centers(self) -> Iterator[Atom]:\n yield from self._atoms\n\n def __iter__(self) -> Iterator[Atom]:\n yield from (atom for atom in self._atoms if not atom.ghost)\n\n def __len__(self) -> int:\n return len([atom for atom in self._atoms if not atom.ghost])\n\n def __format__(self, fmt: str) -> str:\n fp = StringIO()\n self.dump(fp, fmt)\n return fp.getvalue()\n\n def items(self) -> Iterator[Tuple[str, Vec]]:\n for atom in self:\n yield atom.specie, atom.coord\n\n dumps = __format__\n\n def dump(self, f: IO[str], fmt: str) -> None:\n if fmt == '':\n f.write(repr(self))\n elif fmt == 'xyz':\n f.write('{}\\n'.format(len(self)))\n f.write('Formula: {}\\n'.format(self.formula))\n for specie, coord in self.items():\n f.write('{:>2} {}\\n'.format(\n specie, ' '.join('{:15.8}'.format(x) for x in coord)\n ))\n elif fmt == 'aims':\n for atom in self.centers:\n specie, r = atom.specie, atom.coord\n key = (specie, r, atom.ghost, fmt)\n try:\n f.write(_string_cache[key])\n except KeyError:\n kind = 'atom' if not atom.ghost else 'empty'\n s = f'{kind} {r[0]:15.8f} {r[1]:15.8f} {r[2]:15.8f} {specie:>2}\\n'\n f.write(s)\n _string_cache[key] = s\n elif fmt == 'mopac':\n f.write('* Formula: {}\\n'.format(self.formula))\n for specie, coord in self.items():\n f.write('{:>2} {}\\n'.format(\n specie, ' '.join('{:15.8} 1'.format(x) for x in coord)\n ))\n else:\n raise ValueError(\"Unknown format: '{}'\".format(fmt))\n\n def copy(self) -> 'Molecule':\n return Molecule([atom.copy() for atom in self._atoms])\n\n def ghost(self) -> 'Molecule':\n m = self.copy()\n for atom in m:\n atom.ghost = True\n return m\n\n def write(self, filename: str) -> None:\n ext = os.path.splitext(filename)[1]\n if ext == 'xyz':\n fmt = 'xyz'\n elif ext == 'aims' or os.path.basename(filename) == 'geometry.in':\n fmt = 'aims'\n elif ext == 'mopac':\n fmt = 'mopac'\n with open(filename, 'w') as f:\n self.dump(f, fmt)\n\n\nclass Crystal(Molecule):\n def __init__(self, atoms: List[Atom], lattice: List[Vec]) -> None:\n Molecule.__init__(self, atoms)\n self.lattice = lattice\n\n @classmethod\n def from_coords(cls, species: List[str], coords: List[Vec], # type: ignore\n lattice: List[Vec]) -> 'Crystal':\n return cls(\n [Atom(sp, coord) for sp, coord in zip(species, coords)],\n lattice\n )\n\n def dump(self, f: IO[str], fmt: str) -> None:\n if fmt == '':\n f.write(repr(self))\n elif fmt == 'aims':\n for label, (x, y, z) in zip('abc', self.lattice):\n f.write(f'lattice_vector {x:15.8f} {y:15.8f} {z:15.8f}\\n')\n super().dump(f, fmt)\n else:\n raise ValueError(f'Unknown format: {fmt!r}')\n\n def copy(self) -> 'Crystal':\n return Crystal(\n [atom.copy() for atom in self._atoms],\n self.lattice.copy()\n )\n\n @property\n def abc(self) -> np.ndarray:\n return np.array(self.lattice)\n\n def get_kgrid(self, density: float = 0.06) -> Tuple[int, int, int]:\n rec_lattice = 2*np.pi*np.linalg.inv(self.abc.T)\n rec_lens = np.sqrt((rec_lattice**2).sum(1))\n nkpts = np.ceil(rec_lens/(density*bohr))\n return int(nkpts[0]), int(nkpts[1]), int(nkpts[2])\n\n def supercell(self, ns: Tuple[int, int, int]) -> 'Crystal':\n abc = self.abc\n latt_vectors = np.array([\n sum(s*vec for s, vec in zip(shift, abc))\n for shift in product(*map(range, ns))\n ])\n species = list(chain.from_iterable(repeat(self.species, len(latt_vectors))))\n coords = [\n (x, y, z) for x, y, z in\n (self.xyz[None, :, :]+latt_vectors[:, None, :]).reshape((-1, 3))\n ]\n lattice = [(x, y, z) for x, y, z in abc*np.array(ns)[:, None]]\n return Crystal.from_coords(species, coords, lattice)\n\n\ndef get_vec(ws: List[str]) -> Vec:\n return float(ws[0]), float(ws[1]), float(ws[2])\n\n\ndef load(fp: IO[str], fmt: str) -> Molecule:\n if fmt == 'xyz':\n n = int(fp.readline())\n fp.readline()\n species = []\n coords = []\n for _ in range(n):\n ws = fp.readline().split()\n species.append(ws[0])\n coords.append(get_vec(ws[1:4]))\n return Molecule.from_coords(species, coords)\n if fmt == 'aims':\n atoms = []\n lattice = []\n while True:\n l = fp.readline()\n if l == '':\n break\n l = l.strip()\n if not l or l.startswith('#'):\n continue\n ws = l.split()\n what = ws[0]\n if what in ['atom', 'empty']:\n atoms.append(Atom(ws[4], get_vec(ws[1:4]), ghost=what == 'empty'))\n elif what == 'lattice_vector':\n lattice.append(get_vec(ws[1:4]))\n if lattice:\n assert len(lattice) == 3\n return Crystal(atoms, lattice)\n else:\n return Molecule(atoms)\n raise ValueError(f'Unknown format: {fmt}')\n\n\ndef loads(s: str, fmt: str) -> Molecule:\n fp = StringIO(s)\n return load(fp, fmt)\n\n\ndef readfile(path: str, fmt: str = None) -> Molecule:\n if not fmt:\n ext = os.path.splitext(path)[1]\n if ext == '.xyz':\n fmt = 'xyz'\n elif ext == '.aims' or os.path.basename(path) == 'geometry.in':\n fmt = 'aims'\n else:\n raise RuntimeError('Cannot determine format')\n with open(path) as f:\n return load(f, fmt)\n", "repo_name": "jhrmnn/caftools", "sub_path": "caftools/geomlib2.py", "file_name": "geomlib2.py", "file_ext": "py", "file_size_in_byte": 9534, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "typing.Tuple", "line_number": 21, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 24, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 24, "usage_type": "name"}, {"api_name": "typing.Sized", "line_number": 51, "usage_type": "name"}, {"api_name": "typing.Iterable", "line_number": 51, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 52, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 56, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 60, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 64, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 73, "usage_type": "call"}, {"api_name": "numpy.ndarray", "line_number": 72, "usage_type": "attribute"}, {"api_name": "typing.List", "line_number": 77, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 85, "usage_type": "call"}, {"api_name": "numpy.ndarray", "line_number": 84, "usage_type": "attribute"}, {"api_name": "typing.DefaultDict", "line_number": 89, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 98, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 99, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 99, "usage_type": "call"}, {"api_name": "numpy.ndarray", "line_number": 96, "usage_type": "attribute"}, {"api_name": "typing.List", "line_number": 103, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 112, "usage_type": "name"}, {"api_name": "numpy.ndarray", "line_number": 112, "usage_type": "attribute"}, {"api_name": "typing.Iterator", "line_number": 125, "usage_type": "name"}, {"api_name": "typing.Iterator", "line_number": 128, "usage_type": "name"}, {"api_name": "io.StringIO", "line_number": 135, "usage_type": "call"}, {"api_name": "typing.Iterator", "line_number": 139, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 139, "usage_type": "name"}, {"api_name": "typing.IO", "line_number": 145, "usage_type": "name"}, {"api_name": "os.path.splitext", "line_number": 185, "usage_type": "call"}, {"api_name": "os.path", "line_number": 185, "usage_type": "attribute"}, {"api_name": "os.path.basename", "line_number": 188, "usage_type": "call"}, {"api_name": "os.path", "line_number": 188, "usage_type": "attribute"}, {"api_name": "typing.List", "line_number": 197, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 202, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 203, "usage_type": "name"}, {"api_name": "typing.IO", "line_number": 209, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 227, "usage_type": "call"}, {"api_name": "numpy.ndarray", "line_number": 226, "usage_type": "attribute"}, {"api_name": "numpy.pi", "line_number": 230, "usage_type": "attribute"}, {"api_name": "numpy.linalg.inv", "line_number": 230, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 230, "usage_type": "attribute"}, {"api_name": "numpy.sqrt", "line_number": 231, "usage_type": "call"}, {"api_name": "numpy.ceil", "line_number": 232, "usage_type": "call"}, {"api_name": "typing.Tuple", "line_number": 229, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 235, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 237, "usage_type": "call"}, {"api_name": "itertools.product", "line_number": 239, "usage_type": "call"}, {"api_name": "itertools.chain.from_iterable", "line_number": 241, "usage_type": "call"}, {"api_name": "itertools.chain", "line_number": 241, "usage_type": "name"}, {"api_name": "itertools.repeat", "line_number": 241, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 246, "usage_type": "call"}, {"api_name": "typing.List", "line_number": 250, "usage_type": "name"}, {"api_name": "typing.IO", "line_number": 254, "usage_type": "name"}, {"api_name": "io.StringIO", "line_number": 290, "usage_type": "call"}, {"api_name": "os.path.splitext", "line_number": 296, "usage_type": "call"}, {"api_name": "os.path", "line_number": 296, "usage_type": "attribute"}, {"api_name": "os.path.basename", "line_number": 299, "usage_type": "call"}, {"api_name": "os.path", "line_number": 299, "usage_type": "attribute"}]} +{"seq_id": "26278822995", "text": "import matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport tensorflow as tf\r\nimport keras\r\n\r\nimport OPTIONS\r\n\r\n\r\ndef test_model():\r\n try:\r\n model = keras.models.load_model('saved_model.h5')\r\n except Exception as e:\r\n print('Cant load the saved_model.h5 file')\r\n return\r\n\r\n data = __get_data()\r\n class_names = ['car', 'non-car']\r\n\r\n loss, accuracy = model.evaluate(data)\r\n\r\n print('Test loss: ' + str(loss))\r\n print('Test accuracy: ' + str(accuracy))\r\n\r\n data = __get_data(batch_size=None)\r\n # plt.figure(figsize=(10, 10))\r\n count = 0\r\n for i, (x, y) in enumerate(data):\r\n if count >= 10:\r\n return\r\n\r\n img_arr = tf.expand_dims(x, 0)\r\n\r\n predictions = model.predict(img_arr)\r\n\r\n score = tf.nn.softmax(predictions[0])\r\n percent = int(100 * np.max(score))\r\n title = \"{} - {} %\".format(class_names[np.argmax(score)], percent)\r\n\r\n plt.imshow(x.numpy().astype(int))\r\n plt.title(title)\r\n plt.axis(\"off\")\r\n plt.show()\r\n\r\n count += 1\r\n\r\ndef __get_data(batch_size=32):\r\n data_dir = OPTIONS.DATA_DIR\r\n image_height = OPTIONS.IMAGE_HEIGHT\r\n image_width = OPTIONS.IMAGE_WIDTH\r\n\r\n test_ds = tf.keras.preprocessing.image_dataset_from_directory(\r\n data_dir / 'split' / 'test',\r\n image_size=(image_height, image_width),\r\n batch_size=batch_size)\r\n\r\n return test_ds\r\n", "repo_name": "idan5510/project", "sub_path": "test.py", "file_name": "test.py", "file_ext": "py", "file_size_in_byte": 1426, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "keras.models.load_model", "line_number": 11, "usage_type": "call"}, {"api_name": "keras.models", "line_number": 11, "usage_type": "attribute"}, {"api_name": "tensorflow.expand_dims", "line_number": 31, "usage_type": "call"}, {"api_name": "tensorflow.nn.softmax", "line_number": 35, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 35, "usage_type": "attribute"}, {"api_name": "numpy.max", "line_number": 36, "usage_type": "call"}, {"api_name": "numpy.argmax", "line_number": 37, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 39, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 39, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 40, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 40, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.axis", "line_number": 41, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 41, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 42, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 42, "usage_type": "name"}, {"api_name": "OPTIONS.DATA_DIR", "line_number": 47, "usage_type": "attribute"}, {"api_name": "OPTIONS.IMAGE_HEIGHT", "line_number": 48, "usage_type": "attribute"}, {"api_name": "OPTIONS.IMAGE_WIDTH", "line_number": 49, "usage_type": "attribute"}, {"api_name": "tensorflow.keras.preprocessing.image_dataset_from_directory", "line_number": 51, "usage_type": "call"}, {"api_name": "tensorflow.keras", "line_number": 51, "usage_type": "attribute"}]} +{"seq_id": "29967802911", "text": "from typing import Callable, Tuple\n\nfrom numpy.typing import NDArray\nfrom numpy import cumsum, equal, roll\n\nimport evaluate\n\nfrom transformers.tokenization_utils import PreTrainedTokenizerBase\n\n\ndef get_flores_compute_metrics(tokenizer: PreTrainedTokenizerBase) -> Callable:\n chrf = evaluate.load(\"chrf\")\n\n def compute_metrics(eval_preds):\n logits, label_ids = eval_preds\n label_ids[label_ids == -100] = tokenizer.pad_token_id\n\n references = tokenizer.batch_decode(label_ids, skip_special_tokens=True)\n predictions = tokenizer.batch_decode(logits, skip_special_tokens=True)\n\n chrf_metrics = chrf.compute(\n predictions=predictions,\n references=references,\n word_order=2,\n )\n\n return {\"chrf++\": chrf_metrics[\"score\"]}\n\n\n return compute_metrics\n\n\ndef remove_cotr_prefix_from_logits(tokenizer: PreTrainedTokenizerBase, logits: NDArray) -> NDArray:\n \"\"\"\n >>> from lme.compute_metrics_utils.flores200 import remove_cotr_prefix_from_logits\n >>> from transformers import AutoTokenizer\n >>> tokenizer = AutoTokenizer.from_pretrained(\"google/mt5-base\")\n >>> sentence = \"i went to the store i bought some milk\"\n >>> input_ids = tokenizer(sentence, return_tensors=\"np\").input_ids\n >>> tokenized_output = remove_cotr_prefix_from_logits(tokenizer, input_ids)\n >>> actual_output = tokenizer.batch_decode(tokenized_output, skip_special_tokens=True)[0]\n >>> target_output = \"i bought some milk\"\n >>> assert actual_output == target_output, f\"Target output: {target_output}\\\\nActual output: {actual_output}\"\n\n \"\"\"\n target_sep_token_id = 250099 # tokenizer.encode(\"\")[0]\n label_start_idx = roll(equal(logits, target_sep_token_id), 1, axis=1)\n label_mask = cumsum(label_start_idx, axis=1)\n\n eval_target = logits.copy()\n eval_target[label_mask == 0] = tokenizer.pad_token_id\n\n return eval_target\n\n\n# Remove chain of thought reasoning input prefix from evaluation target logits \n# Since the model is trained on the task with the chain of thought reasoning outputs\n# in the training target, we will remove the prefix from the evaluation target logits\ndef get_flores_compute_metrics_cotr(tokenizer: PreTrainedTokenizerBase) -> Callable:\n chrf = evaluate.load(\"chrf\")\n\n def compute_metrics(eval_preds: Tuple[NDArray, NDArray]):\n \"\"\"\n Parameters\n ----------\n eval_preds: Tuple of two numpy ndarray\n\n logits: NDArray of shape (batch_size, sequence_length)\n label_ids: NDArray of shape (batch_size, sequence_length)\n \"\"\"\n logits, label_ids = eval_preds\n label_ids[label_ids == -100] = tokenizer.pad_token_id\n\n eval_target = remove_cotr_prefix_from_logits(tokenizer, logits)\n\n references = tokenizer.batch_decode(label_ids, skip_special_tokens=True)\n predictions = tokenizer.batch_decode(eval_target, skip_special_tokens=True)\n\n chrf_metrics = chrf.compute(\n predictions=predictions,\n references=references,\n word_order=2,\n )\n\n return {\"chrf++\": chrf_metrics[\"score\"]}\n\n return compute_metrics\n\n\nif __name__ == \"__main__\":\n import doctest; doctest.testmod()\n", "repo_name": "sebastian-nehrdich/language-models-bair", "sub_path": "lme/compute_metrics_utils/flores200.py", "file_name": "flores200.py", "file_ext": "py", "file_size_in_byte": 3251, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "transformers.tokenization_utils.PreTrainedTokenizerBase", "line_number": 11, "usage_type": "name"}, {"api_name": "evaluate.load", "line_number": 12, "usage_type": "call"}, {"api_name": "typing.Callable", "line_number": 11, "usage_type": "name"}, {"api_name": "transformers.tokenization_utils.PreTrainedTokenizerBase", "line_number": 33, "usage_type": "name"}, {"api_name": "numpy.typing.NDArray", "line_number": 33, "usage_type": "name"}, {"api_name": "numpy.roll", "line_number": 47, "usage_type": "call"}, {"api_name": "numpy.equal", "line_number": 47, "usage_type": "call"}, {"api_name": "numpy.cumsum", "line_number": 48, "usage_type": "call"}, {"api_name": "transformers.tokenization_utils.PreTrainedTokenizerBase", "line_number": 59, "usage_type": "name"}, {"api_name": "evaluate.load", "line_number": 60, "usage_type": "call"}, {"api_name": "typing.Tuple", "line_number": 62, "usage_type": "name"}, {"api_name": "numpy.typing.NDArray", "line_number": 62, "usage_type": "name"}, {"api_name": "typing.Callable", "line_number": 59, "usage_type": "name"}, {"api_name": "doctest.testmod", "line_number": 91, "usage_type": "call"}]} +{"seq_id": "33606673337", "text": "from dependencies import spark_pg_utils\n\n\ndef solution_1(spark):\n\n import pyspark.sql.functions as F\n\n req_df = spark.read_table_as_df(\"request_accepted_602\")\n req_df.show()\n\n result_df = req_df.select([F.col('requester_id').alias('id'), F.col('accepter_id').alias('friend_id')]) \\\n .union(req_df.select([F.col('accepter_id').alias('id'), F.col('requester_id').alias('friend_id')])) \\\n .groupby('id').agg(F.count('friend_id').alias('num')) \\\n .orderBy(F.desc('num')) \\\n .limit(1)\n\n result_df.show()\n\n\nif __name__ == '__main__':\n spark_pg_utils.execute(solution_1)\n", "repo_name": "sp496/leetcode-pyspark", "sub_path": "dataframe_solutions/Medium/602.py", "file_name": "602.py", "file_ext": "py", "file_size_in_byte": 610, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "pyspark.sql.functions.col", "line_number": 11, "usage_type": "call"}, {"api_name": "pyspark.sql.functions", "line_number": 11, "usage_type": "name"}, {"api_name": "pyspark.sql.functions.col", "line_number": 12, "usage_type": "call"}, {"api_name": "pyspark.sql.functions", "line_number": 12, "usage_type": "name"}, {"api_name": "pyspark.sql.functions.count", "line_number": 13, "usage_type": "call"}, {"api_name": "pyspark.sql.functions", "line_number": 13, "usage_type": "name"}, {"api_name": "pyspark.sql.functions.desc", "line_number": 14, "usage_type": "call"}, {"api_name": "pyspark.sql.functions", "line_number": 14, "usage_type": "name"}, {"api_name": "dependencies.spark_pg_utils.execute", "line_number": 21, "usage_type": "call"}, {"api_name": "dependencies.spark_pg_utils", "line_number": 21, "usage_type": "name"}]} +{"seq_id": "70429895413", "text": "import streamlit as st\nimport requests\nimport json\nimport time\nimport io\nimport cv2\nimport numpy as np\nimport os\nimport textwrap\nfrom PIL import Image, ImageDraw, ImageFont, ImageFilter, ImageChops\nimport random\n\nMAIN_URL = \"https://api.thenextleg.io/v2/\"\nHEADERS = {\n \"Authorization\": \"Bearer 947c9027-64b2-4607-868d-7ea215fbf61e\",\n \"Content-Type\": \"application/json\",\n}\ndownload_headers = {\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36\"\n}\n\n# Load the cascade\nface_cascade = cv2.CascadeClassifier(\n cv2.data.haarcascades + \"haarcascade_frontalface_default.xml\"\n)\n\ncwd = os.getcwd() + \"/\"\n\n\ndef generate_detailed_prompt(location, time, mood, other_details):\n final = \"\"\n if location != \"\":\n final += f\"Location: {location} \"\n if time != \"\":\n final += f\"Time: {time} \"\n if mood != \"\":\n final += f\"Mood: {mood} \"\n if other_details != \"\":\n final += f\"Other Details: {other_details} \"\n return final\n\n\ndef add_border(input_image, border_size):\n # Input image dimensions\n width, height = input_image.size\n\n # New image dimensions\n new_width = width + 2 * border_size\n new_height = height + 2 * border_size\n\n # Create a new transparent image with the new dimensions\n bordered_image = Image.new(\"RGBA\", (new_width, new_height), (0, 0, 0, 0))\n\n # Paste the original image into the center of the new image\n bordered_image.paste(input_image, (border_size, border_size))\n\n return bordered_image\n\n\ndef color_distance(color1, color2):\n \"\"\"Calculate the Euclidean distance between two RGB colors.\"\"\"\n r_diff = color1[0] - color2[0]\n g_diff = color1[1] - color2[1]\n b_diff = color1[2] - color2[2]\n\n return (r_diff**2 + g_diff**2 + b_diff**2) ** 0.5\n\n\ndef make_black_border_transparent(img, threshold=30):\n img = img.convert(\"RGBA\")\n datas = img.getdata()\n\n width, height = img.size\n border_pixels = []\n\n BLACK = (0, 0, 0)\n\n # Identify black and near-black border pixels\n for y in range(height):\n for x in range(width):\n if color_distance(datas[y * width + x][:3], BLACK) <= threshold:\n border_pixels.append((x, y))\n\n # Modify identified pixels to transparent\n for pixel in border_pixels:\n img.putpixel(pixel, (0, 0, 0, 0))\n # Add neighboring pixels to ensure we get the edge aliasing\n neighbors = [\n (pixel[0] + dx, pixel[1] + dy) for dx in [-1, 0, 1] for dy in [-1, 0, 1]\n ]\n for neighbor in neighbors:\n if 0 <= neighbor[0] < width and 0 <= neighbor[1] < height:\n img.putpixel(neighbor, (0, 0, 0, 0))\n\n return img\n\n\ndef detect_faces(image, show_faces=None):\n # Convert the image to grayscale\n gray = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2GRAY)\n\n # Detect faces\n faces = face_cascade.detectMultiScale(gray, 1.1, 4)\n\n # Draw rectangles around the faces and number them if they are to be shown\n draw = ImageDraw.Draw(image)\n font = ImageFont.truetype(f\"{cwd}streamlit_components/Roboto-Black.ttf\", 25)\n for index, (x, y, w, h) in enumerate(faces):\n if show_faces is None or show_faces[index]:\n draw.rectangle([x, y, x + w, y + h], outline=\"blue\", width=2)\n draw.text((x, y), str(index + 1), fill=\"red\", font=font)\n\n return image, faces\n\n\ndef swap_faces(image, faces, detected_faces, labaled_faces):\n image.save(f\"{cwd}temp_folder/main.png\")\n faces = [Image.open(image) for image in faces]\n for idx, face in enumerate(faces):\n face.save(f\"{cwd}temp_folder/face{idx+1}.png\")\n cropped_faces = [\n image.crop((x, y - 20, x + w, y + h + 20)) for (x, y, w, h) in detected_faces\n ]\n cropped_files = []\n for idx, image in enumerate(cropped_faces):\n add_border(image, 100).save(f\"{cwd}temp_folder/cropImage{idx+1}.png\")\n cropped_files.append(f\"{cwd}temp_folder/cropImage{idx+1}.png\")\n swapped_faces = []\n for input_file, label in zip(cropped_files, labaled_faces):\n if label == \"\":\n swapped_faces.append(Image.open(input_file))\n else:\n base_command = \"python classes/run.py\"\n source_option = f\"--source temp_folder/face{label}.png\"\n target_option = f\"--target {input_file}\"\n output_option = (\n f\"--output temp_folder/output{label}.png\" # Customize your output path\n )\n other_options = \"--keep-fps --keep-frames --temp-frame-quality 100\" #\n os.system(\n f\"{base_command} {source_option} {target_option} {output_option} {other_options}\"\n )\n swapped_faces.append(Image.open(f\"temp_folder/output{label}.png\"))\n\n main_image = Image.open(\"temp_folder/main.png\")\n for idx, (x, y, h, w) in enumerate(detected_faces):\n mask = make_black_border_transparent(swapped_faces[idx]).split()[3]\n main_image.paste(swapped_faces[idx], (x - 100, y - 120), mask)\n return main_image\n\n\ndef download_image(buttonID, num):\n response = requests.get(\n f\"{MAIN_URL}button?buttonMessageId={buttonID}&button=U{num}\", headers=HEADERS\n )\n progress = 0\n progress_bar = st.progress(0)\n while progress != 100:\n time.sleep(1)\n response_button = get_image_progress(response.json()[\"messageId\"])\n progress = response_button[\"progress\"]\n progress_bar.progress(int(progress))\n image_bytes = requests.get(response_button[\"response\"][\"imageUrl\"]).content\n return Image.open(io.BytesIO(image_bytes))\n\n\ndef save_data(data):\n with open(\"streamlit_data.json\", \"w\") as f:\n json.dump(data, f, indent=4)\n\n\ndef display_uploaded_images(uploaded_images, col):\n upload_image = col.columns(3)\n for index, img in enumerate(uploaded_images):\n upload_image[index].image(img, width=200)\n upload_image[index].write(f\"Face {index + 1}\")\n\n\ndef get_image_from_api(prompt):\n payload = json.dumps(\n {\n \"msg\": prompt,\n \"ref\": \"\",\n \"webhookOverride\": \"\",\n \"ignorePrefilter\": \"false\",\n }\n )\n response = requests.post(f\"{MAIN_URL}imagine\", headers=HEADERS, data=payload)\n print(response)\n return response.json()\n\n\ndef get_image_progress(messageId):\n response = requests.get(f\"{MAIN_URL}message/{messageId}\", headers=HEADERS)\n return response.json()\n\n\ndef display_images(images, type_display=None):\n cols = st.columns(len(images))\n if type_display == None:\n for idx, (col, url) in enumerate(zip(cols, images)):\n if url == st.session_state.get(\"selected_image\"):\n col.markdown(\n f\"\",\n unsafe_allow_html=True,\n )\n else:\n col.markdown(\n f\"\",\n unsafe_allow_html=True,\n )\n clicked = col.button(f\"Select Image {idx + 1}\")\n if clicked:\n st.session_state.selected_image = url\n st.experimental_rerun()\n else:\n for idx, (col, url) in enumerate(zip(cols, images)):\n if url == st.session_state.get(\"anim_selected_image\"):\n col.markdown(\n f\"\",\n unsafe_allow_html=True,\n )\n else:\n col.markdown(\n f\"\",\n unsafe_allow_html=True,\n )\n clicked = col.button(f\"Select Animated Image {idx + 1}\")\n if clicked:\n st.session_state.anim_selected_image = url\n st.experimental_rerun()\n\n\ndef post_image_discord(image):\n img_byte_arr = io.BytesIO()\n image.save(img_byte_arr, format=\"PNG\")\n img_byte_arr = img_byte_arr.getvalue()\n\n webhook = \"https://discord.com/api/webhooks/1145980484711612476/XkbQtaW4Kn7oigvruxPMC6fnTyJcJF5wrJHUoaCUhW2tBLRL5WlXI4FaiE_s-mo733B_\"\n\n data = {\"content\": \"Uploading a file...\"}\n\n files = {\"file\": (\"filename.jpg\", img_byte_arr)}\n\n response = requests.post(webhook, files=files, data=data)\n if response.status_code == 200:\n json_response = response.json()\n file_url = json_response[\"attachments\"][0][\"url\"]\n return file_url\n else:\n return f\"Error {response.status_code}: {response.text}\"\n\n\ndef generate_pdf(images):\n file_name = f\"test{time.time()}.pdf\"\n try:\n images[0].save(file_name, save_all=True, append_images=images[1:])\n except:\n images[0].save(file_name, save_all=True)\n with open(file_name, \"rb\") as f:\n pdf_bytes = f.read()\n return pdf_bytes\n\n\ndef fix_story(story: str, name: str, pronoun: str):\n story = story.replace(\"{name}\", name)\n if pronoun.lower() == \"he\":\n story = story.replace(\".{pronoun1}\", \". He\")\n story = story.replace(\". {pronoun1}\", \". He\")\n story = story.replace(\"{pronoun1}\", \"he\")\n story = story.replace(\".{pronoun2}\", \". Him\")\n story = story.replace(\". {pronoun2}\", \". Him\")\n story = story.replace(\"{pronoun2}\", \"him\")\n story = story.replace(\".{pronoun3}\", \". His\")\n story = story.replace(\". {pronoun3}\", \". His\")\n story = story.replace(\"{pronoun3}\", \"his\")\n elif pronoun.lower() == \"she\":\n story = story.replace(\".{pronoun1}\", \". She\")\n story = story.replace(\". {pronoun1}\", \". She\")\n story = story.replace(\"{pronoun1}\", \"she\")\n story = story.replace(\".{pronoun2}\", \". Her\")\n story = story.replace(\". {pronoun2}\", \". Her\")\n story = story.replace(\"{pronoun2}\", \"her\")\n story = story.replace(\".{pronoun3}\", \". Her\")\n story = story.replace(\". {pronoun3}\", \". Her\")\n story = story.replace(\"{pronoun3}\", \"her\")\n elif pronoun.lower() == \"they\":\n story = story.replace(\".{pronoun1}\", \". They\")\n story = story.replace(\". {pronoun1}\", \". They\")\n story = story.replace(\"{pronoun1}\", \"they\")\n story = story.replace(\".{pronoun2}\", \". Them\")\n story = story.replace(\". {pronoun2}\", \". Them\")\n story = story.replace(\"{pronoun2}\", \"them\")\n story = story.replace(\".{pronoun3}\", \". Their\")\n story = story.replace(\". {pronoun3}\", \". Their\")\n story = story.replace(\"{pronoun3}\", \"their\")\n return story\n\n\ndef create_white_gradient(img):\n width, height = img.width // 4, img.height\n\n image = Image.new(\"RGBA\", (width, height), (255, 255, 255, 0))\n\n for x in range(width):\n alpha = int((x / width) * 255)\n for y in range(height):\n image.putpixel((x, y), (255, 255, 255, alpha))\n\n white_image = Image.new(\"RGBA\", (5 * img.width // 4, height), (255, 255, 255, 255))\n final_image = Image.new(\"RGBA\", (width + 5 * img.width // 4, height))\n final_image.paste(image, (0, 0))\n final_image.paste(white_image, (width, 0))\n\n return final_image\n\n\ndef combine_gradient_image(img, gradient):\n mask = gradient.split()[3]\n width, height = img.width, img.height\n fin_image = Image.new(\"RGBA\", (3 * width // 2, height))\n fin_image.paste(img, (0, 0))\n fin_image.paste(gradient, (width - width // 4, 0), mask)\n return fin_image\n\n\ndef add_text_to_image(img, text, font_name, font_size):\n font_name = f\"./fonts/{font_name}.otf\"\n gradient = create_white_gradient(img)\n combined_image = combine_gradient_image(img, gradient)\n\n font = ImageFont.truetype(font_name, font_size)\n\n draw = ImageDraw.Draw(combined_image)\n\n a = img.width + 40 # start width\n b = combined_image.width - 40 # end width\n\n wrapper = textwrap.TextWrapper(\n width=40\n ) # change 40 to control the number of words per line\n word_list = text.split(\" \")\n wrapped_text = \"\\n\".join(\n [\n \" \".join(wrapper.wrap(\" \".join(word_list[i : i + 40])))\n for i in range(0, len(word_list), 40)\n ]\n )\n\n colored_text = []\n for word in wrapped_text.split():\n if random.randint(1, 4) == 1:\n colored_text.append(\n (\n word,\n (\n random.randint(100, 255),\n random.randint(100, 255),\n random.randint(100, 255),\n ),\n )\n )\n else:\n colored_text.append((word, (0, 0, 0))) # default color, black\n\n line_spacing = 20\n\n total_height = 0\n lines = []\n line = []\n line_width = 0\n word_heights = []\n\n for word, color in colored_text:\n bbox = draw.textbbox((0, 0), word, font)\n word_width = bbox[2] - bbox[0]\n word_height = bbox[3] - bbox[1]\n\n if line_width + word_width > b - a:\n lines.append(line)\n total_height += word_height + line_spacing\n word_heights.append(word_height)\n line = []\n line_width = 0\n\n line.append((word, color))\n line_width += word_width + draw.textbbox((0, 0), \" \", font)[2]\n\n if line:\n lines.append(line)\n total_height += word_height\n word_heights.append(word_height)\n\n image_height = combined_image.size[1]\n start_y = max((image_height - total_height) // 2, 0)\n\n x = a\n y = start_y\n\n for i, line in enumerate(lines):\n x = a\n for word, color in line:\n bbox = draw.textbbox((x, y), word, font)\n word_width = bbox[2] - bbox[0]\n\n draw.text((x, y), word, font=font, fill=color)\n\n x += word_width + draw.textbbox((0, 0), \" \", font)[2]\n\n y += word_heights[i] + line_spacing\n\n return combined_image\n", "repo_name": "oltiMetdaan/AIBook", "sub_path": "streamlit_components/functions.py", "file_name": "functions.py", "file_ext": "py", "file_size_in_byte": 13930, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "cv2.CascadeClassifier", "line_number": 23, "usage_type": "call"}, {"api_name": "cv2.data", "line_number": 24, "usage_type": "attribute"}, {"api_name": "os.getcwd", "line_number": 27, "usage_type": "call"}, {"api_name": "PIL.Image.new", "line_number": 52, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 52, "usage_type": "name"}, {"api_name": "cv2.cvtColor", "line_number": 100, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 100, "usage_type": "call"}, {"api_name": "cv2.COLOR_RGB2GRAY", "line_number": 100, "usage_type": "attribute"}, {"api_name": "PIL.ImageDraw.Draw", "line_number": 106, "usage_type": "call"}, {"api_name": "PIL.ImageDraw", "line_number": 106, "usage_type": "name"}, {"api_name": "PIL.ImageFont.truetype", "line_number": 107, "usage_type": "call"}, {"api_name": "PIL.ImageFont", "line_number": 107, "usage_type": "name"}, {"api_name": "PIL.Image.open", "line_number": 118, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 118, "usage_type": "name"}, {"api_name": "PIL.Image.open", "line_number": 131, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 131, "usage_type": "name"}, {"api_name": "os.system", "line_number": 140, "usage_type": "call"}, {"api_name": "PIL.Image.open", "line_number": 143, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 143, "usage_type": "name"}, {"api_name": "PIL.Image.open", "line_number": 145, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 145, "usage_type": "name"}, {"api_name": "requests.get", "line_number": 153, "usage_type": "call"}, {"api_name": "streamlit.progress", "line_number": 157, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 159, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 163, "usage_type": "call"}, {"api_name": "PIL.Image.open", "line_number": 164, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 164, "usage_type": "name"}, {"api_name": "io.BytesIO", "line_number": 164, "usage_type": "call"}, {"api_name": "json.dump", "line_number": 169, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 180, "usage_type": "call"}, {"api_name": "requests.post", "line_number": 188, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 194, "usage_type": "call"}, {"api_name": "streamlit.columns", "line_number": 199, "usage_type": "call"}, {"api_name": "streamlit.session_state.get", "line_number": 202, "usage_type": "call"}, {"api_name": "streamlit.session_state", "line_number": 202, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 214, "usage_type": "attribute"}, {"api_name": "streamlit.experimental_rerun", "line_number": 215, "usage_type": "call"}, {"api_name": "streamlit.session_state.get", "line_number": 218, "usage_type": "call"}, {"api_name": "streamlit.session_state", "line_number": 218, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 230, "usage_type": "attribute"}, {"api_name": "streamlit.experimental_rerun", "line_number": 231, "usage_type": "call"}, {"api_name": "io.BytesIO", "line_number": 235, "usage_type": "call"}, {"api_name": "requests.post", "line_number": 245, "usage_type": "call"}, {"api_name": "time.time", "line_number": 255, "usage_type": "call"}, {"api_name": "PIL.Image.new", "line_number": 303, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 303, "usage_type": "name"}, {"api_name": "PIL.Image.new", "line_number": 310, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 310, "usage_type": "name"}, {"api_name": "PIL.Image.new", "line_number": 311, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 311, "usage_type": "name"}, {"api_name": "PIL.Image.new", "line_number": 321, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 321, "usage_type": "name"}, {"api_name": "PIL.ImageFont.truetype", "line_number": 332, "usage_type": "call"}, {"api_name": "PIL.ImageFont", "line_number": 332, "usage_type": "name"}, {"api_name": "PIL.ImageDraw.Draw", "line_number": 334, "usage_type": "call"}, {"api_name": "PIL.ImageDraw", "line_number": 334, "usage_type": "name"}, {"api_name": "textwrap.TextWrapper", "line_number": 339, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 352, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 357, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 358, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 359, "usage_type": "call"}]} +{"seq_id": "8787030740", "text": "'''\n@Author: your name\n@Date: 2020-01-06 17:08:52\n@LastEditTime : 2020-01-07 13:25:31\n@LastEditors : Please set LastEditors\n@Description: In User Settings Edit\n@FilePath: /KGCN_Keras-master/utils/io.py\n'''\n# -*- coding: utf-8 -*-\n\nimport os\nimport json\nimport pickle\n\n\ndef pickle_load(filename: str):\n try:\n with open(filename, 'rb') as f:\n obj = pickle.load(f)\n print(f'Logging Info - Loaded: {filename}')\n except EOFError:\n print(f'Logging Error - Cannot load: {filename}')\n obj = None\n\n return obj\n\n\ndef pickle_dump(filename: str, obj):\n with open(filename, 'wb') as f:\n pickle.dump(obj, f)\n print(f'Logging Info - Saved: {filename}')\n\n\ndef write_log(filename: str, log, mode='w'):\n with open(filename, mode) as writers:\n writers.write('\\n')\n json.dump(log, writers, indent=4, ensure_ascii=False)\n\n\ndef format_filename(_dir: str, filename_template: str, **kwargs):\n \"\"\"Obtain the filename of data base on the provided template and parameters\"\"\"\n filename = os.path.join(_dir, filename_template.format(**kwargs))\n return filename\n", "repo_name": "xzenglab/KGNN", "sub_path": "utils/io.py", "file_name": "io.py", "file_ext": "py", "file_size_in_byte": 1120, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 69, "dataset": "github-code", "pt": "21", "api": [{"api_name": "pickle.load", "line_number": 19, "usage_type": "call"}, {"api_name": "pickle.dump", "line_number": 30, "usage_type": "call"}, {"api_name": "json.dump", "line_number": 37, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 42, "usage_type": "call"}, {"api_name": "os.path", "line_number": 42, "usage_type": "attribute"}]} +{"seq_id": "40281927341", "text": "import random\nimport networkx as nx\nfrom matplotlib import pyplot as plt\nfrom collections import Counter\nimport math\nfrom utils.plotTools import plot_qwak\nimport os\nimport ast\nimport numpy as np\nimport json\nfrom sklearn.linear_model import LinearRegression\n\nfrom scripts import load_list_from_file, write_list_to_file, load_or_generate_data, draw_graph, draw_graph_from_adjacency_matrix\nfrom scripts_tempHelix import generate_static_temporal_helix, generate_temporal_helix, multiple_exponential_temporal_helix\n\ndef estimate_hitting_time(reps, start_vertex, end_vertex, num_simulations=10):\n \"\"\"\n Estimate the hitting time between two vertices in a list of lollipop graphs.\n\n Parameters:\n m_values (list): The list of m values, each representing the number of vertices in the complete graph part of a lollipop graph.\n n_values (list): The list of n values, each representing the number of vertices in the path part of a lollipop graph.\n start_vertex (int): The starting vertex for the random walk.\n end_vertex (int): The target vertex for the random walk.\n num_simulations (int): The number of simulations to perform.\n\n Returns:\n hitting_times (list): A list of estimated average hitting times for each lollipop graph.\n \"\"\"\n\n hitting_times = []\n\n for rep in range(1,reps+1):\n print(f'\\nCalculatig hitting time for reps = {rep} ; n = {3+3*rep}')\n total_steps_for_all_simulations = 0\n\n # Create the lollipop graph\n graph = nx.from_numpy_array(generate_temporal_helix(rep,0))\n current_node = list(graph.nodes)[start_vertex]\n end_node = list(graph.nodes)[end_vertex]\n print(f'Starting node: {current_node} \\t Neighbors: {list(nx.neighbors(graph,current_node))}')\n print(f'End node: {end_node} \\t Neighbors: {list(nx.neighbors(graph,end_node))}')\n for s in range(num_simulations):\n if s == 0 or s == 1 or s % 5 == 0:\n print(f'----> Sample number:{s}')\n pass\n total_steps_this_simulation = 0\n current_node = list(graph.nodes)[start_vertex]\n # Loop continues until end_vertex is reached\n while current_node != end_node:\n # Choose a neighbor randomly\n graph = nx.from_numpy_array(generate_temporal_helix(rep,total_steps_this_simulation))\n neighbors = list(nx.neighbors(graph, current_node))\n if neighbors:\n current_node = random.choice(neighbors)\n total_steps_this_simulation += 1\n # print(current_node)\n # print(end_node)\n # print()\n\n # Accumulate the total steps for this simulation\n total_steps_for_all_simulations += total_steps_this_simulation\n\n # Average the total steps over the number of simulations\n average_hitting_time = total_steps_for_all_simulations / num_simulations\n hitting_times.append(average_hitting_time)\n\n return hitting_times\n\ndef theoretical_hitting_time(reps,epsilon,factor):\n cover_times = []\n k = 0\n for n in range(1,reps+1):\n k = n**epsilon\n cover_times.append(2**(factor*k))\n return cover_times\n \n return hitting_times\n \nepsilon = 0.50\n\nreps = 8\nnrange2 = [3 + 3*rep for rep in range(1,reps)]\nnrange3 = [3 + 3*rep for rep in range(1,reps+1)]\nfactor = 4.5\n\nfromNode = 0\ntoNode = -1\n\n\nsamples = 20\n\n\nhitting_times_file = f'Datasets/DynGraphsDTRW/hittingTimeV2TemporalHelix_N{nrange2[0]}-{nrange2[-1]}_EPS{epsilon}_S{samples}.txt'\n\nif os.path.exists(hitting_times_file):\n hitting_times = load_list_from_file(hitting_times_file)\n estimate_hitting_time_memory = [x for x in theoretical_hitting_time(reps,epsilon,factor)]\n print('File exists!')\nelse:\n print('File Doesnt Exist!')\n hitting_times = estimate_hitting_time(reps,fromNode,toNode, num_simulations=samples)\n write_list_to_file(hitting_times_file, hitting_times)\n estimate_hitting_time_memory = [x for x in theoretical_hitting_time(reps,epsilon,factor)]\n \nalphaLabelList = [r'StaticTempHelix RW',r'$2^{' +f'{factor}' +r'n^\\epsilon}$']\n\nparams = {\n 'font_size' : 14,\n 'figsize': (11, 5),\n 'plot_title' : f'Hitting Time',\n 'x_label' : 'N',\n 'y_label' : \"Steps\",\n 'legend_labels' : alphaLabelList,\n 'legend_loc': \"best\",\n # 'legend_title' : r'$\\alpha$',\n 'legend_ncol' : 3,\n 'color_list' : ['#0000FF', '#008000', '#525252'],\n 'line_style_list' : ['--', '-','-.' ],\n # 'save_path' : f'Output/OrientedDynamics/orientedDynamics_N{N}_NWALKS{len(alphaList)}_Alphas{str([round(a, 2) for a in alphaList]).replace(\", \", \"-\").replace(\"[\", \"\").replace(\"]\", \"\")}_TMAX{round(t)}.png',\n 'use_loglog': False,\n 'use_cbar' : False,\n 'cbar_label' : None, \n 'cbar_ticks' : None,\n 'cbar_tick_labels' : None,\n 'x_lim' : None,\n # 'x_num_ticks' : 7,\n # 'y_num_ticks' : 7,\n # 'x_round_val' : 1,\n # 'y_round_val' : 3,\n}\n\nplot_qwak(x_value_matrix = [list(nrange3),list(nrange3)] , y_value_matrix = [hitting_times,estimate_hitting_time_memory],**params)\n", "repo_name": "JaimePSantos/DynamicRandomWalks", "sub_path": "ClassicalWalks/DiscreteTime/run-htDynTH.py", "file_name": "run-htDynTH.py", "file_ext": "py", "file_size_in_byte": 5097, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "networkx.from_numpy_array", "line_number": 38, "usage_type": "call"}, {"api_name": "scripts_tempHelix.generate_temporal_helix", "line_number": 38, "usage_type": "call"}, {"api_name": "networkx.neighbors", "line_number": 41, "usage_type": "call"}, {"api_name": "networkx.neighbors", "line_number": 42, "usage_type": "call"}, {"api_name": "networkx.from_numpy_array", "line_number": 52, "usage_type": "call"}, {"api_name": "scripts_tempHelix.generate_temporal_helix", "line_number": 52, "usage_type": "call"}, {"api_name": "networkx.neighbors", "line_number": 53, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 55, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 96, "usage_type": "call"}, {"api_name": "os.path", "line_number": 96, "usage_type": "attribute"}, {"api_name": "scripts.load_list_from_file", "line_number": 97, "usage_type": "call"}, {"api_name": "scripts.write_list_to_file", "line_number": 103, "usage_type": "call"}, {"api_name": "utils.plotTools.plot_qwak", "line_number": 133, "usage_type": "call"}]} +{"seq_id": "11474074262", "text": "# -*- coding: utf-8 -*-\r\n\r\n\"\"\"\r\nReport 4: Floating Point Numbers\r\n\r\nStoring and using floating point numbers on a computer uses an appoximation\r\nbecause memory is limited, and relies on the binary system instead of the base\r\n10 system.\r\n\r\nTo convert to binary scientific notation, \r\n\r\n(-1)^s * (1.mantissa) * 2^(exponent - bias)\r\n\r\nfor normalized numbers and\r\n\r\n(-1)^s * (0.mantissa) * 2^(1 - bias)\r\n\r\nfor denormalized numbers. The mantissa is the set of digits after the decimal\r\npoint, and \"s\" stands for the sign of the number.\r\n\r\nMachine Epsilon: the smallest number that can be added to 1 to give a number \r\ngreater than 1.\r\n\"\"\"\r\n\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\ndef find_epsilon():\r\n \r\n \"\"\"\r\n Finds and prints the exponent of the machine epsilon in base 2 and the\r\n actual value of the machine epsilon in base 10.\r\n \r\n Parameters:\r\n None\r\n \r\n Returns: \r\n None\r\n \"\"\"\r\n \r\n n = 1\r\n x = 2.**(-n)\r\n \r\n while 1 + x != 1:\r\n n += 1\r\n x = 2.**(-n)\r\n \r\n print('The base 2 exponent of the machine epsilon', -(n-1))\r\n print('The machine epsilon in base 10 is', 2.**(1-n))\r\n \r\n\r\ndef find_largest():\r\n \r\n \"\"\"\r\n Finds and prints the exponent of the largest floating point number and\r\n the actual value of the largest floating point number, both in base 2.\r\n \r\n Parameters:\r\n None\r\n \r\n Returns:\r\n None\r\n \"\"\"\r\n \r\n n = 1\r\n \r\n while True:\r\n try:\r\n x = 2.**n\r\n n += 1\r\n except:\r\n print('The largest exponent is', n - 1)\r\n print('The largest floating point number is 2^' + str(n - 1))\r\n break\r\n\r\n\r\ndef find_smallest():\r\n\r\n \"\"\"\r\n Finds and prints the exponent of the smallest floating point number and\r\n the actual value of the smallest floating point number, both in base 2.\r\n \r\n Parameters:\r\n None\r\n \r\n Returns:\r\n None\r\n \"\"\"\r\n \r\n n = 1\r\n x = 2.**n\r\n \r\n while x != 0:\r\n n -= 1\r\n x = 2.**n\r\n \r\n print('The smallest exponent is', n + 1)\r\n print('The smallest floating point number is 2^', n + 1)\r\n \r\n\r\n# Plot a function close to zero and observe the behavior\r\n# F(x) = log(x + 1) / x\r\nplt.figure(figsize = (10, 10))\r\n\r\nx = np.linspace(-1e-7, 1e-7, 1001)\r\ny = np.where(x == 0, 1.0, np.log(1 + x)/x)\r\n\r\nplt.plot(x, y, color = 'steelblue')\r\n\r\nplt.title('F(x) Near Zero', fontsize = 16)\r\nplt.xlabel('x', fontsize = 14, labelpad = 15)\r\nplt.ylabel('y', fontsize = 14, labelpad = 15)\r\nplt.ticklabel_format(axis = 'both', useMathText = True)\r\n\r\n\r\n# Plot the same function closer to zero\r\nplt.figure(figsize = (10, 10))\r\n\r\nx = np.linspace(-1e-15, 1e-15, 1001)\r\ny = np.where(x == 0, 1.0, np.log(1 + x)/x)\r\n\r\nplt.plot(x, y, color = 'steelblue')\r\n\r\nplt.title('F(x) More Near Zero', fontsize = 16)\r\nplt.xlabel('x', fontsize = 14, labelpad = 15)\r\nplt.ylabel('y', fontsize = 14, labelpad = 15)\r\nplt.ticklabel_format(axis = 'both', useMathText = True)\r\n\r\n\r\n# Plot the function and the Taylor series approximation\r\nplt.figure(figsize = (10, 10))\r\n\r\nx = np.linspace(-1e-7, 1e-7, 1001)\r\ny = np.where(x == 0, 1.0, np.log(1 + x)/x)\r\nz = 1 - ((x/2) + ((x**2)/3) - ((x**3)/4))\r\n\r\nplt.plot(x, y, color = 'steelblue', label = 'F(x)')\r\nplt.plot(x, z, color = 'maroon', label = 'Taylor')\r\n\r\nplt.title('F(x) and its Taylor Series Approx.', fontsize = 16)\r\nplt.xlabel('x', fontsize = 14, labelpad = 15)\r\nplt.ylabel('y', fontsize = 14, labelpad = 15)\r\nplt.ticklabel_format(axis = 'both', useMathText = True)\r\n\r\nplt.legend()", "repo_name": "JNAnnis/Reports337", "sub_path": "Report_04_Updated.py", "file_name": "Report_04_Updated.py", "file_ext": "py", "file_size_in_byte": 3595, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "matplotlib.pyplot.figure", "line_number": 105, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 105, "usage_type": "name"}, {"api_name": "numpy.linspace", "line_number": 107, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 108, "usage_type": "call"}, {"api_name": "numpy.log", "line_number": 108, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 110, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 110, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 112, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 112, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 113, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 113, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 114, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 114, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ticklabel_format", "line_number": 115, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 115, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 119, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 119, "usage_type": "name"}, {"api_name": "numpy.linspace", "line_number": 121, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 122, "usage_type": "call"}, {"api_name": "numpy.log", "line_number": 122, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 124, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 124, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 126, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 126, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 127, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 127, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 128, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 128, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ticklabel_format", "line_number": 129, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 129, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 133, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 133, "usage_type": "name"}, {"api_name": "numpy.linspace", "line_number": 135, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 136, "usage_type": "call"}, {"api_name": "numpy.log", "line_number": 136, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 139, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 139, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 140, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 140, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 142, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 142, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 143, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 143, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 144, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 144, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ticklabel_format", "line_number": 145, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 145, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 147, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 147, "usage_type": "name"}]} +{"seq_id": "70569645172", "text": "#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\"\"\"\nPolimath challenge code.\n\nExtracting xml and generating categories.\n Specific details can be found in CHALLENGE.txt\n\"\"\"\nimport os\nimport argparse\nfrom jinja2 import Environment, PackageLoader, FileSystemLoader\n\nfrom modules.categoryXML import categoriesXml\nfrom modules.categoryDb import categoriesDb\nfrom modules.exceptions import CategoryNotFount\n\n\ndef saveCategoryHtml(categoryHtml, categoryId):\n \"\"\"\n \"\"\"\n file = open('%s.html' % categoryId, 'w')\n file.write(categoryHtml)\n file.close()\n\n\ndef renderCategoryHtml(categoryList):\n \"\"\"\n \"\"\"\n PATH = os.path.dirname(os.path.abspath(__file__))\n env = Environment(loader=FileSystemLoader(os.path.join(PATH, 'templates')))\n template = env.get_template('categoryTemplate.html')\n render = template.render({'category':categoryList})\n return render\n\n\ndef processSubCategories(db, categ, parentCategories):\n \"\"\"\n \"\"\"\n if len(parentCategories) > 0:\n print('Started processing: Level %s, %s subcategories.' % (parentCategories[0][2], parentCategories[0][1]))\n categories = categ.requestCategories(categoryFilter=parentCategories[0][0])\n categories = categ.getXmlCategories(categ.stringToXML(categories))\n if len(categories) > 1:\n parsedCategories = categ.parseCategories(categories)\n db.insertCategories(parsedCategories)\n return processSubCategories(db, categ, parentCategories[1:]) # Keep current node processing\n else:\n print('-------------')\n return\n\n\ndef getCategoryChildren(db, parentCategory):\n \"\"\"\n \"\"\"\n categories = []\n for category in parentCategory:\n category['children'] = db.findChildren(category['categoryid'])\n if len(category['children']) > 1:\n category['children'] = getCategoryChildren(db, category['children'][1:])\n categories.append(category)\n return categories\n\n\ndef createCategories():\n \"\"\"\n \"\"\"\n print('Connecting to database.')\n db = categoriesDb()\n db.connectDb()\n db.createCategoriesTable()\n\n categ = categoriesXml()\n print('Getting basic Level 1 categories.')\n categories = categ.requestCategories(levelFilter=0)\n categories = categ.getXmlCategories(categ.stringToXML(categories))\n\n print('Parsing categories.')\n parsedCategories = categ.parseCategories(categories)\n processSubCategories(db, categ, parsedCategories)\n print('Categories creation complete.')\n db.disconnectDb()\n\n\ndef renderCategory(categoryId):\n \"\"\"\n \"\"\"\n print('Connecting to database.')\n db = categoriesDb()\n db.connectDb()\n print('Finding Category %s.' % categoryId)\n category = db.findChildren(categoryId) # db.findCategory(categoryId)\n category = getCategoryChildren(db, category[1:])\n\n saveCategoryHtml(renderCategoryHtml(category), categoryId)\n print('Html generated with name %s.html' % categoryId)\n db.disconnectDb()\n\n\ndef main():\n \"\"\"\n Main function\n \"\"\"\n print('Starting challenge.')\n parser = argparse.ArgumentParser()\n # Help values\n parser.add_argument('--rebuild', action=\"store_true\", help='Refresh the category list.')\n parser.add_argument('--render', type=int, help='Creates the html with the category description.', default=False)\n # Process the desired output\n args = parser.parse_args()\n\n if args.rebuild:\n print(\"You asked for rebuild\")\n createCategories()\n elif args.render:\n print(\"You asked for render\")\n renderCategory(args.render)\n else:\n print('Please select a valid argument.')\n\n print('Challenge finished!')\n print('Bye bye')\n\nmain()\n", "repo_name": "jaconsta/polimath-challenge", "sub_path": "challenge.py", "file_name": "challenge.py", "file_ext": "py", "file_size_in_byte": 3669, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "os.path.dirname", "line_number": 29, "usage_type": "call"}, {"api_name": "os.path", "line_number": 29, "usage_type": "attribute"}, {"api_name": "os.path.abspath", "line_number": 29, "usage_type": "call"}, {"api_name": "jinja2.Environment", "line_number": 30, "usage_type": "call"}, {"api_name": "jinja2.FileSystemLoader", "line_number": 30, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 30, "usage_type": "call"}, {"api_name": "os.path", "line_number": 30, "usage_type": "attribute"}, {"api_name": "modules.categoryDb.categoriesDb", "line_number": 68, "usage_type": "call"}, {"api_name": "modules.categoryXML.categoriesXml", "line_number": 72, "usage_type": "call"}, {"api_name": "modules.categoryDb.categoriesDb", "line_number": 88, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 104, "usage_type": "call"}]} +{"seq_id": "2570755384", "text": "import click\nimport numpy as np\nimport pandas as pd\nimport requests\nfrom fake_useragent import UserAgent\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\nfrom bs4 import BeautifulSoup\nfrom time import sleep\n\n\nURL = \"http://www.blood.in.ua/declaration/\"\nM = [\"чоловік\", \"батько\", \"вітчим\", \"син\", \"брат\", \"дядько\", \"племінник\", \"небіж\"]\nF = [\n \"дружина\", \"мати\", \"матір\", \"мачуха\", \"донька\", \n \"дочка\", \"сестра\", \"тітка\", \"племінниця\", \"небога\" \n ]\n\n\ndef load_page(url: str, selenium_method : bool = False):\n \"\"\" Повертає вміст сторінки через selenium. \"\"\"\n \n if selenium_method:\n \n options = Options()\n options.headless = True\n\n with webdriver.Chrome(\"./chromedriver.exe\", options=options) as browser:\n browser.get(url)\n sleep(np.random.uniform(2, 7))\n html = browser.page_source\n return html\n \n else:\n ua = UserAgent()\n return requests.get(url, headers={\"User-Agent\": ua.random}).content\n\n\ndef get_relatives(name: str) -> dict:\n \"\"\" Отримує род. зв. у табличному форматі. \"\"\"\n\n dashed_name = \"-\".join(name.split(\" \")).lower()\n\n html = load_page(URL + dashed_name, selenium_method=False)\n soup = BeautifulSoup(html, \"lxml\")\n\n df = pd.read_html(soup.prettify())[0]\n df.columns = [\"ПІБ\", \"Місце роботи\", \"Початок роботи\", \"Кінець роботи\"]\n\n # split на подвійному пробілі\n df[\"Посада\"] = df[\"Місце роботи\"].str.split(\" \").str[1]\n df[\"Місце роботи\"] = df[\"Місце роботи\"].str.split(\" \").str[0]\n df[\"Стать\"] = df[\"ПІБ\"].str.lower()\n df[\"Стать\"] = np.select(\n condlist=[\n df[\"Стать\"].str.contains(\"|\".join(M)),\n df[\"Стать\"].str.contains(\"|\".join(F)),\n ],\n choicelist=[\"ЧОЛОВІК\", \"ЖІНКА\"],\n default=\"НЕВІДОМО\",\n )\n\n return df.groupby(\"ПІБ\").agg(list).to_dict(\"index\")\n\n\ndef table_to_text(relatives: dict) -> iter:\n \"\"\" Конвертує род. зв. з табличного формату в текстовий \"\"\"\n\n for name in relatives.keys():\n pairs = []\n for pair in zip(\n relatives[name].get(\"Місце роботи\", \"\"),\n relatives[name].get(\"Початок роботи\", \"\"),\n relatives[name].get(\"Кінець роботи\", \"\"),\n relatives[name].get(\"Посада\", \"\"),\n ):\n pairs.append(pair)\n\n gender = relatives[name][\"Стать\"][0]\n word = \"працювала\" if gender == \"ЖІНКА\" else \"працював\"\n\n size = len(pairs)\n\n positions = [pairs[i][-1] for i in range(size - 1)]\n places = [pairs[i][0] for i in range(size - 1)]\n\n tenure_tuple = [(pairs[i][1], pairs[i][2]) for i in range(size - 1)]\n tenure = [\"-\".join(pair) for pair in tenure_tuple]\n\n past_experience = [\n f\"{pos} ({prd}) в {plc}\" for pos, prd, plc in zip(positions, tenure, places)\n ]\n exp = \", \".join(past_experience)\n\n p1 = f\"{name} - з {pairs[-1][1]} по {pairs[-1][2]} працює {pairs[-1][-1]} в {pairs[-1][0]}.\"\n p2 = f\"До цього, протягом {pairs[0][1]}-{pairs[-1][1]}, {word} на таких посадах: {exp}.\"\n\n if size > 1:\n yield \" \".join([p1, p2])\n else:\n yield p1\n\n\ndef writer(output_path, name, result):\n with open(output_path, \"a\") as output_file:\n output_file.write(f\"\\n{name}:\\n\")\n if isinstance(result, str):\n output_file.write(\"Сталася помилка\\n\")\n else:\n for counter, value in enumerate(result, 1):\n output_file.write(f\"{counter}. {value}\\n\")\n\n\ndef main(input_path, output_path):\n with open(input_path, encoding=\"utf-8\") as input_file:\n for name in input_file:\n \n relatives_dict = get_relatives(name)\n try:\n result = list(table_to_text(relatives_dict))\n except TypeError:\n result = \"Сталася помилка\"\n writer(output_path, name, result)\n\n\n@click.command()\n@click.argument('input_path', type=click.Path(exists=True))\n@click.argument('output_path', type=click.Path())\ndef cli(input_path, output_path):\n main(input_path, output_path)\n\n\nif __name__ == \"__main__\":\n cli()", "repo_name": "chesnosud/chesnosud", "sub_path": "chesnosud/relatives.py", "file_name": "relatives.py", "file_ext": "py", "file_size_in_byte": 4647, "program_lang": "python", "lang": "uk", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "selenium.webdriver.chrome.options.Options", "line_number": 25, "usage_type": "call"}, {"api_name": "selenium.webdriver.Chrome", "line_number": 28, "usage_type": "call"}, {"api_name": "selenium.webdriver", "line_number": 28, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 30, "usage_type": "call"}, {"api_name": "numpy.random.uniform", "line_number": 30, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 30, "usage_type": "attribute"}, {"api_name": "fake_useragent.UserAgent", "line_number": 35, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 36, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 45, "usage_type": "call"}, {"api_name": "pandas.read_html", "line_number": 47, "usage_type": "call"}, {"api_name": "numpy.select", "line_number": 54, "usage_type": "call"}, {"api_name": "click.command", "line_number": 126, "usage_type": "call"}, {"api_name": "click.argument", "line_number": 127, "usage_type": "call"}, {"api_name": "click.Path", "line_number": 127, "usage_type": "call"}, {"api_name": "click.argument", "line_number": 128, "usage_type": "call"}, {"api_name": "click.Path", "line_number": 128, "usage_type": "call"}]} +{"seq_id": "629463001", "text": "# -*- coding: utf-8 -*-\nimport nltk\nfrom nltk.tokenize import word_tokenize, sent_tokenize\nimport random\n\nclass Classifier:\n\n def __init__(self,whoText, sampleText,test_sent,fL):\n self.fL = fL\n self.features = self.featuresets(whoText,sampleText)\n self.classifier(self.features)\n self.sents = sent_tokenize(test_sent)\n self.printSentences(self.sents) \n\n\n def featuresets(self,whoTxt,sampleTxt):\n self.who_text = whoTxt\n self.sample_text = sampleTxt\n self.who_words = [(self.feature_extractor(word),'KATHI') for word in self.sample_text.read().split('\\n')] + [(self.feature_extractor(word),'PER@') for word in self.who_text.read().split('\\n') if '#' not in word]\n random.shuffle(self.who_words)\n return(self.who_words)\n \n def classifier(self,train_data):\n self.classifier = nltk.NaiveBayesClassifier.train(train_data)\n \n def feature_extractor(self,word):\n return {'who':word}\n \n def printSentences(self, sentences):\n self.finalList = []\n for s in sentences:\n for(a,b) in nltk.pos_tag(word_tokenize(s)):\n if 'NN' in b and self.classifier.classify(self.feature_extractor(a)) == 'PER@':\n self.finalList.append(s)\n self.fL += self.finalList\n \n \n\n ", "repo_name": "saisravankathi/nltk", "sub_path": "FAQCreator/who.py", "file_name": "who.py", "file_ext": "py", "file_size_in_byte": 1337, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "nltk.tokenize.sent_tokenize", "line_number": 12, "usage_type": "call"}, {"api_name": "random.shuffle", "line_number": 20, "usage_type": "call"}, {"api_name": "nltk.NaiveBayesClassifier.train", "line_number": 24, "usage_type": "call"}, {"api_name": "nltk.NaiveBayesClassifier", "line_number": 24, "usage_type": "attribute"}, {"api_name": "nltk.pos_tag", "line_number": 32, "usage_type": "call"}, {"api_name": "nltk.tokenize.word_tokenize", "line_number": 32, "usage_type": "call"}]} +{"seq_id": "70309691254", "text": "\"\"\"Matplotlib Parallel coordinates plot.\"\"\"\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom ...plot_utils import _scale_fig_size\nfrom . import backend_kwarg_defaults, backend_show, create_axes_grid\n\n\ndef plot_parallel(\n ax,\n colornd,\n colord,\n shadend,\n diverging_mask,\n posterior,\n textsize,\n var_names,\n legend,\n figsize,\n backend_kwargs,\n backend_config, # pylint: disable=unused-argument\n show,\n):\n \"\"\"Matplotlib parallel plot.\"\"\"\n if backend_kwargs is None:\n backend_kwargs = {}\n\n backend_kwargs = {\n **backend_kwarg_defaults(),\n **backend_kwargs,\n }\n\n figsize, _, _, xt_labelsize, _, _ = _scale_fig_size(figsize, textsize, 1, 1)\n backend_kwargs.setdefault(\"figsize\", figsize)\n backend_kwargs[\"squeeze\"] = True\n if ax is None:\n _, ax = create_axes_grid(1, backend_kwargs=backend_kwargs)\n\n ax.plot(posterior[:, ~diverging_mask], color=colornd, alpha=shadend)\n\n if np.any(diverging_mask):\n ax.plot(posterior[:, diverging_mask], color=colord, lw=1)\n\n ax.tick_params(labelsize=textsize)\n ax.set_xticks(range(len(var_names)))\n ax.set_xticklabels(var_names)\n\n if legend:\n ax.plot([], color=colornd, label=\"non-divergent\")\n if np.any(diverging_mask):\n ax.plot([], color=colord, label=\"divergent\")\n ax.legend(fontsize=xt_labelsize)\n\n if backend_show(show):\n plt.show()\n\n return ax\n", "repo_name": "arviz-devs/arviz", "sub_path": "arviz/plots/backends/matplotlib/parallelplot.py", "file_name": "parallelplot.py", "file_ext": "py", "file_size_in_byte": 1449, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1461, "dataset": "github-code", "pt": "21", "api": [{"api_name": "plot_utils._scale_fig_size", "line_number": 33, "usage_type": "call"}, {"api_name": "numpy.any", "line_number": 41, "usage_type": "call"}, {"api_name": "numpy.any", "line_number": 50, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.show", "line_number": 55, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 55, "usage_type": "name"}]} +{"seq_id": "5060907215", "text": "import llog\n\nfrom bisect import bisect_left\nfrom datetime import datetime, tzinfo, timedelta\nimport logging\nimport time\n\nimport consts\nimport mbase32\n\nlog = logging.getLogger(__name__)\n\naccept_chars = b\" !\\\"#$%&`()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\\\]^_'abcdefghijklmnopqrstuvwxyz{|}~\"\naccept_chars = sorted(accept_chars)\n\nwidth = 16\n\ndef hex_dump(data, offset = 0, length = None):\n assert type(data) in (bytes, bytearray), type(data)\n\n output = bytearray()\n col1 = bytearray()\n col2 = bytearray()\n\n if length == None:\n length = len(data)\n\n line = 0\n i = offset\n while i < length:\n j = 0\n while j < width and i < length:\n val = data[i]\n col1 += format(val, \"02x\").encode()\n\n si = bisect_left(accept_chars, data[i])\n if si != len(accept_chars) and accept_chars[si] == data[i]:\n col2.append(data[i])\n else:\n col2 += b'.'\n\n if j % 2 == 1:\n col1 += b' '\n\n j += 1\n i += 1\n\n output += format(line * width, \"#06x\").encode()\n output += b\" \"\n line += 1\n while len(col1) < (width*5/2):\n col1 += b' '\n\n output += col1\n output += b' '\n output += col2\n output += b'\\n'\n col1.clear()\n col2.clear()\n\n return output.decode()\n\nbc_masks = [0x2, 0xC, 0xF0]\nbc_shifts = [1, 2, 4]\n\ndef log_base2_8bit(val):\n r = 0\n\n for i in range(2, -1, -1):\n if val & bc_masks[i]:\n val >>= bc_shifts[i]\n r |= bc_shifts[i]\n\n return r\n\ndef hex_string(val):\n if not val:\n return None\n\n buf = \"\"\n\n for b in val:\n if b <= 0x0F:\n buf += '0'\n buf += hex(b)[2:]\n\n return buf\n\n#TODO: Maybe move this to db.py and make it use cursor if in PostgreSQL mode.\ndef page_query(query, page_size=10):\n \"Batch fetch an SQLAlchemy query.\"\n\n offset = 0\n\n while True:\n page = query.limit(page_size).offset(offset).all()\n\n for row in page:\n yield row\n\n if len(page) < page_size:\n break\n\n offset += page_size\n\ndef decode_key(encoded):\n assert consts.NODE_ID_BITS == 512\n assert type(encoded) is str, type(encoded)\n\n significant_bits = None\n\n kl = len(encoded)\n\n if kl == 128:\n data_key = bytes.fromhex(encoded)\n elif kl in (102, 103):\n data_key = bytes(mbase32.decode(encoded))\n if len(data_key) < consts.NODE_ID_BYTES:\n significant_bits = 5 * kl\n else:\n data_key = mbase32.decode(encoded, False)\n significant_bits = 5 * kl\n\n return data_key, significant_bits\n\ndef calc_raw_distance(data1, data2):\n \"Calculates the XOR distance, return is absolute value.\"\n\n assert type(data1) in (bytes, bytearray)\\\n and type(data2) in (bytes, bytearray)\n\n buf = bytearray()\n\n for i in range(len(data1)):\n buf.append(data1[i] ^ data2[i])\n\n return buf\n\ndef calc_log_distance(nid, pid):\n \"Returns: distance, direction.\"\n \" distance is in log base2.\"\n\n id_size = len(nid)\n assert id_size >= len(pid)\n\n if log.isEnabledFor(logging.DEBUG):\n log.debug(\"pid=\\n[{}], nid=\\n[{}].\".format(hex_dump(pid),\\\n hex_dump(nid)))\n\n dist = 0\n direction = 0\n\n for i in range(id_size):\n if pid[i] != nid[i]:\n direction = 1 if pid[i] > nid[i] else -1\n\n xv = pid[i] ^ nid[i]\n xv = log_base2_8bit(xv) + 1\n\n # (byte * 8) + bit.\n dist = ((id_size - 1 - i) << 3) + xv\n\n break\n\n return dist, direction\n\nZERO_TIMEDELTA = timedelta(0)\nclass UtcTzInfo(tzinfo):\n def utcoffset(self, dt):\n return ZERO_TIMEDELTA\n\n def tzname(self, dt):\n return \"UTC\"\n\n def dst(self, dt):\n return ZERO_TIMEDELTA\n\nUTC_TZINFO = UtcTzInfo()\n\ndef utc_datetime():\n return datetime.now(UTC_TZINFO)\n\nISO_FMT_UTC = \"%Y-%m-%dT%H:%M:%S.%fZ\"\nISO_FMT = \"%Y-%m-%dT%H:%M:%S.%f\"\n\ndef parse_iso_datetime(date_str):\n if date_str.endswith('Z'):\n return datetime.strptime(date_str, ISO_FMT_UTC)\\\n .replace(tzinfo=UTC_TZINFO)\n else:\n return datetime.strptime(date_str, ISO_FMT)\n\ndef format_iso_datetime(adatetime):\n if adatetime.tzinfo is UTC_TZINFO:\n return adatetime.strftime(ISO_FMT_UTC)\n else:\n return adatetime.strftime(ISO_FMT)\n\niso_fmt_human_no_ms = \"%Y-%m-%d %H:%M:%S\"\n\ndef get_utc_offset_seconds():\n return time.altzone if time.daylight else time.timezone\n\ndef format_human_no_ms_datetime(datetime, convert_local=True, assume_gmt=False):\n if convert_local and (assume_gmt or datetime.tzinfo is UTC_TZINFO):\n datetime = datetime - timedelta(seconds=get_utc_offset_seconds())\n return datetime.strftime(iso_fmt_human_no_ms)\n", "repo_name": "bitcoinembassy/morphis", "sub_path": "mutil.py", "file_name": "mutil.py", "file_ext": "py", "file_size_in_byte": 4821, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 15, "dataset": "github-code", "pt": "21", "api": [{"api_name": "logging.getLogger", "line_number": 11, "usage_type": "call"}, {"api_name": "bisect.bisect_left", "line_number": 36, "usage_type": "call"}, {"api_name": "consts.NODE_ID_BITS", "line_number": 107, "usage_type": "attribute"}, {"api_name": "mbase32.decode", "line_number": 117, "usage_type": "call"}, {"api_name": "consts.NODE_ID_BYTES", "line_number": 118, "usage_type": "attribute"}, {"api_name": "mbase32.decode", "line_number": 121, "usage_type": "call"}, {"api_name": "logging.DEBUG", "line_number": 146, "usage_type": "attribute"}, {"api_name": "datetime.timedelta", "line_number": 167, "usage_type": "call"}, {"api_name": "datetime.tzinfo", "line_number": 168, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 181, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 181, "usage_type": "name"}, {"api_name": "datetime.datetime.strptime", "line_number": 188, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 188, "usage_type": "name"}, {"api_name": "datetime.datetime.strptime", "line_number": 191, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 191, "usage_type": "name"}, {"api_name": "time.daylight", "line_number": 202, "usage_type": "attribute"}, {"api_name": "time.altzone", "line_number": 202, "usage_type": "attribute"}, {"api_name": "time.timezone", "line_number": 202, "usage_type": "attribute"}, {"api_name": "datetime.datetime.tzinfo", "line_number": 205, "usage_type": "attribute"}, {"api_name": "datetime.datetime", "line_number": 205, "usage_type": "name"}, {"api_name": "datetime.datetime", "line_number": 206, "usage_type": "name"}, {"api_name": "datetime.timedelta", "line_number": 206, "usage_type": "call"}, {"api_name": "datetime.datetime.strftime", "line_number": 207, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 207, "usage_type": "name"}]} +{"seq_id": "19603969880", "text": "\"\"\"Prepare to remove foreign key from artgen_sql\n\nRevision ID: c557bac33c96\nRevises: \nCreate Date: 2023-10-20 21:18:59.532519\n\n\"\"\"\nfrom alembic import op\n\nrevision = 'c557bac33c96'\ndown_revision = None\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n op.drop_constraint('artgen_sql_ibfk_1', 'artgen_sql', type_='foreignkey')\n op.drop_constraint('artgen_sql_ibfk_2', 'artgen_sql', type_='foreignkey')\n\n\ndef downgrade():\n op.create_foreign_key('artgen_sql_ibfk_1', 'artgen_sql', 'genre_sql', ['genre_name'], ['genre'])\n op.create_foreign_key('artgen_sql_ibfk_2', 'artgen_sql', 'genre_sql', ['genre_name'], ['genre'])\n", "repo_name": "rawcsav/SpotifyFlask", "sub_path": "migrations/versions/c557bac33c96_prepare_to_remove_foreign_key_from_.py", "file_name": "c557bac33c96_prepare_to_remove_foreign_key_from_.py", "file_ext": "py", "file_size_in_byte": 635, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "alembic.op.drop_constraint", "line_number": 17, "usage_type": "call"}, {"api_name": "alembic.op", "line_number": 17, "usage_type": "name"}, {"api_name": "alembic.op.drop_constraint", "line_number": 18, "usage_type": "call"}, {"api_name": "alembic.op", "line_number": 18, "usage_type": "name"}, {"api_name": "alembic.op.create_foreign_key", "line_number": 22, "usage_type": "call"}, {"api_name": "alembic.op", "line_number": 22, "usage_type": "name"}, {"api_name": "alembic.op.create_foreign_key", "line_number": 23, "usage_type": "call"}, {"api_name": "alembic.op", "line_number": 23, "usage_type": "name"}]} +{"seq_id": "39079333082", "text": "\"\"\"This file contains functions for utility.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\n\nimport time\nimport logging\nimport collections\nimport argparse\n\nlogging.basicConfig(level=logging.INFO)\n\nEDGES = ['oor', 'ool', 'oio', 'lt', 'rt', 'sp', 'chs', 'chr', 'chl', 'cf', 'iol', 'ior']\n\n\n# B-0 oio K-0 [10,270,90];\n# B-0 ool C-0 nt K-0 B-0 S [5,270,180];\n\ndef str2list(_str):\n _list = _str[1:-1].split(\",\")\n _list = list(map(int, _list))\n return _list\n\n\ndef split_triplet(triplet_str):\n elements = triplet_str.split(' ')\n first_node = []\n edge = []\n second_node = []\n attribute = ''\n dist_angle_list = str2list(elements[-1])\n elements = elements[:-1]\n if '(' in elements:\n start, end = elements.index('('), elements.index(')')\n attribute = \" \".join(elements[start: end + 1])\n elements = elements[:start] + elements[end + 1:]\n for ele in elements:\n if ele in EDGES:\n edge.append(ele)\n elif not edge:\n first_node.append(ele)\n else:\n second_node.append(ele)\n assert len(edge) == 1, \"edge should only contain one element {}\".format(elements)\n return \" \".join(first_node), \" \".join(edge), \" \".join(second_node), dist_angle_list\n\n\ndef convert_map(graph):\n tidied_map = collections.defaultdict(dict)\n for triplet in graph.strip().split(';'):\n triplet = triplet.strip()\n if not triplet:\n continue\n start, edge, end, _ = split_triplet(triplet)\n start, edge, end = start.strip(), edge.strip(), end.strip()\n tidied_map[start][edge] = end\n return tidied_map\n\n\ndef convert_map2(graph):\n tidied_map = collections.defaultdict(dict)\n for triplet in graph.strip().split(';'):\n triplet = triplet.strip()\n if not triplet:\n continue\n start, edge, end, dist_angle_list = split_triplet(triplet)\n start, edge, end = start.strip(), edge.strip(), end.strip()\n dist_angle_list.append(end)\n tidied_map[start][edge] = dist_angle_list\n return tidied_map\n\ndef parse_output(pred, tidied_map2):\n pred_list = pred.split(\" \")\n output = []\n prev_out = \"\"\n for a in range(0, len(pred_list)-1, 2):\n node = pred_list[a]\n edge = pred_list[a+1]\n if node!=prev_out and a!=0:\n # print(\"prev out - \", prev_out, \"curr-node\", node)\n node = prev_out\n prev_out = tidied_map2[node][edge][-1]\n output.append(tidied_map2[node][edge][:-1])\n return output\n\ndef print_pred(preds=None):\n outputs = []\n if preds is None: \n with open(\"../data/pred_test.txt\", \"r\") as f:\n preds = f.readlines()\n with open(\"../data/custom.graph\", \"r\") as f:\n graph = f.readline()\n tidied_map2 = convert_map2(graph)\n # print(tidied_map2)\n for line in preds:\n out = parse_output(line, tidied_map2)\n for outs in out:\n outputs.append(\"Dist={}, Angle={}, Final Angle={}\".format(outs[0],outs[1],outs[2]))\n outputs.append(\"\\n\")\n with open(\"../data/custom.instructions\", \"w\") as f:\n f.writelines(\"\\n\".join(outputs))\n\n\n\nif __name__ == '__main__':\n print_pred()\n # parser = argparse.ArgumentParser(\n # description='Test convert_map')\n # parser.add_argument('prediction_file', help='Prediction File')\n # args = parser.parse_args()\n # with open(args.prediction_file) as prediction_file:\n # predictions = prediction_file.readlines()\n # map_dict = convert_map2(predictions)\n # print(map_dict)\n", "repo_name": "VrutikShah/natural-control", "sub_path": "utils.py", "file_name": "utils.py", "file_ext": "py", "file_size_in_byte": 3561, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "logging.basicConfig", "line_number": 11, "usage_type": "call"}, {"api_name": "logging.INFO", "line_number": 11, "usage_type": "attribute"}, {"api_name": "collections.defaultdict", "line_number": 49, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 61, "usage_type": "call"}]} +{"seq_id": "19664158553", "text": "import sys\r\nimport os\r\nimport librosa\r\nfrom argparse import ArgumentParser\r\n\r\nimport numpy as np\r\nfrom scipy.io import wavfile\r\n\r\n\r\ndef change_extension(filename, new_extension):\r\n \"\"\"\r\n Change the extension of the given file\r\n\r\n Parameters\r\n ----------\r\n filename : str\r\n The filename whose extension needs to be changed\r\n new_extension : str\r\n The new extension\r\n\r\n Return\r\n ------\r\n newfilename : str\r\n The new filename\r\n \"\"\"\r\n dirname = os.path.dirname(filename)\r\n fname = os.path.basename(filename)\r\n basename = fname.split(\".\")[0]\r\n return os.path.join(dirname, \"{}.{}\".format(basename, new_extension))\r\n\r\n\r\ndef wav2mono(signal):\r\n \"\"\"Converts a wav signal to mono. If the signal is already mono, it is not modified.\r\n\r\n Parameters\r\n ----------\r\n signal: ndarray\r\n The wav sound signal\r\n \r\n Return:\r\n -------\r\n signal: ndarray\r\n A mono wav signal \r\n \"\"\"\r\n signal = np.squeeze(signal)\r\n if len(signal.shape) < 1:\r\n return signal\r\n axis = 0 if signal.shape[0] == 2 else 1\r\n return np.mean(signal, axis=axis)\r\n\r\n\r\ndef extract_wave_files(path):\r\n \"\"\"\r\n List the .wave file in the directory corresponding to `path`\r\n\r\n Parameters\r\n ----------\r\n path : str\r\n The path to a directory\r\n\r\n Return\r\n ------\r\n wave_files : list of str\r\n The wave files in `path`\r\n \"\"\"\r\n walked = list(os.walk(path))\r\n all_files = list()\r\n for r, _, f in walked:\r\n all_files.extend([os.path.join(r, fi) for fi in f])\r\n return [f for f in all_files if f.endswith(\".wav\")]\r\n\r\n\r\ndef main(argv):\r\n parser = ArgumentParser(description='Converts a bunch of .wav file in .mfcc files.')\r\n parser.add_argument('-c', '--n_coef', dest=\"n_coef\", type=int, default=13,\r\n help='The number of coefficients to extract per input signal.')\r\n parser.add_argument('-f', '--files', dest='files', nargs='+', default=[],\r\n help='The input .wav sound file to convert.')\r\n parser.add_argument('-p', \"--path\", dest=\"path\", default=None,\r\n help=\"Path in which the .wav files are located and must be converted \"\r\n \"(ignored if some files are passed with the -f flag).\")\r\n params = parser.parse_args(args=argv)\r\n\r\n files = params.files if len(params.files) > 0 or params.path is None else extract_wave_files(params.path)\r\n\r\n print(\"{} file(s) to be converted...\".format(len(files)))\r\n\r\n for filename in np.unique(files):\r\n try:\r\n print(\"Converting '{}'...\".format(filename))\r\n sampling_rate, signal = wavfile.read(filename)\r\n signal = wav2mono(signal) # to handle stereophonic signals\r\n mfcc = librosa.feature.mfcc(signal, sr=sampling_rate, n_mfcc=params.n_coef)\r\n output_file = change_extension(filename, \"mfcc\")\r\n with open(output_file, \"w+\") as out:\r\n out.write(\"{} {}\".format(mfcc.shape[0], mfcc.shape[1]) + os.linesep)\r\n for i in range(mfcc.shape[0]):\r\n for j in range(mfcc.shape[1]):\r\n out.write(\"{} \".format(mfcc[i, j]))\r\n out.write(os.linesep)\r\n\r\n except IOError as e:\r\n print(\"Couldn't convert file '{}': {}\".format(filename, e.strerror))\r\n\r\n\r\nif __name__ == \"__main__\":\r\n \"\"\"Dependencies: librosa, numpy, scipy\r\n Installation with anaconda (windows):\r\n - conda install scipy numpy\r\n - conda install -c conda-forge librosa=0.4.3\r\n\r\n Installation with pip (does not work on windows):\r\n - pip install scipy numpy librosa\r\n \"\"\"\r\n main(sys.argv[1:])", "repo_name": "Kwantuum/Projet3", "sub_path": "p3_code/wav2mfcc.py", "file_name": "wav2mfcc.py", "file_ext": "py", "file_size_in_byte": 3724, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "os.path.dirname", "line_number": 26, "usage_type": "call"}, {"api_name": "os.path", "line_number": 26, "usage_type": "attribute"}, {"api_name": "os.path.basename", "line_number": 27, "usage_type": "call"}, {"api_name": "os.path", "line_number": 27, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 29, "usage_type": "call"}, {"api_name": "os.path", "line_number": 29, "usage_type": "attribute"}, {"api_name": "numpy.squeeze", "line_number": 45, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 49, "usage_type": "call"}, {"api_name": "os.walk", "line_number": 66, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 69, "usage_type": "call"}, {"api_name": "os.path", "line_number": 69, "usage_type": "attribute"}, {"api_name": "argparse.ArgumentParser", "line_number": 74, "usage_type": "call"}, {"api_name": "numpy.unique", "line_number": 88, "usage_type": "call"}, {"api_name": "scipy.io.wavfile.read", "line_number": 91, "usage_type": "call"}, {"api_name": "scipy.io.wavfile", "line_number": 91, "usage_type": "name"}, {"api_name": "librosa.feature.mfcc", "line_number": 93, "usage_type": "call"}, {"api_name": "librosa.feature", "line_number": 93, "usage_type": "attribute"}, {"api_name": "os.linesep", "line_number": 96, "usage_type": "attribute"}, {"api_name": "os.linesep", "line_number": 100, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 115, "usage_type": "attribute"}]} +{"seq_id": "73352876534", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Mar 24 01:09:23 2021\r\n\r\n@author: julius52700@gmail.com\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom scipy.integrate import solve_ivp\r\nimport matplotlib.cm as cm\r\nfrom matplotlib.animation import FuncAnimation\r\nimport matplotlib as mpl\r\nfrom matplotlib.gridspec import GridSpec\r\n\r\n# Fundamental Constants\r\nMsun = 2e30 # Solar Mass (k)\r\nG = 6.67e-11 # Gravitational Constant\r\nAU = 1.5e11 # Astronmical Unit (m)\r\nrE = 1.*AU # Orbital radius of Earth (m)\r\nRsun = 7e8 # Radius of the sun (m)\r\nyr2s = 86400*365 # Conversion of year to second\r\n\r\n#%%\r\n# Adjustable parameters\r\n\r\n# Simulation properties\r\ntmax = 1e0*yr2s # Simulation time\r\n\r\n# Sail properties\r\naE = 1e-3 # Maxium acceleration of the sail at 1AU.\r\ndelay = 0.*yr2s # How long does the sail wait \r\n # on the earth orbit before starting manuver\r\nperihelion = 10*Rsun\r\n\r\n# Visualization properties\r\nBox_size = 3e11 # Size of the plot\r\nframes = int(1e3) # Output frames\r\nTracing = False # Viewing the sail with tracing mode.\r\nSAVE_VIDEO = False # Whether you want to save the video\r\n\r\n#%%\r\ndef initial_condition():\r\n def cicular(k):\r\n v_sun_circular = np.sqrt(G*Msun/k)\r\n return [0, -k, v_sun_circular, 0]\r\n def eliptical():\r\n a = AU\r\n R_init = a*2-1*Rsun\r\n v = np.sqrt(G*Msun*(2/R_init-1/a))\r\n return [R_init, 0, 0, v]\r\n return cicular(AU)\r\ny_0 = initial_condition()\r\n#%%\r\ndef Etot(x, y, vx, vy):\r\n r = np.sqrt(x**2 + y**2)\r\n K = 0.5*(vx**2 + vy**2)\r\n return K - G*Msun/r\r\n\r\n#%%\r\ndef Decide_Pointing(t, x, y, vx, vy):\r\n r = np.array([x, y])\r\n v = np.array([vx, vy])\r\n rhat = r/np.linalg.norm(r)\r\n vhat = v/np.linalg.norm(v)\r\n Acc = False\r\n if t > delay:\r\n if np.linalg.norm(r)>perihelion and Acc == False:\r\n phat = (rhat - vhat)/np.sqrt(2)\r\n else:\r\n Acc = True\r\n phat = (rhat + vhat)/np.sqrt(2)\r\n else:\r\n phat = np.array([-rhat[1], rhat[0]])\r\n return phat\r\n#%%\r\ndef function(t, y):\r\n r_vec = y[:2]\r\n r = np.linalg.norm(r_vec)\r\n v_vec = y[2:]\r\n phat = Decide_Pointing(t, y[0], y[1], y[2], y[3])\r\n dxdt = v_vec[0]\r\n dydt = v_vec[1]\r\n a_rp = aE*rE**2/r**2*np.dot(r_vec, phat)/np.linalg.norm(r_vec)*phat\r\n a_g = -G*Msun/r**3*r_vec\r\n a = a_rp + a_g\r\n dvxdt = a[0]\r\n dvydt = a[1]\r\n return np.array([dxdt, dydt, dvxdt, dvydt])\r\n#%%\r\n# Solving the orbit\r\nsol = solve_ivp(fun=function,\r\n t_span=[0, tmax],\r\n y0=y_0,\r\n t_eval=np.linspace(0,tmax,frames),\r\n method='LSODA')\r\n\r\nt = sol.t\r\nData = sol.y\r\nx = Data[0,:]\r\ny = Data[1,:]\r\nvx = Data[2,:]\r\nvy = Data[3,:]\r\n\r\n#%%\r\n# Visualization Setup\r\nCOLOR = '#303030'\r\nLineColor = 'silver'\r\n#fig, ax = plt.subplots(facecolor=COLOR)\r\nfig = plt.figure(figsize = (8, 4.5), facecolor=COLOR)\r\ngs = GridSpec(2, 4, figure=fig)\r\n\r\n# Picture\r\nax = fig.add_subplot(gs[:, :2])\r\nax.set_facecolor(COLOR)\r\nax.xaxis.set_visible(False)\r\nax.yaxis.set_visible(False)\r\nax.spines['bottom'].set_color(COLOR)\r\nax.spines['top'].set_color(COLOR) \r\nax.spines['right'].set_color(COLOR)\r\nax.spines['left'].set_color(COLOR)\r\n\r\n# Solar system bodies\r\nsun = plt.Circle((0, 0), Rsun, color='y')\r\nmercury = plt.Circle((0, 0), 0.387*AU, edgecolor='cyan', fill=False)\r\nvenus = plt.Circle((0, 0), 0.723*AU, edgecolor='y', fill=False)\r\nearth = plt.Circle((0, 0), 1.*AU, edgecolor='skyblue', fill=False)\r\nmars = plt.Circle((0, 0), 1.524*AU, edgecolor='r', fill=False)\r\n\r\nax.add_patch(sun)\r\nax.add_patch(mercury)\r\nax.add_patch(venus)\r\nax.add_patch(earth)\r\nax.add_patch(mars)\r\n\r\nax.set_aspect('equal', 'box')\r\n\r\nline, = ax.plot(x[0], y[0], color='silver', linestyle='-', linewidth=1)\r\ndot, = ax.plot([], [], color='silver', marker='o', markersize=1, markeredgecolor='w', linestyle='')\r\n#Vel = ax.text(0.05, 0.9, 'Velocity: {:.2e} m/s'.format(np.sqrt(vx[0]**2 + vy[0]**2)), horizontalalignment='left',\r\n# verticalalignment='top', transform=ax.transAxes, color='w')\r\n#E_tot = ax.text(0.05, 0.85, 'Specific Total Energy: {:.2e} J/kg'.format(Etot(x[0], y[0], vx[0], vy[0])), horizontalalignment='left', \r\n# verticalalignment='top', transform=ax.transAxes, color='w')\r\n#Time = ax.text(0.05, 0.95, 'Time: {:.2f} yr'.format(t[0]/86400/365), horizontalalignment='left', \r\n# verticalalignment='top', transform=ax.transAxes, color='w')\r\n\r\nax.set_xlim([-Box_size,Box_size])\r\nax.set_ylim([-Box_size,Box_size])\r\n#%%\r\n# Velocity Plot\r\nax1 = fig.add_subplot(gs[0, 2:])\r\nax1.set_facecolor(COLOR)\r\nvelline, = ax1.plot(t[0]/yr2s, np.sqrt(vx[0]**2+vy[0]**2), color='silver')\r\nax1.spines['bottom'].set_color(LineColor)\r\nax1.spines['top'].set_color(LineColor) \r\nax1.spines['right'].set_color(LineColor)\r\nax1.spines['left'].set_color(LineColor)\r\nax1.set_xlim([0,tmax/yr2s])\r\nax1.set_ylim([0,np.max(np.sqrt(vx**2+vy**2))*1.2])\r\nax1.tick_params(labelcolor=LineColor, labelsize='medium', width=3, colors=LineColor)\r\nax1.ticklabel_format(axis='y', style='sci', useMathText=True, scilimits=(4,5))\r\nax1.set_xlabel('Time (yr)')\r\nax1.set_ylabel('Velocity (m/s)')\r\nax1.xaxis.label.set_color(LineColor)\r\nax1.yaxis.label.set_color(LineColor)\r\n\r\n#%%\r\n# Energy Plot\r\nax2 = fig.add_subplot(gs[1, 2:])\r\nax2.set_facecolor(COLOR)\r\nEtotline, = ax2.plot(t[0]/yr2s, Etot(x[0], y[0], vx[0], vy[0]), color='silver')\r\nax2.spines['bottom'].set_color(LineColor)\r\nax2.spines['top'].set_color(LineColor) \r\nax2.spines['right'].set_color(LineColor)\r\nax2.spines['left'].set_color(LineColor)\r\nax2.set_xlim([0, tmax/yr2s])\r\nax2.set_ylim([np.min(Etot(x, y, vx, vy))*1.2, np.max(Etot(x, y, vx, vy))*1.2])\r\nax2.tick_params(labelcolor=LineColor, labelsize='medium', width=3, colors=LineColor)\r\nax2.ticklabel_format(style='sci', useMathText=True)\r\nax2.set_xlabel('Time (yr)')\r\nax2.set_ylabel('Specific total energy (J/kg)')\r\nax2.xaxis.label.set_color(LineColor)\r\nax2.yaxis.label.set_color(LineColor)\r\n\r\nplt.tight_layout()\r\n#%%\r\nms2AUyr = 86400*365/1.5e11\r\ndef update(i):\r\n dot.set_data(x[i], y[i])\r\n line.set_data(x[:i], y[:i])\r\n velline.set_data(t[:i]/yr2s, np.sqrt(vx[:i]**2+vy[:i]**2))\r\n Etotline.set_data(t[:i]/yr2s, Etot(x[:i], y[:i], vx[:i], vy[:i]))\r\n r = np.sqrt(x[i]**2 + y[i]**2)\r\n if Tracing:\r\n ax.set_xlim([-1.5*r,1.5*r])\r\n ax.set_ylim([-1.5*r,1.5*r])\r\n O1 = ax.add_patch(sun)\r\n O2 = ax.add_patch(mercury)\r\n O3 = ax.add_patch(venus)\r\n O4 = ax.add_patch(earth)\r\n O5 = ax.add_patch(mars)\r\n #Vel.set_text('Velocity: {:.2e} m/s'.format(np.sqrt(vx[i]**2 + vy[i]**2)))\r\n #Vel.set_text('Velocity: {:.2e} AU/yr'.format(np.sqrt(vx[i]**2 + vy[i]**2)*ms2AUyr))\r\n #E_tot.set_text('Total Energy: {:.2e} J/kg'.format(Etot(x[i], y[i], vx[i], vy[i])))\r\n #Time.set_text('Time: {:.2f} yr'.format(t[i]/86400/365))\r\n return [dot, line, velline, Etotline, O1, O2, O3, O4, O5]\r\n\r\n\r\nani = FuncAnimation(fig=fig, \r\n func=update,\r\n frames=frames, \r\n interval=10000/frames, \r\n blit=True, \r\n repeat=False)\r\n\r\nif SAVE_VIDEO:\r\n ani.save(\"sail.mp4\", dpi=300, savefig_kwargs={'facecolor':COLOR})\r\nplt.show()\r\n", "repo_name": "CFP106020008/Light-Sail-Simulation", "sub_path": "LightSail.py", "file_name": "LightSail.py", "file_ext": "py", "file_size_in_byte": 7222, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "numpy.sqrt", "line_number": 45, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 50, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 56, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 62, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 63, "usage_type": "call"}, {"api_name": "numpy.linalg.norm", "line_number": 64, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 64, "usage_type": "attribute"}, {"api_name": "numpy.linalg.norm", "line_number": 65, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 65, "usage_type": "attribute"}, {"api_name": "numpy.linalg.norm", "line_number": 68, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 68, "usage_type": "attribute"}, {"api_name": "numpy.sqrt", "line_number": 69, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 72, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 74, "usage_type": "call"}, {"api_name": "numpy.linalg.norm", "line_number": 79, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 79, "usage_type": "attribute"}, {"api_name": "numpy.dot", "line_number": 84, "usage_type": "call"}, {"api_name": "numpy.linalg.norm", "line_number": 84, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 84, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 89, "usage_type": "call"}, {"api_name": "scipy.integrate.solve_ivp", "line_number": 92, "usage_type": "call"}, {"api_name": "numpy.linspace", "line_number": 95, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 110, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 110, "usage_type": "name"}, {"api_name": "matplotlib.gridspec.GridSpec", "line_number": 111, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.Circle", "line_number": 124, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 124, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.Circle", "line_number": 125, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 125, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.Circle", "line_number": 126, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 126, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.Circle", "line_number": 127, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 127, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.Circle", "line_number": 128, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 128, "usage_type": "name"}, {"api_name": "numpy.sqrt", "line_number": 153, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 159, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 159, "usage_type": "call"}, {"api_name": "numpy.min", "line_number": 177, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 177, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.tight_layout", "line_number": 185, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 185, "usage_type": "name"}, {"api_name": "numpy.sqrt", "line_number": 191, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 193, "usage_type": "call"}, {"api_name": "matplotlib.animation.FuncAnimation", "line_number": 209, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.show", "line_number": 218, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 218, "usage_type": "name"}]} +{"seq_id": "5143210542", "text": "import sys\nimport socket\nimport threading\nimport datetime\n\nfrom queue import *\nfrom Commands.commands import *\nfrom client import *\nfrom dungeon import *\n\nmessageQueue = Queue()\nactiveDungeon = Dungeon()\n\nclientIndex = 0\ncurrentClients = {}\ncurrentClientsLock = threading.Lock()\n\nzombieIndex = 0\nzombieClients = {}\n\ndeadEntitiesIndex = 0\ndeadEntities = {}\n\nhost = ''\nport = 0\n\ndef get_entity( entity_type, entity_key ):\n \"\"\"\n\n :param entity_type: The Type of entity (See Entity for type constants)\n :param entity_key: The key for the entity. (for default and zombies this is there name else it is the socket related to the client) leave None to return all\n :return: None if not found\n \"\"\"\n entities = {Entity.ENTITY_DEFAULT: deadEntities, Entity.ENTITY_CLIENT: currentClients, Entity.ENTITY_ZOMBIE: zombieClients}\n if entity_key is None and entity_type in entities:\n return entities[ entity_type ]\n elif entity_type in entities and entity_key in entities[entity_key]:\n return entities[ entity_type ][ entity_key ]\n else:\n return None\n\n\ndef debug_print(text):\n print(str(datetime.datetime.now()) + ':' + text)\n\n\ndef sendString(socket,str):\n\n str = ''.join([\"-\"*20]) + \"\\n\" + str\n data= bytes(str,'utf-8')\n try:\n if socket.send(len(data).to_bytes(2, byteorder='big')) == 0:\n raise socket.error\n\n if socket.send(data) == 0:\n raise socket.error\n except:\n messageQueue.put( ClientLost( socket ) )\n\ndef clientReceive(sock):\n\n clientValid = True\n\n clientName = ''\n\n currentClientsLock.acquire()\n\n if sock in currentClients:\n clientName = currentClients[sock].clientName\n else:\n clientName = 'N/A'\n currentClientsLock.release()\n return\n\n\n currentClientsLock.release()\n\n debug_print(clientName + ':clientReceive running')\n\n while clientValid == True:\n try:\n data = sock.recv(2)\n\n currentClientsLock.acquire()\n\n if sock in currentClients:\n clientName = currentClients[sock].clientName\n else:\n clientName = 'N/A'\n clientValid = False\n currentClientsLock.release()\n\n if len(data) == 0:\n # on OSX, 'closed' sockets send 0 bytes, so trap this\n raise socket.error\n\n size = int.from_bytes(data, byteorder='big')\n\n data = sock.recv(size)\n\n if len(data) > 0:\n incoming_msg = data.decode('utf-8')\n\n debug_print('recv:' + clientName + ':' + incoming_msg)\n\n for act in ClientActionDispatcher( sock, incoming_msg).RunCommand(currentClients, activeDungeon):\n messageQueue.put( act )\n # messageQueue.put(ClientMessage(sock, incoming_msg, ClientMessage.MESSAGE_TYPE_ALL_OTHER) )\n\n except socket.error:\n debug_print(clientName +':clientReceive - lost client')\n clientValid = False\n messageQueue.put(ClientLost(sock))\n\n\ndef acceptClients(serversocket):\n debug_print('acceptThread running')\n while(True):\n (clientsocket, address) = serversocket.accept()\n messageQueue.put( ClientJoined( clientsocket ) )\n\n while clientsocket not in currentClients: # wait for the user to be added to users\n pass\n\n messageQueue.put(ClientJoined(clientsocket).welcome()[0])\n currentClients[clientsocket].pendingAction = ClientContinue(clientsocket)\n\n\n\n\n\ndef handleClientLost(command):\n global zombieIndex\n\n currentClientsLock.acquire()\n try:\n\n for c in command.RunCommand(currentClients):\n messageQueue.put( c )\n\n debug_print('Removing lost client:' + currentClients[command.socket].clientName)\n\n zombieClients[\"zombie_\"+ str(zombieIndex)] = ZombieClient(currentClients[command.socket])\n zombieIndex += 1\n\n del currentClients[command.socket]\n except:\n pass\n\n currentClientsLock.release()\n\n\ndef handleClientJoined(command):\n global clientIndex\n\n clientName = 'client-' + str(clientIndex)\n clientIndex += 1\n\n currentClientsLock.acquire()\n\n currentClients[command.socket] = Client(clientName)\n\n for c in command.RunCommand( currentClients ):\n messageQueue.put( c )\n\n currentClientsLock.release()\n\n message = 'Joined server as:' + clientName\n debug_print('send:' + clientName + ':' + message)\n\n sendString(command.socket, message)\n\n thread = threading.Thread(target=clientReceive, args=(command.socket,))\n thread.start()\n\n\ndef handleClientMessage(command):\n\n currentClientsLock.acquire()\n\n clientName = \"None\"\n\n if command.socket in currentClients:\n clientName = currentClients[ command.socket ].clientName\n\n command.senMessage( sendString, currentClients )\n\n currentClientsLock.release()\n\n debug_print('send:' + clientName + ':'+command.message)\n\ndef main():\n serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n serversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n\n host = '0.0.0.0'\n port = 9000\n\n if len(sys.argv) > 1:\n host = sys.argv[1]\n\n if len(sys.argv) > 2:\n port = sys.argv[2]\n\n try:\n serversocket.bind((host, port))\n except socket.error as err:\n debug_print('Can\\'t start server, is another instance running?')\n debug_print(format(err))\n exit()\n\n debug_print(host +':' + str(port))\n\n serversocket.listen(5)\n\n thread = threading.Thread(target=acceptClients,args=(serversocket,))\n thread.start()\n\n while True:\n\n if messageQueue.qsize()>0:\n command = messageQueue.get()\n\n if isinstance(command, ClientJoined):\n handleClientJoined(command)\n\n if isinstance(command, ClientLost):\n handleClientLost(command)\n\n if isinstance(command, ClientMessage):\n handleClientMessage(command)\n\n\nif __name__ == '__main__':\n main()", "repo_name": "Ashley-Sands/Comp-260-MUD-Server", "sub_path": "mudserver.py", "file_name": "mudserver.py", "file_ext": "py", "file_size_in_byte": 6071, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "threading.Lock", "line_number": 16, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 44, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 44, "usage_type": "attribute"}, {"api_name": "socket.send", "line_number": 52, "usage_type": "call"}, {"api_name": "socket.error", "line_number": 53, "usage_type": "attribute"}, {"api_name": "socket.send", "line_number": 55, "usage_type": "call"}, {"api_name": "socket.error", "line_number": 56, "usage_type": "attribute"}, {"api_name": "socket.error", "line_number": 95, "usage_type": "attribute"}, {"api_name": "socket.error", "line_number": 110, "usage_type": "attribute"}, {"api_name": "threading.Thread", "line_number": 173, "usage_type": "call"}, {"api_name": "socket.socket", "line_number": 193, "usage_type": "call"}, {"api_name": "socket.AF_INET", "line_number": 193, "usage_type": "attribute"}, {"api_name": "socket.SOCK_STREAM", "line_number": 193, "usage_type": "attribute"}, {"api_name": "socket.SOL_SOCKET", "line_number": 194, "usage_type": "attribute"}, {"api_name": "socket.SO_REUSEADDR", "line_number": 194, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 199, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 200, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 202, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 203, "usage_type": "attribute"}, {"api_name": "socket.error", "line_number": 207, "usage_type": "attribute"}, {"api_name": "threading.Thread", "line_number": 216, "usage_type": "call"}]} +{"seq_id": "74940727732", "text": "from channels.generic.websocket import AsyncWebsocketConsumer\nfrom api.models import Client, Server\nimport json\n\n\nclass BoardConsumer(AsyncWebsocketConsumer):\n async def connect(self):\n self.board_id = self.scope['url_route']['kwargs']['board_id']\n self.board_group_name = 'board_%s' % self.board_id\n print(self.channel_name)\n await self.channel_layer.group_add(\n self.board_group_name,\n self.channel_name\n )\n await self.accept()\n\n async def disconnect(self, close_code):\n print(self.channel_name)\n await self.channel_layer.group_discard(\n self.board_group_name,\n self.channel_name\n )\n\n async def receive(self, text_data):\n text_data_json = json.loads(text_data)\n message = text_data_json['message']\n await self.channel_layer.group_send(\n self.board_group_name,\n {\n 'type': 'board_clip',\n 'message': message\n }\n )\n\n async def board_clip(self, event):\n message = event['message']\n\n # Send message to WebSocket\n await self.send(text_data=json.dumps({\n 'message': message\n }))\n\n# class ChatConsumer(WebsocketConsumer):\n\n# def connect(self):\n# self.board_id = self.scope['url_route']['kwargs']['board_id']\n# Client.objects.create(name=self.channel_name, id=self.board_id)\n# Server.objects.create(name=self.channel_name, id=self.board_id)\n\n\n# def disconnect(self, close_code):\n# # Note that in some rare cases (power loss, etc) disconnect may fail\n# # to run; this naive example would leave zombie channel names around.\n# Clients.objects.filter(channel_name=self.channel_name).delete()\n\n# def chat_message(self, event):\n# # Handles the \"chat.message\" event when it's sent to us.\n# self.send(text_data=event[\"text\"])", "repo_name": "gurpreetsingh00885/klips", "sub_path": "klips/consumers.py", "file_name": "consumers.py", "file_ext": "py", "file_size_in_byte": 1935, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 0, "dataset": "github-code", "pt": "21", "api": [{"api_name": "channels.generic.websocket.AsyncWebsocketConsumer", "line_number": 6, "usage_type": "name"}, {"api_name": "json.loads", "line_number": 25, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 39, "usage_type": "call"}]} +{"seq_id": "12567693935", "text": "import math\nimport logging\nimport sys\nimport pyexiv2\nfrom typing import List, TypedDict, Union\nfrom datetime import datetime\nfrom glob import glob\n\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.DEBUG)\n\nhandler = logging.StreamHandler(sys.stdout)\nhandler.setLevel(logging.DEBUG)\nformatter = logging.Formatter('%(message)s')\nhandler.setFormatter(formatter)\nlogger.addHandler(handler)\n\n\nDATE_FIELD = \"Exif.Photo.DateTimeOriginal\"\nGPS_LAT_FIELD = \"Exif.GPSInfo.GPSLatitude\"\nGPS_LONG_FIELD = \"Exif.GPSInfo.GPSLongitude\"\nGPS_ALT_FIELD = \"Exif.GPSInfo.GPSAltitude\"\n\nMAX_DIFF_DAYS = 14\n\n\nclass Coordinates():\n lat: str\n long: str\n\n\nclass ImageData(TypedDict):\n file: str\n date: str\n datetime: datetime\n gps: Union[Coordinates, None]\n\n\ndef get_datetime(date: str) -> datetime:\n return datetime.strptime(date, \"%Y:%m:%d %H:%M:%S\")\n\n\ndef find_images(path: str, with_gps=True) -> List[ImageData]:\n images = glob(path)\n image_data = []\n for image in images:\n exivimg = pyexiv2.Image(image)\n data = exivimg.read_exif()\n exivimg.close()\n gps_data = (\n {\n GPS_LAT_FIELD: data[GPS_LAT_FIELD],\n GPS_LONG_FIELD: data[GPS_LONG_FIELD]\n }\n if GPS_LAT_FIELD in data and GPS_LONG_FIELD in data\n else None\n )\n if gps_data and GPS_ALT_FIELD in data:\n gps_data[GPS_ALT_FIELD] = data[GPS_ALT_FIELD]\n if (not with_gps and not gps_data) or (with_gps and gps_data):\n image_data.append({\n \"file\": image,\n \"date\": data[DATE_FIELD],\n \"datetime\": get_datetime(data[DATE_FIELD]),\n \"gps\": gps_data\n })\n\n return image_data\n\n\n# bindary search\ndef find_nearest(\n image, images_with_gps: List[ImageData]\n) -> ImageData:\n min_index, max_index = 0, len(images_with_gps) - 1\n match = None\n while match is None:\n diff = (max_index - min_index)\n if diff == 0:\n match = images_with_gps[max_index]\n elif diff == 1:\n diff_max = abs(images_with_gps[max_index][\"datetime\"] - image[\"datetime\"])\n diff_min = abs(images_with_gps[min_index][\"datetime\"] - image[\"datetime\"])\n match = (\n images_with_gps[max_index] if diff_max < diff_min\n else images_with_gps[min_index]\n )\n else:\n mid_index = min_index + math.ceil(diff / 2)\n if image[\"date\"] == images_with_gps[mid_index][\"date\"]:\n match = images_with_gps[mid_index]\n elif image[\"date\"] > images_with_gps[mid_index][\"date\"]:\n min_index = mid_index\n elif image[\"date\"] < images_with_gps[mid_index][\"date\"]:\n max_index = mid_index\n\n return match\n\n\ndef in_bounds(date_a, date_b) -> bool:\n max_date = max(get_datetime(date_a), get_datetime(date_b))\n min_date = min(get_datetime(date_a), get_datetime(date_b))\n datetime_diff = max_date - min_date\n if datetime_diff.days > MAX_DIFF_DAYS:\n return False\n return True\n\n\ndef add_gps_to_image(image: ImageData, gps):\n exivimg = pyexiv2.Image(image[\"file\"])\n exivimg.modify_exif(gps)\n exivimg.close()\n\n\ndef gps_approximator(base_path, process_path, dry_run=False):\n images_with_gps = sorted(find_images(base_path), key=lambda x: x['date'])\n pwg_len = len(images_with_gps)\n logger.info(f\"images as base: {pwg_len}\")\n if pwg_len == 0:\n logger.error(\"No base images were found\")\n sys.exit(1)\n\n images_without_gps = find_images(process_path, False)\n pwog_len = len(images_without_gps)\n logger.info(f\"images to process: {pwog_len}\")\n logger.debug(\"\\n\")\n if pwog_len == 0:\n logger.error(\"No images to process were found\")\n sys.exit(1)\n\n matched = []\n unmatched = []\n failed = []\n for current_image, index in zip(images_without_gps, range(pwog_len)):\n logger.debug(f\"# processing {index + 1}/{pwog_len}\")\n logger.debug(f\" file: {current_image['file']}\")\n match = find_nearest(current_image, images_with_gps)\n if in_bounds(current_image[\"date\"], match[\"date\"]):\n if not dry_run:\n try:\n add_gps_to_image(current_image, match[\"gps\"])\n except Exception:\n logger.exception(\n f\"Failed to add GPS data to images {current_image['file']}\"\n )\n failed.append(current_image)\n\n logger.debug(f\" match: {match['file']}\")\n matched.append((current_image, match))\n else:\n logger.debug(\" unmatched\")\n unmatched.append(current_image)\n\n logger.debug(\"\\n\")\n logger.info(f\"matched images: {len(matched)}\")\n logger.info(f\"unmatched images: {len(unmatched)}\")\n logger.info(f\"failed images: {len(failed)}\")\n\n\nUSAGE = \"\"\"\nUsage:\n python3 gps_approximator.py [base_collection] [process_collection] [--dry_run]\n base_collection: glob to determine the base collection images\n process_collection: glob to determine the images to process\n --dry_run (optional): do not actualy modify the images\n\"\"\"\n\nif __name__ == \"__main__\":\n args = sys.argv\n if len(args) < 3 or len(args) > 4:\n logger.error(f\"Error: expected 2 or 3 parameters \\n{USAGE}\")\n sys.exit(1)\n\n dry_run = len(args) == 4 and args[3] == \"--dry\"\n\n gps_approximator(args[1], args[2], dry_run)\n", "repo_name": "jacksbox/photo_gps_data_approximator", "sub_path": "gps_approximator.py", "file_name": "gps_approximator.py", "file_ext": "py", "file_size_in_byte": 5510, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 3, "dataset": "github-code", "pt": "21", "api": [{"api_name": "logging.getLogger", "line_number": 9, "usage_type": "call"}, {"api_name": "logging.DEBUG", "line_number": 10, "usage_type": "attribute"}, {"api_name": "logging.StreamHandler", "line_number": 12, "usage_type": "call"}, {"api_name": "sys.stdout", "line_number": 12, "usage_type": "attribute"}, {"api_name": "logging.DEBUG", "line_number": 13, "usage_type": "attribute"}, {"api_name": "logging.Formatter", "line_number": 14, "usage_type": "call"}, {"api_name": "typing.TypedDict", "line_number": 32, "usage_type": "name"}, {"api_name": "datetime.datetime", "line_number": 35, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 36, "usage_type": "name"}, {"api_name": "datetime.datetime.strptime", "line_number": 40, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 40, "usage_type": "name"}, {"api_name": "datetime.datetime", "line_number": 39, "usage_type": "name"}, {"api_name": "glob.glob", "line_number": 44, "usage_type": "call"}, {"api_name": "pyexiv2.Image", "line_number": 47, "usage_type": "call"}, {"api_name": "typing.List", "line_number": 43, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 73, "usage_type": "name"}, {"api_name": "math.ceil", "line_number": 89, "usage_type": "call"}, {"api_name": "pyexiv2.Image", "line_number": 110, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 121, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 129, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 169, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 172, "usage_type": "call"}]} +{"seq_id": "18205613650", "text": "import os\nfrom sys import implementation\nimport requests\nimport json\nimport re\nfrom .config import *\nfrom dotenv import load_dotenv\nfrom datetime import datetime\nimport requests\nimport asyncio\nfrom concurrent.futures import ThreadPoolExecutor\nimport time\nimport src.init as init\nfrom halo import Halo\n\nrateLimitFlag = False\n\n\ndef get_submissions_async_request(session, id, title):\n data = init.data\n data[\"variables\"][\"questionSlug\"] = title\n with session.post(init.baseurl+\"/graphql\", json=data) as response:\n resp = json.loads(response.content.decode('utf-8'))\n if response.status_code != 200:\n print(\"FAILURE::{0}\".format(data))\n\n for submission in resp[\"data\"][\"submissionList\"][\"submissions\"]:\n if submission[\"statusDisplay\"] == \"Accepted\":\n init.solvedSubmissions[id] = submission\n\n\nasync def get_submissions_asynchronous():\n with ThreadPoolExecutor(max_workers=5) as executor:\n with requests.Session() as session:\n # Set any session parameters here before calling `fetch`\n requests.utils.add_dict_to_cookiejar(session.cookies, init.cookies)\n\n loop = asyncio.get_event_loop()\n tasks = [\n loop.run_in_executor(\n executor,\n get_submissions_async_request,\n # Allows us to pass in multiple arguments to `fetch`\n *(session, id, title)\n )\n for id, title in init.solvedQuestions.items()\n ]\n for response in await asyncio.gather(*tasks):\n pass\n\n\ndef get_submission_code_async_request(session, id, submission):\n\n if str(id) in init.availableSubmissions:\n return\n\n with session.get(init.baseurl+submission[\"url\"]) as response:\n if response.status_code != 200:\n if response.status_code == 429:\n init.rateLimitedQuestions.update({\n id: submission\n })\n return\n print(\"FAILURE::{0}\".format(id))\n\n code = re.search(\"submissionCode:.*\", response.text).group(0)\n # if not code:\n\n title = init.solvedQuestions[id]\n lang = submission[\"lang\"]\n filename = \"{}.{}.{}\".format(id, title, init.language[lang])\n\n fd = open(init.codeDirectory+filename, \"w+\")\n fd.write(eval(code[16:-1]))\n # write into file\n\n init.jsonfile.append({\n \"id\": id,\n \"title\": \" \".join(title.split(\"-\")),\n \"url\": title,\n \"filename\": filename,\n \"timestamp\": datetime.utcfromtimestamp(int(submission[\"timestamp\"])).strftime('%d-%m-%Y'),\n \"memory\": submission[\"memory\"],\n \"runtime\": submission[\"runtime\"],\n \"language\": lang\n })\n\n return\n\n\nasync def get_submission_code_asynchronous():\n with ThreadPoolExecutor(max_workers=5) as executor:\n with requests.Session() as session:\n # Set any session parameters here before calling `fetch`\n requests.utils.add_dict_to_cookiejar(session.cookies, init.cookies)\n\n loop = asyncio.get_event_loop()\n tasks = [\n loop.run_in_executor(\n executor,\n get_submission_code_async_request,\n # Allows us to pass in multiple arguments to `fetch`\n *(session, id, submission)\n )\n for id, submission in init.solvedSubmissions.items()\n ]\n for response in await asyncio.gather(*tasks):\n pass\n\n\ndef getallsubmissions():\n loop = asyncio.get_event_loop()\n future = asyncio.ensure_future(get_submission_code_asynchronous())\n loop.run_until_complete(future)\n\n# @Halo(text='Loading Questions', spinner='dots')\n\n\ndef downloadAllSubmissions():\n global rateLimitFlag\n\n spinner = Halo(text='Gathering questions', spinner='dots')\n spinner.start()\n init.solvedQuestions = getSolvedQuestions()\n spinner.succeed(\"Questions loaded successfully\")\n spinner = Halo(text='Loading submissions', spinner='dots')\n spinner.start()\n # global solvedSubmissions\n\n if len(init.solvedSubmissions) == 0:\n loop = asyncio.get_event_loop()\n future = asyncio.ensure_future(get_submissions_asynchronous())\n loop.run_until_complete(future)\n\n getallsubmissions()\n\n spinner.succeed(\"Submissions loaded successfully\")\n spinner = Halo(text='Creating files', spinner='dots')\n spinner.start()\n\n while init.rateLimitedQuestions:\n init.solvedSubmissions = init.rateLimitedQuestions.copy()\n init.rateLimitedQuestions.clear()\n time.sleep(5)\n getallsubmissions()\n\n spinner.succeed(\"Files saved successfully at submissions/\")\n\n spinner = Halo(text='Gathering details', spinner='dots')\n spinner.start()\n with open(init.submissionDirectory+'submission.json', 'w') as f:\n json.dump(init.jsonfile, f)\n spinner.succeed(\"Collected required details\")\n spinner.stop()\n\n\ndef listSubmission():\n spinner = Halo(text='Gathering questions', spinner='dots')\n spinner.start()\n init.solvedQuestions = getSolvedQuestions()\n print(init.solvedQuestions)\n spinner.succeed(\"Questions loaded successfully\")\n spinner = Halo(text='Loading submissions', spinner='dots')\n spinner.start()\n # global solvedSubmissions\n\n if len(init.solvedSubmissions) == 0:\n loop = asyncio.get_event_loop()\n future = asyncio.ensure_future(get_submissions_asynchronous())\n loop.run_until_complete(future)\n\n print(init.solvedSubmissions)\n init.jsonfile = []\n for id, submission in init.solvedSubmissions.items():\n title = init.solvedQuestions[id]\n lang = submission[\"lang\"]\n # write into file\n filename = \"{}.{}.{}\".format(id, title, init.language[lang])\n\n init.jsonfile.append({\n \"id\": id,\n \"title\": \" \".join(title.split(\"-\")),\n \"url\": title,\n \"filename\": filename,\n \"timestamp\": datetime.utcfromtimestamp(int(submission[\"timestamp\"])).strftime('%d-%m-%Y'),\n \"memory\": submission[\"memory\"],\n \"runtime\": submission[\"runtime\"],\n \"language\": lang\n })\n spinner.succeed(\"Submissions loaded successfully\")\n", "repo_name": "SocioDroid/leetcode-py-cli", "sub_path": "src/service_async.py", "file_name": "service_async.py", "file_ext": "py", "file_size_in_byte": 6356, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 18, "dataset": "github-code", "pt": "21", "api": [{"api_name": "src.init.data", "line_number": 20, "usage_type": "attribute"}, {"api_name": "src.init", "line_number": 20, "usage_type": "name"}, {"api_name": "src.init.baseurl", "line_number": 22, "usage_type": "attribute"}, {"api_name": "src.init", "line_number": 22, "usage_type": "name"}, {"api_name": "json.loads", "line_number": 23, "usage_type": "call"}, {"api_name": "src.init.solvedSubmissions", "line_number": 29, "usage_type": "attribute"}, {"api_name": "src.init", "line_number": 29, "usage_type": "name"}, {"api_name": "concurrent.futures.ThreadPoolExecutor", "line_number": 33, "usage_type": "call"}, {"api_name": "requests.Session", "line_number": 34, "usage_type": "call"}, {"api_name": "requests.utils.add_dict_to_cookiejar", "line_number": 36, "usage_type": "call"}, {"api_name": "requests.utils", "line_number": 36, "usage_type": "attribute"}, {"api_name": "src.init.cookies", "line_number": 36, "usage_type": "attribute"}, {"api_name": "src.init", "line_number": 36, "usage_type": "name"}, {"api_name": "asyncio.get_event_loop", "line_number": 38, "usage_type": "call"}, {"api_name": "src.init.solvedQuestions.items", "line_number": 46, "usage_type": "call"}, {"api_name": "src.init.solvedQuestions", "line_number": 46, "usage_type": "attribute"}, {"api_name": "src.init", "line_number": 46, "usage_type": "name"}, {"api_name": "asyncio.gather", "line_number": 48, "usage_type": "call"}, {"api_name": "src.init.availableSubmissions", "line_number": 54, "usage_type": "attribute"}, {"api_name": "src.init", "line_number": 54, "usage_type": "name"}, {"api_name": "src.init.baseurl", "line_number": 57, "usage_type": "attribute"}, {"api_name": "src.init", "line_number": 57, "usage_type": "name"}, {"api_name": "src.init.rateLimitedQuestions.update", "line_number": 60, "usage_type": "call"}, {"api_name": "src.init.rateLimitedQuestions", "line_number": 60, "usage_type": "attribute"}, {"api_name": "src.init", "line_number": 60, "usage_type": "name"}, {"api_name": "re.search", "line_number": 66, "usage_type": "call"}, {"api_name": "src.init.solvedQuestions", "line_number": 69, "usage_type": "attribute"}, {"api_name": "src.init", "line_number": 69, "usage_type": "name"}, {"api_name": "src.init.language", "line_number": 71, "usage_type": "attribute"}, {"api_name": "src.init", "line_number": 71, "usage_type": "name"}, {"api_name": "src.init.codeDirectory", "line_number": 73, "usage_type": "attribute"}, {"api_name": "src.init", "line_number": 73, "usage_type": "name"}, {"api_name": "src.init.jsonfile.append", "line_number": 77, "usage_type": "call"}, {"api_name": "src.init.jsonfile", "line_number": 77, "usage_type": "attribute"}, {"api_name": "src.init", "line_number": 77, "usage_type": "name"}, {"api_name": "datetime.datetime.utcfromtimestamp", "line_number": 82, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 82, "usage_type": "name"}, {"api_name": "concurrent.futures.ThreadPoolExecutor", "line_number": 92, "usage_type": "call"}, {"api_name": "requests.Session", "line_number": 93, "usage_type": "call"}, {"api_name": "requests.utils.add_dict_to_cookiejar", "line_number": 95, "usage_type": "call"}, {"api_name": "requests.utils", "line_number": 95, "usage_type": "attribute"}, {"api_name": "src.init.cookies", "line_number": 95, "usage_type": "attribute"}, {"api_name": "src.init", "line_number": 95, "usage_type": "name"}, {"api_name": "asyncio.get_event_loop", "line_number": 97, "usage_type": "call"}, {"api_name": "src.init.solvedSubmissions.items", "line_number": 105, "usage_type": "call"}, {"api_name": "src.init.solvedSubmissions", "line_number": 105, "usage_type": "attribute"}, {"api_name": "src.init", "line_number": 105, "usage_type": "name"}, {"api_name": "asyncio.gather", "line_number": 107, "usage_type": "call"}, {"api_name": "asyncio.get_event_loop", "line_number": 112, "usage_type": "call"}, {"api_name": "asyncio.ensure_future", "line_number": 113, "usage_type": "call"}, {"api_name": "halo.Halo", "line_number": 122, "usage_type": "call"}, {"api_name": "src.init.solvedQuestions", "line_number": 124, "usage_type": "attribute"}, {"api_name": "src.init", "line_number": 124, "usage_type": "name"}, {"api_name": "halo.Halo", "line_number": 126, "usage_type": "call"}, {"api_name": "src.init.solvedSubmissions", "line_number": 130, "usage_type": "attribute"}, {"api_name": "src.init", "line_number": 130, "usage_type": "name"}, {"api_name": "asyncio.get_event_loop", "line_number": 131, "usage_type": "call"}, {"api_name": "asyncio.ensure_future", "line_number": 132, "usage_type": "call"}, {"api_name": "halo.Halo", "line_number": 138, "usage_type": "call"}, {"api_name": "src.init.rateLimitedQuestions", "line_number": 141, "usage_type": "attribute"}, {"api_name": "src.init", "line_number": 141, "usage_type": "name"}, {"api_name": "src.init.solvedSubmissions", "line_number": 142, "usage_type": "attribute"}, {"api_name": "src.init", "line_number": 142, "usage_type": "name"}, {"api_name": "src.init.rateLimitedQuestions.copy", "line_number": 142, "usage_type": "call"}, {"api_name": "src.init.rateLimitedQuestions", "line_number": 142, "usage_type": "attribute"}, {"api_name": "src.init.rateLimitedQuestions.clear", "line_number": 143, "usage_type": "call"}, {"api_name": "src.init.rateLimitedQuestions", "line_number": 143, "usage_type": "attribute"}, {"api_name": "src.init", "line_number": 143, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 144, "usage_type": "call"}, {"api_name": "halo.Halo", "line_number": 149, "usage_type": "call"}, {"api_name": "src.init.submissionDirectory", "line_number": 151, "usage_type": "attribute"}, {"api_name": "src.init", "line_number": 151, "usage_type": "name"}, {"api_name": "json.dump", "line_number": 152, "usage_type": "call"}, {"api_name": "src.init.jsonfile", "line_number": 152, "usage_type": "attribute"}, {"api_name": "src.init", "line_number": 152, "usage_type": "name"}, {"api_name": "halo.Halo", "line_number": 158, "usage_type": "call"}, {"api_name": "src.init.solvedQuestions", "line_number": 160, "usage_type": "attribute"}, {"api_name": "src.init", "line_number": 160, "usage_type": "name"}, {"api_name": "src.init.solvedQuestions", "line_number": 161, "usage_type": "attribute"}, {"api_name": "src.init", "line_number": 161, "usage_type": "name"}, {"api_name": "halo.Halo", "line_number": 163, "usage_type": "call"}, {"api_name": "src.init.solvedSubmissions", "line_number": 167, "usage_type": "attribute"}, {"api_name": "src.init", "line_number": 167, "usage_type": "name"}, {"api_name": "asyncio.get_event_loop", "line_number": 168, "usage_type": "call"}, {"api_name": "asyncio.ensure_future", "line_number": 169, "usage_type": "call"}, {"api_name": "src.init.solvedSubmissions", "line_number": 172, "usage_type": "attribute"}, {"api_name": "src.init", "line_number": 172, "usage_type": "name"}, {"api_name": "src.init.jsonfile", "line_number": 173, "usage_type": "attribute"}, {"api_name": "src.init", "line_number": 173, "usage_type": "name"}, {"api_name": "src.init.solvedSubmissions.items", "line_number": 174, "usage_type": "call"}, {"api_name": "src.init.solvedSubmissions", "line_number": 174, "usage_type": "attribute"}, {"api_name": "src.init", "line_number": 174, "usage_type": "name"}, {"api_name": "src.init.solvedQuestions", "line_number": 175, "usage_type": "attribute"}, {"api_name": "src.init", "line_number": 175, "usage_type": "name"}, {"api_name": "src.init.language", "line_number": 178, "usage_type": "attribute"}, {"api_name": "src.init", "line_number": 178, "usage_type": "name"}, {"api_name": "src.init.jsonfile.append", "line_number": 180, "usage_type": "call"}, {"api_name": "src.init.jsonfile", "line_number": 180, "usage_type": "attribute"}, {"api_name": "src.init", "line_number": 180, "usage_type": "name"}, {"api_name": "datetime.datetime.utcfromtimestamp", "line_number": 185, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 185, "usage_type": "name"}]} +{"seq_id": "43763922527", "text": "import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport statsmodels.graphics.tsaplots as sgt\nimport statsmodels.tsa.stattools as sts\nfrom statsmodels.tsa.arima_model import ARIMA\nfrom scipy.stats.distributions import chi2\nfrom math import sqrt\n\n\n# ------------------------\n\n# load data\n# ----------\nraw_csv_data = pd.read_csv(\"../data/Index2018.csv\") \ndf_comp=raw_csv_data.copy()\n# -- make the index a datetime object\ndf_comp.date = pd.to_datetime(df_comp.date, dayfirst = True)\ndf_comp.set_index(\"date\", inplace=True)\ndf_comp=df_comp.asfreq('b')\n# -- fill na values\ndf_comp=df_comp.fillna(method='ffill')\n# -- redefine column names and add a new column on returns - we will be working on returns\ndf_comp['market_value']=df_comp.ftse\n\n\n\n\n# split dataset (on straight data = prices)\n# ----------\nsize = int(len(df_comp) * 0.8)\ndf = df_comp.iloc[:size]\ndf_test = df_comp.iloc[size:]\n# -- creating returns column from train dataset\ndf['returns'] = df.market_value.pct_change(1)*100\n\n\n\n# review ACF and PACF (in reality is more functional to run auto_arima vs checking ACF/PACF manually, but this is for sake of example)\n# ----------\n# not done here\n\n\n\n# select ARMA model (by looking to PACF here) and iterating through more models\n# ----------\nmodel_arima_111 = ARIMA(df.market_value, order=(1,1,1)).fit()\nprint(model_arima_111.summary())\nprint('----------')\nmodel_arima_511 = ARIMA(df.market_value, order=(5,1,1)).fit()\nprint(model_arima_511.summary())\nprint('----------')\n\n\n\n\n# compare LLR results across models to see which model is best\n# ----------\ndef LLR_test(mod_1, mod_2, DF=1):\n L1 = mod_1.fit().llf\n L2 = mod_2.fit().llf\n LR = (2*(L2-L1))\n p = chi2.sf(LR, DF).round(3)\n return p\n\nprint(\"\\nLLR test p-value = \" + str(LLR_test(model_arima_111, model_arima_511, DF = 4)))\n\n\n\n\n# analyzing residuals\n# ----------\ndf['residuals_model_arima_111'] = model_arima_111.resid.iloc[:]\nsgt.plot_acf(residuals_model_arima_111[1:], zero = False, lags = 40)\nplt.title(\"ACF Of Residuals for ARIMA(1,1,1)\",size=20)\ndf['residuals_model_arima_511'] = model_arima_511.resid.iloc[:]\nsgt.plot_acf(residuals_model_arima_511[1:], zero = False, lags = 40)\nplt.title(\"ACF Of Residuals for ARIMA(5,1,1)\",size=20)\nplt.show()\n\n", "repo_name": "warpalatino/public", "sub_path": "Machine learning/ML/ARIMA/DS1_arima_model_1.py", "file_name": "DS1_arima_model_1.py", "file_ext": "py", "file_size_in_byte": 2243, "program_lang": "python", "lang": "en", "doc_type": "code", "stars": 1, "dataset": "github-code", "pt": "21", "api": [{"api_name": "pandas.read_csv", "line_number": 16, "usage_type": "call"}, {"api_name": "pandas.to_datetime", "line_number": 19, "usage_type": "call"}, {"api_name": "statsmodels.tsa.arima_model.ARIMA", "line_number": 48, "usage_type": "call"}, {"api_name": "statsmodels.tsa.arima_model.ARIMA", "line_number": 51, "usage_type": "call"}, {"api_name": "scipy.stats.distributions.chi2.sf", "line_number": 64, "usage_type": "call"}, {"api_name": "scipy.stats.distributions.chi2", "line_number": 64, "usage_type": "name"}, {"api_name": "statsmodels.graphics.tsaplots.plot_acf", "line_number": 75, "usage_type": "call"}, {"api_name": "statsmodels.graphics.tsaplots", "line_number": 75, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 76, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 76, "usage_type": "name"}, {"api_name": "statsmodels.graphics.tsaplots.plot_acf", "line_number": 78, "usage_type": "call"}, {"api_name": "statsmodels.graphics.tsaplots", "line_number": 78, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 79, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 79, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 80, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 80, "usage_type": "name"}]} +{"seq_id": "71356220214", "text": "# -*- encoding: utf-8 -*-\r\n\"\"\"\r\nCopyright (c) 2019 - present AppSeed.us\r\n\"\"\"\r\nfrom apps.home import blueprint\r\nfrom flask import render_template, request\r\nfrom flask_login import login_required\r\nfrom jinja2 import TemplateNotFound\r\nimport pandas as pd\r\n@blueprint.route('/index')\r\n@login_required\r\ndef index():\r\n StackedPlotContribution = pd.read_excel (\"/workspace/atlantisTemplateWORKS/apps/data/Dashboard Data.xlsx\",sheet_name='Stacked Plot Contribution')\r\n Display = StackedPlotContribution.iloc[:,1].tolist()\r\n Facebook = StackedPlotContribution.iloc[:,2].tolist()\r\n GooglePLA = StackedPlotContribution.iloc[:,3].tolist()\r\n GoogleSearch = StackedPlotContribution.iloc[:,4].tolist()\r\n Microsoft = StackedPlotContribution.iloc[:,5].tolist()\r\n BaseRevenue = StackedPlotContribution.iloc[:,6].tolist()\r\n labels = StackedPlotContribution.iloc[:,7].tolist()\r\n\r\n return render_template('home/index.html', Display=Display , Facebook = Facebook,GooglePLA =GooglePLA,GoogleSearch =GoogleSearch,Microsoft=Microsoft,BaseRevenue = BaseRevenue,labels = labels)\r\n\r\n\r\n@blueprint.route('/