shahp7575 commited on
Commit
3a7f06a
1 Parent(s): 59a4724

commit files to HF hub

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +3 -0
  2. 00nanhai__captchacker2.jsonl +0 -0
  3. 0xIslamTaha__Python-Rootkit.jsonl +0 -0
  4. 12dmodel__deep_motion_mag.jsonl +7 -0
  5. 1aN0rmus__TekDefense-Automater.jsonl +0 -0
  6. 1tayH__noisy.jsonl +14 -0
  7. 2gis__k8s-handle.jsonl +0 -0
  8. 360netlab__DGA.jsonl +1 -0
  9. 9miao__G-Firefly.jsonl +0 -0
  10. A-bone1__Attention-ocr-Chinese-Version.jsonl +0 -0
  11. A3M4__YouTube-Report.jsonl +1 -0
  12. AIChallenger__AI_Challenger_2017.jsonl +0 -0
  13. Academic-Hammer__SciTSR.jsonl +13 -0
  14. AceLewis__my_first_calculator.py.jsonl +0 -0
  15. AkariAsai__learning_to_retrieve_reasoning_paths.jsonl +0 -0
  16. AlansCodeLog__blender-debugger-for-vscode.jsonl +0 -0
  17. Alex-Fabbri__Multi-News.jsonl +0 -0
  18. AlexTan-b-z__ZhihuSpider.jsonl +42 -0
  19. Alexander-H-Liu__End-to-end-ASR-Pytorch.jsonl +0 -0
  20. AlfredXiangWu__LightCNN.jsonl +1 -0
  21. Algorithm79__Dotfiles_i3.jsonl +0 -0
  22. AlphaMycelium__pathfinder.vim.jsonl +37 -0
  23. AlvarBer__Persimmon.jsonl +33 -0
  24. AnasAboureada__Penetration-Testing-Study-Notes.jsonl +1 -0
  25. AonCyberLabs__EvilAbigail.jsonl +12 -0
  26. Ape__samsungctl.jsonl +6 -0
  27. Azelphur__pyPushBullet.jsonl +15 -0
  28. BIGBALLON__CIFAR-ZOO.jsonl +5 -0
  29. Befzz__blender3d_import_psk_psa.jsonl +0 -0
  30. Behappy123__market-maker.jsonl +0 -0
  31. Billwilliams1952__PiCameraApp.jsonl +11 -0
  32. BishopFox__rickmote.jsonl +47 -0
  33. Blockstream__satellite.jsonl +0 -0
  34. BoboTiG__python-mss.jsonl +45 -0
  35. BrieflyX__ctf-pwns.jsonl +0 -0
  36. CLUEbenchmark__CLUE.jsonl +0 -0
  37. CQFIO__FastImageProcessing.jsonl +0 -0
  38. CR-Gjx__LeakGAN.jsonl +8 -0
  39. Cadene__bootstrap.pytorch.jsonl +26 -0
  40. Cadene__pretrained-models.pytorch.jsonl +0 -0
  41. CalciferZh__minimal-hand.jsonl +16 -0
  42. CamDavidsonPilon__PyProcess.jsonl +38 -0
  43. Chung-I__Variational-Recurrent-Autoencoder-Tensorflow.jsonl +0 -0
  44. ClementPinard__DepthNet.jsonl +2 -0
  45. ClementPinard__Pytorch-Correlation-extension.jsonl +1 -0
  46. ClusterHQ__powerstrip.jsonl +16 -0
  47. CoinCheung__BiSeNet.jsonl +8 -0
  48. Critical-Start__pastebin_scraper.jsonl +4 -0
  49. CroweCybersecurity__ad-ldap-enum.jsonl +4 -0
  50. DataBiosphere__dsub.jsonl +0 -0
.gitattributes CHANGED
@@ -25,3 +25,6 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
25
  *.zip filter=lfs diff=lfs merge=lfs -text
26
  *.zstandard filter=lfs diff=lfs merge=lfs -text
27
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
25
  *.zip filter=lfs diff=lfs merge=lfs -text
26
  *.zstandard filter=lfs diff=lfs merge=lfs -text
27
  *tfevents* filter=lfs diff=lfs merge=lfs -text
28
+ bruderstein__PythonScript.jsonl filter=lfs diff=lfs merge=lfs -text
29
+ securesystemslab__zippy.jsonl filter=lfs diff=lfs merge=lfs -text
30
+ tp4a__teleport.jsonl filter=lfs diff=lfs merge=lfs -text
00nanhai__captchacker2.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
0xIslamTaha__Python-Rootkit.jsonl ADDED
File without changes
12dmodel__deep_motion_mag.jsonl ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {"nwo":"12dmodel\/deep_motion_mag","sha":"485243bd7428d08059c313321b5e6ebfd7f61991","path":"preprocessor.py","language":"python","identifier":"get_possion_noise","parameters":"(image)","argument_list":"","return_statement":"return tf.multiply(n, n_str)","docstring":"Add poisson noise.\n\n This function approximate posson noise upto 2nd order.\n Assume images were in 0-255, and converted to the range of -1 to 1.","docstring_summary":"Add poisson noise.","docstring_tokens":["Add","poisson","noise","."],"function":"def get_possion_noise(image):\n \"\"\"Add poisson noise.\n\n This function approximate posson noise upto 2nd order.\n Assume images were in 0-255, and converted to the range of -1 to 1.\n \"\"\"\n n = tf.random_normal(shape=tf.shape(image), mean=0.0, stddev=1.0)\n # strength ~ sqrt image value in 255, divided by 127.5 to convert\n # back to -1, 1 range.\n n_str = tf.sqrt(image + 1.0) \/ np.sqrt(127.5)\n return tf.multiply(n, n_str)","function_tokens":["def","get_possion_noise","(","image",")",":","n","=","tf",".","random_normal","(","shape","=","tf",".","shape","(","image",")",",","mean","=","0.0",",","stddev","=","1.0",")","# strength ~ sqrt image value in 255, divided by 127.5 to convert","# back to -1, 1 range.","n_str","=","tf",".","sqrt","(","image","+","1.0",")","\/","np",".","sqrt","(","127.5",")","return","tf",".","multiply","(","n",",","n_str",")"],"url":"https:\/\/github.com\/12dmodel\/deep_motion_mag\/blob\/485243bd7428d08059c313321b5e6ebfd7f61991\/preprocessor.py#L16-L26"}
2
+ {"nwo":"12dmodel\/deep_motion_mag","sha":"485243bd7428d08059c313321b5e6ebfd7f61991","path":"ops.py","language":"python","identifier":"expand_dims_1_to_4","parameters":"(tensor, dims=None)","argument_list":"","return_statement":"return tf.expand_dims(\n tf.expand_dims(\n tf.expand_dims(tensor, dims[0]),\n dims[1]),\n dims[2])","docstring":"Expand dimension from 1 to 4.\n\n Useful for multiplying amplification factor.","docstring_summary":"Expand dimension from 1 to 4.","docstring_tokens":["Expand","dimension","from","1","to","4","."],"function":"def expand_dims_1_to_4(tensor, dims=None):\n \"\"\"Expand dimension from 1 to 4.\n\n Useful for multiplying amplification factor.\n \"\"\"\n if not dims:\n dims = [-1, -1, -1]\n return tf.expand_dims(\n tf.expand_dims(\n tf.expand_dims(tensor, dims[0]),\n dims[1]),\n dims[2])","function_tokens":["def","expand_dims_1_to_4","(","tensor",",","dims","=","None",")",":","if","not","dims",":","dims","=","[","-","1",",","-","1",",","-","1","]","return","tf",".","expand_dims","(","tf",".","expand_dims","(","tf",".","expand_dims","(","tensor",",","dims","[","0","]",")",",","dims","[","1","]",")",",","dims","[","2","]",")"],"url":"https:\/\/github.com\/12dmodel\/deep_motion_mag\/blob\/485243bd7428d08059c313321b5e6ebfd7f61991\/ops.py#L77-L88"}
3
+ {"nwo":"12dmodel\/deep_motion_mag","sha":"485243bd7428d08059c313321b5e6ebfd7f61991","path":"magnet.py","language":"python","identifier":"MagNet3Frames.setup_for_inference","parameters":"(self, checkpoint_dir, image_width, image_height)","argument_list":"","return_statement":"","docstring":"Setup model for inference.\n\n Build computation graph, initialize variables, and load checkpoint.","docstring_summary":"Setup model for inference.","docstring_tokens":["Setup","model","for","inference","."],"function":"def setup_for_inference(self, checkpoint_dir, image_width, image_height):\n \"\"\"Setup model for inference.\n\n Build computation graph, initialize variables, and load checkpoint.\n \"\"\"\n self.image_width = image_width\n self.image_height = image_height\n # Figure out image dimension\n self._build_feed_model()\n ginit_op = tf.global_variables_initializer()\n linit_op = tf.local_variables_initializer()\n self.sess.run([ginit_op, linit_op])\n\n if self.load(checkpoint_dir):\n print(\"[*] Load Success\")\n else:\n raise RuntimeError('MagNet: Failed to load checkpoint file.')\n self.is_graph_built = True","function_tokens":["def","setup_for_inference","(","self",",","checkpoint_dir",",","image_width",",","image_height",")",":","self",".","image_width","=","image_width","self",".","image_height","=","image_height","# Figure out image dimension","self",".","_build_feed_model","(",")","ginit_op","=","tf",".","global_variables_initializer","(",")","linit_op","=","tf",".","local_variables_initializer","(",")","self",".","sess",".","run","(","[","ginit_op",",","linit_op","]",")","if","self",".","load","(","checkpoint_dir",")",":","print","(","\"[*] Load Success\"",")","else",":","raise","RuntimeError","(","'MagNet: Failed to load checkpoint file.'",")","self",".","is_graph_built","=","True"],"url":"https:\/\/github.com\/12dmodel\/deep_motion_mag\/blob\/485243bd7428d08059c313321b5e6ebfd7f61991\/magnet.py#L198-L215"}
4
+ {"nwo":"12dmodel\/deep_motion_mag","sha":"485243bd7428d08059c313321b5e6ebfd7f61991","path":"magnet.py","language":"python","identifier":"MagNet3Frames.inference","parameters":"(self, frameA, frameB, amplification_factor)","argument_list":"","return_statement":"return out_amp","docstring":"Run Magnification on two frames.\n\n Args:\n frameA: path to first frame\n frameB: path to second frame\n amplification_factor: float for amplification factor","docstring_summary":"Run Magnification on two frames.","docstring_tokens":["Run","Magnification","on","two","frames","."],"function":"def inference(self, frameA, frameB, amplification_factor):\n \"\"\"Run Magnification on two frames.\n\n Args:\n frameA: path to first frame\n frameB: path to second frame\n amplification_factor: float for amplification factor\n \"\"\"\n in_frames = [load_train_data([frameA, frameB, frameB],\n gray_scale=self.n_channels==1, is_testing=True)]\n in_frames = np.array(in_frames).astype(np.float32)\n\n out_amp = self.sess.run(self.test_output,\n feed_dict={self.test_input: in_frames,\n self.test_amplification_factor:\n [amplification_factor]})\n return out_amp","function_tokens":["def","inference","(","self",",","frameA",",","frameB",",","amplification_factor",")",":","in_frames","=","[","load_train_data","(","[","frameA",",","frameB",",","frameB","]",",","gray_scale","=","self",".","n_channels","==","1",",","is_testing","=","True",")","]","in_frames","=","np",".","array","(","in_frames",")",".","astype","(","np",".","float32",")","out_amp","=","self",".","sess",".","run","(","self",".","test_output",",","feed_dict","=","{","self",".","test_input",":","in_frames",",","self",".","test_amplification_factor",":","[","amplification_factor","]","}",")","return","out_amp"],"url":"https:\/\/github.com\/12dmodel\/deep_motion_mag\/blob\/485243bd7428d08059c313321b5e6ebfd7f61991\/magnet.py#L217-L233"}
5
+ {"nwo":"12dmodel\/deep_motion_mag","sha":"485243bd7428d08059c313321b5e6ebfd7f61991","path":"magnet.py","language":"python","identifier":"MagNet3Frames.run","parameters":"(self,\n checkpoint_dir,\n vid_dir,\n frame_ext,\n out_dir,\n amplification_factor,\n velocity_mag=False)","argument_list":"","return_statement":"","docstring":"Magnify a video in the two-frames mode.\n\n Args:\n checkpoint_dir: checkpoint directory.\n vid_dir: directory containing video frames videos are processed\n in sorted order.\n out_dir: directory to place output frames and resulting video.\n amplification_factor: the amplification factor,\n with 0 being no change.\n velocity_mag: if True, process video in Dynamic mode.","docstring_summary":"Magnify a video in the two-frames mode.","docstring_tokens":["Magnify","a","video","in","the","two","-","frames","mode","."],"function":"def run(self,\n checkpoint_dir,\n vid_dir,\n frame_ext,\n out_dir,\n amplification_factor,\n velocity_mag=False):\n \"\"\"Magnify a video in the two-frames mode.\n\n Args:\n checkpoint_dir: checkpoint directory.\n vid_dir: directory containing video frames videos are processed\n in sorted order.\n out_dir: directory to place output frames and resulting video.\n amplification_factor: the amplification factor,\n with 0 being no change.\n velocity_mag: if True, process video in Dynamic mode.\n \"\"\"\n vid_name = os.path.basename(out_dir)\n # make folder\n mkdir(out_dir)\n vid_frames = sorted(glob(os.path.join(vid_dir, '*.' + frame_ext)))\n first_frame = vid_frames[0]\n im = imread(first_frame)\n image_height, image_width = im.shape\n if not self.is_graph_built:\n self.setup_for_inference(checkpoint_dir, image_width, image_height)\n try:\n i = int(self.ckpt_name.split('-')[-1])\n print(\"Iteration number is {:d}\".format(i))\n vid_name = vid_name + '_' + str(i)\n except:\n print(\"Cannot get iteration number\")\n if velocity_mag:\n print(\"Running in Dynamic mode\")\n\n prev_frame = first_frame\n desc = vid_name if len(vid_name) < 10 else vid_name[:10]\n for frame in tqdm(vid_frames, desc=desc):\n file_name = os.path.basename(frame)\n out_amp = self.inference(prev_frame, frame, amplification_factor)\n\n im_path = os.path.join(out_dir, file_name)\n save_images(out_amp, [1, 1], im_path)\n if velocity_mag:\n prev_frame = frame\n\n # Try to combine it into a video\n call([DEFAULT_VIDEO_CONVERTER, '-y', '-f', 'image2', '-r', '30', '-i',\n os.path.join(out_dir, '%06d.png'), '-c:v', 'libx264',\n os.path.join(out_dir, vid_name + '.mp4')]\n )","function_tokens":["def","run","(","self",",","checkpoint_dir",",","vid_dir",",","frame_ext",",","out_dir",",","amplification_factor",",","velocity_mag","=","False",")",":","vid_name","=","os",".","path",".","basename","(","out_dir",")","# make folder","mkdir","(","out_dir",")","vid_frames","=","sorted","(","glob","(","os",".","path",".","join","(","vid_dir",",","'*.'","+","frame_ext",")",")",")","first_frame","=","vid_frames","[","0","]","im","=","imread","(","first_frame",")","image_height",",","image_width","=","im",".","shape","if","not","self",".","is_graph_built",":","self",".","setup_for_inference","(","checkpoint_dir",",","image_width",",","image_height",")","try",":","i","=","int","(","self",".","ckpt_name",".","split","(","'-'",")","[","-","1","]",")","print","(","\"Iteration number is {:d}\"",".","format","(","i",")",")","vid_name","=","vid_name","+","'_'","+","str","(","i",")","except",":","print","(","\"Cannot get iteration number\"",")","if","velocity_mag",":","print","(","\"Running in Dynamic mode\"",")","prev_frame","=","first_frame","desc","=","vid_name","if","len","(","vid_name",")","<","10","else","vid_name","[",":","10","]","for","frame","in","tqdm","(","vid_frames",",","desc","=","desc",")",":","file_name","=","os",".","path",".","basename","(","frame",")","out_amp","=","self",".","inference","(","prev_frame",",","frame",",","amplification_factor",")","im_path","=","os",".","path",".","join","(","out_dir",",","file_name",")","save_images","(","out_amp",",","[","1",",","1","]",",","im_path",")","if","velocity_mag",":","prev_frame","=","frame","# Try to combine it into a video","call","(","[","DEFAULT_VIDEO_CONVERTER",",","'-y'",",","'-f'",",","'image2'",",","'-r'",",","'30'",",","'-i'",",","os",".","path",".","join","(","out_dir",",","'%06d.png'",")",",","'-c:v'",",","'libx264'",",","os",".","path",".","join","(","out_dir",",","vid_name","+","'.mp4'",")","]",")"],"url":"https:\/\/github.com\/12dmodel\/deep_motion_mag\/blob\/485243bd7428d08059c313321b5e6ebfd7f61991\/magnet.py#L235-L286"}
6
+ {"nwo":"12dmodel\/deep_motion_mag","sha":"485243bd7428d08059c313321b5e6ebfd7f61991","path":"magnet.py","language":"python","identifier":"MagNet3Frames._build_IIR_filtering_graphs","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Assume a_0 = 1","docstring_summary":"Assume a_0 = 1","docstring_tokens":["Assume","a_0","=","1"],"function":"def _build_IIR_filtering_graphs(self):\n \"\"\"\n Assume a_0 = 1\n \"\"\"\n self.input_image = tf.placeholder(tf.float32,\n [1, self.image_height,\n self.image_width,\n self.n_channels],\n name='input_image')\n self.filtered_enc = tf.placeholder(tf.float32,\n [1, None, None,\n self.shape_dims],\n name='filtered_enc')\n self.out_texture_enc = tf.placeholder(tf.float32,\n [1, None, None,\n self.texture_dims],\n name='out_texture_enc')\n self.ref_shape_enc = tf.placeholder(tf.float32,\n [1, None, None,\n self.shape_dims],\n name='ref_shape_enc')\n self.amplification_factor = tf.placeholder(tf.float32, [None],\n name='amplification_factor')\n with tf.variable_scope('ynet_3frames'):\n with tf.variable_scope('encoder'):\n self.texture_enc, self.shape_rep = \\\n self._encoder(self.input_image)\n with tf.variable_scope('manipulator'):\n # set encoder a to zero because we do temporal filtering\n # instead of taking the difference.\n self.out_shape_enc = self.manipulator(0.0,\n self.filtered_enc,\n self.amplification_factor)\n self.out_shape_enc += self.ref_shape_enc - self.filtered_enc\n with tf.variable_scope('decoder'):\n self.output_image = tf.clip_by_value(\n self._decoder(self.out_texture_enc,\n self.out_shape_enc),\n -1.0, 1.0)\n\n self.saver = tf.train.Saver()","function_tokens":["def","_build_IIR_filtering_graphs","(","self",")",":","self",".","input_image","=","tf",".","placeholder","(","tf",".","float32",",","[","1",",","self",".","image_height",",","self",".","image_width",",","self",".","n_channels","]",",","name","=","'input_image'",")","self",".","filtered_enc","=","tf",".","placeholder","(","tf",".","float32",",","[","1",",","None",",","None",",","self",".","shape_dims","]",",","name","=","'filtered_enc'",")","self",".","out_texture_enc","=","tf",".","placeholder","(","tf",".","float32",",","[","1",",","None",",","None",",","self",".","texture_dims","]",",","name","=","'out_texture_enc'",")","self",".","ref_shape_enc","=","tf",".","placeholder","(","tf",".","float32",",","[","1",",","None",",","None",",","self",".","shape_dims","]",",","name","=","'ref_shape_enc'",")","self",".","amplification_factor","=","tf",".","placeholder","(","tf",".","float32",",","[","None","]",",","name","=","'amplification_factor'",")","with","tf",".","variable_scope","(","'ynet_3frames'",")",":","with","tf",".","variable_scope","(","'encoder'",")",":","self",".","texture_enc",",","self",".","shape_rep","=","self",".","_encoder","(","self",".","input_image",")","with","tf",".","variable_scope","(","'manipulator'",")",":","# set encoder a to zero because we do temporal filtering","# instead of taking the difference.","self",".","out_shape_enc","=","self",".","manipulator","(","0.0",",","self",".","filtered_enc",",","self",".","amplification_factor",")","self",".","out_shape_enc","+=","self",".","ref_shape_enc","-","self",".","filtered_enc","with","tf",".","variable_scope","(","'decoder'",")",":","self",".","output_image","=","tf",".","clip_by_value","(","self",".","_decoder","(","self",".","out_texture_enc",",","self",".","out_shape_enc",")",",","-","1.0",",","1.0",")","self",".","saver","=","tf",".","train",".","Saver","(",")"],"url":"https:\/\/github.com\/12dmodel\/deep_motion_mag\/blob\/485243bd7428d08059c313321b5e6ebfd7f61991\/magnet.py#L289-L329"}
7
+ {"nwo":"12dmodel\/deep_motion_mag","sha":"485243bd7428d08059c313321b5e6ebfd7f61991","path":"magnet.py","language":"python","identifier":"MagNet3Frames.run_temporal","parameters":"(self,\n checkpoint_dir,\n vid_dir,\n frame_ext,\n out_dir,\n amplification_factor,\n fl, fh, fs,\n n_filter_tap,\n filter_type)","argument_list":"","return_statement":"","docstring":"Magnify video with a temporal filter.\n\n Args:\n checkpoint_dir: checkpoint directory.\n vid_dir: directory containing video frames videos are processed\n in sorted order.\n out_dir: directory to place output frames and resulting video.\n amplification_factor: the amplification factor,\n with 0 being no change.\n fl: low cutoff frequency.\n fh: high cutoff frequency.\n fs: sampling rate of the video.\n n_filter_tap: number of filter tap to use.\n filter_type: Type of filter to use. Can be one of \"fir\",\n \"butter\", or \"differenceOfIIR\". For \"differenceOfIIR\",\n fl and fh specifies rl and rh coefficients as in Wadhwa et al.","docstring_summary":"Magnify video with a temporal filter.","docstring_tokens":["Magnify","video","with","a","temporal","filter","."],"function":"def run_temporal(self,\n checkpoint_dir,\n vid_dir,\n frame_ext,\n out_dir,\n amplification_factor,\n fl, fh, fs,\n n_filter_tap,\n filter_type):\n \"\"\"Magnify video with a temporal filter.\n\n Args:\n checkpoint_dir: checkpoint directory.\n vid_dir: directory containing video frames videos are processed\n in sorted order.\n out_dir: directory to place output frames and resulting video.\n amplification_factor: the amplification factor,\n with 0 being no change.\n fl: low cutoff frequency.\n fh: high cutoff frequency.\n fs: sampling rate of the video.\n n_filter_tap: number of filter tap to use.\n filter_type: Type of filter to use. Can be one of \"fir\",\n \"butter\", or \"differenceOfIIR\". For \"differenceOfIIR\",\n fl and fh specifies rl and rh coefficients as in Wadhwa et al.\n \"\"\"\n\n nyq = fs \/ 2.0\n if filter_type == 'fir':\n filter_b = firwin(n_filter_tap, [fl, fh], nyq=nyq, pass_zero=False)\n filter_a = []\n elif filter_type == 'butter':\n filter_b, filter_a = butter(n_filter_tap, [fl\/nyq, fh\/nyq],\n btype='bandpass')\n filter_a = filter_a[1:]\n elif filter_type == 'differenceOfIIR':\n # This is a copy of what Neal did. Number of taps are ignored.\n # Treat fl and fh as rl and rh as in Wadhwa's code.\n # Write down the difference of difference equation in Fourier\n # domain to proof this:\n filter_b = [fh - fl, fl - fh]\n filter_a = [-1.0*(2.0 - fh - fl), (1.0 - fl) * (1.0 - fh)]\n else:\n raise ValueError('Filter type must be either '\n '[\"fir\", \"butter\", \"differenceOfIIR\"] got ' + \\\n filter_type)\n head, tail = os.path.split(out_dir)\n tail = tail + '_fl{}_fh{}_fs{}_n{}_{}'.format(fl, fh, fs,\n n_filter_tap,\n filter_type)\n out_dir = os.path.join(head, tail)\n vid_name = os.path.basename(out_dir)\n # make folder\n mkdir(out_dir)\n vid_frames = sorted(glob(os.path.join(vid_dir, '*.' + frame_ext)))\n first_frame = vid_frames[0]\n im = imread(first_frame)\n image_height, image_width = im.shape\n if not self.is_graph_built:\n self.image_width = image_width\n self.image_height = image_height\n # Figure out image dimension\n self._build_IIR_filtering_graphs()\n ginit_op = tf.global_variables_initializer()\n linit_op = tf.local_variables_initializer()\n self.sess.run([ginit_op, linit_op])\n\n if self.load(checkpoint_dir):\n print(\"[*] Load Success\")\n else:\n raise RuntimeError('MagNet: Failed to load checkpoint file.')\n self.is_graph_built = True\n try:\n i = int(self.ckpt_name.split('-')[-1])\n print(\"Iteration number is {:d}\".format(i))\n vid_name = vid_name + '_' + str(i)\n except:\n print(\"Cannot get iteration number\")\n\n if len(filter_a) is not 0:\n x_state = []\n y_state = []\n\n for frame in tqdm(vid_frames, desc='Applying IIR'):\n file_name = os.path.basename(frame)\n frame_no, _ = os.path.splitext(file_name)\n frame_no = int(frame_no)\n in_frames = [load_train_data([frame, frame, frame],\n gray_scale=self.n_channels==1, is_testing=True)]\n in_frames = np.array(in_frames).astype(np.float32)\n\n texture_enc, x = self.sess.run([self.texture_enc, self.shape_rep],\n feed_dict={\n self.input_image:\n in_frames[:, :, :, :3],})\n x_state.insert(0, x)\n # set up initial condition.\n while len(x_state) < len(filter_b):\n x_state.insert(0, x)\n if len(x_state) > len(filter_b):\n x_state = x_state[:len(filter_b)]\n y = np.zeros_like(x)\n for i in range(len(x_state)):\n y += x_state[i] * filter_b[i]\n for i in range(len(y_state)):\n y -= y_state[i] * filter_a[i]\n # update y state\n y_state.insert(0, y)\n if len(y_state) > len(filter_a):\n y_state = y_state[:len(filter_a)]\n\n out_amp = self.sess.run(self.output_image,\n feed_dict={self.out_texture_enc:\n texture_enc,\n self.filtered_enc: y,\n self.ref_shape_enc: x,\n self.amplification_factor:\n [amplification_factor]})\n\n im_path = os.path.join(out_dir, file_name)\n out_amp = np.squeeze(out_amp)\n out_amp = (127.5*(out_amp+1)).astype('uint8')\n cv2.imwrite(im_path, cv2.cvtColor(out_amp,\n code=cv2.COLOR_RGB2BGR))\n else:\n # This does FIR in fourier domain. Equivalent to cyclic\n # convolution.\n x_state = None\n for i, frame in tqdm(enumerate(vid_frames),\n desc='Getting encoding'):\n file_name = os.path.basename(frame)\n in_frames = [load_train_data([frame, frame, frame],\n gray_scale=self.n_channels==1, is_testing=True)]\n in_frames = np.array(in_frames).astype(np.float32)\n\n texture_enc, x = self.sess.run([self.texture_enc, self.shape_rep],\n feed_dict={\n self.input_image:\n in_frames[:, :, :, :3],})\n if x_state is None:\n x_state = np.zeros(x.shape + (len(vid_frames),),\n dtype='float32')\n x_state[:, :, :, :, i] = x\n\n filter_fft = np.fft.fft(np.fft.ifftshift(filter_b),\n n=x_state.shape[-1])\n # Filtering\n for i in trange(x_state.shape[1], desc=\"Applying FIR filter\"):\n x_fft = np.fft.fft(x_state[:, i, :, :], axis=-1)\n x_fft *= filter_fft[np.newaxis, np.newaxis, np.newaxis, :]\n x_state[:, i, :, :] = np.fft.ifft(x_fft)\n\n for i, frame in tqdm(enumerate(vid_frames), desc='Decoding'):\n file_name = os.path.basename(frame)\n frame_no, _ = os.path.splitext(file_name)\n frame_no = int(frame_no)\n in_frames = [load_train_data([frame, frame, frame],\n gray_scale=self.n_channels==1, is_testing=True)]\n in_frames = np.array(in_frames).astype(np.float32)\n texture_enc, _ = self.sess.run([self.texture_enc, self.shape_rep],\n feed_dict={\n self.input_image:\n in_frames[:, :, :, :3],\n })\n out_amp = self.sess.run(self.output_image,\n feed_dict={self.out_texture_enc: texture_enc,\n self.filtered_enc: x_state[:, :, :, :, i],\n self.ref_shape_enc: x,\n self.amplification_factor: [amplification_factor]})\n\n im_path = os.path.join(out_dir, file_name)\n out_amp = np.squeeze(out_amp)\n out_amp = (127.5*(out_amp+1)).astype('uint8')\n cv2.imwrite(im_path, cv2.cvtColor(out_amp,\n code=cv2.COLOR_RGB2BGR))\n del x_state\n\n # Try to combine it into a video\n call([DEFAULT_VIDEO_CONVERTER, '-y', '-f', 'image2', '-r', '30', '-i',\n os.path.join(out_dir, '%06d.png'), '-c:v', 'libx264',\n os.path.join(out_dir, vid_name + '.mp4')]\n )","function_tokens":["def","run_temporal","(","self",",","checkpoint_dir",",","vid_dir",",","frame_ext",",","out_dir",",","amplification_factor",",","fl",",","fh",",","fs",",","n_filter_tap",",","filter_type",")",":","nyq","=","fs","\/","2.0","if","filter_type","==","'fir'",":","filter_b","=","firwin","(","n_filter_tap",",","[","fl",",","fh","]",",","nyq","=","nyq",",","pass_zero","=","False",")","filter_a","=","[","]","elif","filter_type","==","'butter'",":","filter_b",",","filter_a","=","butter","(","n_filter_tap",",","[","fl","\/","nyq",",","fh","\/","nyq","]",",","btype","=","'bandpass'",")","filter_a","=","filter_a","[","1",":","]","elif","filter_type","==","'differenceOfIIR'",":","# This is a copy of what Neal did. Number of taps are ignored.","# Treat fl and fh as rl and rh as in Wadhwa's code.","# Write down the difference of difference equation in Fourier","# domain to proof this:","filter_b","=","[","fh","-","fl",",","fl","-","fh","]","filter_a","=","[","-","1.0","*","(","2.0","-","fh","-","fl",")",",","(","1.0","-","fl",")","*","(","1.0","-","fh",")","]","else",":","raise","ValueError","(","'Filter type must be either '","'[\"fir\", \"butter\", \"differenceOfIIR\"] got '","+","filter_type",")","head",",","tail","=","os",".","path",".","split","(","out_dir",")","tail","=","tail","+","'_fl{}_fh{}_fs{}_n{}_{}'",".","format","(","fl",",","fh",",","fs",",","n_filter_tap",",","filter_type",")","out_dir","=","os",".","path",".","join","(","head",",","tail",")","vid_name","=","os",".","path",".","basename","(","out_dir",")","# make folder","mkdir","(","out_dir",")","vid_frames","=","sorted","(","glob","(","os",".","path",".","join","(","vid_dir",",","'*.'","+","frame_ext",")",")",")","first_frame","=","vid_frames","[","0","]","im","=","imread","(","first_frame",")","image_height",",","image_width","=","im",".","shape","if","not","self",".","is_graph_built",":","self",".","image_width","=","image_width","self",".","image_height","=","image_height","# Figure out image dimension","self",".","_build_IIR_filtering_graphs","(",")","ginit_op","=","tf",".","global_variables_initializer","(",")","linit_op","=","tf",".","local_variables_initializer","(",")","self",".","sess",".","run","(","[","ginit_op",",","linit_op","]",")","if","self",".","load","(","checkpoint_dir",")",":","print","(","\"[*] Load Success\"",")","else",":","raise","RuntimeError","(","'MagNet: Failed to load checkpoint file.'",")","self",".","is_graph_built","=","True","try",":","i","=","int","(","self",".","ckpt_name",".","split","(","'-'",")","[","-","1","]",")","print","(","\"Iteration number is {:d}\"",".","format","(","i",")",")","vid_name","=","vid_name","+","'_'","+","str","(","i",")","except",":","print","(","\"Cannot get iteration number\"",")","if","len","(","filter_a",")","is","not","0",":","x_state","=","[","]","y_state","=","[","]","for","frame","in","tqdm","(","vid_frames",",","desc","=","'Applying IIR'",")",":","file_name","=","os",".","path",".","basename","(","frame",")","frame_no",",","_","=","os",".","path",".","splitext","(","file_name",")","frame_no","=","int","(","frame_no",")","in_frames","=","[","load_train_data","(","[","frame",",","frame",",","frame","]",",","gray_scale","=","self",".","n_channels","==","1",",","is_testing","=","True",")","]","in_frames","=","np",".","array","(","in_frames",")",".","astype","(","np",".","float32",")","texture_enc",",","x","=","self",".","sess",".","run","(","[","self",".","texture_enc",",","self",".","shape_rep","]",",","feed_dict","=","{","self",".","input_image",":","in_frames","[",":",",",":",",",":",",",":","3","]",",","}",")","x_state",".","insert","(","0",",","x",")","# set up initial condition.","while","len","(","x_state",")","<","len","(","filter_b",")",":","x_state",".","insert","(","0",",","x",")","if","len","(","x_state",")",">","len","(","filter_b",")",":","x_state","=","x_state","[",":","len","(","filter_b",")","]","y","=","np",".","zeros_like","(","x",")","for","i","in","range","(","len","(","x_state",")",")",":","y","+=","x_state","[","i","]","*","filter_b","[","i","]","for","i","in","range","(","len","(","y_state",")",")",":","y","-=","y_state","[","i","]","*","filter_a","[","i","]","# update y state","y_state",".","insert","(","0",",","y",")","if","len","(","y_state",")",">","len","(","filter_a",")",":","y_state","=","y_state","[",":","len","(","filter_a",")","]","out_amp","=","self",".","sess",".","run","(","self",".","output_image",",","feed_dict","=","{","self",".","out_texture_enc",":","texture_enc",",","self",".","filtered_enc",":","y",",","self",".","ref_shape_enc",":","x",",","self",".","amplification_factor",":","[","amplification_factor","]","}",")","im_path","=","os",".","path",".","join","(","out_dir",",","file_name",")","out_amp","=","np",".","squeeze","(","out_amp",")","out_amp","=","(","127.5","*","(","out_amp","+","1",")",")",".","astype","(","'uint8'",")","cv2",".","imwrite","(","im_path",",","cv2",".","cvtColor","(","out_amp",",","code","=","cv2",".","COLOR_RGB2BGR",")",")","else",":","# This does FIR in fourier domain. Equivalent to cyclic","# convolution.","x_state","=","None","for","i",",","frame","in","tqdm","(","enumerate","(","vid_frames",")",",","desc","=","'Getting encoding'",")",":","file_name","=","os",".","path",".","basename","(","frame",")","in_frames","=","[","load_train_data","(","[","frame",",","frame",",","frame","]",",","gray_scale","=","self",".","n_channels","==","1",",","is_testing","=","True",")","]","in_frames","=","np",".","array","(","in_frames",")",".","astype","(","np",".","float32",")","texture_enc",",","x","=","self",".","sess",".","run","(","[","self",".","texture_enc",",","self",".","shape_rep","]",",","feed_dict","=","{","self",".","input_image",":","in_frames","[",":",",",":",",",":",",",":","3","]",",","}",")","if","x_state","is","None",":","x_state","=","np",".","zeros","(","x",".","shape","+","(","len","(","vid_frames",")",",",")",",","dtype","=","'float32'",")","x_state","[",":",",",":",",",":",",",":",",","i","]","=","x","filter_fft","=","np",".","fft",".","fft","(","np",".","fft",".","ifftshift","(","filter_b",")",",","n","=","x_state",".","shape","[","-","1","]",")","# Filtering","for","i","in","trange","(","x_state",".","shape","[","1","]",",","desc","=","\"Applying FIR filter\"",")",":","x_fft","=","np",".","fft",".","fft","(","x_state","[",":",",","i",",",":",",",":","]",",","axis","=","-","1",")","x_fft","*=","filter_fft","[","np",".","newaxis",",","np",".","newaxis",",","np",".","newaxis",",",":","]","x_state","[",":",",","i",",",":",",",":","]","=","np",".","fft",".","ifft","(","x_fft",")","for","i",",","frame","in","tqdm","(","enumerate","(","vid_frames",")",",","desc","=","'Decoding'",")",":","file_name","=","os",".","path",".","basename","(","frame",")","frame_no",",","_","=","os",".","path",".","splitext","(","file_name",")","frame_no","=","int","(","frame_no",")","in_frames","=","[","load_train_data","(","[","frame",",","frame",",","frame","]",",","gray_scale","=","self",".","n_channels","==","1",",","is_testing","=","True",")","]","in_frames","=","np",".","array","(","in_frames",")",".","astype","(","np",".","float32",")","texture_enc",",","_","=","self",".","sess",".","run","(","[","self",".","texture_enc",",","self",".","shape_rep","]",",","feed_dict","=","{","self",".","input_image",":","in_frames","[",":",",",":",",",":",",",":","3","]",",","}",")","out_amp","=","self",".","sess",".","run","(","self",".","output_image",",","feed_dict","=","{","self",".","out_texture_enc",":","texture_enc",",","self",".","filtered_enc",":","x_state","[",":",",",":",",",":",",",":",",","i","]",",","self",".","ref_shape_enc",":","x",",","self",".","amplification_factor",":","[","amplification_factor","]","}",")","im_path","=","os",".","path",".","join","(","out_dir",",","file_name",")","out_amp","=","np",".","squeeze","(","out_amp",")","out_amp","=","(","127.5","*","(","out_amp","+","1",")",")",".","astype","(","'uint8'",")","cv2",".","imwrite","(","im_path",",","cv2",".","cvtColor","(","out_amp",",","code","=","cv2",".","COLOR_RGB2BGR",")",")","del","x_state","# Try to combine it into a video","call","(","[","DEFAULT_VIDEO_CONVERTER",",","'-y'",",","'-f'",",","'image2'",",","'-r'",",","'30'",",","'-i'",",","os",".","path",".","join","(","out_dir",",","'%06d.png'",")",",","'-c:v'",",","'libx264'",",","os",".","path",".","join","(","out_dir",",","vid_name","+","'.mp4'",")","]",")"],"url":"https:\/\/github.com\/12dmodel\/deep_motion_mag\/blob\/485243bd7428d08059c313321b5e6ebfd7f61991\/magnet.py#L331-L512"}
1aN0rmus__TekDefense-Automater.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
1tayH__noisy.jsonl ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {"nwo":"1tayH\/noisy","sha":"c21e7682d5626d96d0f6ee56a5ed749078d34aac","path":"noisy.py","language":"python","identifier":"Crawler.__init__","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Initializes the Crawl class","docstring_summary":"Initializes the Crawl class","docstring_tokens":["Initializes","the","Crawl","class"],"function":"def __init__(self):\n \"\"\"\n Initializes the Crawl class\n \"\"\"\n self._config = {}\n self._links = []\n self._start_time = None","function_tokens":["def","__init__","(","self",")",":","self",".","_config","=","{","}","self",".","_links","=","[","]","self",".","_start_time","=","None"],"url":"https:\/\/github.com\/1tayH\/noisy\/blob\/c21e7682d5626d96d0f6ee56a5ed749078d34aac\/noisy.py#L26-L32"}
2
+ {"nwo":"1tayH\/noisy","sha":"c21e7682d5626d96d0f6ee56a5ed749078d34aac","path":"noisy.py","language":"python","identifier":"Crawler._request","parameters":"(self, url)","argument_list":"","return_statement":"return response","docstring":"Sends a POST\/GET requests using a random user agent\n :param url: the url to visit\n :return: the response Requests object","docstring_summary":"Sends a POST\/GET requests using a random user agent\n :param url: the url to visit\n :return: the response Requests object","docstring_tokens":["Sends","a","POST","\/","GET","requests","using","a","random","user","agent",":","param","url",":","the","url","to","visit",":","return",":","the","response","Requests","object"],"function":"def _request(self, url):\n \"\"\"\n Sends a POST\/GET requests using a random user agent\n :param url: the url to visit\n :return: the response Requests object\n \"\"\"\n random_user_agent = random.choice(self._config[\"user_agents\"])\n headers = {'user-agent': random_user_agent}\n\n response = requests.get(url, headers=headers, timeout=5)\n\n return response","function_tokens":["def","_request","(","self",",","url",")",":","random_user_agent","=","random",".","choice","(","self",".","_config","[","\"user_agents\"","]",")","headers","=","{","'user-agent'",":","random_user_agent","}","response","=","requests",".","get","(","url",",","headers","=","headers",",","timeout","=","5",")","return","response"],"url":"https:\/\/github.com\/1tayH\/noisy\/blob\/c21e7682d5626d96d0f6ee56a5ed749078d34aac\/noisy.py#L40-L51"}
3
+ {"nwo":"1tayH\/noisy","sha":"c21e7682d5626d96d0f6ee56a5ed749078d34aac","path":"noisy.py","language":"python","identifier":"Crawler._normalize_link","parameters":"(link, root_url)","argument_list":"","return_statement":"return link","docstring":"Normalizes links extracted from the DOM by making them all absolute, so\n we can request them, for example, turns a \"\/images\" link extracted from https:\/\/imgur.com\n to \"https:\/\/imgur.com\/images\"\n :param link: link found in the DOM\n :param root_url: the URL the DOM was loaded from\n :return: absolute link","docstring_summary":"Normalizes links extracted from the DOM by making them all absolute, so\n we can request them, for example, turns a \"\/images\" link extracted from https:\/\/imgur.com\n to \"https:\/\/imgur.com\/images\"\n :param link: link found in the DOM\n :param root_url: the URL the DOM was loaded from\n :return: absolute link","docstring_tokens":["Normalizes","links","extracted","from","the","DOM","by","making","them","all","absolute","so","we","can","request","them","for","example","turns","a","\/","images","link","extracted","from","https",":","\/\/","imgur",".","com","to","https",":","\/\/","imgur",".","com","\/","images",":","param","link",":","link","found","in","the","DOM",":","param","root_url",":","the","URL","the","DOM","was","loaded","from",":","return",":","absolute","link"],"function":"def _normalize_link(link, root_url):\n \"\"\"\n Normalizes links extracted from the DOM by making them all absolute, so\n we can request them, for example, turns a \"\/images\" link extracted from https:\/\/imgur.com\n to \"https:\/\/imgur.com\/images\"\n :param link: link found in the DOM\n :param root_url: the URL the DOM was loaded from\n :return: absolute link\n \"\"\"\n try:\n parsed_url = urlparse(link)\n except ValueError:\n # urlparse can get confused about urls with the ']'\n # character and thinks it must be a malformed IPv6 URL\n return None\n parsed_root_url = urlparse(root_url)\n\n # '\/\/' means keep the current protocol used to access this URL\n if link.startswith(\"\/\/\"):\n return \"{}:\/\/{}{}\".format(parsed_root_url.scheme, parsed_url.netloc, parsed_url.path)\n\n # possibly a relative path\n if not parsed_url.scheme:\n return urljoin(root_url, link)\n\n return link","function_tokens":["def","_normalize_link","(","link",",","root_url",")",":","try",":","parsed_url","=","urlparse","(","link",")","except","ValueError",":","# urlparse can get confused about urls with the ']'","# character and thinks it must be a malformed IPv6 URL","return","None","parsed_root_url","=","urlparse","(","root_url",")","# '\/\/' means keep the current protocol used to access this URL","if","link",".","startswith","(","\"\/\/\"",")",":","return","\"{}:\/\/{}{}\"",".","format","(","parsed_root_url",".","scheme",",","parsed_url",".","netloc",",","parsed_url",".","path",")","# possibly a relative path","if","not","parsed_url",".","scheme",":","return","urljoin","(","root_url",",","link",")","return","link"],"url":"https:\/\/github.com\/1tayH\/noisy\/blob\/c21e7682d5626d96d0f6ee56a5ed749078d34aac\/noisy.py#L54-L79"}
4
+ {"nwo":"1tayH\/noisy","sha":"c21e7682d5626d96d0f6ee56a5ed749078d34aac","path":"noisy.py","language":"python","identifier":"Crawler._is_valid_url","parameters":"(url)","argument_list":"","return_statement":"return re.match(regex, url) is not None","docstring":"Check if a url is a valid url.\n Used to filter out invalid values that were found in the \"href\" attribute,\n for example \"javascript:void(0)\"\n taken from https:\/\/stackoverflow.com\/questions\/7160737\n :param url: url to be checked\n :return: boolean indicating whether the URL is valid or not","docstring_summary":"Check if a url is a valid url.\n Used to filter out invalid values that were found in the \"href\" attribute,\n for example \"javascript:void(0)\"\n taken from https:\/\/stackoverflow.com\/questions\/7160737\n :param url: url to be checked\n :return: boolean indicating whether the URL is valid or not","docstring_tokens":["Check","if","a","url","is","a","valid","url",".","Used","to","filter","out","invalid","values","that","were","found","in","the","href","attribute","for","example","javascript",":","void","(","0",")","taken","from","https",":","\/\/","stackoverflow",".","com","\/","questions","\/","7160737",":","param","url",":","url","to","be","checked",":","return",":","boolean","indicating","whether","the","URL","is","valid","or","not"],"function":"def _is_valid_url(url):\n \"\"\"\n Check if a url is a valid url.\n Used to filter out invalid values that were found in the \"href\" attribute,\n for example \"javascript:void(0)\"\n taken from https:\/\/stackoverflow.com\/questions\/7160737\n :param url: url to be checked\n :return: boolean indicating whether the URL is valid or not\n \"\"\"\n regex = re.compile(\n r'^(?:http|ftp)s?:\/\/' # http:\/\/ or https:\/\/\n r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\\.)+(?:[A-Z]{2,6}\\.?|[A-Z0-9-]{2,}\\.?)|' # domain...\n r'\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})' # ...or ip\n r'(?::\\d+)?' # optional port\n r'(?:\/?|[\/?]\\S+)$', re.IGNORECASE)\n return re.match(regex, url) is not None","function_tokens":["def","_is_valid_url","(","url",")",":","regex","=","re",".","compile","(","r'^(?:http|ftp)s?:\/\/'","# http:\/\/ or https:\/\/","r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\\.)+(?:[A-Z]{2,6}\\.?|[A-Z0-9-]{2,}\\.?)|'","# domain...","r'\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})'","# ...or ip","r'(?::\\d+)?'","# optional port","r'(?:\/?|[\/?]\\S+)$'",",","re",".","IGNORECASE",")","return","re",".","match","(","regex",",","url",")","is","not","None"],"url":"https:\/\/github.com\/1tayH\/noisy\/blob\/c21e7682d5626d96d0f6ee56a5ed749078d34aac\/noisy.py#L82-L97"}
5
+ {"nwo":"1tayH\/noisy","sha":"c21e7682d5626d96d0f6ee56a5ed749078d34aac","path":"noisy.py","language":"python","identifier":"Crawler._is_blacklisted","parameters":"(self, url)","argument_list":"","return_statement":"return any(blacklisted_url in url for blacklisted_url in self._config[\"blacklisted_urls\"])","docstring":"Checks is a URL is blacklisted\n :param url: full URL\n :return: boolean indicating whether a URL is blacklisted or not","docstring_summary":"Checks is a URL is blacklisted\n :param url: full URL\n :return: boolean indicating whether a URL is blacklisted or not","docstring_tokens":["Checks","is","a","URL","is","blacklisted",":","param","url",":","full","URL",":","return",":","boolean","indicating","whether","a","URL","is","blacklisted","or","not"],"function":"def _is_blacklisted(self, url):\n \"\"\"\n Checks is a URL is blacklisted\n :param url: full URL\n :return: boolean indicating whether a URL is blacklisted or not\n \"\"\"\n return any(blacklisted_url in url for blacklisted_url in self._config[\"blacklisted_urls\"])","function_tokens":["def","_is_blacklisted","(","self",",","url",")",":","return","any","(","blacklisted_url","in","url","for","blacklisted_url","in","self",".","_config","[","\"blacklisted_urls\"","]",")"],"url":"https:\/\/github.com\/1tayH\/noisy\/blob\/c21e7682d5626d96d0f6ee56a5ed749078d34aac\/noisy.py#L99-L105"}
6
+ {"nwo":"1tayH\/noisy","sha":"c21e7682d5626d96d0f6ee56a5ed749078d34aac","path":"noisy.py","language":"python","identifier":"Crawler._should_accept_url","parameters":"(self, url)","argument_list":"","return_statement":"return url and self._is_valid_url(url) and not self._is_blacklisted(url)","docstring":"filters url if it is blacklisted or not valid, we put filtering logic here\n :param url: full url to be checked\n :return: boolean of whether or not the url should be accepted and potentially visited","docstring_summary":"filters url if it is blacklisted or not valid, we put filtering logic here\n :param url: full url to be checked\n :return: boolean of whether or not the url should be accepted and potentially visited","docstring_tokens":["filters","url","if","it","is","blacklisted","or","not","valid","we","put","filtering","logic","here",":","param","url",":","full","url","to","be","checked",":","return",":","boolean","of","whether","or","not","the","url","should","be","accepted","and","potentially","visited"],"function":"def _should_accept_url(self, url):\n \"\"\"\n filters url if it is blacklisted or not valid, we put filtering logic here\n :param url: full url to be checked\n :return: boolean of whether or not the url should be accepted and potentially visited\n \"\"\"\n return url and self._is_valid_url(url) and not self._is_blacklisted(url)","function_tokens":["def","_should_accept_url","(","self",",","url",")",":","return","url","and","self",".","_is_valid_url","(","url",")","and","not","self",".","_is_blacklisted","(","url",")"],"url":"https:\/\/github.com\/1tayH\/noisy\/blob\/c21e7682d5626d96d0f6ee56a5ed749078d34aac\/noisy.py#L107-L113"}
7
+ {"nwo":"1tayH\/noisy","sha":"c21e7682d5626d96d0f6ee56a5ed749078d34aac","path":"noisy.py","language":"python","identifier":"Crawler._extract_urls","parameters":"(self, body, root_url)","argument_list":"","return_statement":"return filtered_urls","docstring":"gathers links to be visited in the future from a web page's body.\n does it by finding \"href\" attributes in the DOM\n :param body: the HTML body to extract links from\n :param root_url: the root URL of the given body\n :return: list of extracted links","docstring_summary":"gathers links to be visited in the future from a web page's body.\n does it by finding \"href\" attributes in the DOM\n :param body: the HTML body to extract links from\n :param root_url: the root URL of the given body\n :return: list of extracted links","docstring_tokens":["gathers","links","to","be","visited","in","the","future","from","a","web","page","s","body",".","does","it","by","finding","href","attributes","in","the","DOM",":","param","body",":","the","HTML","body","to","extract","links","from",":","param","root_url",":","the","root","URL","of","the","given","body",":","return",":","list","of","extracted","links"],"function":"def _extract_urls(self, body, root_url):\n \"\"\"\n gathers links to be visited in the future from a web page's body.\n does it by finding \"href\" attributes in the DOM\n :param body: the HTML body to extract links from\n :param root_url: the root URL of the given body\n :return: list of extracted links\n \"\"\"\n pattern = r\"href=[\\\"'](?!#)(.*?)[\\\"'].*?\" # ignore links starting with #, no point in re-visiting the same page\n urls = re.findall(pattern, str(body))\n\n normalize_urls = [self._normalize_link(url, root_url) for url in urls]\n filtered_urls = list(filter(self._should_accept_url, normalize_urls))\n\n return filtered_urls","function_tokens":["def","_extract_urls","(","self",",","body",",","root_url",")",":","pattern","=","r\"href=[\\\"'](?!#)(.*?)[\\\"'].*?\"","# ignore links starting with #, no point in re-visiting the same page","urls","=","re",".","findall","(","pattern",",","str","(","body",")",")","normalize_urls","=","[","self",".","_normalize_link","(","url",",","root_url",")","for","url","in","urls","]","filtered_urls","=","list","(","filter","(","self",".","_should_accept_url",",","normalize_urls",")",")","return","filtered_urls"],"url":"https:\/\/github.com\/1tayH\/noisy\/blob\/c21e7682d5626d96d0f6ee56a5ed749078d34aac\/noisy.py#L115-L129"}
8
+ {"nwo":"1tayH\/noisy","sha":"c21e7682d5626d96d0f6ee56a5ed749078d34aac","path":"noisy.py","language":"python","identifier":"Crawler._remove_and_blacklist","parameters":"(self, link)","argument_list":"","return_statement":"","docstring":"Removes a link from our current links list\n and blacklists it so we don't visit it in the future\n :param link: link to remove and blacklist","docstring_summary":"Removes a link from our current links list\n and blacklists it so we don't visit it in the future\n :param link: link to remove and blacklist","docstring_tokens":["Removes","a","link","from","our","current","links","list","and","blacklists","it","so","we","don","t","visit","it","in","the","future",":","param","link",":","link","to","remove","and","blacklist"],"function":"def _remove_and_blacklist(self, link):\n \"\"\"\n Removes a link from our current links list\n and blacklists it so we don't visit it in the future\n :param link: link to remove and blacklist\n \"\"\"\n self._config['blacklisted_urls'].append(link)\n del self._links[self._links.index(link)]","function_tokens":["def","_remove_and_blacklist","(","self",",","link",")",":","self",".","_config","[","'blacklisted_urls'","]",".","append","(","link",")","del","self",".","_links","[","self",".","_links",".","index","(","link",")","]"],"url":"https:\/\/github.com\/1tayH\/noisy\/blob\/c21e7682d5626d96d0f6ee56a5ed749078d34aac\/noisy.py#L131-L138"}
9
+ {"nwo":"1tayH\/noisy","sha":"c21e7682d5626d96d0f6ee56a5ed749078d34aac","path":"noisy.py","language":"python","identifier":"Crawler._browse_from_links","parameters":"(self, depth=0)","argument_list":"","return_statement":"","docstring":"Selects a random link out of the available link list and visits it.\n Blacklists any link that is not responsive or that contains no other links.\n Please note that this function is recursive and will keep calling itself until\n a dead end has reached or when we ran out of links\n :param depth: our current link depth","docstring_summary":"Selects a random link out of the available link list and visits it.\n Blacklists any link that is not responsive or that contains no other links.\n Please note that this function is recursive and will keep calling itself until\n a dead end has reached or when we ran out of links\n :param depth: our current link depth","docstring_tokens":["Selects","a","random","link","out","of","the","available","link","list","and","visits","it",".","Blacklists","any","link","that","is","not","responsive","or","that","contains","no","other","links",".","Please","note","that","this","function","is","recursive","and","will","keep","calling","itself","until","a","dead","end","has","reached","or","when","we","ran","out","of","links",":","param","depth",":","our","current","link","depth"],"function":"def _browse_from_links(self, depth=0):\n \"\"\"\n Selects a random link out of the available link list and visits it.\n Blacklists any link that is not responsive or that contains no other links.\n Please note that this function is recursive and will keep calling itself until\n a dead end has reached or when we ran out of links\n :param depth: our current link depth\n \"\"\"\n is_depth_reached = depth >= self._config['max_depth']\n if not len(self._links) or is_depth_reached:\n logging.debug(\"Hit a dead end, moving to the next root URL\")\n # escape from the recursion, we don't have links to continue or we have reached the max depth\n return\n\n if self._is_timeout_reached():\n raise self.CrawlerTimedOut\n\n random_link = random.choice(self._links)\n try:\n logging.info(\"Visiting {}\".format(random_link))\n sub_page = self._request(random_link).content\n sub_links = self._extract_urls(sub_page, random_link)\n\n # sleep for a random amount of time\n time.sleep(random.randrange(self._config[\"min_sleep\"], self._config[\"max_sleep\"]))\n\n # make sure we have more than 1 link to pick from\n if len(sub_links) > 1:\n # extract links from the new page\n self._links = self._extract_urls(sub_page, random_link)\n else:\n # else retry with current link list\n # remove the dead-end link from our list\n self._remove_and_blacklist(random_link)\n\n except requests.exceptions.RequestException:\n logging.debug(\"Exception on URL: %s, removing from list and trying again!\" % random_link)\n self._remove_and_blacklist(random_link)\n\n self._browse_from_links(depth + 1)","function_tokens":["def","_browse_from_links","(","self",",","depth","=","0",")",":","is_depth_reached","=","depth",">=","self",".","_config","[","'max_depth'","]","if","not","len","(","self",".","_links",")","or","is_depth_reached",":","logging",".","debug","(","\"Hit a dead end, moving to the next root URL\"",")","# escape from the recursion, we don't have links to continue or we have reached the max depth","return","if","self",".","_is_timeout_reached","(",")",":","raise","self",".","CrawlerTimedOut","random_link","=","random",".","choice","(","self",".","_links",")","try",":","logging",".","info","(","\"Visiting {}\"",".","format","(","random_link",")",")","sub_page","=","self",".","_request","(","random_link",")",".","content","sub_links","=","self",".","_extract_urls","(","sub_page",",","random_link",")","# sleep for a random amount of time","time",".","sleep","(","random",".","randrange","(","self",".","_config","[","\"min_sleep\"","]",",","self",".","_config","[","\"max_sleep\"","]",")",")","# make sure we have more than 1 link to pick from","if","len","(","sub_links",")",">","1",":","# extract links from the new page","self",".","_links","=","self",".","_extract_urls","(","sub_page",",","random_link",")","else",":","# else retry with current link list","# remove the dead-end link from our list","self",".","_remove_and_blacklist","(","random_link",")","except","requests",".","exceptions",".","RequestException",":","logging",".","debug","(","\"Exception on URL: %s, removing from list and trying again!\"","%","random_link",")","self",".","_remove_and_blacklist","(","random_link",")","self",".","_browse_from_links","(","depth","+","1",")"],"url":"https:\/\/github.com\/1tayH\/noisy\/blob\/c21e7682d5626d96d0f6ee56a5ed749078d34aac\/noisy.py#L140-L179"}
10
+ {"nwo":"1tayH\/noisy","sha":"c21e7682d5626d96d0f6ee56a5ed749078d34aac","path":"noisy.py","language":"python","identifier":"Crawler.load_config_file","parameters":"(self, file_path)","argument_list":"","return_statement":"","docstring":"Loads and decodes a JSON config file, sets the config of the crawler instance\n to the loaded one\n :param file_path: path of the config file\n :return:","docstring_summary":"Loads and decodes a JSON config file, sets the config of the crawler instance\n to the loaded one\n :param file_path: path of the config file\n :return:","docstring_tokens":["Loads","and","decodes","a","JSON","config","file","sets","the","config","of","the","crawler","instance","to","the","loaded","one",":","param","file_path",":","path","of","the","config","file",":","return",":"],"function":"def load_config_file(self, file_path):\n \"\"\"\n Loads and decodes a JSON config file, sets the config of the crawler instance\n to the loaded one\n :param file_path: path of the config file\n :return:\n \"\"\"\n with open(file_path, 'r') as config_file:\n config = json.load(config_file)\n self.set_config(config)","function_tokens":["def","load_config_file","(","self",",","file_path",")",":","with","open","(","file_path",",","'r'",")","as","config_file",":","config","=","json",".","load","(","config_file",")","self",".","set_config","(","config",")"],"url":"https:\/\/github.com\/1tayH\/noisy\/blob\/c21e7682d5626d96d0f6ee56a5ed749078d34aac\/noisy.py#L181-L190"}
11
+ {"nwo":"1tayH\/noisy","sha":"c21e7682d5626d96d0f6ee56a5ed749078d34aac","path":"noisy.py","language":"python","identifier":"Crawler.set_config","parameters":"(self, config)","argument_list":"","return_statement":"","docstring":"Sets the config of the crawler instance to the provided dict\n :param config: dict of configuration options, for example:\n {\n \"root_urls\": [],\n \"blacklisted_urls\": [],\n \"click_depth\": 5\n ...\n }","docstring_summary":"Sets the config of the crawler instance to the provided dict\n :param config: dict of configuration options, for example:\n {\n \"root_urls\": [],\n \"blacklisted_urls\": [],\n \"click_depth\": 5\n ...\n }","docstring_tokens":["Sets","the","config","of","the","crawler","instance","to","the","provided","dict",":","param","config",":","dict","of","configuration","options","for","example",":","{","root_urls",":","[]","blacklisted_urls",":","[]","click_depth",":","5","...","}"],"function":"def set_config(self, config):\n \"\"\"\n Sets the config of the crawler instance to the provided dict\n :param config: dict of configuration options, for example:\n {\n \"root_urls\": [],\n \"blacklisted_urls\": [],\n \"click_depth\": 5\n ...\n }\n \"\"\"\n self._config = config","function_tokens":["def","set_config","(","self",",","config",")",":","self",".","_config","=","config"],"url":"https:\/\/github.com\/1tayH\/noisy\/blob\/c21e7682d5626d96d0f6ee56a5ed749078d34aac\/noisy.py#L192-L203"}
12
+ {"nwo":"1tayH\/noisy","sha":"c21e7682d5626d96d0f6ee56a5ed749078d34aac","path":"noisy.py","language":"python","identifier":"Crawler.set_option","parameters":"(self, option, value)","argument_list":"","return_statement":"","docstring":"Sets a specific key in the config dict\n :param option: the option key in the config, for example: \"max_depth\"\n :param value: value for the option","docstring_summary":"Sets a specific key in the config dict\n :param option: the option key in the config, for example: \"max_depth\"\n :param value: value for the option","docstring_tokens":["Sets","a","specific","key","in","the","config","dict",":","param","option",":","the","option","key","in","the","config","for","example",":","max_depth",":","param","value",":","value","for","the","option"],"function":"def set_option(self, option, value):\n \"\"\"\n Sets a specific key in the config dict\n :param option: the option key in the config, for example: \"max_depth\"\n :param value: value for the option\n \"\"\"\n self._config[option] = value","function_tokens":["def","set_option","(","self",",","option",",","value",")",":","self",".","_config","[","option","]","=","value"],"url":"https:\/\/github.com\/1tayH\/noisy\/blob\/c21e7682d5626d96d0f6ee56a5ed749078d34aac\/noisy.py#L205-L211"}
13
+ {"nwo":"1tayH\/noisy","sha":"c21e7682d5626d96d0f6ee56a5ed749078d34aac","path":"noisy.py","language":"python","identifier":"Crawler._is_timeout_reached","parameters":"(self)","argument_list":"","return_statement":"return is_timeout_set and is_timed_out","docstring":"Determines whether the specified timeout has reached, if no timeout\n is specified then return false\n :return: boolean indicating whether the timeout has reached","docstring_summary":"Determines whether the specified timeout has reached, if no timeout\n is specified then return false\n :return: boolean indicating whether the timeout has reached","docstring_tokens":["Determines","whether","the","specified","timeout","has","reached","if","no","timeout","is","specified","then","return","false",":","return",":","boolean","indicating","whether","the","timeout","has","reached"],"function":"def _is_timeout_reached(self):\n \"\"\"\n Determines whether the specified timeout has reached, if no timeout\n is specified then return false\n :return: boolean indicating whether the timeout has reached\n \"\"\"\n is_timeout_set = self._config[\"timeout\"] is not False # False is set when no timeout is desired\n end_time = self._start_time + datetime.timedelta(seconds=self._config[\"timeout\"])\n is_timed_out = datetime.datetime.now() >= end_time\n\n return is_timeout_set and is_timed_out","function_tokens":["def","_is_timeout_reached","(","self",")",":","is_timeout_set","=","self",".","_config","[","\"timeout\"","]","is","not","False","# False is set when no timeout is desired","end_time","=","self",".","_start_time","+","datetime",".","timedelta","(","seconds","=","self",".","_config","[","\"timeout\"","]",")","is_timed_out","=","datetime",".","datetime",".","now","(",")",">=","end_time","return","is_timeout_set","and","is_timed_out"],"url":"https:\/\/github.com\/1tayH\/noisy\/blob\/c21e7682d5626d96d0f6ee56a5ed749078d34aac\/noisy.py#L213-L223"}
14
+ {"nwo":"1tayH\/noisy","sha":"c21e7682d5626d96d0f6ee56a5ed749078d34aac","path":"noisy.py","language":"python","identifier":"Crawler.crawl","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Collects links from our root urls, stores them and then calls\n `_browse_from_links` to browse them","docstring_summary":"Collects links from our root urls, stores them and then calls\n `_browse_from_links` to browse them","docstring_tokens":["Collects","links","from","our","root","urls","stores","them","and","then","calls","_browse_from_links","to","browse","them"],"function":"def crawl(self):\n \"\"\"\n Collects links from our root urls, stores them and then calls\n `_browse_from_links` to browse them\n \"\"\"\n self._start_time = datetime.datetime.now()\n\n while True:\n url = random.choice(self._config[\"root_urls\"])\n try:\n body = self._request(url).content\n self._links = self._extract_urls(body, url)\n logging.debug(\"found {} links\".format(len(self._links)))\n self._browse_from_links()\n\n except requests.exceptions.RequestException:\n logging.warn(\"Error connecting to root url: {}\".format(url))\n \n except MemoryError:\n logging.warn(\"Error: content at url: {} is exhausting the memory\".format(url))\n\n except LocationParseError:\n logging.warn(\"Error encountered during parsing of: {}\".format(url))\n\n except self.CrawlerTimedOut:\n logging.info(\"Timeout has exceeded, exiting\")\n return","function_tokens":["def","crawl","(","self",")",":","self",".","_start_time","=","datetime",".","datetime",".","now","(",")","while","True",":","url","=","random",".","choice","(","self",".","_config","[","\"root_urls\"","]",")","try",":","body","=","self",".","_request","(","url",")",".","content","self",".","_links","=","self",".","_extract_urls","(","body",",","url",")","logging",".","debug","(","\"found {} links\"",".","format","(","len","(","self",".","_links",")",")",")","self",".","_browse_from_links","(",")","except","requests",".","exceptions",".","RequestException",":","logging",".","warn","(","\"Error connecting to root url: {}\"",".","format","(","url",")",")","except","MemoryError",":","logging",".","warn","(","\"Error: content at url: {} is exhausting the memory\"",".","format","(","url",")",")","except","LocationParseError",":","logging",".","warn","(","\"Error encountered during parsing of: {}\"",".","format","(","url",")",")","except","self",".","CrawlerTimedOut",":","logging",".","info","(","\"Timeout has exceeded, exiting\"",")","return"],"url":"https:\/\/github.com\/1tayH\/noisy\/blob\/c21e7682d5626d96d0f6ee56a5ed749078d34aac\/noisy.py#L225-L251"}
2gis__k8s-handle.jsonl ADDED
File without changes
360netlab__DGA.jsonl ADDED
@@ -0,0 +1 @@
 
 
1
+ {"nwo":"360netlab\/DGA","sha":"f6e1a197556e9925903b1940d401b02b3650e573","path":"code\/shiotob\/dga.py","language":"python","identifier":"get_next_domain","parameters":"(domain, crc, version)","argument_list":"","return_statement":"return domain","docstring":"calculate the new hostname length\n max: 255\/16 = 15\n min: 10","docstring_summary":"calculate the new hostname length\n max: 255\/16 = 15\n min: 10","docstring_tokens":["calculate","the","new","hostname","length","max",":","255","\/","16","=","15","min",":","10"],"function":"def get_next_domain(domain, crc, version):\n qwerty = 'qwertyuiopasdfghjklzxcvbnm123945678'\n\n def sum_of_characters(domain):\n return sum([ord(d) for d in domain[:-3]])\n\n sof = sum_of_characters(domain)\n if version == 2:\n sof ^= crc\n\n ascii_codes = [ord(d) for d in domain] + 100*[0]\n old_hostname_length = len(domain) - 4\n for i in range(0, 66):\n for j in range(0, 66):\n edi = j + i\n if edi < 65:\n p = (old_hostname_length * ascii_codes[j]) \n cl = p ^ ascii_codes[edi] ^ sof\n ascii_codes[edi] = cl & 0xFF\n\n \"\"\"\n calculate the new hostname length\n max: 255\/16 = 15\n min: 10\n \"\"\"\n cx = ((ascii_codes[2]*old_hostname_length) ^ ascii_codes[0]) & 0xFF\n hostname_length = int(cx\/16) # at most 15\n if hostname_length < 10:\n hostname_length = old_hostname_length\n\n \"\"\"\n generate hostname\n \"\"\"\n for i in range(hostname_length):\n index = int(ascii_codes[i]\/8) # max 31 --> last 3 chars of qwerty unreachable\n bl = ord(qwerty[index])\n ascii_codes[i] = bl\n\n hostname = ''.join([chr(a) for a in ascii_codes[:hostname_length]])\n\n \"\"\"\n append .net or .com (alternating)\n \"\"\"\n tld = '.com' if domain.endswith('.net') else '.net'\n domain = hostname + tld\n\n return domain","function_tokens":["def","get_next_domain","(","domain",",","crc",",","version",")",":","qwerty","=","'qwertyuiopasdfghjklzxcvbnm123945678'","def","sum_of_characters","(","domain",")",":","return","sum","(","[","ord","(","d",")","for","d","in","domain","[",":","-","3","]","]",")","sof","=","sum_of_characters","(","domain",")","if","version","==","2",":","sof","^=","crc","ascii_codes","=","[","ord","(","d",")","for","d","in","domain","]","+","100","*","[","0","]","old_hostname_length","=","len","(","domain",")","-","4","for","i","in","range","(","0",",","66",")",":","for","j","in","range","(","0",",","66",")",":","edi","=","j","+","i","if","edi","<","65",":","p","=","(","old_hostname_length","*","ascii_codes","[","j","]",")","cl","=","p","^","ascii_codes","[","edi","]","^","sof","ascii_codes","[","edi","]","=","cl","&","0xFF","cx","=","(","(","ascii_codes","[","2","]","*","old_hostname_length",")","^","ascii_codes","[","0","]",")","&","0xFF","hostname_length","=","int","(","cx","\/","16",")","# at most 15","if","hostname_length","<","10",":","hostname_length","=","old_hostname_length","\"\"\"\n generate hostname\n \"\"\"","for","i","in","range","(","hostname_length",")",":","index","=","int","(","ascii_codes","[","i","]","\/","8",")","# max 31 --> last 3 chars of qwerty unreachable","bl","=","ord","(","qwerty","[","index","]",")","ascii_codes","[","i","]","=","bl","hostname","=","''",".","join","(","[","chr","(","a",")","for","a","in","ascii_codes","[",":","hostname_length","]","]",")","\"\"\"\n append .net or .com (alternating)\n \"\"\"","tld","=","'.com'","if","domain",".","endswith","(","'.net'",")","else","'.net'","domain","=","hostname","+","tld","return","domain"],"url":"https:\/\/github.com\/360netlab\/DGA\/blob\/f6e1a197556e9925903b1940d401b02b3650e573\/code\/shiotob\/dga.py#L78-L124"}
9miao__G-Firefly.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
A-bone1__Attention-ocr-Chinese-Version.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
A3M4__YouTube-Report.jsonl ADDED
@@ -0,0 +1 @@
 
 
1
+ {"nwo":"A3M4\/YouTube-Report","sha":"dcdbc29e8c05fca643da03ca0ae3fa7bd1b8d0a9","path":"parse.py","language":"python","identifier":"HTML._find_times","parameters":"(self)","argument_list":"","return_statement":"return times","docstring":"Find and format times within the HTML file.\n\n Returns\n -------\n times : List[str]\n e.g. \"19 Feb 2013, 11:56:19 UTC Tue\"","docstring_summary":"Find and format times within the HTML file.","docstring_tokens":["Find","and","format","times","within","the","HTML","file","."],"function":"def _find_times(self):\n \"\"\"\n Find and format times within the HTML file.\n\n Returns\n -------\n times : List[str]\n e.g. \"19 Feb 2013, 11:56:19 UTC Tue\"\n \"\"\"\n # Format all matched dates\n times = [\n datetime_obj.strftime(\"%d %b %Y, %H:%M:%S UTC %a\")\n for datetime_obj in self._find_times_datetime()\n ]\n return times","function_tokens":["def","_find_times","(","self",")",":","# Format all matched dates","times","=","[","datetime_obj",".","strftime","(","\"%d %b %Y, %H:%M:%S UTC %a\"",")","for","datetime_obj","in","self",".","_find_times_datetime","(",")","]","return","times"],"url":"https:\/\/github.com\/A3M4\/YouTube-Report\/blob\/dcdbc29e8c05fca643da03ca0ae3fa7bd1b8d0a9\/parse.py#L93-L107"}
AIChallenger__AI_Challenger_2017.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
Academic-Hammer__SciTSR.jsonl ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {"nwo":"Academic-Hammer\/SciTSR","sha":"79954b5143295162ceaf7e9d9af918a29fe12f55","path":"scitsr\/table.py","language":"python","identifier":"Box.__init__","parameters":"(self, pos)","argument_list":"","return_statement":"","docstring":"pos: (x1, x2, y1, y2)","docstring_summary":"pos: (x1, x2, y1, y2)","docstring_tokens":["pos",":","(","x1","x2","y1","y2",")"],"function":"def __init__(self, pos):\n \"\"\"pos: (x1, x2, y1, y2)\"\"\"\n self.set_pos(pos)","function_tokens":["def","__init__","(","self",",","pos",")",":","self",".","set_pos","(","pos",")"],"url":"https:\/\/github.com\/Academic-Hammer\/SciTSR\/blob\/79954b5143295162ceaf7e9d9af918a29fe12f55\/scitsr\/table.py#L30-L32"}
2
+ {"nwo":"Academic-Hammer\/SciTSR","sha":"79954b5143295162ceaf7e9d9af918a29fe12f55","path":"scitsr\/eval.py","language":"python","identifier":"eval_relations","parameters":"(gt:List[List], res:List[List], cmp_blank=True)","argument_list":"","return_statement":"return precision, recall","docstring":"Evaluate results\n\n Args:\n gt: a list of list of Relation\n res: a list of list of Relation","docstring_summary":"Evaluate results","docstring_tokens":["Evaluate","results"],"function":"def eval_relations(gt:List[List], res:List[List], cmp_blank=True):\n \"\"\"Evaluate results\n\n Args:\n gt: a list of list of Relation\n res: a list of list of Relation\n \"\"\"\n\n #TODO to know how to calculate the total recall and prec\n\n assert len(gt) == len(res)\n tot_prec = 0\n tot_recall = 0\n total = 0\n # print(\"evaluating result...\")\n\n # for _gt, _res in tqdm(zip(gt, res)):\n # for _gt, _res in tqdm(zip(gt, res), total=len(gt), desc='eval'):\n idx, t = 0, len(gt) \n for _gt, _res in zip(gt, res):\n idx += 1\n print('Eval %d\/%d (%d%%)' % (idx, t, idx \/ t * 100), ' ' * 45, end='\\r')\n corr = compare_rel(_gt, _res, cmp_blank)\n precision = corr \/ len(_res) if len(_res) != 0 else 0\n recall = corr \/ len(_gt) if len(_gt) != 0 else 0\n tot_prec += precision\n tot_recall += recall\n total += 1\n # print()\n \n precision = tot_prec \/ total\n recall = tot_recall \/ total\n # print(\"Test on %d instances. Precision: %.2f, Recall: %.2f\" % (\n # total, precision, recall))\n return precision, recall","function_tokens":["def","eval_relations","(","gt",":","List","[","List","]",",","res",":","List","[","List","]",",","cmp_blank","=","True",")",":","#TODO to know how to calculate the total recall and prec","assert","len","(","gt",")","==","len","(","res",")","tot_prec","=","0","tot_recall","=","0","total","=","0","# print(\"evaluating result...\")","# for _gt, _res in tqdm(zip(gt, res)):","# for _gt, _res in tqdm(zip(gt, res), total=len(gt), desc='eval'):","idx",",","t","=","0",",","len","(","gt",")","for","_gt",",","_res","in","zip","(","gt",",","res",")",":","idx","+=","1","print","(","'Eval %d\/%d (%d%%)'","%","(","idx",",","t",",","idx","\/","t","*","100",")",",","' '","*","45",",","end","=","'\\r'",")","corr","=","compare_rel","(","_gt",",","_res",",","cmp_blank",")","precision","=","corr","\/","len","(","_res",")","if","len","(","_res",")","!=","0","else","0","recall","=","corr","\/","len","(","_gt",")","if","len","(","_gt",")","!=","0","else","0","tot_prec","+=","precision","tot_recall","+=","recall","total","+=","1","# print()","precision","=","tot_prec","\/","total","recall","=","tot_recall","\/","total","# print(\"Test on %d instances. Precision: %.2f, Recall: %.2f\" % (","# total, precision, recall))","return","precision",",","recall"],"url":"https:\/\/github.com\/Academic-Hammer\/SciTSR\/blob\/79954b5143295162ceaf7e9d9af918a29fe12f55\/scitsr\/eval.py#L30-L64"}
3
+ {"nwo":"Academic-Hammer\/SciTSR","sha":"79954b5143295162ceaf7e9d9af918a29fe12f55","path":"scitsr\/eval.py","language":"python","identifier":"Table2Relations","parameters":"(t:Table)","argument_list":"","return_statement":"return ret","docstring":"Convert a Table object to a List of Relation.","docstring_summary":"Convert a Table object to a List of Relation.","docstring_tokens":["Convert","a","Table","object","to","a","List","of","Relation","."],"function":"def Table2Relations(t:Table):\n \"\"\"Convert a Table object to a List of Relation.\n \"\"\"\n ret = []\n cl = t.coo2cell_id\n # remove duplicates with pair set\n used = set()\n\n # look right\n for r in range(t.row_n):\n for cFrom in range(t.col_n - 1):\n cTo = cFrom + 1\n loop = True\n while loop and cTo < t.col_n:\n fid, tid = cl[r][cFrom], cl[r][cTo]\n if fid != -1 and tid != -1 and fid != tid:\n if (fid, tid) not in used:\n ret.append(Relation(\n from_text=t.cells[fid].text,\n to_text=t.cells[tid].text,\n direction=DIR_HORIZ,\n from_id=fid,\n to_id=tid,\n no_blanks=cTo - cFrom - 1\n ))\n used.add((fid, tid))\n loop = False\n else:\n if fid != -1 and tid != -1 and fid == tid:\n cFrom = cTo\n cTo += 1\n \n # look down\n for c in range(t.col_n):\n for rFrom in range(t.row_n - 1):\n rTo = rFrom + 1\n loop = True\n while loop and rTo < t.row_n:\n fid, tid = cl[rFrom][c], cl[rTo][c]\n if fid != -1 and tid != -1 and fid != tid:\n if (fid, tid) not in used: \n ret.append(Relation(\n from_text=t.cells[fid].text,\n to_text=t.cells[tid].text,\n direction=DIR_VERT,\n from_id=fid,\n to_id=tid,\n no_blanks=rTo - rFrom - 1\n ))\n used.add((fid, tid))\n loop = False\n else:\n if fid != -1 and tid != -1 and fid == tid:\n rFrom = rTo\n rTo += 1\n\n return ret","function_tokens":["def","Table2Relations","(","t",":","Table",")",":","ret","=","[","]","cl","=","t",".","coo2cell_id","# remove duplicates with pair set","used","=","set","(",")","# look right","for","r","in","range","(","t",".","row_n",")",":","for","cFrom","in","range","(","t",".","col_n","-","1",")",":","cTo","=","cFrom","+","1","loop","=","True","while","loop","and","cTo","<","t",".","col_n",":","fid",",","tid","=","cl","[","r","]","[","cFrom","]",",","cl","[","r","]","[","cTo","]","if","fid","!=","-","1","and","tid","!=","-","1","and","fid","!=","tid",":","if","(","fid",",","tid",")","not","in","used",":","ret",".","append","(","Relation","(","from_text","=","t",".","cells","[","fid","]",".","text",",","to_text","=","t",".","cells","[","tid","]",".","text",",","direction","=","DIR_HORIZ",",","from_id","=","fid",",","to_id","=","tid",",","no_blanks","=","cTo","-","cFrom","-","1",")",")","used",".","add","(","(","fid",",","tid",")",")","loop","=","False","else",":","if","fid","!=","-","1","and","tid","!=","-","1","and","fid","==","tid",":","cFrom","=","cTo","cTo","+=","1","# look down","for","c","in","range","(","t",".","col_n",")",":","for","rFrom","in","range","(","t",".","row_n","-","1",")",":","rTo","=","rFrom","+","1","loop","=","True","while","loop","and","rTo","<","t",".","row_n",":","fid",",","tid","=","cl","[","rFrom","]","[","c","]",",","cl","[","rTo","]","[","c","]","if","fid","!=","-","1","and","tid","!=","-","1","and","fid","!=","tid",":","if","(","fid",",","tid",")","not","in","used",":","ret",".","append","(","Relation","(","from_text","=","t",".","cells","[","fid","]",".","text",",","to_text","=","t",".","cells","[","tid","]",".","text",",","direction","=","DIR_VERT",",","from_id","=","fid",",","to_id","=","tid",",","no_blanks","=","rTo","-","rFrom","-","1",")",")","used",".","add","(","(","fid",",","tid",")",")","loop","=","False","else",":","if","fid","!=","-","1","and","tid","!=","-","1","and","fid","==","tid",":","rFrom","=","rTo","rTo","+=","1","return","ret"],"url":"https:\/\/github.com\/Academic-Hammer\/SciTSR\/blob\/79954b5143295162ceaf7e9d9af918a29fe12f55\/scitsr\/eval.py#L89-L145"}
4
+ {"nwo":"Academic-Hammer\/SciTSR","sha":"79954b5143295162ceaf7e9d9af918a29fe12f55","path":"scitsr\/eval.py","language":"python","identifier":"json2Table","parameters":"(json_obj, tid=\"\", splitted_content=False)","argument_list":"","return_statement":"return Table(row_n + 1, col_n + 1, cells, tid)","docstring":"Construct a Table object from json object\n\n Args:\n json_obj: a json object\n Returns:\n a Table object","docstring_summary":"Construct a Table object from json object","docstring_tokens":["Construct","a","Table","object","from","json","object"],"function":"def json2Table(json_obj, tid=\"\", splitted_content=False):\n \"\"\"Construct a Table object from json object\n\n Args:\n json_obj: a json object\n Returns:\n a Table object\n \"\"\"\n jo = json_obj[\"cells\"]\n row_n, col_n = 0, 0\n cells = []\n for co in jo:\n content = co[\"content\"]\n if content is None: continue\n if splitted_content:\n content = \" \".join(content)\n else:\n content = content.strip()\n if content == \"\": continue\n start_row = co[\"start_row\"]\n end_row = co[\"end_row\"]\n start_col = co[\"start_col\"]\n end_col = co[\"end_col\"]\n row_n = max(row_n, end_row)\n col_n = max(col_n, end_col)\n cell = Chunk(content, (start_row, end_row, start_col, end_col))\n cells.append(cell)\n return Table(row_n + 1, col_n + 1, cells, tid)","function_tokens":["def","json2Table","(","json_obj",",","tid","=","\"\"",",","splitted_content","=","False",")",":","jo","=","json_obj","[","\"cells\"","]","row_n",",","col_n","=","0",",","0","cells","=","[","]","for","co","in","jo",":","content","=","co","[","\"content\"","]","if","content","is","None",":","continue","if","splitted_content",":","content","=","\" \"",".","join","(","content",")","else",":","content","=","content",".","strip","(",")","if","content","==","\"\"",":","continue","start_row","=","co","[","\"start_row\"","]","end_row","=","co","[","\"end_row\"","]","start_col","=","co","[","\"start_col\"","]","end_col","=","co","[","\"end_col\"","]","row_n","=","max","(","row_n",",","end_row",")","col_n","=","max","(","col_n",",","end_col",")","cell","=","Chunk","(","content",",","(","start_row",",","end_row",",","start_col",",","end_col",")",")","cells",".","append","(","cell",")","return","Table","(","row_n","+","1",",","col_n","+","1",",","cells",",","tid",")"],"url":"https:\/\/github.com\/Academic-Hammer\/SciTSR\/blob\/79954b5143295162ceaf7e9d9af918a29fe12f55\/scitsr\/eval.py#L147-L174"}
5
+ {"nwo":"Academic-Hammer\/SciTSR","sha":"79954b5143295162ceaf7e9d9af918a29fe12f55","path":"scitsr\/model.py","language":"python","identifier":"Attention.forward","parameters":"(self, x, y, mask)","argument_list":"","return_statement":"return x","docstring":"Shapes:\n mask: [nodes\/edges, edges\/nodes]\n q: [nodes\/edges, h]\n k: [edges\/nodes, h]\n v: [edges\/nodes, h]\n score: [nodes\/edges, edges\/nodes]\n x_atten: [nodes\/edges, h]","docstring_summary":"Shapes:\n mask: [nodes\/edges, edges\/nodes]\n q: [nodes\/edges, h]\n k: [edges\/nodes, h]\n v: [edges\/nodes, h]\n score: [nodes\/edges, edges\/nodes]\n x_atten: [nodes\/edges, h]","docstring_tokens":["Shapes",":","mask",":","[","nodes","\/","edges","edges","\/","nodes","]","q",":","[","nodes","\/","edges","h","]","k",":","[","edges","\/","nodes","h","]","v",":","[","edges","\/","nodes","h","]","score",":","[","nodes","\/","edges","edges","\/","nodes","]","x_atten",":","[","nodes","\/","edges","h","]"],"function":"def forward(self, x, y, mask):\n \"\"\"\n Shapes:\n mask: [nodes\/edges, edges\/nodes]\n q: [nodes\/edges, h]\n k: [edges\/nodes, h]\n v: [edges\/nodes, h]\n score: [nodes\/edges, edges\/nodes]\n x_atten: [nodes\/edges, h]\n \"\"\"\n q = self.linear_q(x)\n k = self.linear_k(y)\n v = self.linear_v(y)\n score = torch.mm(q, k.t()) \/ math.sqrt(self.size)\n score = self.masked_softmax(score, mask, dim=1)\n x_atten = torch.mm(score, v)\n # dropout\n x_atten = self.dropout(x_atten)\n x = self.layer_norm_1(x + x_atten)\n x_linear = self.feed_forward(x)\n # dropout\n x_linear = self.dropout(x_linear)\n x = self.layer_norm_2(x + x_linear)\n return x","function_tokens":["def","forward","(","self",",","x",",","y",",","mask",")",":","q","=","self",".","linear_q","(","x",")","k","=","self",".","linear_k","(","y",")","v","=","self",".","linear_v","(","y",")","score","=","torch",".","mm","(","q",",","k",".","t","(",")",")","\/","math",".","sqrt","(","self",".","size",")","score","=","self",".","masked_softmax","(","score",",","mask",",","dim","=","1",")","x_atten","=","torch",".","mm","(","score",",","v",")","# dropout","x_atten","=","self",".","dropout","(","x_atten",")","x","=","self",".","layer_norm_1","(","x","+","x_atten",")","x_linear","=","self",".","feed_forward","(","x",")","# dropout","x_linear","=","self",".","dropout","(","x_linear",")","x","=","self",".","layer_norm_2","(","x","+","x_linear",")","return","x"],"url":"https:\/\/github.com\/Academic-Hammer\/SciTSR\/blob\/79954b5143295162ceaf7e9d9af918a29fe12f55\/scitsr\/model.py#L38-L61"}
6
+ {"nwo":"Academic-Hammer\/SciTSR","sha":"79954b5143295162ceaf7e9d9af918a29fe12f55","path":"scitsr\/graph.py","language":"python","identifier":"Vertex.__init__","parameters":"(self, vid: int, chunk: Chunk, tab_h, tab_w)","argument_list":"","return_statement":"","docstring":"Args:\n vid: Vertex id\n chunk: the chunk to extract features\n tab_h: height of the table (y-axis)\n tab_w: width of the table (x-axis)","docstring_summary":"Args:\n vid: Vertex id\n chunk: the chunk to extract features\n tab_h: height of the table (y-axis)\n tab_w: width of the table (x-axis)","docstring_tokens":["Args",":","vid",":","Vertex","id","chunk",":","the","chunk","to","extract","features","tab_h",":","height","of","the","table","(","y","-","axis",")","tab_w",":","width","of","the","table","(","x","-","axis",")"],"function":"def __init__(self, vid: int, chunk: Chunk, tab_h, tab_w):\n \"\"\"\n Args:\n vid: Vertex id\n chunk: the chunk to extract features\n tab_h: height of the table (y-axis)\n tab_w: width of the table (x-axis)\n \"\"\"\n self.vid = vid\n self.tab_h = tab_h\n self.tab_w = tab_w\n self.chunk = chunk\n self.features = self.get_features()","function_tokens":["def","__init__","(","self",",","vid",":","int",",","chunk",":","Chunk",",","tab_h",",","tab_w",")",":","self",".","vid","=","vid","self",".","tab_h","=","tab_h","self",".","tab_w","=","tab_w","self",".","chunk","=","chunk","self",".","features","=","self",".","get_features","(",")"],"url":"https:\/\/github.com\/Academic-Hammer\/SciTSR\/blob\/79954b5143295162ceaf7e9d9af918a29fe12f55\/scitsr\/graph.py#L15-L27"}
7
+ {"nwo":"Academic-Hammer\/SciTSR","sha":"79954b5143295162ceaf7e9d9af918a29fe12f55","path":"scitsr\/train.py","language":"python","identifier":"patch_chunks","parameters":"(dataset_folder)","argument_list":"","return_statement":"return 1","docstring":"To patch the all chunk files of the train & test dataset that have the problem of duplicate last character\n\tof the last cell in all chunk files\n\t:param dataset_folder: train dataset path\n\t:return: 1","docstring_summary":"To patch the all chunk files of the train & test dataset that have the problem of duplicate last character\n\tof the last cell in all chunk files\n\t:param dataset_folder: train dataset path\n\t:return: 1","docstring_tokens":["To","patch","the","all","chunk","files","of","the","train","&","test","dataset","that","have","the","problem","of","duplicate","last","character","of","the","last","cell","in","all","chunk","files",":","param","dataset_folder",":","train","dataset","path",":","return",":","1"],"function":"def patch_chunks(dataset_folder):\n\t\"\"\"\n\tTo patch the all chunk files of the train & test dataset that have the problem of duplicate last character\n\tof the last cell in all chunk files\n\t:param dataset_folder: train dataset path\n\t:return: 1\n\t\"\"\"\n\timport os\n\timport shutil\n\tfrom pathlib import Path\n\n\tshutil.move(os.path.join(dataset_folder, \"chunk\"), os.path.join(dataset_folder, \"chunk-old\"))\n\tdir_ = Path(os.path.join(dataset_folder, \"chunk-old\"))\n\tos.makedirs(os.path.join(dataset_folder, \"chunk\"), exist_ok=True)\n\n\tfor chunk_path in dir_.iterdir():\n\t\t# print(chunk_path)\n\t\twith open(str(chunk_path), encoding=\"utf-8\") as f:\n\t\t\tchunks = json.load(f)['chunks']\n\t\tchunks[-1]['text'] = chunks[-1]['text'][:-1]\n\n\t\twith open(str(chunk_path).replace(\"chunk-old\", \"chunk\"), \"w\", encoding=\"utf-8\") as ofile:\n\t\t\tjson.dump({\"chunks\": chunks}, ofile)\n\tprint(\"Input files patched, ready for the use\")\n\treturn 1","function_tokens":["def","patch_chunks","(","dataset_folder",")",":","import","os","import","shutil","from","pathlib","import","Path","shutil",".","move","(","os",".","path",".","join","(","dataset_folder",",","\"chunk\"",")",",","os",".","path",".","join","(","dataset_folder",",","\"chunk-old\"",")",")","dir_","=","Path","(","os",".","path",".","join","(","dataset_folder",",","\"chunk-old\"",")",")","os",".","makedirs","(","os",".","path",".","join","(","dataset_folder",",","\"chunk\"",")",",","exist_ok","=","True",")","for","chunk_path","in","dir_",".","iterdir","(",")",":","# print(chunk_path)","with","open","(","str","(","chunk_path",")",",","encoding","=","\"utf-8\"",")","as","f",":","chunks","=","json",".","load","(","f",")","[","'chunks'","]","chunks","[","-","1","]","[","'text'","]","=","chunks","[","-","1","]","[","'text'","]","[",":","-","1","]","with","open","(","str","(","chunk_path",")",".","replace","(","\"chunk-old\"",",","\"chunk\"",")",",","\"w\"",",","encoding","=","\"utf-8\"",")","as","ofile",":","json",".","dump","(","{","\"chunks\"",":","chunks","}",",","ofile",")","print","(","\"Input files patched, ready for the use\"",")","return","1"],"url":"https:\/\/github.com\/Academic-Hammer\/SciTSR\/blob\/79954b5143295162ceaf7e9d9af918a29fe12f55\/scitsr\/train.py#L146-L170"}
8
+ {"nwo":"Academic-Hammer\/SciTSR","sha":"79954b5143295162ceaf7e9d9af918a29fe12f55","path":"scitsr\/train.py","language":"python","identifier":"Trainer.test_epoch","parameters":"(self, epoch, dataset, should_print=False, use_mask=True)","argument_list":"","return_statement":"return acc","docstring":"use_mask: mask the 0 label","docstring_summary":"use_mask: mask the 0 label","docstring_tokens":["use_mask",":","mask","the","0","label"],"function":"def test_epoch(self, epoch, dataset, should_print=False, use_mask=True):\n \"\"\"\n use_mask: mask the 0 label\n \"\"\"\n self.model.eval()\n acc_list = []\n for index, data in tqdm(enumerate(dataset)):\n self._to_device(data)\n percent = index \/ len(dataset) * 100\n if should_print:\n print('[Epoch %d] Test | Data %d (%d%%): acc: | path: %s' % \\\n (epoch, index, percent, data.path), ' ' * 30, end='\\r')\n outputs = self.model(data.nodes, data.edges, data.adj, data.incidence)\n _lab_len = len(data.labels)\n if use_mask:\n for i in data.labels: \n if i == 0: _lab_len -= 1\n _labels = torch.LongTensor(\n [(-1 if i == 0 else i) for i in data.labels]).to(self.device)\n else: _labels = data.labels\n acc = (outputs.max(dim=1)[1] == _labels).float().sum().item() \/ _lab_len\n acc_list.append(acc)\n # if index % 10 == 0:\n if should_print:\n print('[Epoch %d] Test | Data %d (%d%%): acc: %.3f | path: %s' % \\\n (epoch, index, percent, acc, data.path), ' ' * 30, end='\\n')\n acc = sum(acc_list) \/ len(acc_list)\n return acc","function_tokens":["def","test_epoch","(","self",",","epoch",",","dataset",",","should_print","=","False",",","use_mask","=","True",")",":","self",".","model",".","eval","(",")","acc_list","=","[","]","for","index",",","data","in","tqdm","(","enumerate","(","dataset",")",")",":","self",".","_to_device","(","data",")","percent","=","index","\/","len","(","dataset",")","*","100","if","should_print",":","print","(","'[Epoch %d] Test | Data %d (%d%%): acc: | path: %s'","%","(","epoch",",","index",",","percent",",","data",".","path",")",",","' '","*","30",",","end","=","'\\r'",")","outputs","=","self",".","model","(","data",".","nodes",",","data",".","edges",",","data",".","adj",",","data",".","incidence",")","_lab_len","=","len","(","data",".","labels",")","if","use_mask",":","for","i","in","data",".","labels",":","if","i","==","0",":","_lab_len","-=","1","_labels","=","torch",".","LongTensor","(","[","(","-","1","if","i","==","0","else","i",")","for","i","in","data",".","labels","]",")",".","to","(","self",".","device",")","else",":","_labels","=","data",".","labels","acc","=","(","outputs",".","max","(","dim","=","1",")","[","1","]","==","_labels",")",".","float","(",")",".","sum","(",")",".","item","(",")","\/","_lab_len","acc_list",".","append","(","acc",")","# if index % 10 == 0:","if","should_print",":","print","(","'[Epoch %d] Test | Data %d (%d%%): acc: %.3f | path: %s'","%","(","epoch",",","index",",","percent",",","acc",",","data",".","path",")",",","' '","*","30",",","end","=","'\\n'",")","acc","=","sum","(","acc_list",")","\/","len","(","acc_list",")","return","acc"],"url":"https:\/\/github.com\/Academic-Hammer\/SciTSR\/blob\/79954b5143295162ceaf7e9d9af918a29fe12f55\/scitsr\/train.py#L108-L135"}
9
+ {"nwo":"Academic-Hammer\/SciTSR","sha":"79954b5143295162ceaf7e9d9af918a29fe12f55","path":"scitsr\/data\/utils.py","language":"python","identifier":"json2Table","parameters":"(json_obj, tid=\"\", splitted_content=False)","argument_list":"","return_statement":"return Table(row_n + 1, col_n + 1, cells, tid)","docstring":"Construct a Table object from json object\n Args:\n json_obj: a json object\n Returns:\n a Table object","docstring_summary":"Construct a Table object from json object\n Args:\n json_obj: a json object\n Returns:\n a Table object","docstring_tokens":["Construct","a","Table","object","from","json","object","Args",":","json_obj",":","a","json","object","Returns",":","a","Table","object"],"function":"def json2Table(json_obj, tid=\"\", splitted_content=False):\n \"\"\"Construct a Table object from json object\n Args:\n json_obj: a json object\n Returns:\n a Table object\n \"\"\"\n jo = json_obj[\"cells\"]\n row_n, col_n = 0, 0\n cells = []\n for co in jo:\n content = co[\"content\"]\n if content is None: continue\n if splitted_content:\n content = \" \".join(content)\n else:\n content = content.strip()\n if content == \"\": continue\n start_row = co[\"start_row\"]\n end_row = co[\"end_row\"]\n start_col = co[\"start_col\"]\n end_col = co[\"end_col\"]\n row_n = max(row_n, end_row)\n col_n = max(col_n, end_col)\n cell = Chunk(content, (start_row, end_row, start_col, end_col))\n cells.append(cell)\n return Table(row_n + 1, col_n + 1, cells, tid)","function_tokens":["def","json2Table","(","json_obj",",","tid","=","\"\"",",","splitted_content","=","False",")",":","jo","=","json_obj","[","\"cells\"","]","row_n",",","col_n","=","0",",","0","cells","=","[","]","for","co","in","jo",":","content","=","co","[","\"content\"","]","if","content","is","None",":","continue","if","splitted_content",":","content","=","\" \"",".","join","(","content",")","else",":","content","=","content",".","strip","(",")","if","content","==","\"\"",":","continue","start_row","=","co","[","\"start_row\"","]","end_row","=","co","[","\"end_row\"","]","start_col","=","co","[","\"start_col\"","]","end_col","=","co","[","\"end_col\"","]","row_n","=","max","(","row_n",",","end_row",")","col_n","=","max","(","col_n",",","end_col",")","cell","=","Chunk","(","content",",","(","start_row",",","end_row",",","start_col",",","end_col",")",")","cells",".","append","(","cell",")","return","Table","(","row_n","+","1",",","col_n","+","1",",","cells",",","tid",")"],"url":"https:\/\/github.com\/Academic-Hammer\/SciTSR\/blob\/79954b5143295162ceaf7e9d9af918a29fe12f55\/scitsr\/data\/utils.py#L38-L64"}
10
+ {"nwo":"Academic-Hammer\/SciTSR","sha":"79954b5143295162ceaf7e9d9af918a29fe12f55","path":"scitsr\/data\/utils.py","language":"python","identifier":"add_knn_edges","parameters":"(chunks, relations, k=20, debug=False)","argument_list":"","return_statement":"return relations, recall","docstring":"Add edges according to knn of vertexes.","docstring_summary":"Add edges according to knn of vertexes.","docstring_tokens":["Add","edges","according","to","knn","of","vertexes","."],"function":"def add_knn_edges(chunks, relations, k=20, debug=False):\n \"\"\"Add edges according to knn of vertexes.\n \"\"\"\n edges = set()\n rel_recall = {}\n for i, j, _ in relations:\n edges.add((i, j) if i < j else (j, i))\n rel_recall[(i, j) if i < j else (j, i)] = False\n for i in range(len(chunks)):\n _dis_ij = []\n for j in range(len(chunks)):\n if j == i: continue\n _dis_ij.append((_eul_dis(chunks, i, j), j))\n sorted_dis_ij = sorted(_dis_ij)\n for _, j in sorted_dis_ij[:k]:\n _i, _j = (i, j) if i < j else (j, i)\n if (_i, _j) in rel_recall: rel_recall[(_i, _j)] = True\n if (_i, _j) not in edges:\n edges.add((_i, _j))\n relations.append((_i, _j, 0))\n cnt = 0\n for _, val in rel_recall.items():\n if val: cnt += 1\n recall = 0 if len(rel_recall) == 0 else cnt \/ len(rel_recall)\n if debug:\n print(\"add knn edge. recall:%.3f\" % recall)\n return relations, recall","function_tokens":["def","add_knn_edges","(","chunks",",","relations",",","k","=","20",",","debug","=","False",")",":","edges","=","set","(",")","rel_recall","=","{","}","for","i",",","j",",","_","in","relations",":","edges",".","add","(","(","i",",","j",")","if","i","<","j","else","(","j",",","i",")",")","rel_recall","[","(","i",",","j",")","if","i","<","j","else","(","j",",","i",")","]","=","False","for","i","in","range","(","len","(","chunks",")",")",":","_dis_ij","=","[","]","for","j","in","range","(","len","(","chunks",")",")",":","if","j","==","i",":","continue","_dis_ij",".","append","(","(","_eul_dis","(","chunks",",","i",",","j",")",",","j",")",")","sorted_dis_ij","=","sorted","(","_dis_ij",")","for","_",",","j","in","sorted_dis_ij","[",":","k","]",":","_i",",","_j","=","(","i",",","j",")","if","i","<","j","else","(","j",",","i",")","if","(","_i",",","_j",")","in","rel_recall",":","rel_recall","[","(","_i",",","_j",")","]","=","True","if","(","_i",",","_j",")","not","in","edges",":","edges",".","add","(","(","_i",",","_j",")",")","relations",".","append","(","(","_i",",","_j",",","0",")",")","cnt","=","0","for","_",",","val","in","rel_recall",".","items","(",")",":","if","val",":","cnt","+=","1","recall","=","0","if","len","(","rel_recall",")","==","0","else","cnt","\/","len","(","rel_recall",")","if","debug",":","print","(","\"add knn edge. recall:%.3f\"","%","recall",")","return","relations",",","recall"],"url":"https:\/\/github.com\/Academic-Hammer\/SciTSR\/blob\/79954b5143295162ceaf7e9d9af918a29fe12f55\/scitsr\/data\/utils.py#L120-L146"}
11
+ {"nwo":"Academic-Hammer\/SciTSR","sha":"79954b5143295162ceaf7e9d9af918a29fe12f55","path":"scitsr\/data\/loader.py","language":"python","identifier":"TableDataset.clean_chunk_rel","parameters":"(self, chunks, relations)","argument_list":"","return_statement":"return new_chunks, new_rels","docstring":"Remove null chunks","docstring_summary":"Remove null chunks","docstring_tokens":["Remove","null","chunks"],"function":"def clean_chunk_rel(self, chunks, relations):\n \"\"\"Remove null chunks\"\"\"\n new_chunks = []\n oldid2newid = [-1 for i in range(len(chunks))]\n for i, c in enumerate(chunks):\n if c.x2 == c.x1 or c.y2 == c.y1 or c.text == \"\":\n continue\n oldid2newid[i] = len(new_chunks)\n new_chunks.append(c)\n new_rels = []\n for i, j, t in relations:\n ni = oldid2newid[i]\n nj = oldid2newid[j]\n if ni != -1 and nj != -1: new_rels.append((ni, nj, t))\n return new_chunks, new_rels","function_tokens":["def","clean_chunk_rel","(","self",",","chunks",",","relations",")",":","new_chunks","=","[","]","oldid2newid","=","[","-","1","for","i","in","range","(","len","(","chunks",")",")","]","for","i",",","c","in","enumerate","(","chunks",")",":","if","c",".","x2","==","c",".","x1","or","c",".","y2","==","c",".","y1","or","c",".","text","==","\"\"",":","continue","oldid2newid","[","i","]","=","len","(","new_chunks",")","new_chunks",".","append","(","c",")","new_rels","=","[","]","for","i",",","j",",","t","in","relations",":","ni","=","oldid2newid","[","i","]","nj","=","oldid2newid","[","j","]","if","ni","!=","-","1","and","nj","!=","-","1",":","new_rels",".","append","(","(","ni",",","nj",",","t",")",")","return","new_chunks",",","new_rels"],"url":"https:\/\/github.com\/Academic-Hammer\/SciTSR\/blob\/79954b5143295162ceaf7e9d9af918a29fe12f55\/scitsr\/data\/loader.py#L140-L154"}
12
+ {"nwo":"Academic-Hammer\/SciTSR","sha":"79954b5143295162ceaf7e9d9af918a29fe12f55","path":"scitsr\/data\/rel_gen.py","language":"python","identifier":"dump_iters_as_tsv","parameters":"(filename, iterables, spliter=\"\\t\")","argument_list":"","return_statement":"","docstring":"Dump iters as tsv.\n item1\\titem2\\t... (from iterable1)\n item1\\titem2\\t... (from iterable2)","docstring_summary":"Dump iters as tsv.\n item1\\titem2\\t... (from iterable1)\n item1\\titem2\\t... (from iterable2)","docstring_tokens":["Dump","iters","as","tsv",".","item1","\\","titem2","\\","t","...","(","from","iterable1",")","item1","\\","titem2","\\","t","...","(","from","iterable2",")"],"function":"def dump_iters_as_tsv(filename, iterables, spliter=\"\\t\"):\n \"\"\"\n Dump iters as tsv.\n item1\\titem2\\t... (from iterable1)\n item1\\titem2\\t... (from iterable2)\n \"\"\"\n with open(filename, \"w\") as f:\n for iterable in iterables:\n iterable = [str(i) for i in iterable]\n f.write(spliter.join(iterable) + \"\\n\")","function_tokens":["def","dump_iters_as_tsv","(","filename",",","iterables",",","spliter","=","\"\\t\"",")",":","with","open","(","filename",",","\"w\"",")","as","f",":","for","iterable","in","iterables",":","iterable","=","[","str","(","i",")","for","i","in","iterable","]","f",".","write","(","spliter",".","join","(","iterable",")","+","\"\\n\"",")"],"url":"https:\/\/github.com\/Academic-Hammer\/SciTSR\/blob\/79954b5143295162ceaf7e9d9af918a29fe12f55\/scitsr\/data\/rel_gen.py#L18-L27"}
13
+ {"nwo":"Academic-Hammer\/SciTSR","sha":"79954b5143295162ceaf7e9d9af918a29fe12f55","path":"scitsr\/data\/rel_gen.py","language":"python","identifier":"match","parameters":"(src:dict, trg:dict, src_chunks, trg_chunks, fid)","argument_list":"","return_statement":"return sid2tid","docstring":"Match chunks to latex cells w.r.t. the contents.","docstring_summary":"Match chunks to latex cells w.r.t. the contents.","docstring_tokens":["Match","chunks","to","latex","cells","w",".","r",".","t",".","the","contents","."],"function":"def match(src:dict, trg:dict, src_chunks, trg_chunks, fid):\n \"\"\"Match chunks to latex cells w.r.t. the contents.\"\"\"\n sid2tid = {}\n print(\"--------%s---------------------------\" % fid)\n for stxt, sids in src.items():\n if stxt in trg:\n tids = trg[stxt]\n if len(sids) == 1 and len(tids) == 1: sid2tid[sids[0]] = tids[0]\n elif len(sids) == len(tids):\n schunks = [(sid, src_chunks[sid]) for sid in sids]\n tchunks = [(tid, trg_chunks[tid]) for tid in tids]\n sorted_sc = sorted(schunks, key=lambda x: (-x[1].y1, x[1].x1))\n sorted_tc = sorted(tchunks, key=lambda x: (x[1].x1, x[1].y1))\n for (sid, _), (tid, _) in zip(sorted_sc, sorted_tc):\n sid2tid[sid] = tid\n else: \n print(\"[W] length of sids and tids doesn't match\")\n else: \n print(\"[W] no match for text %s\" % stxt)\n print(\"-----------------------------------------------------------\")\n return sid2tid","function_tokens":["def","match","(","src",":","dict",",","trg",":","dict",",","src_chunks",",","trg_chunks",",","fid",")",":","sid2tid","=","{","}","print","(","\"--------%s---------------------------\"","%","fid",")","for","stxt",",","sids","in","src",".","items","(",")",":","if","stxt","in","trg",":","tids","=","trg","[","stxt","]","if","len","(","sids",")","==","1","and","len","(","tids",")","==","1",":","sid2tid","[","sids","[","0","]","]","=","tids","[","0","]","elif","len","(","sids",")","==","len","(","tids",")",":","schunks","=","[","(","sid",",","src_chunks","[","sid","]",")","for","sid","in","sids","]","tchunks","=","[","(","tid",",","trg_chunks","[","tid","]",")","for","tid","in","tids","]","sorted_sc","=","sorted","(","schunks",",","key","=","lambda","x",":","(","-","x","[","1","]",".","y1",",","x","[","1","]",".","x1",")",")","sorted_tc","=","sorted","(","tchunks",",","key","=","lambda","x",":","(","x","[","1","]",".","x1",",","x","[","1","]",".","y1",")",")","for","(","sid",",","_",")",",","(","tid",",","_",")","in","zip","(","sorted_sc",",","sorted_tc",")",":","sid2tid","[","sid","]","=","tid","else",":","print","(","\"[W] length of sids and tids doesn't match\"",")","else",":","print","(","\"[W] no match for text %s\"","%","stxt",")","print","(","\"-----------------------------------------------------------\"",")","return","sid2tid"],"url":"https:\/\/github.com\/Academic-Hammer\/SciTSR\/blob\/79954b5143295162ceaf7e9d9af918a29fe12f55\/scitsr\/data\/rel_gen.py#L30-L50"}
AceLewis__my_first_calculator.py.jsonl ADDED
File without changes
AkariAsai__learning_to_retrieve_reasoning_paths.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
AlansCodeLog__blender-debugger-for-vscode.jsonl ADDED
File without changes
Alex-Fabbri__Multi-News.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
AlexTan-b-z__ZhihuSpider.jsonl ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {"nwo":"AlexTan-b-z\/ZhihuSpider","sha":"7f35d157fa7f3a7ac8545b386e98286ee2764462","path":"zhihu\/zhihu\/proxy.py","language":"python","identifier":"GetIPPOOLS","parameters":"(num)","argument_list":"","return_statement":"return IPPOOL","docstring":"#\u81ea\u5df1\u83b7\u53d6\u7684ip\n IPPOOLS1=urllib.request.urlopen(\"http:\/\/127.0.0.1:8000\/?types=0&count=20&country=%E5%9B%BD%E5%86%85\").read().decode(\"utf-8\",'ignore')\n IPPOOLS2=re.findall('\\\"(\\d+\\.\\d+\\.\\d+\\.\\d+\\\"\\,\\s*\\d+)',IPPOOLS1)\n IPPOOL=[i.replace('\", ',':') for i in IPPOOLS2]","docstring_summary":"#\u81ea\u5df1\u83b7\u53d6\u7684ip\n IPPOOLS1=urllib.request.urlopen(\"http:\/\/127.0.0.1:8000\/?types=0&count=20&country=%E5%9B%BD%E5%86%85\").read().decode(\"utf-8\",'ignore')\n IPPOOLS2=re.findall('\\\"(\\d+\\.\\d+\\.\\d+\\.\\d+\\\"\\,\\s*\\d+)',IPPOOLS1)\n IPPOOL=[i.replace('\", ',':') for i in IPPOOLS2]","docstring_tokens":["#\u81ea\u5df1\u83b7\u53d6\u7684ip","IPPOOLS1","=","urllib",".","request",".","urlopen","(","http",":","\/\/","127",".","0",".","0",".","1",":","8000","\/","?types","=","0&count","=","20&country","=","%E5%9B%BD%E5%86%85",")",".","read","()",".","decode","(","utf","-","8","ignore",")","IPPOOLS2","=","re",".","findall","(","\\","(","\\","d","+","\\",".","\\","d","+","\\",".","\\","d","+","\\",".","\\","d","+","\\","\\","\\","s","*","\\","d","+",")","IPPOOLS1",")","IPPOOL","=","[","i",".","replace","(",":",")","for","i","in","IPPOOLS2","]"],"function":"def GetIPPOOLS(num):\n #\u5927\u8c61\u4ee3\u7406\u4e70\u7684ip,5\u514320000\u4e2a\uff0c\u6bcf\u5341\u4e2a\u5dee\u4e0d\u591a\u6709\u4e00\u4e2a\u80fd\u7528\n IPPOOL=urllib.request.urlopen(\"http:\/\/tpv.daxiangdaili.com\/ip\/?tid=559480480576119&num=\"+str(num)+\"&operator=1&filter=on&protocol=http&category=2&delay=1\").read().decode(\"utf-8\",\"ignore\").split('\\r\\n')\n '''\n #\u81ea\u5df1\u83b7\u53d6\u7684ip\n IPPOOLS1=urllib.request.urlopen(\"http:\/\/127.0.0.1:8000\/?types=0&count=20&country=%E5%9B%BD%E5%86%85\").read().decode(\"utf-8\",'ignore')\n IPPOOLS2=re.findall('\\\"(\\d+\\.\\d+\\.\\d+\\.\\d+\\\"\\,\\s*\\d+)',IPPOOLS1)\n IPPOOL=[i.replace('\", ',':') for i in IPPOOLS2]\n '''\n return IPPOOL","function_tokens":["def","GetIPPOOLS","(","num",")",":","#\u5927\u8c61\u4ee3\u7406\u4e70\u7684ip,5\u514320000\u4e2a\uff0c\u6bcf\u5341\u4e2a\u5dee\u4e0d\u591a\u6709\u4e00\u4e2a\u80fd\u7528","IPPOOL","=","urllib",".","request",".","urlopen","(","\"http:\/\/tpv.daxiangdaili.com\/ip\/?tid=559480480576119&num=\"","+","str","(","num",")","+","\"&operator=1&filter=on&protocol=http&category=2&delay=1\"",")",".","read","(",")",".","decode","(","\"utf-8\"",",","\"ignore\"",")",".","split","(","'\\r\\n'",")","return","IPPOOL"],"url":"https:\/\/github.com\/AlexTan-b-z\/ZhihuSpider\/blob\/7f35d157fa7f3a7ac8545b386e98286ee2764462\/zhihu\/zhihu\/proxy.py#L17-L26"}
2
+ {"nwo":"AlexTan-b-z\/ZhihuSpider","sha":"7f35d157fa7f3a7ac8545b386e98286ee2764462","path":"zhihu\/zhihu\/proxy.py","language":"python","identifier":"initIPPOOLS","parameters":"(rconn)","argument_list":"","return_statement":"","docstring":"\u628a\u6709\u6548\u7684IP\u5b58\u5165\tREDIS\u6570\u636e\u5e93","docstring_summary":"\u628a\u6709\u6548\u7684IP\u5b58\u5165\tREDIS\u6570\u636e\u5e93","docstring_tokens":["\u628a\u6709\u6548\u7684IP\u5b58\u5165","REDIS\u6570\u636e\u5e93"],"function":"def initIPPOOLS(rconn):\n \"\"\"\u628a\u6709\u6548\u7684IP\u5b58\u5165\tREDIS\u6570\u636e\u5e93\"\"\"\n\n ipNum=len(rconn.keys('IP*'))\n if ipNum<IPPOOLNUM:\n IPPOOLS=GetIPPOOLS(IPPOOLNUM)\n for ipall in IPPOOLS:\n try:\n ip=ipall.split(':')[0]\n port=ipall.split(':')[1]\n telnetlib.Telnet(ip,port=port,timeout=2) #\u68c0\u9a8c\u4ee3\u7406ip\u662f\u5426\u6709\u6548\n except:\n logger.warning(\"The ip is not available !( IP:%s )\" % ipall)\n else:\n logger.warning(\"Get ip Success!( IP:%s )\" % ipall)\n rconn.set(\"IP:%s:10\"%(ipall),ipall) #10 is status\n else:\n logger.warning(\"The number of the IP is %s!\" % str(ipNum))","function_tokens":["def","initIPPOOLS","(","rconn",")",":","ipNum","=","len","(","rconn",".","keys","(","'IP*'",")",")","if","ipNum","<","IPPOOLNUM",":","IPPOOLS","=","GetIPPOOLS","(","IPPOOLNUM",")","for","ipall","in","IPPOOLS",":","try",":","ip","=","ipall",".","split","(","':'",")","[","0","]","port","=","ipall",".","split","(","':'",")","[","1","]","telnetlib",".","Telnet","(","ip",",","port","=","port",",","timeout","=","2",")","#\u68c0\u9a8c\u4ee3\u7406ip\u662f\u5426\u6709\u6548","except",":","logger",".","warning","(","\"The ip is not available !( IP:%s )\"","%","ipall",")","else",":","logger",".","warning","(","\"Get ip Success!( IP:%s )\"","%","ipall",")","rconn",".","set","(","\"IP:%s:10\"","%","(","ipall",")",",","ipall",")","#10 is status","else",":","logger",".","warning","(","\"The number of the IP is %s!\"","%","str","(","ipNum",")",")"],"url":"https:\/\/github.com\/AlexTan-b-z\/ZhihuSpider\/blob\/7f35d157fa7f3a7ac8545b386e98286ee2764462\/zhihu\/zhihu\/proxy.py#L28-L45"}
3
+ {"nwo":"AlexTan-b-z\/ZhihuSpider","sha":"7f35d157fa7f3a7ac8545b386e98286ee2764462","path":"zhihu\/zhihu\/proxy.py","language":"python","identifier":"updateIPPOOLS","parameters":"(rconn,ip,status,flag=0)","argument_list":"","return_statement":"","docstring":"update status","docstring_summary":"update status","docstring_tokens":["update","status"],"function":"def updateIPPOOLS(rconn,ip,status,flag=0): # 0\u4ee3\u8868\u5bf9status\u51cf\u4e00\uff0c-1\u4ee3\u8868\u51cf2\uff0c1\u4ee3\u8868\u52a01\n if int(status) < 1:\n removeIPPOOLS(rconn,ip,status)\n return\n '''update status'''\n if flag == 1: #+status\n if int(status) < 10:\n rconn.delete('IP:'+ ip + ':' + status)\n status = int(status) + 1\n rconn.set(\"IP:%s:%s\"%(ip,str(status)),ip)\n elif flag == -1:\n rconn.delete('IP:'+ ip + ':' + status)\n status = int(status) - 2\n rconn.set(\"IP:%s:%s\"%(ip,str(status)),ip)\n else:\n rconn.delete('IP:'+ ip + ':' + status)\n status = int(status) - 1\n rconn.set(\"IP:%s:%s\"%(ip,str(status)),ip)","function_tokens":["def","updateIPPOOLS","(","rconn",",","ip",",","status",",","flag","=","0",")",":","# 0\u4ee3\u8868\u5bf9status\u51cf\u4e00\uff0c-1\u4ee3\u8868\u51cf2\uff0c1\u4ee3\u8868\u52a01","if","int","(","status",")","<","1",":","removeIPPOOLS","(","rconn",",","ip",",","status",")","return","if","flag","==","1",":","#+status","if","int","(","status",")","<","10",":","rconn",".","delete","(","'IP:'","+","ip","+","':'","+","status",")","status","=","int","(","status",")","+","1","rconn",".","set","(","\"IP:%s:%s\"","%","(","ip",",","str","(","status",")",")",",","ip",")","elif","flag","==","-","1",":","rconn",".","delete","(","'IP:'","+","ip","+","':'","+","status",")","status","=","int","(","status",")","-","2","rconn",".","set","(","\"IP:%s:%s\"","%","(","ip",",","str","(","status",")",")",",","ip",")","else",":","rconn",".","delete","(","'IP:'","+","ip","+","':'","+","status",")","status","=","int","(","status",")","-","1","rconn",".","set","(","\"IP:%s:%s\"","%","(","ip",",","str","(","status",")",")",",","ip",")"],"url":"https:\/\/github.com\/AlexTan-b-z\/ZhihuSpider\/blob\/7f35d157fa7f3a7ac8545b386e98286ee2764462\/zhihu\/zhihu\/proxy.py#L47-L64"}
4
+ {"nwo":"AlexTan-b-z\/ZhihuSpider","sha":"7f35d157fa7f3a7ac8545b386e98286ee2764462","path":"zhihu\/zhihu\/cookie.py","language":"python","identifier":"initCookie","parameters":"(rconn, spiderName)","argument_list":"","return_statement":"","docstring":"\u83b7\u53d6\u6240\u6709\u8d26\u53f7\u7684Cookies\uff0c\u5b58\u5165Redis\u3002\u5982\u679cRedis\u5df2\u6709\u8be5\u8d26\u53f7\u7684Cookie\uff0c\u5219\u4e0d\u518d\u83b7\u53d6\u3002","docstring_summary":"\u83b7\u53d6\u6240\u6709\u8d26\u53f7\u7684Cookies\uff0c\u5b58\u5165Redis\u3002\u5982\u679cRedis\u5df2\u6709\u8be5\u8d26\u53f7\u7684Cookie\uff0c\u5219\u4e0d\u518d\u83b7\u53d6\u3002","docstring_tokens":["\u83b7\u53d6\u6240\u6709\u8d26\u53f7\u7684Cookies\uff0c\u5b58\u5165Redis\u3002\u5982\u679cRedis\u5df2\u6709\u8be5\u8d26\u53f7\u7684Cookie\uff0c\u5219\u4e0d\u518d\u83b7\u53d6\u3002"],"function":"def initCookie(rconn, spiderName):\n \"\"\" \u83b7\u53d6\u6240\u6709\u8d26\u53f7\u7684Cookies\uff0c\u5b58\u5165Redis\u3002\u5982\u679cRedis\u5df2\u6709\u8be5\u8d26\u53f7\u7684Cookie\uff0c\u5219\u4e0d\u518d\u83b7\u53d6\u3002 \"\"\"\n for zhihu in myZhiHu:\n if rconn.get(\"%s:Cookies:%s--%s\" % (spiderName, zhihu[0], zhihu[1])) is None: # 'zhihuspider:Cookies:\u8d26\u53f7--\u5bc6\u7801'\uff0c\u4e3aNone\u5373\u4e0d\u5b58\u5728\u3002\n cookie = getCookie(zhihu[0], zhihu[1],zhihu[2])\n if len(cookie) > 0:\n rconn.set(\"%s:Cookies:%s--%s\" % (spiderName, zhihu[0], zhihu[1]), cookie)\n cookieNum = str(rconn.keys()).count(\"zhihuspider:Cookies\")\n logger.warning(\"The num of the cookies is %s\" % cookieNum)\n if cookieNum == 0:\n logger.warning('Stopping...')\n os.system(\"pause\")","function_tokens":["def","initCookie","(","rconn",",","spiderName",")",":","for","zhihu","in","myZhiHu",":","if","rconn",".","get","(","\"%s:Cookies:%s--%s\"","%","(","spiderName",",","zhihu","[","0","]",",","zhihu","[","1","]",")",")","is","None",":","# 'zhihuspider:Cookies:\u8d26\u53f7--\u5bc6\u7801'\uff0c\u4e3aNone\u5373\u4e0d\u5b58\u5728\u3002","cookie","=","getCookie","(","zhihu","[","0","]",",","zhihu","[","1","]",",","zhihu","[","2","]",")","if","len","(","cookie",")",">","0",":","rconn",".","set","(","\"%s:Cookies:%s--%s\"","%","(","spiderName",",","zhihu","[","0","]",",","zhihu","[","1","]",")",",","cookie",")","cookieNum","=","str","(","rconn",".","keys","(",")",")",".","count","(","\"zhihuspider:Cookies\"",")","logger",".","warning","(","\"The num of the cookies is %s\"","%","cookieNum",")","if","cookieNum","==","0",":","logger",".","warning","(","'Stopping...'",")","os",".","system","(","\"pause\"",")"],"url":"https:\/\/github.com\/AlexTan-b-z\/ZhihuSpider\/blob\/7f35d157fa7f3a7ac8545b386e98286ee2764462\/zhihu\/zhihu\/cookie.py#L145-L156"}
5
+ {"nwo":"AlexTan-b-z\/ZhihuSpider","sha":"7f35d157fa7f3a7ac8545b386e98286ee2764462","path":"zhihu\/zhihu\/cookie.py","language":"python","identifier":"updateCookie","parameters":"(accountText, rconn, spiderName, cookie)","argument_list":"","return_statement":"","docstring":"\u66f4\u65b0\u4e00\u4e2a\u8d26\u53f7\u7684Cookie","docstring_summary":"\u66f4\u65b0\u4e00\u4e2a\u8d26\u53f7\u7684Cookie","docstring_tokens":["\u66f4\u65b0\u4e00\u4e2a\u8d26\u53f7\u7684Cookie"],"function":"def updateCookie(accountText, rconn, spiderName, cookie):\n \"\"\" \u66f4\u65b0\u4e00\u4e2a\u8d26\u53f7\u7684Cookie \"\"\"\n account = accountText.split(\"--\")[0]\n #pdb.set_trace()\n new_cookie = UpdateCookie(account, cookie)\n if len(new_cookie) > 0:\n logger.warning(\"The cookie of %s has been updated successfully!\" % account)\n rconn.set(\"%s:Cookies:%s\" % (spiderName, accountText), new_cookie)\n else:\n logger.warning(\"The cookie of %s updated failed! Remove it!\" % accountText)\n removeCookie(accountText, rconn, spiderName)","function_tokens":["def","updateCookie","(","accountText",",","rconn",",","spiderName",",","cookie",")",":","account","=","accountText",".","split","(","\"--\"",")","[","0","]","#pdb.set_trace()","new_cookie","=","UpdateCookie","(","account",",","cookie",")","if","len","(","new_cookie",")",">","0",":","logger",".","warning","(","\"The cookie of %s has been updated successfully!\"","%","account",")","rconn",".","set","(","\"%s:Cookies:%s\"","%","(","spiderName",",","accountText",")",",","new_cookie",")","else",":","logger",".","warning","(","\"The cookie of %s updated failed! Remove it!\"","%","accountText",")","removeCookie","(","accountText",",","rconn",",","spiderName",")"],"url":"https:\/\/github.com\/AlexTan-b-z\/ZhihuSpider\/blob\/7f35d157fa7f3a7ac8545b386e98286ee2764462\/zhihu\/zhihu\/cookie.py#L158-L168"}
6
+ {"nwo":"AlexTan-b-z\/ZhihuSpider","sha":"7f35d157fa7f3a7ac8545b386e98286ee2764462","path":"zhihu\/zhihu\/cookie.py","language":"python","identifier":"removeCookie","parameters":"(accountText, rconn, spiderName)","argument_list":"","return_statement":"","docstring":"\u5220\u9664\u67d0\u4e2a\u8d26\u53f7\u7684Cookie","docstring_summary":"\u5220\u9664\u67d0\u4e2a\u8d26\u53f7\u7684Cookie","docstring_tokens":["\u5220\u9664\u67d0\u4e2a\u8d26\u53f7\u7684Cookie"],"function":"def removeCookie(accountText, rconn, spiderName):\n \"\"\" \u5220\u9664\u67d0\u4e2a\u8d26\u53f7\u7684Cookie \"\"\"\n rconn.delete(\"%s:Cookies:%s\" % (spiderName, accountText))\n cookieNum = str(rconn.keys()).count(\"zhihuspider:Cookies\")\n logger.warning(\"The num of the cookies left is %s\" % cookieNum)\n if cookieNum == 0:\n logger.warning(\"Stopping...\")\n os.system(\"pause\")","function_tokens":["def","removeCookie","(","accountText",",","rconn",",","spiderName",")",":","rconn",".","delete","(","\"%s:Cookies:%s\"","%","(","spiderName",",","accountText",")",")","cookieNum","=","str","(","rconn",".","keys","(",")",")",".","count","(","\"zhihuspider:Cookies\"",")","logger",".","warning","(","\"The num of the cookies left is %s\"","%","cookieNum",")","if","cookieNum","==","0",":","logger",".","warning","(","\"Stopping...\"",")","os",".","system","(","\"pause\"",")"],"url":"https:\/\/github.com\/AlexTan-b-z\/ZhihuSpider\/blob\/7f35d157fa7f3a7ac8545b386e98286ee2764462\/zhihu\/zhihu\/cookie.py#L170-L177"}
7
+ {"nwo":"AlexTan-b-z\/ZhihuSpider","sha":"7f35d157fa7f3a7ac8545b386e98286ee2764462","path":"zhihu\/zhihu\/scrapy_redis\/scheduler.py","language":"python","identifier":"Scheduler.__init__","parameters":"(self, server,\n persist=False,\n flush_on_start=False,\n queue_key=defaults.SCHEDULER_QUEUE_KEY,\n queue_cls=defaults.SCHEDULER_QUEUE_CLASS,\n dupefilter_key=defaults.SCHEDULER_DUPEFILTER_KEY,\n dupefilter_cls=defaults.SCHEDULER_DUPEFILTER_CLASS,\n idle_before_close=0,\n serializer=None)","argument_list":"","return_statement":"","docstring":"Initialize scheduler.\n\n Parameters\n ----------\n server : Redis\n The redis server instance.\n persist : bool\n Whether to flush requests when closing. Default is False.\n flush_on_start : bool\n Whether to flush requests on start. Default is False.\n queue_key : str\n Requests queue key.\n queue_cls : str\n Importable path to the queue class.\n dupefilter_key : str\n Duplicates filter key.\n dupefilter_cls : str\n Importable path to the dupefilter class.\n idle_before_close : int\n Timeout before giving up.","docstring_summary":"Initialize scheduler.","docstring_tokens":["Initialize","scheduler","."],"function":"def __init__(self, server,\n persist=False,\n flush_on_start=False,\n queue_key=defaults.SCHEDULER_QUEUE_KEY,\n queue_cls=defaults.SCHEDULER_QUEUE_CLASS,\n dupefilter_key=defaults.SCHEDULER_DUPEFILTER_KEY,\n dupefilter_cls=defaults.SCHEDULER_DUPEFILTER_CLASS,\n idle_before_close=0,\n serializer=None):\n \"\"\"Initialize scheduler.\n\n Parameters\n ----------\n server : Redis\n The redis server instance.\n persist : bool\n Whether to flush requests when closing. Default is False.\n flush_on_start : bool\n Whether to flush requests on start. Default is False.\n queue_key : str\n Requests queue key.\n queue_cls : str\n Importable path to the queue class.\n dupefilter_key : str\n Duplicates filter key.\n dupefilter_cls : str\n Importable path to the dupefilter class.\n idle_before_close : int\n Timeout before giving up.\n\n \"\"\"\n if idle_before_close < 0:\n raise TypeError(\"idle_before_close cannot be negative\")\n\n self.server = server\n self.persist = persist\n self.flush_on_start = flush_on_start\n self.queue_key = queue_key\n self.queue_cls = queue_cls\n self.dupefilter_cls = dupefilter_cls\n self.dupefilter_key = dupefilter_key\n self.idle_before_close = idle_before_close\n self.serializer = serializer\n self.stats = None","function_tokens":["def","__init__","(","self",",","server",",","persist","=","False",",","flush_on_start","=","False",",","queue_key","=","defaults",".","SCHEDULER_QUEUE_KEY",",","queue_cls","=","defaults",".","SCHEDULER_QUEUE_CLASS",",","dupefilter_key","=","defaults",".","SCHEDULER_DUPEFILTER_KEY",",","dupefilter_cls","=","defaults",".","SCHEDULER_DUPEFILTER_CLASS",",","idle_before_close","=","0",",","serializer","=","None",")",":","if","idle_before_close","<","0",":","raise","TypeError","(","\"idle_before_close cannot be negative\"",")","self",".","server","=","server","self",".","persist","=","persist","self",".","flush_on_start","=","flush_on_start","self",".","queue_key","=","queue_key","self",".","queue_cls","=","queue_cls","self",".","dupefilter_cls","=","dupefilter_cls","self",".","dupefilter_key","=","dupefilter_key","self",".","idle_before_close","=","idle_before_close","self",".","serializer","=","serializer","self",".","stats","=","None"],"url":"https:\/\/github.com\/AlexTan-b-z\/ZhihuSpider\/blob\/7f35d157fa7f3a7ac8545b386e98286ee2764462\/zhihu\/zhihu\/scrapy_redis\/scheduler.py#L34-L77"}
8
+ {"nwo":"AlexTan-b-z\/ZhihuSpider","sha":"7f35d157fa7f3a7ac8545b386e98286ee2764462","path":"zhihu\/zhihu\/scrapy_redis\/pipelines.py","language":"python","identifier":"RedisPipeline.__init__","parameters":"(self, server,\n key=defaults.PIPELINE_KEY,\n serialize_func=default_serialize)","argument_list":"","return_statement":"","docstring":"Initialize pipeline.\n\n Parameters\n ----------\n server : StrictRedis\n Redis client instance.\n key : str\n Redis key where to store items.\n serialize_func : callable\n Items serializer function.","docstring_summary":"Initialize pipeline.","docstring_tokens":["Initialize","pipeline","."],"function":"def __init__(self, server,\n key=defaults.PIPELINE_KEY,\n serialize_func=default_serialize):\n \"\"\"Initialize pipeline.\n\n Parameters\n ----------\n server : StrictRedis\n Redis client instance.\n key : str\n Redis key where to store items.\n serialize_func : callable\n Items serializer function.\n\n \"\"\"\n self.server = server\n self.key = key\n self.serialize = serialize_func","function_tokens":["def","__init__","(","self",",","server",",","key","=","defaults",".","PIPELINE_KEY",",","serialize_func","=","default_serialize",")",":","self",".","server","=","server","self",".","key","=","key","self",".","serialize","=","serialize_func"],"url":"https:\/\/github.com\/AlexTan-b-z\/ZhihuSpider\/blob\/7f35d157fa7f3a7ac8545b386e98286ee2764462\/zhihu\/zhihu\/scrapy_redis\/pipelines.py#L23-L40"}
9
+ {"nwo":"AlexTan-b-z\/ZhihuSpider","sha":"7f35d157fa7f3a7ac8545b386e98286ee2764462","path":"zhihu\/zhihu\/scrapy_redis\/pipelines.py","language":"python","identifier":"RedisPipeline.item_key","parameters":"(self, item, spider)","argument_list":"","return_statement":"return self.key % {'spider': spider.name}","docstring":"Returns redis key based on given spider.\n\n Override this function to use a different key depending on the item\n and\/or spider.","docstring_summary":"Returns redis key based on given spider.","docstring_tokens":["Returns","redis","key","based","on","given","spider","."],"function":"def item_key(self, item, spider):\n \"\"\"Returns redis key based on given spider.\n\n Override this function to use a different key depending on the item\n and\/or spider.\n\n \"\"\"\n return self.key % {'spider': spider.name}","function_tokens":["def","item_key","(","self",",","item",",","spider",")",":","return","self",".","key","%","{","'spider'",":","spider",".","name","}"],"url":"https:\/\/github.com\/AlexTan-b-z\/ZhihuSpider\/blob\/7f35d157fa7f3a7ac8545b386e98286ee2764462\/zhihu\/zhihu\/scrapy_redis\/pipelines.py#L69-L76"}
10
+ {"nwo":"AlexTan-b-z\/ZhihuSpider","sha":"7f35d157fa7f3a7ac8545b386e98286ee2764462","path":"zhihu\/zhihu\/scrapy_redis\/queue.py","language":"python","identifier":"Base.__init__","parameters":"(self, server, spider, key, serializer=None)","argument_list":"","return_statement":"","docstring":"Initialize per-spider redis queue.\n\n Parameters\n ----------\n server : StrictRedis\n Redis client instance.\n spider : Spider\n Scrapy spider instance.\n key: str\n Redis key where to put and get messages.\n serializer : object\n Serializer object with ``loads`` and ``dumps`` methods.","docstring_summary":"Initialize per-spider redis queue.","docstring_tokens":["Initialize","per","-","spider","redis","queue","."],"function":"def __init__(self, server, spider, key, serializer=None):\n \"\"\"Initialize per-spider redis queue.\n\n Parameters\n ----------\n server : StrictRedis\n Redis client instance.\n spider : Spider\n Scrapy spider instance.\n key: str\n Redis key where to put and get messages.\n serializer : object\n Serializer object with ``loads`` and ``dumps`` methods.\n\n \"\"\"\n if serializer is None:\n # Backward compatibility.\n # TODO: deprecate pickle.\n serializer = picklecompat\n if not hasattr(serializer, 'loads'):\n raise TypeError(\"serializer does not implement 'loads' function: %r\"\n % serializer)\n if not hasattr(serializer, 'dumps'):\n raise TypeError(\"serializer '%s' does not implement 'dumps' function: %r\"\n % serializer)\n\n self.server = server\n self.spider = spider\n self.key = key % {'spider': spider.name}\n self.serializer = serializer","function_tokens":["def","__init__","(","self",",","server",",","spider",",","key",",","serializer","=","None",")",":","if","serializer","is","None",":","# Backward compatibility.","# TODO: deprecate pickle.","serializer","=","picklecompat","if","not","hasattr","(","serializer",",","'loads'",")",":","raise","TypeError","(","\"serializer does not implement 'loads' function: %r\"","%","serializer",")","if","not","hasattr","(","serializer",",","'dumps'",")",":","raise","TypeError","(","\"serializer '%s' does not implement 'dumps' function: %r\"","%","serializer",")","self",".","server","=","server","self",".","spider","=","spider","self",".","key","=","key","%","{","'spider'",":","spider",".","name","}","self",".","serializer","=","serializer"],"url":"https:\/\/github.com\/AlexTan-b-z\/ZhihuSpider\/blob\/7f35d157fa7f3a7ac8545b386e98286ee2764462\/zhihu\/zhihu\/scrapy_redis\/queue.py#L9-L38"}
11
+ {"nwo":"AlexTan-b-z\/ZhihuSpider","sha":"7f35d157fa7f3a7ac8545b386e98286ee2764462","path":"zhihu\/zhihu\/scrapy_redis\/queue.py","language":"python","identifier":"Base._encode_request","parameters":"(self, request)","argument_list":"","return_statement":"return self.serializer.dumps(obj)","docstring":"Encode a request object","docstring_summary":"Encode a request object","docstring_tokens":["Encode","a","request","object"],"function":"def _encode_request(self, request):\n \"\"\"Encode a request object\"\"\"\n obj = request_to_dict(request, self.spider)\n return self.serializer.dumps(obj)","function_tokens":["def","_encode_request","(","self",",","request",")",":","obj","=","request_to_dict","(","request",",","self",".","spider",")","return","self",".","serializer",".","dumps","(","obj",")"],"url":"https:\/\/github.com\/AlexTan-b-z\/ZhihuSpider\/blob\/7f35d157fa7f3a7ac8545b386e98286ee2764462\/zhihu\/zhihu\/scrapy_redis\/queue.py#L40-L43"}
12
+ {"nwo":"AlexTan-b-z\/ZhihuSpider","sha":"7f35d157fa7f3a7ac8545b386e98286ee2764462","path":"zhihu\/zhihu\/scrapy_redis\/queue.py","language":"python","identifier":"Base._decode_request","parameters":"(self, encoded_request)","argument_list":"","return_statement":"return request_from_dict(obj, self.spider)","docstring":"Decode an request previously encoded","docstring_summary":"Decode an request previously encoded","docstring_tokens":["Decode","an","request","previously","encoded"],"function":"def _decode_request(self, encoded_request):\n \"\"\"Decode an request previously encoded\"\"\"\n obj = self.serializer.loads(encoded_request)\n return request_from_dict(obj, self.spider)","function_tokens":["def","_decode_request","(","self",",","encoded_request",")",":","obj","=","self",".","serializer",".","loads","(","encoded_request",")","return","request_from_dict","(","obj",",","self",".","spider",")"],"url":"https:\/\/github.com\/AlexTan-b-z\/ZhihuSpider\/blob\/7f35d157fa7f3a7ac8545b386e98286ee2764462\/zhihu\/zhihu\/scrapy_redis\/queue.py#L45-L48"}
13
+ {"nwo":"AlexTan-b-z\/ZhihuSpider","sha":"7f35d157fa7f3a7ac8545b386e98286ee2764462","path":"zhihu\/zhihu\/scrapy_redis\/queue.py","language":"python","identifier":"Base.__len__","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Return the length of the queue","docstring_summary":"Return the length of the queue","docstring_tokens":["Return","the","length","of","the","queue"],"function":"def __len__(self):\n \"\"\"Return the length of the queue\"\"\"\n raise NotImplementedError","function_tokens":["def","__len__","(","self",")",":","raise","NotImplementedError"],"url":"https:\/\/github.com\/AlexTan-b-z\/ZhihuSpider\/blob\/7f35d157fa7f3a7ac8545b386e98286ee2764462\/zhihu\/zhihu\/scrapy_redis\/queue.py#L50-L52"}
14
+ {"nwo":"AlexTan-b-z\/ZhihuSpider","sha":"7f35d157fa7f3a7ac8545b386e98286ee2764462","path":"zhihu\/zhihu\/scrapy_redis\/queue.py","language":"python","identifier":"Base.push","parameters":"(self, request)","argument_list":"","return_statement":"","docstring":"Push a request","docstring_summary":"Push a request","docstring_tokens":["Push","a","request"],"function":"def push(self, request):\n \"\"\"Push a request\"\"\"\n raise NotImplementedError","function_tokens":["def","push","(","self",",","request",")",":","raise","NotImplementedError"],"url":"https:\/\/github.com\/AlexTan-b-z\/ZhihuSpider\/blob\/7f35d157fa7f3a7ac8545b386e98286ee2764462\/zhihu\/zhihu\/scrapy_redis\/queue.py#L54-L56"}
15
+ {"nwo":"AlexTan-b-z\/ZhihuSpider","sha":"7f35d157fa7f3a7ac8545b386e98286ee2764462","path":"zhihu\/zhihu\/scrapy_redis\/queue.py","language":"python","identifier":"Base.pop","parameters":"(self, timeout=0)","argument_list":"","return_statement":"","docstring":"Pop a request","docstring_summary":"Pop a request","docstring_tokens":["Pop","a","request"],"function":"def pop(self, timeout=0):\n \"\"\"Pop a request\"\"\"\n raise NotImplementedError","function_tokens":["def","pop","(","self",",","timeout","=","0",")",":","raise","NotImplementedError"],"url":"https:\/\/github.com\/AlexTan-b-z\/ZhihuSpider\/blob\/7f35d157fa7f3a7ac8545b386e98286ee2764462\/zhihu\/zhihu\/scrapy_redis\/queue.py#L58-L60"}
16
+ {"nwo":"AlexTan-b-z\/ZhihuSpider","sha":"7f35d157fa7f3a7ac8545b386e98286ee2764462","path":"zhihu\/zhihu\/scrapy_redis\/queue.py","language":"python","identifier":"Base.clear","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Clear queue\/stack","docstring_summary":"Clear queue\/stack","docstring_tokens":["Clear","queue","\/","stack"],"function":"def clear(self):\n \"\"\"Clear queue\/stack\"\"\"\n self.server.delete(self.key)","function_tokens":["def","clear","(","self",")",":","self",".","server",".","delete","(","self",".","key",")"],"url":"https:\/\/github.com\/AlexTan-b-z\/ZhihuSpider\/blob\/7f35d157fa7f3a7ac8545b386e98286ee2764462\/zhihu\/zhihu\/scrapy_redis\/queue.py#L62-L64"}
17
+ {"nwo":"AlexTan-b-z\/ZhihuSpider","sha":"7f35d157fa7f3a7ac8545b386e98286ee2764462","path":"zhihu\/zhihu\/scrapy_redis\/queue.py","language":"python","identifier":"FifoQueue.__len__","parameters":"(self)","argument_list":"","return_statement":"return self.server.llen(self.key)","docstring":"Return the length of the queue","docstring_summary":"Return the length of the queue","docstring_tokens":["Return","the","length","of","the","queue"],"function":"def __len__(self):\n \"\"\"Return the length of the queue\"\"\"\n return self.server.llen(self.key)","function_tokens":["def","__len__","(","self",")",":","return","self",".","server",".","llen","(","self",".","key",")"],"url":"https:\/\/github.com\/AlexTan-b-z\/ZhihuSpider\/blob\/7f35d157fa7f3a7ac8545b386e98286ee2764462\/zhihu\/zhihu\/scrapy_redis\/queue.py#L70-L72"}
18
+ {"nwo":"AlexTan-b-z\/ZhihuSpider","sha":"7f35d157fa7f3a7ac8545b386e98286ee2764462","path":"zhihu\/zhihu\/scrapy_redis\/queue.py","language":"python","identifier":"FifoQueue.push","parameters":"(self, request)","argument_list":"","return_statement":"","docstring":"Push a request","docstring_summary":"Push a request","docstring_tokens":["Push","a","request"],"function":"def push(self, request):\n \"\"\"Push a request\"\"\"\n self.server.lpush(self.key, self._encode_request(request))","function_tokens":["def","push","(","self",",","request",")",":","self",".","server",".","lpush","(","self",".","key",",","self",".","_encode_request","(","request",")",")"],"url":"https:\/\/github.com\/AlexTan-b-z\/ZhihuSpider\/blob\/7f35d157fa7f3a7ac8545b386e98286ee2764462\/zhihu\/zhihu\/scrapy_redis\/queue.py#L74-L76"}
19
+ {"nwo":"AlexTan-b-z\/ZhihuSpider","sha":"7f35d157fa7f3a7ac8545b386e98286ee2764462","path":"zhihu\/zhihu\/scrapy_redis\/queue.py","language":"python","identifier":"FifoQueue.pop","parameters":"(self, timeout=0)","argument_list":"","return_statement":"","docstring":"Pop a request","docstring_summary":"Pop a request","docstring_tokens":["Pop","a","request"],"function":"def pop(self, timeout=0):\n \"\"\"Pop a request\"\"\"\n if timeout > 0:\n data = self.server.brpop(self.key, timeout)\n if isinstance(data, tuple):\n data = data[1]\n else:\n data = self.server.rpop(self.key)\n if data:\n return self._decode_request(data)","function_tokens":["def","pop","(","self",",","timeout","=","0",")",":","if","timeout",">","0",":","data","=","self",".","server",".","brpop","(","self",".","key",",","timeout",")","if","isinstance","(","data",",","tuple",")",":","data","=","data","[","1","]","else",":","data","=","self",".","server",".","rpop","(","self",".","key",")","if","data",":","return","self",".","_decode_request","(","data",")"],"url":"https:\/\/github.com\/AlexTan-b-z\/ZhihuSpider\/blob\/7f35d157fa7f3a7ac8545b386e98286ee2764462\/zhihu\/zhihu\/scrapy_redis\/queue.py#L78-L87"}
20
+ {"nwo":"AlexTan-b-z\/ZhihuSpider","sha":"7f35d157fa7f3a7ac8545b386e98286ee2764462","path":"zhihu\/zhihu\/scrapy_redis\/queue.py","language":"python","identifier":"PriorityQueue.__len__","parameters":"(self)","argument_list":"","return_statement":"return self.server.zcard(self.key)","docstring":"Return the length of the queue","docstring_summary":"Return the length of the queue","docstring_tokens":["Return","the","length","of","the","queue"],"function":"def __len__(self):\n \"\"\"Return the length of the queue\"\"\"\n return self.server.zcard(self.key)","function_tokens":["def","__len__","(","self",")",":","return","self",".","server",".","zcard","(","self",".","key",")"],"url":"https:\/\/github.com\/AlexTan-b-z\/ZhihuSpider\/blob\/7f35d157fa7f3a7ac8545b386e98286ee2764462\/zhihu\/zhihu\/scrapy_redis\/queue.py#L93-L95"}
21
+ {"nwo":"AlexTan-b-z\/ZhihuSpider","sha":"7f35d157fa7f3a7ac8545b386e98286ee2764462","path":"zhihu\/zhihu\/scrapy_redis\/queue.py","language":"python","identifier":"PriorityQueue.push","parameters":"(self, request)","argument_list":"","return_statement":"","docstring":"Push a request","docstring_summary":"Push a request","docstring_tokens":["Push","a","request"],"function":"def push(self, request):\n \"\"\"Push a request\"\"\"\n data = self._encode_request(request)\n score = -request.priority\n # We don't use zadd method as the order of arguments change depending on\n # whether the class is Redis or StrictRedis, and the option of using\n # kwargs only accepts strings, not bytes.\n self.server.execute_command('ZADD', self.key, score, data)","function_tokens":["def","push","(","self",",","request",")",":","data","=","self",".","_encode_request","(","request",")","score","=","-","request",".","priority","# We don't use zadd method as the order of arguments change depending on","# whether the class is Redis or StrictRedis, and the option of using","# kwargs only accepts strings, not bytes.","self",".","server",".","execute_command","(","'ZADD'",",","self",".","key",",","score",",","data",")"],"url":"https:\/\/github.com\/AlexTan-b-z\/ZhihuSpider\/blob\/7f35d157fa7f3a7ac8545b386e98286ee2764462\/zhihu\/zhihu\/scrapy_redis\/queue.py#L97-L104"}
22
+ {"nwo":"AlexTan-b-z\/ZhihuSpider","sha":"7f35d157fa7f3a7ac8545b386e98286ee2764462","path":"zhihu\/zhihu\/scrapy_redis\/queue.py","language":"python","identifier":"PriorityQueue.pop","parameters":"(self, timeout=0)","argument_list":"","return_statement":"","docstring":"Pop a request\n timeout not support in this queue class","docstring_summary":"Pop a request\n timeout not support in this queue class","docstring_tokens":["Pop","a","request","timeout","not","support","in","this","queue","class"],"function":"def pop(self, timeout=0):\n \"\"\"\n Pop a request\n timeout not support in this queue class\n \"\"\"\n # use atomic range\/remove using multi\/exec\n pipe = self.server.pipeline()\n pipe.multi()\n pipe.zrange(self.key, 0, 0).zremrangebyrank(self.key, 0, 0)\n results, count = pipe.execute()\n if results:\n return self._decode_request(results[0])","function_tokens":["def","pop","(","self",",","timeout","=","0",")",":","# use atomic range\/remove using multi\/exec","pipe","=","self",".","server",".","pipeline","(",")","pipe",".","multi","(",")","pipe",".","zrange","(","self",".","key",",","0",",","0",")",".","zremrangebyrank","(","self",".","key",",","0",",","0",")","results",",","count","=","pipe",".","execute","(",")","if","results",":","return","self",".","_decode_request","(","results","[","0","]",")"],"url":"https:\/\/github.com\/AlexTan-b-z\/ZhihuSpider\/blob\/7f35d157fa7f3a7ac8545b386e98286ee2764462\/zhihu\/zhihu\/scrapy_redis\/queue.py#L106-L117"}
23
+ {"nwo":"AlexTan-b-z\/ZhihuSpider","sha":"7f35d157fa7f3a7ac8545b386e98286ee2764462","path":"zhihu\/zhihu\/scrapy_redis\/queue.py","language":"python","identifier":"LifoQueue.__len__","parameters":"(self)","argument_list":"","return_statement":"return self.server.llen(self.key)","docstring":"Return the length of the stack","docstring_summary":"Return the length of the stack","docstring_tokens":["Return","the","length","of","the","stack"],"function":"def __len__(self):\n \"\"\"Return the length of the stack\"\"\"\n return self.server.llen(self.key)","function_tokens":["def","__len__","(","self",")",":","return","self",".","server",".","llen","(","self",".","key",")"],"url":"https:\/\/github.com\/AlexTan-b-z\/ZhihuSpider\/blob\/7f35d157fa7f3a7ac8545b386e98286ee2764462\/zhihu\/zhihu\/scrapy_redis\/queue.py#L123-L125"}
24
+ {"nwo":"AlexTan-b-z\/ZhihuSpider","sha":"7f35d157fa7f3a7ac8545b386e98286ee2764462","path":"zhihu\/zhihu\/scrapy_redis\/queue.py","language":"python","identifier":"LifoQueue.push","parameters":"(self, request)","argument_list":"","return_statement":"","docstring":"Push a request","docstring_summary":"Push a request","docstring_tokens":["Push","a","request"],"function":"def push(self, request):\n \"\"\"Push a request\"\"\"\n self.server.lpush(self.key, self._encode_request(request))","function_tokens":["def","push","(","self",",","request",")",":","self",".","server",".","lpush","(","self",".","key",",","self",".","_encode_request","(","request",")",")"],"url":"https:\/\/github.com\/AlexTan-b-z\/ZhihuSpider\/blob\/7f35d157fa7f3a7ac8545b386e98286ee2764462\/zhihu\/zhihu\/scrapy_redis\/queue.py#L127-L129"}
25
+ {"nwo":"AlexTan-b-z\/ZhihuSpider","sha":"7f35d157fa7f3a7ac8545b386e98286ee2764462","path":"zhihu\/zhihu\/scrapy_redis\/queue.py","language":"python","identifier":"LifoQueue.pop","parameters":"(self, timeout=0)","argument_list":"","return_statement":"","docstring":"Pop a request","docstring_summary":"Pop a request","docstring_tokens":["Pop","a","request"],"function":"def pop(self, timeout=0):\n \"\"\"Pop a request\"\"\"\n if timeout > 0:\n data = self.server.blpop(self.key, timeout)\n if isinstance(data, tuple):\n data = data[1]\n else:\n data = self.server.lpop(self.key)\n\n if data:\n return self._decode_request(data)","function_tokens":["def","pop","(","self",",","timeout","=","0",")",":","if","timeout",">","0",":","data","=","self",".","server",".","blpop","(","self",".","key",",","timeout",")","if","isinstance","(","data",",","tuple",")",":","data","=","data","[","1","]","else",":","data","=","self",".","server",".","lpop","(","self",".","key",")","if","data",":","return","self",".","_decode_request","(","data",")"],"url":"https:\/\/github.com\/AlexTan-b-z\/ZhihuSpider\/blob\/7f35d157fa7f3a7ac8545b386e98286ee2764462\/zhihu\/zhihu\/scrapy_redis\/queue.py#L131-L141"}
26
+ {"nwo":"AlexTan-b-z\/ZhihuSpider","sha":"7f35d157fa7f3a7ac8545b386e98286ee2764462","path":"zhihu\/zhihu\/scrapy_redis\/connection.py","language":"python","identifier":"get_redis_from_settings","parameters":"(settings)","argument_list":"","return_statement":"return get_redis(**params)","docstring":"Returns a redis client instance from given Scrapy settings object.\n\n This function uses ``get_client`` to instantiate the client and uses\n ``defaults.REDIS_PARAMS`` global as defaults values for the parameters. You\n can override them using the ``REDIS_PARAMS`` setting.\n\n Parameters\n ----------\n settings : Settings\n A scrapy settings object. See the supported settings below.\n\n Returns\n -------\n server\n Redis client instance.\n\n Other Parameters\n ----------------\n REDIS_URL : str, optional\n Server connection URL.\n REDIS_HOST : str, optional\n Server host.\n REDIS_PORT : str, optional\n Server port.\n REDIS_ENCODING : str, optional\n Data encoding.\n REDIS_PARAMS : dict, optional\n Additional client parameters.","docstring_summary":"Returns a redis client instance from given Scrapy settings object.","docstring_tokens":["Returns","a","redis","client","instance","from","given","Scrapy","settings","object","."],"function":"def get_redis_from_settings(settings):\n \"\"\"Returns a redis client instance from given Scrapy settings object.\n\n This function uses ``get_client`` to instantiate the client and uses\n ``defaults.REDIS_PARAMS`` global as defaults values for the parameters. You\n can override them using the ``REDIS_PARAMS`` setting.\n\n Parameters\n ----------\n settings : Settings\n A scrapy settings object. See the supported settings below.\n\n Returns\n -------\n server\n Redis client instance.\n\n Other Parameters\n ----------------\n REDIS_URL : str, optional\n Server connection URL.\n REDIS_HOST : str, optional\n Server host.\n REDIS_PORT : str, optional\n Server port.\n REDIS_ENCODING : str, optional\n Data encoding.\n REDIS_PARAMS : dict, optional\n Additional client parameters.\n\n \"\"\"\n params = defaults.REDIS_PARAMS.copy()\n params.update(settings.getdict('REDIS_PARAMS'))\n # XXX: Deprecate REDIS_* settings.\n for source, dest in SETTINGS_PARAMS_MAP.items():\n val = settings.get(source)\n if val:\n params[dest] = val\n\n # Allow ``redis_cls`` to be a path to a class.\n if isinstance(params.get('redis_cls'), six.string_types):\n params['redis_cls'] = load_object(params['redis_cls'])\n\n return get_redis(**params)","function_tokens":["def","get_redis_from_settings","(","settings",")",":","params","=","defaults",".","REDIS_PARAMS",".","copy","(",")","params",".","update","(","settings",".","getdict","(","'REDIS_PARAMS'",")",")","# XXX: Deprecate REDIS_* settings.","for","source",",","dest","in","SETTINGS_PARAMS_MAP",".","items","(",")",":","val","=","settings",".","get","(","source",")","if","val",":","params","[","dest","]","=","val","# Allow ``redis_cls`` to be a path to a class.","if","isinstance","(","params",".","get","(","'redis_cls'",")",",","six",".","string_types",")",":","params","[","'redis_cls'","]","=","load_object","(","params","[","'redis_cls'","]",")","return","get_redis","(","*","*","params",")"],"url":"https:\/\/github.com\/AlexTan-b-z\/ZhihuSpider\/blob\/7f35d157fa7f3a7ac8545b386e98286ee2764462\/zhihu\/zhihu\/scrapy_redis\/connection.py#L17-L60"}
27
+ {"nwo":"AlexTan-b-z\/ZhihuSpider","sha":"7f35d157fa7f3a7ac8545b386e98286ee2764462","path":"zhihu\/zhihu\/scrapy_redis\/connection.py","language":"python","identifier":"get_redis","parameters":"(**kwargs)","argument_list":"","return_statement":"","docstring":"Returns a redis client instance.\n\n Parameters\n ----------\n redis_cls : class, optional\n Defaults to ``redis.StrictRedis``.\n url : str, optional\n If given, ``redis_cls.from_url`` is used to instantiate the class.\n **kwargs\n Extra parameters to be passed to the ``redis_cls`` class.\n\n Returns\n -------\n server\n Redis client instance.","docstring_summary":"Returns a redis client instance.","docstring_tokens":["Returns","a","redis","client","instance","."],"function":"def get_redis(**kwargs):\n \"\"\"Returns a redis client instance.\n\n Parameters\n ----------\n redis_cls : class, optional\n Defaults to ``redis.StrictRedis``.\n url : str, optional\n If given, ``redis_cls.from_url`` is used to instantiate the class.\n **kwargs\n Extra parameters to be passed to the ``redis_cls`` class.\n\n Returns\n -------\n server\n Redis client instance.\n\n \"\"\"\n redis_cls = kwargs.pop('redis_cls', defaults.REDIS_CLS)\n url = kwargs.pop('url', None)\n if url:\n return redis_cls.from_url(url, **kwargs)\n else:\n return redis_cls(**kwargs)","function_tokens":["def","get_redis","(","*","*","kwargs",")",":","redis_cls","=","kwargs",".","pop","(","'redis_cls'",",","defaults",".","REDIS_CLS",")","url","=","kwargs",".","pop","(","'url'",",","None",")","if","url",":","return","redis_cls",".","from_url","(","url",",","*","*","kwargs",")","else",":","return","redis_cls","(","*","*","kwargs",")"],"url":"https:\/\/github.com\/AlexTan-b-z\/ZhihuSpider\/blob\/7f35d157fa7f3a7ac8545b386e98286ee2764462\/zhihu\/zhihu\/scrapy_redis\/connection.py#L67-L90"}
28
+ {"nwo":"AlexTan-b-z\/ZhihuSpider","sha":"7f35d157fa7f3a7ac8545b386e98286ee2764462","path":"zhihu\/zhihu\/scrapy_redis\/spiders.py","language":"python","identifier":"RedisMixin.start_requests","parameters":"(self)","argument_list":"","return_statement":"return self.next_requests()","docstring":"Returns a batch of start requests from redis.","docstring_summary":"Returns a batch of start requests from redis.","docstring_tokens":["Returns","a","batch","of","start","requests","from","redis","."],"function":"def start_requests(self):\n \"\"\"Returns a batch of start requests from redis.\"\"\"\n return self.next_requests()","function_tokens":["def","start_requests","(","self",")",":","return","self",".","next_requests","(",")"],"url":"https:\/\/github.com\/AlexTan-b-z\/ZhihuSpider\/blob\/7f35d157fa7f3a7ac8545b386e98286ee2764462\/zhihu\/zhihu\/scrapy_redis\/spiders.py#L18-L20"}
29
+ {"nwo":"AlexTan-b-z\/ZhihuSpider","sha":"7f35d157fa7f3a7ac8545b386e98286ee2764462","path":"zhihu\/zhihu\/scrapy_redis\/spiders.py","language":"python","identifier":"RedisMixin.setup_redis","parameters":"(self, crawler=None)","argument_list":"","return_statement":"","docstring":"Setup redis connection and idle signal.\n\n This should be called after the spider has set its crawler object.","docstring_summary":"Setup redis connection and idle signal.","docstring_tokens":["Setup","redis","connection","and","idle","signal","."],"function":"def setup_redis(self, crawler=None):\n \"\"\"Setup redis connection and idle signal.\n\n This should be called after the spider has set its crawler object.\n \"\"\"\n if self.server is not None:\n return\n\n if crawler is None:\n # We allow optional crawler argument to keep backwards\n # compatibility.\n # XXX: Raise a deprecation warning.\n crawler = getattr(self, 'crawler', None)\n\n if crawler is None:\n raise ValueError(\"crawler is required\")\n\n settings = crawler.settings\n\n if self.redis_key is None:\n self.redis_key = settings.get(\n 'REDIS_START_URLS_KEY', defaults.START_URLS_KEY,\n )\n\n self.redis_key = self.redis_key % {'name': self.name}\n\n if not self.redis_key.strip():\n raise ValueError(\"redis_key must not be empty\")\n\n if self.redis_batch_size is None:\n # TODO: Deprecate this setting (REDIS_START_URLS_BATCH_SIZE).\n self.redis_batch_size = settings.getint(\n 'REDIS_START_URLS_BATCH_SIZE',\n settings.getint('CONCURRENT_REQUESTS'),\n )\n\n try:\n self.redis_batch_size = int(self.redis_batch_size)\n except (TypeError, ValueError):\n raise ValueError(\"redis_batch_size must be an integer\")\n\n if self.redis_encoding is None:\n self.redis_encoding = settings.get('REDIS_ENCODING', defaults.REDIS_ENCODING)\n\n self.logger.info(\"Reading start URLs from redis key '%(redis_key)s' \"\n \"(batch size: %(redis_batch_size)s, encoding: %(redis_encoding)s\",\n self.__dict__)\n\n self.server = connection.from_settings(crawler.settings)\n # The idle signal is called when the spider has no requests left,\n # that's when we will schedule new requests from redis queue\n crawler.signals.connect(self.spider_idle, signal=signals.spider_idle)","function_tokens":["def","setup_redis","(","self",",","crawler","=","None",")",":","if","self",".","server","is","not","None",":","return","if","crawler","is","None",":","# We allow optional crawler argument to keep backwards","# compatibility.","# XXX: Raise a deprecation warning.","crawler","=","getattr","(","self",",","'crawler'",",","None",")","if","crawler","is","None",":","raise","ValueError","(","\"crawler is required\"",")","settings","=","crawler",".","settings","if","self",".","redis_key","is","None",":","self",".","redis_key","=","settings",".","get","(","'REDIS_START_URLS_KEY'",",","defaults",".","START_URLS_KEY",",",")","self",".","redis_key","=","self",".","redis_key","%","{","'name'",":","self",".","name","}","if","not","self",".","redis_key",".","strip","(",")",":","raise","ValueError","(","\"redis_key must not be empty\"",")","if","self",".","redis_batch_size","is","None",":","# TODO: Deprecate this setting (REDIS_START_URLS_BATCH_SIZE).","self",".","redis_batch_size","=","settings",".","getint","(","'REDIS_START_URLS_BATCH_SIZE'",",","settings",".","getint","(","'CONCURRENT_REQUESTS'",")",",",")","try",":","self",".","redis_batch_size","=","int","(","self",".","redis_batch_size",")","except","(","TypeError",",","ValueError",")",":","raise","ValueError","(","\"redis_batch_size must be an integer\"",")","if","self",".","redis_encoding","is","None",":","self",".","redis_encoding","=","settings",".","get","(","'REDIS_ENCODING'",",","defaults",".","REDIS_ENCODING",")","self",".","logger",".","info","(","\"Reading start URLs from redis key '%(redis_key)s' \"","\"(batch size: %(redis_batch_size)s, encoding: %(redis_encoding)s\"",",","self",".","__dict__",")","self",".","server","=","connection",".","from_settings","(","crawler",".","settings",")","# The idle signal is called when the spider has no requests left,","# that's when we will schedule new requests from redis queue","crawler",".","signals",".","connect","(","self",".","spider_idle",",","signal","=","signals",".","spider_idle",")"],"url":"https:\/\/github.com\/AlexTan-b-z\/ZhihuSpider\/blob\/7f35d157fa7f3a7ac8545b386e98286ee2764462\/zhihu\/zhihu\/scrapy_redis\/spiders.py#L22-L73"}
30
+ {"nwo":"AlexTan-b-z\/ZhihuSpider","sha":"7f35d157fa7f3a7ac8545b386e98286ee2764462","path":"zhihu\/zhihu\/scrapy_redis\/spiders.py","language":"python","identifier":"RedisMixin.next_requests","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Returns a request to be scheduled or none.","docstring_summary":"Returns a request to be scheduled or none.","docstring_tokens":["Returns","a","request","to","be","scheduled","or","none","."],"function":"def next_requests(self):\n \"\"\"Returns a request to be scheduled or none.\"\"\"\n use_set = self.settings.getbool('REDIS_START_URLS_AS_SET', defaults.START_URLS_AS_SET)\n fetch_one = self.server.spop if use_set else self.server.lpop\n # XXX: Do we need to use a timeout here?\n found = 0\n # TODO: Use redis pipeline execution.\n while found < self.redis_batch_size:\n data = fetch_one(self.redis_key)\n if not data:\n # Queue empty.\n break\n req = self.make_request_from_data(data)\n if req:\n yield req\n found += 1\n else:\n self.logger.debug(\"Request not made from data: %r\", data)\n\n if found:\n self.logger.debug(\"Read %s requests from '%s'\", found, self.redis_key)","function_tokens":["def","next_requests","(","self",")",":","use_set","=","self",".","settings",".","getbool","(","'REDIS_START_URLS_AS_SET'",",","defaults",".","START_URLS_AS_SET",")","fetch_one","=","self",".","server",".","spop","if","use_set","else","self",".","server",".","lpop","# XXX: Do we need to use a timeout here?","found","=","0","# TODO: Use redis pipeline execution.","while","found","<","self",".","redis_batch_size",":","data","=","fetch_one","(","self",".","redis_key",")","if","not","data",":","# Queue empty.","break","req","=","self",".","make_request_from_data","(","data",")","if","req",":","yield","req","found","+=","1","else",":","self",".","logger",".","debug","(","\"Request not made from data: %r\"",",","data",")","if","found",":","self",".","logger",".","debug","(","\"Read %s requests from '%s'\"",",","found",",","self",".","redis_key",")"],"url":"https:\/\/github.com\/AlexTan-b-z\/ZhihuSpider\/blob\/7f35d157fa7f3a7ac8545b386e98286ee2764462\/zhihu\/zhihu\/scrapy_redis\/spiders.py#L75-L95"}
31
+ {"nwo":"AlexTan-b-z\/ZhihuSpider","sha":"7f35d157fa7f3a7ac8545b386e98286ee2764462","path":"zhihu\/zhihu\/scrapy_redis\/spiders.py","language":"python","identifier":"RedisMixin.make_request_from_data","parameters":"(self, data)","argument_list":"","return_statement":"return self.make_requests_from_url(url)","docstring":"Returns a Request instance from data coming from Redis.\n\n By default, ``data`` is an encoded URL. You can override this method to\n provide your own message decoding.\n\n Parameters\n ----------\n data : bytes\n Message from redis.","docstring_summary":"Returns a Request instance from data coming from Redis.","docstring_tokens":["Returns","a","Request","instance","from","data","coming","from","Redis","."],"function":"def make_request_from_data(self, data):\n \"\"\"Returns a Request instance from data coming from Redis.\n\n By default, ``data`` is an encoded URL. You can override this method to\n provide your own message decoding.\n\n Parameters\n ----------\n data : bytes\n Message from redis.\n\n \"\"\"\n url = bytes_to_str(data, self.redis_encoding)\n return self.make_requests_from_url(url)","function_tokens":["def","make_request_from_data","(","self",",","data",")",":","url","=","bytes_to_str","(","data",",","self",".","redis_encoding",")","return","self",".","make_requests_from_url","(","url",")"],"url":"https:\/\/github.com\/AlexTan-b-z\/ZhihuSpider\/blob\/7f35d157fa7f3a7ac8545b386e98286ee2764462\/zhihu\/zhihu\/scrapy_redis\/spiders.py#L97-L110"}
32
+ {"nwo":"AlexTan-b-z\/ZhihuSpider","sha":"7f35d157fa7f3a7ac8545b386e98286ee2764462","path":"zhihu\/zhihu\/scrapy_redis\/spiders.py","language":"python","identifier":"RedisMixin.schedule_next_requests","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Schedules a request if available","docstring_summary":"Schedules a request if available","docstring_tokens":["Schedules","a","request","if","available"],"function":"def schedule_next_requests(self):\n \"\"\"Schedules a request if available\"\"\"\n # TODO: While there is capacity, schedule a batch of redis requests.\n for req in self.next_requests():\n self.crawler.engine.crawl(req, spider=self)","function_tokens":["def","schedule_next_requests","(","self",")",":","# TODO: While there is capacity, schedule a batch of redis requests.","for","req","in","self",".","next_requests","(",")",":","self",".","crawler",".","engine",".","crawl","(","req",",","spider","=","self",")"],"url":"https:\/\/github.com\/AlexTan-b-z\/ZhihuSpider\/blob\/7f35d157fa7f3a7ac8545b386e98286ee2764462\/zhihu\/zhihu\/scrapy_redis\/spiders.py#L112-L116"}
33
+ {"nwo":"AlexTan-b-z\/ZhihuSpider","sha":"7f35d157fa7f3a7ac8545b386e98286ee2764462","path":"zhihu\/zhihu\/scrapy_redis\/spiders.py","language":"python","identifier":"RedisMixin.spider_idle","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Schedules a request if available, otherwise waits.","docstring_summary":"Schedules a request if available, otherwise waits.","docstring_tokens":["Schedules","a","request","if","available","otherwise","waits","."],"function":"def spider_idle(self):\n \"\"\"Schedules a request if available, otherwise waits.\"\"\"\n # XXX: Handle a sentinel to close the spider.\n self.schedule_next_requests()\n raise DontCloseSpider","function_tokens":["def","spider_idle","(","self",")",":","# XXX: Handle a sentinel to close the spider.","self",".","schedule_next_requests","(",")","raise","DontCloseSpider"],"url":"https:\/\/github.com\/AlexTan-b-z\/ZhihuSpider\/blob\/7f35d157fa7f3a7ac8545b386e98286ee2764462\/zhihu\/zhihu\/scrapy_redis\/spiders.py#L118-L122"}
34
+ {"nwo":"AlexTan-b-z\/ZhihuSpider","sha":"7f35d157fa7f3a7ac8545b386e98286ee2764462","path":"zhihu\/zhihu\/scrapy_redis\/utils.py","language":"python","identifier":"bytes_to_str","parameters":"(s, encoding='utf-8')","argument_list":"","return_statement":"return s","docstring":"Returns a str if a bytes object is given.","docstring_summary":"Returns a str if a bytes object is given.","docstring_tokens":["Returns","a","str","if","a","bytes","object","is","given","."],"function":"def bytes_to_str(s, encoding='utf-8'):\n \"\"\"Returns a str if a bytes object is given.\"\"\"\n if six.PY3 and isinstance(s, bytes):\n return s.decode(encoding)\n return s","function_tokens":["def","bytes_to_str","(","s",",","encoding","=","'utf-8'",")",":","if","six",".","PY3","and","isinstance","(","s",",","bytes",")",":","return","s",".","decode","(","encoding",")","return","s"],"url":"https:\/\/github.com\/AlexTan-b-z\/ZhihuSpider\/blob\/7f35d157fa7f3a7ac8545b386e98286ee2764462\/zhihu\/zhihu\/scrapy_redis\/utils.py#L4-L8"}
35
+ {"nwo":"AlexTan-b-z\/ZhihuSpider","sha":"7f35d157fa7f3a7ac8545b386e98286ee2764462","path":"zhihu\/zhihu\/scrapy_redis\/dupefilter.py","language":"python","identifier":"RFPDupeFilter.__init__","parameters":"(self, server, key, debug=False)","argument_list":"","return_statement":"","docstring":"Initialize the duplicates filter.\n\n Parameters\n ----------\n server : redis.StrictRedis\n The redis server instance.\n key : str\n Redis key Where to store fingerprints.\n debug : bool, optional\n Whether to log filtered requests.","docstring_summary":"Initialize the duplicates filter.","docstring_tokens":["Initialize","the","duplicates","filter","."],"function":"def __init__(self, server, key, debug=False):\n \"\"\"Initialize the duplicates filter.\n\n Parameters\n ----------\n server : redis.StrictRedis\n The redis server instance.\n key : str\n Redis key Where to store fingerprints.\n debug : bool, optional\n Whether to log filtered requests.\n\n \"\"\"\n self.server = server\n self.key = key\n self.debug = debug\n self.bf = BloomFilter(server, key, blockNum=1) # you can increase blockNum if your are filtering too many urls\n self.logdupes = True","function_tokens":["def","__init__","(","self",",","server",",","key",",","debug","=","False",")",":","self",".","server","=","server","self",".","key","=","key","self",".","debug","=","debug","self",".","bf","=","BloomFilter","(","server",",","key",",","blockNum","=","1",")","# you can increase blockNum if your are filtering too many urls","self",".","logdupes","=","True"],"url":"https:\/\/github.com\/AlexTan-b-z\/ZhihuSpider\/blob\/7f35d157fa7f3a7ac8545b386e98286ee2764462\/zhihu\/zhihu\/scrapy_redis\/dupefilter.py#L25-L42"}
36
+ {"nwo":"AlexTan-b-z\/ZhihuSpider","sha":"7f35d157fa7f3a7ac8545b386e98286ee2764462","path":"zhihu\/zhihu\/scrapy_redis\/dupefilter.py","language":"python","identifier":"RFPDupeFilter.from_settings","parameters":"(cls, settings)","argument_list":"","return_statement":"return cls(server, key=key, debug=debug)","docstring":"Returns an instance from given settings.\n\n This uses by default the key ``dupefilter:<timestamp>``. When using the\n ``scrapy_redis.scheduler.Scheduler`` class, this method is not used as\n it needs to pass the spider name in the key.\n\n Parameters\n ----------\n settings : scrapy.settings.Settings\n\n Returns\n -------\n RFPDupeFilter\n A RFPDupeFilter instance.","docstring_summary":"Returns an instance from given settings.","docstring_tokens":["Returns","an","instance","from","given","settings","."],"function":"def from_settings(cls, settings):\n \"\"\"Returns an instance from given settings.\n\n This uses by default the key ``dupefilter:<timestamp>``. When using the\n ``scrapy_redis.scheduler.Scheduler`` class, this method is not used as\n it needs to pass the spider name in the key.\n\n Parameters\n ----------\n settings : scrapy.settings.Settings\n\n Returns\n -------\n RFPDupeFilter\n A RFPDupeFilter instance.\n\n\n \"\"\"\n server = get_redis_from_settings(settings)\n # XXX: This creates one-time key. needed to support to use this\n # class as standalone dupefilter with scrapy's default scheduler\n # if scrapy passes spider on open() method this wouldn't be needed\n # TODO: Use SCRAPY_JOB env as default and fallback to timestamp.\n key = defaults.DUPEFILTER_KEY % {'timestamp': int(time.time())}\n debug = settings.getbool('DUPEFILTER_DEBUG')\n return cls(server, key=key, debug=debug)","function_tokens":["def","from_settings","(","cls",",","settings",")",":","server","=","get_redis_from_settings","(","settings",")","# XXX: This creates one-time key. needed to support to use this","# class as standalone dupefilter with scrapy's default scheduler","# if scrapy passes spider on open() method this wouldn't be needed","# TODO: Use SCRAPY_JOB env as default and fallback to timestamp.","key","=","defaults",".","DUPEFILTER_KEY","%","{","'timestamp'",":","int","(","time",".","time","(",")",")","}","debug","=","settings",".","getbool","(","'DUPEFILTER_DEBUG'",")","return","cls","(","server",",","key","=","key",",","debug","=","debug",")"],"url":"https:\/\/github.com\/AlexTan-b-z\/ZhihuSpider\/blob\/7f35d157fa7f3a7ac8545b386e98286ee2764462\/zhihu\/zhihu\/scrapy_redis\/dupefilter.py#L45-L70"}
37
+ {"nwo":"AlexTan-b-z\/ZhihuSpider","sha":"7f35d157fa7f3a7ac8545b386e98286ee2764462","path":"zhihu\/zhihu\/scrapy_redis\/dupefilter.py","language":"python","identifier":"RFPDupeFilter.from_crawler","parameters":"(cls, crawler)","argument_list":"","return_statement":"return cls.from_settings(crawler.settings)","docstring":"Returns instance from crawler.\n\n Parameters\n ----------\n crawler : scrapy.crawler.Crawler\n\n Returns\n -------\n RFPDupeFilter\n Instance of RFPDupeFilter.","docstring_summary":"Returns instance from crawler.","docstring_tokens":["Returns","instance","from","crawler","."],"function":"def from_crawler(cls, crawler):\n \"\"\"Returns instance from crawler.\n\n Parameters\n ----------\n crawler : scrapy.crawler.Crawler\n\n Returns\n -------\n RFPDupeFilter\n Instance of RFPDupeFilter.\n\n \"\"\"\n return cls.from_settings(crawler.settings)","function_tokens":["def","from_crawler","(","cls",",","crawler",")",":","return","cls",".","from_settings","(","crawler",".","settings",")"],"url":"https:\/\/github.com\/AlexTan-b-z\/ZhihuSpider\/blob\/7f35d157fa7f3a7ac8545b386e98286ee2764462\/zhihu\/zhihu\/scrapy_redis\/dupefilter.py#L73-L86"}
38
+ {"nwo":"AlexTan-b-z\/ZhihuSpider","sha":"7f35d157fa7f3a7ac8545b386e98286ee2764462","path":"zhihu\/zhihu\/scrapy_redis\/dupefilter.py","language":"python","identifier":"RFPDupeFilter.request_seen","parameters":"(self, request)","argument_list":"","return_statement":"","docstring":"Returns True if request was already seen.\n\n Parameters\n ----------\n request : scrapy.http.Request\n\n Returns\n -------\n bool","docstring_summary":"Returns True if request was already seen.","docstring_tokens":["Returns","True","if","request","was","already","seen","."],"function":"def request_seen(self, request):\n \"\"\"Returns True if request was already seen.\n\n Parameters\n ----------\n request : scrapy.http.Request\n\n Returns\n -------\n bool\n\n \"\"\"\n fp = request_fingerprint(request)\n if self.bf.isContains(fp):\n return True\n else:\n self.bf.insert(fp)\n return False","function_tokens":["def","request_seen","(","self",",","request",")",":","fp","=","request_fingerprint","(","request",")","if","self",".","bf",".","isContains","(","fp",")",":","return","True","else",":","self",".","bf",".","insert","(","fp",")","return","False"],"url":"https:\/\/github.com\/AlexTan-b-z\/ZhihuSpider\/blob\/7f35d157fa7f3a7ac8545b386e98286ee2764462\/zhihu\/zhihu\/scrapy_redis\/dupefilter.py#L88-L105"}
39
+ {"nwo":"AlexTan-b-z\/ZhihuSpider","sha":"7f35d157fa7f3a7ac8545b386e98286ee2764462","path":"zhihu\/zhihu\/scrapy_redis\/dupefilter.py","language":"python","identifier":"RFPDupeFilter.request_fingerprint","parameters":"(self, request)","argument_list":"","return_statement":"return request_fingerprint(request)","docstring":"Returns a fingerprint for a given request.\n\n Parameters\n ----------\n request : scrapy.http.Request\n\n Returns\n -------\n str","docstring_summary":"Returns a fingerprint for a given request.","docstring_tokens":["Returns","a","fingerprint","for","a","given","request","."],"function":"def request_fingerprint(self, request):\n \"\"\"Returns a fingerprint for a given request.\n\n Parameters\n ----------\n request : scrapy.http.Request\n\n Returns\n -------\n str\n\n \"\"\"\n return request_fingerprint(request)","function_tokens":["def","request_fingerprint","(","self",",","request",")",":","return","request_fingerprint","(","request",")"],"url":"https:\/\/github.com\/AlexTan-b-z\/ZhihuSpider\/blob\/7f35d157fa7f3a7ac8545b386e98286ee2764462\/zhihu\/zhihu\/scrapy_redis\/dupefilter.py#L107-L119"}
40
+ {"nwo":"AlexTan-b-z\/ZhihuSpider","sha":"7f35d157fa7f3a7ac8545b386e98286ee2764462","path":"zhihu\/zhihu\/scrapy_redis\/dupefilter.py","language":"python","identifier":"RFPDupeFilter.close","parameters":"(self, reason='')","argument_list":"","return_statement":"","docstring":"Delete data on close. Called by Scrapy's scheduler.\n\n Parameters\n ----------\n reason : str, optional","docstring_summary":"Delete data on close. Called by Scrapy's scheduler.","docstring_tokens":["Delete","data","on","close",".","Called","by","Scrapy","s","scheduler","."],"function":"def close(self, reason=''):\n \"\"\"Delete data on close. Called by Scrapy's scheduler.\n\n Parameters\n ----------\n reason : str, optional\n\n \"\"\"\n self.clear()","function_tokens":["def","close","(","self",",","reason","=","''",")",":","self",".","clear","(",")"],"url":"https:\/\/github.com\/AlexTan-b-z\/ZhihuSpider\/blob\/7f35d157fa7f3a7ac8545b386e98286ee2764462\/zhihu\/zhihu\/scrapy_redis\/dupefilter.py#L121-L129"}
41
+ {"nwo":"AlexTan-b-z\/ZhihuSpider","sha":"7f35d157fa7f3a7ac8545b386e98286ee2764462","path":"zhihu\/zhihu\/scrapy_redis\/dupefilter.py","language":"python","identifier":"RFPDupeFilter.clear","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Clears fingerprints data.","docstring_summary":"Clears fingerprints data.","docstring_tokens":["Clears","fingerprints","data","."],"function":"def clear(self):\n \"\"\"Clears fingerprints data.\"\"\"\n self.server.delete(self.key)","function_tokens":["def","clear","(","self",")",":","self",".","server",".","delete","(","self",".","key",")"],"url":"https:\/\/github.com\/AlexTan-b-z\/ZhihuSpider\/blob\/7f35d157fa7f3a7ac8545b386e98286ee2764462\/zhihu\/zhihu\/scrapy_redis\/dupefilter.py#L131-L133"}
42
+ {"nwo":"AlexTan-b-z\/ZhihuSpider","sha":"7f35d157fa7f3a7ac8545b386e98286ee2764462","path":"zhihu\/zhihu\/scrapy_redis\/dupefilter.py","language":"python","identifier":"RFPDupeFilter.log","parameters":"(self, request, spider)","argument_list":"","return_statement":"","docstring":"Logs given request.\n\n Parameters\n ----------\n request : scrapy.http.Request\n spider : scrapy.spiders.Spider","docstring_summary":"Logs given request.","docstring_tokens":["Logs","given","request","."],"function":"def log(self, request, spider):\n \"\"\"Logs given request.\n\n Parameters\n ----------\n request : scrapy.http.Request\n spider : scrapy.spiders.Spider\n\n \"\"\"\n if self.debug:\n msg = \"Filtered duplicate request: %(request)s\"\n self.logger.debug(msg, {'request': request}, extra={'spider': spider})\n elif self.logdupes:\n msg = (\"Filtered duplicate request %(request)s\"\n \" - no more duplicates will be shown\"\n \" (see DUPEFILTER_DEBUG to show all duplicates)\")\n self.logger.debug(msg, {'request': request}, extra={'spider': spider})\n self.logdupes = False","function_tokens":["def","log","(","self",",","request",",","spider",")",":","if","self",".","debug",":","msg","=","\"Filtered duplicate request: %(request)s\"","self",".","logger",".","debug","(","msg",",","{","'request'",":","request","}",",","extra","=","{","'spider'",":","spider","}",")","elif","self",".","logdupes",":","msg","=","(","\"Filtered duplicate request %(request)s\"","\" - no more duplicates will be shown\"","\" (see DUPEFILTER_DEBUG to show all duplicates)\"",")","self",".","logger",".","debug","(","msg",",","{","'request'",":","request","}",",","extra","=","{","'spider'",":","spider","}",")","self",".","logdupes","=","False"],"url":"https:\/\/github.com\/AlexTan-b-z\/ZhihuSpider\/blob\/7f35d157fa7f3a7ac8545b386e98286ee2764462\/zhihu\/zhihu\/scrapy_redis\/dupefilter.py#L135-L152"}
Alexander-H-Liu__End-to-end-ASR-Pytorch.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
AlfredXiangWu__LightCNN.jsonl ADDED
@@ -0,0 +1 @@
 
 
1
+ {"nwo":"AlfredXiangWu\/LightCNN","sha":"8b33107e836374a892efecd149d2016170167fdd","path":"train.py","language":"python","identifier":"accuracy","parameters":"(output, target, topk=(1,))","argument_list":"","return_statement":"return res","docstring":"Computes the precision@k for the specified values of k","docstring_summary":"Computes the precision","docstring_tokens":["Computes","the","precision"],"function":"def accuracy(output, target, topk=(1,)):\n \"\"\"Computes the precision@k for the specified values of k\"\"\"\n maxk = max(topk)\n batch_size = target.size(0)\n\n _, pred = output.topk(maxk, 1, True, True)\n pred = pred.t()\n correct = pred.eq(target.view(1, -1).expand_as(pred))\n\n res = []\n for k in topk:\n correct_k = correct[:k].view(-1).float().sum(0)\n res.append(correct_k.mul_(100.0 \/ batch_size))\n return res","function_tokens":["def","accuracy","(","output",",","target",",","topk","=","(","1",",",")",")",":","maxk","=","max","(","topk",")","batch_size","=","target",".","size","(","0",")","_",",","pred","=","output",".","topk","(","maxk",",","1",",","True",",","True",")","pred","=","pred",".","t","(",")","correct","=","pred",".","eq","(","target",".","view","(","1",",","-","1",")",".","expand_as","(","pred",")",")","res","=","[","]","for","k","in","topk",":","correct_k","=","correct","[",":","k","]",".","view","(","-","1",")",".","float","(",")",".","sum","(","0",")","res",".","append","(","correct_k",".","mul_","(","100.0","\/","batch_size",")",")","return","res"],"url":"https:\/\/github.com\/AlfredXiangWu\/LightCNN\/blob\/8b33107e836374a892efecd149d2016170167fdd\/train.py#L269-L282"}
Algorithm79__Dotfiles_i3.jsonl ADDED
File without changes
AlphaMycelium__pathfinder.vim.jsonl ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {"nwo":"danth\/pathfinder.vim","sha":"4f67053cbea56a45020d004b6bd059e38934a21a","path":"pathfinder\/debytes.py","language":"python","identifier":"debytes","parameters":"(string)","argument_list":"","return_statement":"","docstring":"Decode string if it is a bytes object.\n\n This is necessary since Neovim, correctly, gives strings as a str, but regular\n Vim leaves them encoded as bytes.","docstring_summary":"Decode string if it is a bytes object.","docstring_tokens":["Decode","string","if","it","is","a","bytes","object","."],"function":"def debytes(string):\n \"\"\"\n Decode string if it is a bytes object.\n\n This is necessary since Neovim, correctly, gives strings as a str, but regular\n Vim leaves them encoded as bytes.\n \"\"\"\n try:\n return string.decode()\n except AttributeError:\n return string","function_tokens":["def","debytes","(","string",")",":","try",":","return","string",".","decode","(",")","except","AttributeError",":","return","string"],"url":"https:\/\/github.com\/danth\/pathfinder.vim\/blob\/4f67053cbea56a45020d004b6bd059e38934a21a\/pathfinder\/debytes.py#L1-L11"}
2
+ {"nwo":"danth\/pathfinder.vim","sha":"4f67053cbea56a45020d004b6bd059e38934a21a","path":"pathfinder\/window.py","language":"python","identifier":"cursor_in_same_position","parameters":"(a, b)","argument_list":"","return_statement":"return a.lnum == b.lnum and a.col == b.col","docstring":"Check if the given views have the cursor on the same position.\n\n The scroll position and other properties may differ.","docstring_summary":"Check if the given views have the cursor on the same position.","docstring_tokens":["Check","if","the","given","views","have","the","cursor","on","the","same","position","."],"function":"def cursor_in_same_position(a, b):\n \"\"\"\n Check if the given views have the cursor on the same position.\n\n The scroll position and other properties may differ.\n \"\"\"\n return a.lnum == b.lnum and a.col == b.col","function_tokens":["def","cursor_in_same_position","(","a",",","b",")",":","return","a",".","lnum","==","b",".","lnum","and","a",".","col","==","b",".","col"],"url":"https:\/\/github.com\/danth\/pathfinder.vim\/blob\/4f67053cbea56a45020d004b6bd059e38934a21a\/pathfinder\/window.py#L19-L25"}
3
+ {"nwo":"danth\/pathfinder.vim","sha":"4f67053cbea56a45020d004b6bd059e38934a21a","path":"pathfinder\/server\/server.py","language":"python","identifier":"Server.message_loop","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Continuously wait for and handle instructions from the client.\n\n This waiting blocks Vim, but that does not matter since nobody is looking at\n it. Blocking also prevents CPU resources from being wasted on redrawing.\n\n :raises EOFError: when the connection is closed.","docstring_summary":"Continuously wait for and handle instructions from the client.","docstring_tokens":["Continuously","wait","for","and","handle","instructions","from","the","client","."],"function":"def message_loop(self):\n \"\"\"\n Continuously wait for and handle instructions from the client.\n\n This waiting blocks Vim, but that does not matter since nobody is looking at\n it. Blocking also prevents CPU resources from being wasted on redrawing.\n\n :raises EOFError: when the connection is closed.\n \"\"\"\n while True:\n try:\n data = self.client_connection.recv()\n\n # If there is still data waiting, then multiple requests were sent,\n # so we skip pathfinding and move on to the next one\n if not self.client_connection.poll():\n self.do_action(data)\n except:\n # Send any unexpected exceptions back to the client\n # to be displayed for debugging purposes\n self.client_connection.send((\"ERROR\", traceback.format_exc()))","function_tokens":["def","message_loop","(","self",")",":","while","True",":","try",":","data","=","self",".","client_connection",".","recv","(",")","# If there is still data waiting, then multiple requests were sent,","# so we skip pathfinding and move on to the next one","if","not","self",".","client_connection",".","poll","(",")",":","self",".","do_action","(","data",")","except",":","# Send any unexpected exceptions back to the client","# to be displayed for debugging purposes","self",".","client_connection",".","send","(","(","\"ERROR\"",",","traceback",".","format_exc","(",")",")",")"],"url":"https:\/\/github.com\/danth\/pathfinder.vim\/blob\/4f67053cbea56a45020d004b6bd059e38934a21a\/pathfinder\/server\/server.py#L41-L61"}
4
+ {"nwo":"danth\/pathfinder.vim","sha":"4f67053cbea56a45020d004b6bd059e38934a21a","path":"pathfinder\/server\/server.py","language":"python","identifier":"Server.do_action","parameters":"(self, data)","argument_list":"","return_statement":"","docstring":"Process an instruction from the client.","docstring_summary":"Process an instruction from the client.","docstring_tokens":["Process","an","instruction","from","the","client","."],"function":"def do_action(self, data):\n \"\"\"Process an instruction from the client.\"\"\"\n self.start_view = data[\"start\"]\n self.target_view = data[\"target\"]\n self.min_line = data[\"min_line\"]\n self.max_line = data[\"max_line\"]\n\n vim.current.buffer[:] = data[\"buffer\"]\n\n vim.current.window.options[\"wrap\"] = data[\"wrap\"]\n vim.options[\"scrolloff\"] = data[\"scrolloff\"]\n vim.options[\"sidescrolloff\"] = data[\"sidescrolloff\"]\n\n # Set size of the entire Vim display to match the size of the\n # corresponding window in the client\n vim.options[\"columns\"] = int(data[\"size\"][0])\n vim.options[\"lines\"] = vim.options[\"cmdheight\"] + int(data[\"size\"][1])\n\n self.pathfind()","function_tokens":["def","do_action","(","self",",","data",")",":","self",".","start_view","=","data","[","\"start\"","]","self",".","target_view","=","data","[","\"target\"","]","self",".","min_line","=","data","[","\"min_line\"","]","self",".","max_line","=","data","[","\"max_line\"","]","vim",".","current",".","buffer","[",":","]","=","data","[","\"buffer\"","]","vim",".","current",".","window",".","options","[","\"wrap\"","]","=","data","[","\"wrap\"","]","vim",".","options","[","\"scrolloff\"","]","=","data","[","\"scrolloff\"","]","vim",".","options","[","\"sidescrolloff\"","]","=","data","[","\"sidescrolloff\"","]","# Set size of the entire Vim display to match the size of the","# corresponding window in the client","vim",".","options","[","\"columns\"","]","=","int","(","data","[","\"size\"","]","[","0","]",")","vim",".","options","[","\"lines\"","]","=","vim",".","options","[","\"cmdheight\"","]","+","int","(","data","[","\"size\"","]","[","1","]",")","self",".","pathfind","(",")"],"url":"https:\/\/github.com\/danth\/pathfinder.vim\/blob\/4f67053cbea56a45020d004b6bd059e38934a21a\/pathfinder\/server\/server.py#L63-L81"}
5
+ {"nwo":"danth\/pathfinder.vim","sha":"4f67053cbea56a45020d004b6bd059e38934a21a","path":"pathfinder\/server\/server.py","language":"python","identifier":"Server.pathfind","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Run the pathfinder, then send the result back to the client.","docstring_summary":"Run the pathfinder, then send the result back to the client.","docstring_tokens":["Run","the","pathfinder","then","send","the","result","back","to","the","client","."],"function":"def pathfind(self):\n \"\"\"Run the pathfinder, then send the result back to the client.\"\"\"\n dijkstra = Dijkstra(\n self.start_view, self.target_view, self.min_line, self.max_line\n )\n motions = dijkstra.find_path(self.client_connection)\n\n # If motions is None, that means we cancelled pathfinding because a new\n # request was received. We also check for another request now in case one was\n # sent during the last iteration of the pathfinding loop.\n if not (motions is None or self.client_connection.poll()):\n self.client_connection.send((\"RESULT\", motions))","function_tokens":["def","pathfind","(","self",")",":","dijkstra","=","Dijkstra","(","self",".","start_view",",","self",".","target_view",",","self",".","min_line",",","self",".","max_line",")","motions","=","dijkstra",".","find_path","(","self",".","client_connection",")","# If motions is None, that means we cancelled pathfinding because a new","# request was received. We also check for another request now in case one was","# sent during the last iteration of the pathfinding loop.","if","not","(","motions","is","None","or","self",".","client_connection",".","poll","(",")",")",":","self",".","client_connection",".","send","(","(","\"RESULT\"",",","motions",")",")"],"url":"https:\/\/github.com\/danth\/pathfinder.vim\/blob\/4f67053cbea56a45020d004b6bd059e38934a21a\/pathfinder\/server\/server.py#L83-L94"}
6
+ {"nwo":"danth\/pathfinder.vim","sha":"4f67053cbea56a45020d004b6bd059e38934a21a","path":"pathfinder\/server\/dijkstra.py","language":"python","identifier":"Dijkstra.find_path","parameters":"(self, client_connection)","argument_list":"","return_statement":"","docstring":"Use Dijkstra's algorithm to find the optimal sequence of motions.\n\n :param client_connection: If another pathfinding request is waiting on this\n connection, exit (returning None) as soon as possible. This cancels the\n pathfinding, moving on to the new request immediately.","docstring_summary":"Use Dijkstra's algorithm to find the optimal sequence of motions.","docstring_tokens":["Use","Dijkstra","s","algorithm","to","find","the","optimal","sequence","of","motions","."],"function":"def find_path(self, client_connection):\n \"\"\"\n Use Dijkstra's algorithm to find the optimal sequence of motions.\n\n :param client_connection: If another pathfinding request is waiting on this\n connection, exit (returning None) as soon as possible. This cancels the\n pathfinding, moving on to the new request immediately.\n \"\"\"\n while len(self._open_queue) > 0 and not client_connection.poll():\n current_node_key, current_distance = self._open_queue.popitem()\n current_node = self._open_nodes.pop(current_node_key)\n self._closed_nodes.add(current_node_key)\n\n if current_node.is_target():\n return current_node.reconstruct_path()\n\n for node in current_node.get_neighbours():\n if node.key in self._closed_nodes:\n continue\n\n new_distance = current_distance + current_node.motion_weight(\n node.came_by_motion\n )\n if (\n node.key not in self._open_nodes\n or new_distance < self._open_queue[node.key]\n ):\n node.set_came_from(current_node)\n self._open_nodes[node.key] = node\n self._open_queue[node.key] = new_distance","function_tokens":["def","find_path","(","self",",","client_connection",")",":","while","len","(","self",".","_open_queue",")",">","0","and","not","client_connection",".","poll","(",")",":","current_node_key",",","current_distance","=","self",".","_open_queue",".","popitem","(",")","current_node","=","self",".","_open_nodes",".","pop","(","current_node_key",")","self",".","_closed_nodes",".","add","(","current_node_key",")","if","current_node",".","is_target","(",")",":","return","current_node",".","reconstruct_path","(",")","for","node","in","current_node",".","get_neighbours","(",")",":","if","node",".","key","in","self",".","_closed_nodes",":","continue","new_distance","=","current_distance","+","current_node",".","motion_weight","(","node",".","came_by_motion",")","if","(","node",".","key","not","in","self",".","_open_nodes","or","new_distance","<","self",".","_open_queue","[","node",".","key","]",")",":","node",".","set_came_from","(","current_node",")","self",".","_open_nodes","[","node",".","key","]","=","node","self",".","_open_queue","[","node",".","key","]","=","new_distance"],"url":"https:\/\/github.com\/danth\/pathfinder.vim\/blob\/4f67053cbea56a45020d004b6bd059e38934a21a\/pathfinder\/server\/dijkstra.py#L39-L68"}
7
+ {"nwo":"danth\/pathfinder.vim","sha":"4f67053cbea56a45020d004b6bd059e38934a21a","path":"pathfinder\/server\/node.py","language":"python","identifier":"Node.get_neighbours","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Yield all neighbours of this node.","docstring_summary":"Yield all neighbours of this node.","docstring_tokens":["Yield","all","neighbours","of","this","node","."],"function":"def get_neighbours(self):\n \"\"\"Yield all neighbours of this node.\"\"\"\n for motion_generator in self.dijkstra.motion_generators:\n for node in motion_generator.generate(self.view):\n if (\n node.view.lnum >= self.dijkstra.min_line\n and node.view.lnum <= self.dijkstra.max_line\n ):\n yield node","function_tokens":["def","get_neighbours","(","self",")",":","for","motion_generator","in","self",".","dijkstra",".","motion_generators",":","for","node","in","motion_generator",".","generate","(","self",".","view",")",":","if","(","node",".","view",".","lnum",">=","self",".","dijkstra",".","min_line","and","node",".","view",".","lnum","<=","self",".","dijkstra",".","max_line",")",":","yield","node"],"url":"https:\/\/github.com\/danth\/pathfinder.vim\/blob\/4f67053cbea56a45020d004b6bd059e38934a21a\/pathfinder\/server\/node.py#L17-L25"}
8
+ {"nwo":"danth\/pathfinder.vim","sha":"4f67053cbea56a45020d004b6bd059e38934a21a","path":"pathfinder\/server\/node.py","language":"python","identifier":"Node.motion_weight","parameters":"(self, motion)","argument_list":"","return_statement":"","docstring":"Return the weight of using a motion from this node.","docstring_summary":"Return the weight of using a motion from this node.","docstring_tokens":["Return","the","weight","of","using","a","motion","from","this","node","."],"function":"def motion_weight(self, motion):\n \"\"\"Return the weight of using a motion from this node.\"\"\"\n if motion != self.came_by_motion:\n # First repetition, return number of characters in the motion\n return len(motion.motion) + (\n 0 if motion.argument is None else len(motion.argument)\n )\n elif self.came_by_motion_repetitions == 1:\n # Second repetition, adding a \"2\" is 1 extra character\n return 1\n else:\n # Difference in length of current and future count\n # 2j -> 3j = 0\n # 9j -> 10j = 1\n return len(str(self.came_by_motion_repetitions + 1)) - len(\n str(self.came_by_motion_repetitions)\n )","function_tokens":["def","motion_weight","(","self",",","motion",")",":","if","motion","!=","self",".","came_by_motion",":","# First repetition, return number of characters in the motion","return","len","(","motion",".","motion",")","+","(","0","if","motion",".","argument","is","None","else","len","(","motion",".","argument",")",")","elif","self",".","came_by_motion_repetitions","==","1",":","# Second repetition, adding a \"2\" is 1 extra character","return","1","else",":","# Difference in length of current and future count","# 2j -> 3j = 0","# 9j -> 10j = 1","return","len","(","str","(","self",".","came_by_motion_repetitions","+","1",")",")","-","len","(","str","(","self",".","came_by_motion_repetitions",")",")"],"url":"https:\/\/github.com\/danth\/pathfinder.vim\/blob\/4f67053cbea56a45020d004b6bd059e38934a21a\/pathfinder\/server\/node.py#L27-L43"}
9
+ {"nwo":"danth\/pathfinder.vim","sha":"4f67053cbea56a45020d004b6bd059e38934a21a","path":"pathfinder\/server\/node.py","language":"python","identifier":"Node.set_came_from","parameters":"(self, node)","argument_list":"","return_statement":"","docstring":"Set the node this node was reached from.","docstring_summary":"Set the node this node was reached from.","docstring_tokens":["Set","the","node","this","node","was","reached","from","."],"function":"def set_came_from(self, node):\n \"\"\"Set the node this node was reached from.\"\"\"\n self.came_from = node\n\n if node.came_by_motion == self.came_by_motion:\n self.came_by_motion_repetitions = node.came_by_motion_repetitions + 1\n else:\n self.came_by_motion_repetitions = 1","function_tokens":["def","set_came_from","(","self",",","node",")",":","self",".","came_from","=","node","if","node",".","came_by_motion","==","self",".","came_by_motion",":","self",".","came_by_motion_repetitions","=","node",".","came_by_motion_repetitions","+","1","else",":","self",".","came_by_motion_repetitions","=","1"],"url":"https:\/\/github.com\/danth\/pathfinder.vim\/blob\/4f67053cbea56a45020d004b6bd059e38934a21a\/pathfinder\/server\/node.py#L45-L52"}
10
+ {"nwo":"danth\/pathfinder.vim","sha":"4f67053cbea56a45020d004b6bd059e38934a21a","path":"pathfinder\/server\/node.py","language":"python","identifier":"Node.reconstruct_path","parameters":"(self)","argument_list":"","return_statement":"return motions","docstring":"Return the sequence of motions used to reach this node.","docstring_summary":"Return the sequence of motions used to reach this node.","docstring_tokens":["Return","the","sequence","of","motions","used","to","reach","this","node","."],"function":"def reconstruct_path(self):\n \"\"\"Return the sequence of motions used to reach this node.\"\"\"\n motions = list()\n node = self\n while node.came_from is not None:\n motions.insert(0, node.came_by_motion)\n node = node.came_from\n return motions","function_tokens":["def","reconstruct_path","(","self",")",":","motions","=","list","(",")","node","=","self","while","node",".","came_from","is","not","None",":","motions",".","insert","(","0",",","node",".","came_by_motion",")","node","=","node",".","came_from","return","motions"],"url":"https:\/\/github.com\/danth\/pathfinder.vim\/blob\/4f67053cbea56a45020d004b6bd059e38934a21a\/pathfinder\/server\/node.py#L57-L64"}
11
+ {"nwo":"danth\/pathfinder.vim","sha":"4f67053cbea56a45020d004b6bd059e38934a21a","path":"pathfinder\/server\/motions\/search.py","language":"python","identifier":"SearchMotionGenerator._escape_magic","parameters":"(self, search_query)","argument_list":"","return_statement":"return search_query","docstring":"Add backslash escapes to any \"magic\" characters in a query.","docstring_summary":"Add backslash escapes to any \"magic\" characters in a query.","docstring_tokens":["Add","backslash","escapes","to","any","magic","characters","in","a","query","."],"function":"def _escape_magic(self, search_query):\n \"\"\"Add backslash escapes to any \"magic\" characters in a query.\"\"\"\n for char in r\"\\^$.*[~\/\":\n search_query = search_query.replace(char, \"\\\\\" + char)\n return search_query","function_tokens":["def","_escape_magic","(","self",",","search_query",")",":","for","char","in","r\"\\^$.*[~\/\"",":","search_query","=","search_query",".","replace","(","char",",","\"\\\\\"","+","char",")","return","search_query"],"url":"https:\/\/github.com\/danth\/pathfinder.vim\/blob\/4f67053cbea56a45020d004b6bd059e38934a21a\/pathfinder\/server\/motions\/search.py#L27-L31"}
12
+ {"nwo":"danth\/pathfinder.vim","sha":"4f67053cbea56a45020d004b6bd059e38934a21a","path":"pathfinder\/server\/motions\/search.py","language":"python","identifier":"SearchMotionGenerator._search","parameters":"(self, text, start, target)","argument_list":"","return_statement":"","docstring":"Return the simplest possible searching motion to reach the given target.\n\n :param text: Contents of the file.\n :param start: Index in ``text`` to start the search from.\n :param target: Index of the target position in ``text``.","docstring_summary":"Return the simplest possible searching motion to reach the given target.","docstring_tokens":["Return","the","simplest","possible","searching","motion","to","reach","the","given","target","."],"function":"def _search(self, text, start, target):\n \"\"\"\n Return the simplest possible searching motion to reach the given target.\n\n :param text: Contents of the file.\n :param start: Index in ``text`` to start the search from.\n :param target: Index of the target position in ``text``.\n \"\"\"\n search_text = text[target:]\n\n # (\"a\", \"ab\", \"abc\", \"abcd\"...) until we reach\n # the end of search_text or find a working query\n for query_length in range(1, len(search_text) + 1):\n query = search_text[:query_length]\n\n # Get a list of all match positions for this search query\n # query=\"x\" text=\"x___x_xx\" == [0, 4, 6, 7]\n pattern = re.escape(query)\n matches = [m.start() for m in re.finditer(pattern, text)]\n\n if matches:\n # Sort the list so it begins with matches after `start`, rather\n # than matches at the beginning of the file\n # sorted([True, False]) == [False, True]\n matches.sort(key=lambda position: position <= start)\n\n if matches[0] == target:\n return self._create_motion(query)\n if matches[-1] == target:\n return self._create_motion(query, \"?\")","function_tokens":["def","_search","(","self",",","text",",","start",",","target",")",":","search_text","=","text","[","target",":","]","# (\"a\", \"ab\", \"abc\", \"abcd\"...) until we reach","# the end of search_text or find a working query","for","query_length","in","range","(","1",",","len","(","search_text",")","+","1",")",":","query","=","search_text","[",":","query_length","]","# Get a list of all match positions for this search query","# query=\"x\" text=\"x___x_xx\" == [0, 4, 6, 7]","pattern","=","re",".","escape","(","query",")","matches","=","[","m",".","start","(",")","for","m","in","re",".","finditer","(","pattern",",","text",")","]","if","matches",":","# Sort the list so it begins with matches after `start`, rather","# than matches at the beginning of the file","# sorted([True, False]) == [False, True]","matches",".","sort","(","key","=","lambda","position",":","position","<=","start",")","if","matches","[","0","]","==","target",":","return","self",".","_create_motion","(","query",")","if","matches","[","-","1","]","==","target",":","return","self",".","_create_motion","(","query",",","\"?\"",")"],"url":"https:\/\/github.com\/danth\/pathfinder.vim\/blob\/4f67053cbea56a45020d004b6bd059e38934a21a\/pathfinder\/server\/motions\/search.py#L33-L62"}
13
+ {"nwo":"danth\/pathfinder.vim","sha":"4f67053cbea56a45020d004b6bd059e38934a21a","path":"pathfinder\/server\/motions\/search.py","language":"python","identifier":"SearchMotionGenerator._search_lines","parameters":"(self, lines, start_line, start_col, target_line, target_col)","argument_list":"","return_statement":"return self._search(text, start, target)","docstring":"Wrapper around _search which handles 2d coordinates and a list of lines.\n\n :param lines: List of lines.\n :param start_line: Starting line, indexed from 0.\n :param start_col: Starting column.\n :param target_line: Target line, indexed from 0.\n :param target_col: Target column.","docstring_summary":"Wrapper around _search which handles 2d coordinates and a list of lines.","docstring_tokens":["Wrapper","around","_search","which","handles","2d","coordinates","and","a","list","of","lines","."],"function":"def _search_lines(self, lines, start_line, start_col, target_line, target_col):\n \"\"\"\n Wrapper around _search which handles 2d coordinates and a list of lines.\n\n :param lines: List of lines.\n :param start_line: Starting line, indexed from 0.\n :param start_col: Starting column.\n :param target_line: Target line, indexed from 0.\n :param target_col: Target column.\n \"\"\"\n text = \"\\n\".join(lines)\n start = sum(len(line) + 1 for line in lines[:start_line]) + start_col\n target = sum(len(line) + 1 for line in lines[:target_line]) + target_col\n return self._search(text, start, target)","function_tokens":["def","_search_lines","(","self",",","lines",",","start_line",",","start_col",",","target_line",",","target_col",")",":","text","=","\"\\n\"",".","join","(","lines",")","start","=","sum","(","len","(","line",")","+","1","for","line","in","lines","[",":","start_line","]",")","+","start_col","target","=","sum","(","len","(","line",")","+","1","for","line","in","lines","[",":","target_line","]",")","+","target_col","return","self",".","_search","(","text",",","start",",","target",")"],"url":"https:\/\/github.com\/danth\/pathfinder.vim\/blob\/4f67053cbea56a45020d004b6bd059e38934a21a\/pathfinder\/server\/motions\/search.py#L64-L77"}
14
+ {"nwo":"danth\/pathfinder.vim","sha":"4f67053cbea56a45020d004b6bd059e38934a21a","path":"pathfinder\/server\/motions\/simple.py","language":"python","identifier":"SimpleMotionGenerator._try_motion","parameters":"(self, view, motion)","argument_list":"","return_statement":"return winsaveview()","docstring":"Use a motion inside Vim, starting from the given view.\n\n If the motion causes an error, return None.","docstring_summary":"Use a motion inside Vim, starting from the given view.","docstring_tokens":["Use","a","motion","inside","Vim","starting","from","the","given","view","."],"function":"def _try_motion(self, view, motion):\n \"\"\"\n Use a motion inside Vim, starting from the given view.\n\n If the motion causes an error, return None.\n \"\"\"\n winrestview(view)\n try:\n vim.command(f\"silent! normal! {motion}\")\n except:\n return None\n return winsaveview()","function_tokens":["def","_try_motion","(","self",",","view",",","motion",")",":","winrestview","(","view",")","try",":","vim",".","command","(","f\"silent! normal! {motion}\"",")","except",":","return","None","return","winsaveview","(",")"],"url":"https:\/\/github.com\/danth\/pathfinder.vim\/blob\/4f67053cbea56a45020d004b6bd059e38934a21a\/pathfinder\/server\/motions\/simple.py#L73-L84"}
15
+ {"nwo":"danth\/pathfinder.vim","sha":"4f67053cbea56a45020d004b6bd059e38934a21a","path":"pathfinder\/server\/motions\/__init__.py","language":"python","identifier":"MotionGenerator.generate","parameters":"(self, view)","argument_list":"","return_statement":"","docstring":"Yield all neighbouring nodes found from the given view.","docstring_summary":"Yield all neighbouring nodes found from the given view.","docstring_tokens":["Yield","all","neighbouring","nodes","found","from","the","given","view","."],"function":"def generate(self, view):\n \"\"\"Yield all neighbouring nodes found from the given view.\"\"\"\n pass","function_tokens":["def","generate","(","self",",","view",")",":","pass"],"url":"https:\/\/github.com\/danth\/pathfinder.vim\/blob\/4f67053cbea56a45020d004b6bd059e38934a21a\/pathfinder\/server\/motions\/__init__.py#L16-L18"}
16
+ {"nwo":"danth\/pathfinder.vim","sha":"4f67053cbea56a45020d004b6bd059e38934a21a","path":"pathfinder\/client\/explore_lines.py","language":"python","identifier":"get_explore_lines","parameters":"(search_area_lines)","argument_list":"","return_statement":"","docstring":":param search_area_lines: Number of lines between, and including, the start and\n target positions.\n :returns: Number of lines to explore either side of the search area.","docstring_summary":":param search_area_lines: Number of lines between, and including, the start and\n target positions.\n :returns: Number of lines to explore either side of the search area.","docstring_tokens":[":","param","search_area_lines",":","Number","of","lines","between","and","including","the","start","and","target","positions",".",":","returns",":","Number","of","lines","to","explore","either","side","of","the","search","area","."],"function":"def get_explore_lines(search_area_lines):\n \"\"\"\n :param search_area_lines: Number of lines between, and including, the start and\n target positions.\n :returns: Number of lines to explore either side of the search area.\n \"\"\"\n # Get setting values from Vim variables\n explore_scale = float(vim.vars[\"pf_explore_scale\"])\n max_explore = int(vim.vars[\"pf_max_explore\"])\n\n if explore_scale < 0:\n # This filtering is disabled, explore the entire buffer\n return len(vim.current.buffer)\n\n # Number of lines to explore above and below the search area is scaled based\n # on the length of the area. This setting defaults to 0.5, if the search area\n # was e.g. 6 lines then 3 more lines would be explored on either side.\n explore_lines = search_area_lines * explore_scale\n if max_explore >= 0:\n # Limit to no more than max_explore lines\n return min(max_explore, explore_lines)\n else:\n # Do not limit\n return explore_lines","function_tokens":["def","get_explore_lines","(","search_area_lines",")",":","# Get setting values from Vim variables","explore_scale","=","float","(","vim",".","vars","[","\"pf_explore_scale\"","]",")","max_explore","=","int","(","vim",".","vars","[","\"pf_max_explore\"","]",")","if","explore_scale","<","0",":","# This filtering is disabled, explore the entire buffer","return","len","(","vim",".","current",".","buffer",")","# Number of lines to explore above and below the search area is scaled based","# on the length of the area. This setting defaults to 0.5, if the search area","# was e.g. 6 lines then 3 more lines would be explored on either side.","explore_lines","=","search_area_lines","*","explore_scale","if","max_explore",">=","0",":","# Limit to no more than max_explore lines","return","min","(","max_explore",",","explore_lines",")","else",":","# Do not limit","return","explore_lines"],"url":"https:\/\/github.com\/danth\/pathfinder.vim\/blob\/4f67053cbea56a45020d004b6bd059e38934a21a\/pathfinder\/client\/explore_lines.py#L4-L27"}
17
+ {"nwo":"danth\/pathfinder.vim","sha":"4f67053cbea56a45020d004b6bd059e38934a21a","path":"pathfinder\/client\/explore_lines.py","language":"python","identifier":"get_line_limits","parameters":"(start_view, target_view)","argument_list":"","return_statement":"return (\n max(1, min_line - explore_lines),\n min(len(vim.current.buffer), max_line + explore_lines),\n )","docstring":"Return the minimum and maximum line numbers to explore.\n\n :param start_view: The start position.\n :param target_view: The target position.\n :returns: Tuple of (min line, max line)","docstring_summary":"Return the minimum and maximum line numbers to explore.","docstring_tokens":["Return","the","minimum","and","maximum","line","numbers","to","explore","."],"function":"def get_line_limits(start_view, target_view):\n \"\"\"\n Return the minimum and maximum line numbers to explore.\n\n :param start_view: The start position.\n :param target_view: The target position.\n :returns: Tuple of (min line, max line)\n \"\"\"\n min_line = min(int(start_view.lnum), int(target_view.lnum))\n max_line = max(int(start_view.lnum), int(target_view.lnum))\n explore_lines = get_explore_lines(max_line - min_line)\n\n return (\n max(1, min_line - explore_lines),\n min(len(vim.current.buffer), max_line + explore_lines),\n )","function_tokens":["def","get_line_limits","(","start_view",",","target_view",")",":","min_line","=","min","(","int","(","start_view",".","lnum",")",",","int","(","target_view",".","lnum",")",")","max_line","=","max","(","int","(","start_view",".","lnum",")",",","int","(","target_view",".","lnum",")",")","explore_lines","=","get_explore_lines","(","max_line","-","min_line",")","return","(","max","(","1",",","min_line","-","explore_lines",")",",","min","(","len","(","vim",".","current",".","buffer",")",",","max_line","+","explore_lines",")",",",")"],"url":"https:\/\/github.com\/danth\/pathfinder.vim\/blob\/4f67053cbea56a45020d004b6bd059e38934a21a\/pathfinder\/client\/explore_lines.py#L30-L45"}
18
+ {"nwo":"danth\/pathfinder.vim","sha":"4f67053cbea56a45020d004b6bd059e38934a21a","path":"pathfinder\/client\/state_tracker.py","language":"python","identifier":"StateTracker.choose_action_using","parameters":"(self, function)","argument_list":"","return_statement":"return result","docstring":"Choose an action to take using the given function.\n\n Function will be called with the arguments (start state, current state,\n time of most recent update). It may return \"reset\" or \"set_target\" to\n call the corresponding method, or any other value to do nothing. The\n function's return value is passed through this method, so can be used\n to take further actions elsewhere.","docstring_summary":"Choose an action to take using the given function.","docstring_tokens":["Choose","an","action","to","take","using","the","given","function","."],"function":"def choose_action_using(self, function):\n \"\"\"\n Choose an action to take using the given function.\n\n Function will be called with the arguments (start state, current state,\n time of most recent update). It may return \"reset\" or \"set_target\" to\n call the corresponding method, or any other value to do nothing. The\n function's return value is passed through this method, so can be used\n to take further actions elsewhere.\n \"\"\"\n current_state = self._record_state()\n\n result = function(self.start_state, current_state, self.update_time)\n if result == \"reset\":\n self._reset(current_state)\n elif result == \"set_target\":\n self._set_target(current_state)\n\n return result","function_tokens":["def","choose_action_using","(","self",",","function",")",":","current_state","=","self",".","_record_state","(",")","result","=","function","(","self",".","start_state",",","current_state",",","self",".","update_time",")","if","result","==","\"reset\"",":","self",".","_reset","(","current_state",")","elif","result","==","\"set_target\"",":","self",".","_set_target","(","current_state",")","return","result"],"url":"https:\/\/github.com\/danth\/pathfinder.vim\/blob\/4f67053cbea56a45020d004b6bd059e38934a21a\/pathfinder\/client\/state_tracker.py#L45-L63"}
19
+ {"nwo":"danth\/pathfinder.vim","sha":"4f67053cbea56a45020d004b6bd059e38934a21a","path":"pathfinder\/client\/output.py","language":"python","identifier":"strtrans","parameters":"(string)","argument_list":"","return_statement":"return vim.eval(f\"strtrans('{escaped_string}')\")","docstring":"Convert special characters like '\u0004' to '^D'.","docstring_summary":"Convert special characters like '\u0004' to '^D'.","docstring_tokens":["Convert","special","characters","like","\u0004","to","^D","."],"function":"def strtrans(string):\n \"\"\"Convert special characters like '\u0004' to '^D'.\"\"\"\n escaped_string = string.replace(\"'\", \"\\\\'\").replace(\"\\\\\", \"\\\\\\\\\")\n return vim.eval(f\"strtrans('{escaped_string}')\")","function_tokens":["def","strtrans","(","string",")",":","escaped_string","=","string",".","replace","(","\"'\"",",","\"\\\\'\"",")",".","replace","(","\"\\\\\"",",","\"\\\\\\\\\"",")","return","vim",".","eval","(","f\"strtrans('{escaped_string}')\"",")"],"url":"https:\/\/github.com\/danth\/pathfinder.vim\/blob\/4f67053cbea56a45020d004b6bd059e38934a21a\/pathfinder\/client\/output.py#L10-L13"}
20
+ {"nwo":"danth\/pathfinder.vim","sha":"4f67053cbea56a45020d004b6bd059e38934a21a","path":"pathfinder\/client\/output.py","language":"python","identifier":"get_count","parameters":"(motion, count)","argument_list":"","return_statement":"return str(count) + motion_str","docstring":"Build a string like 'k', 'hh', '15w","docstring_summary":"Build a string like 'k', 'hh', '15w","docstring_tokens":["Build","a","string","like","k","hh","15w"],"function":"def get_count(motion, count):\n \"\"\"Build a string like 'k', 'hh', '15w'\"\"\"\n motion_str = strtrans(motion.motion + (motion.argument or \"\"))\n if count == 1:\n return motion_str\n\n elif count == 2 and len(motion_str) == 1:\n # It's easier to press a single-character motion twice\n # than to type a 2 before it\n return (motion_str) * 2\n\n return str(count) + motion_str","function_tokens":["def","get_count","(","motion",",","count",")",":","motion_str","=","strtrans","(","motion",".","motion","+","(","motion",".","argument","or","\"\"",")",")","if","count","==","1",":","return","motion_str","elif","count","==","2","and","len","(","motion_str",")","==","1",":","# It's easier to press a single-character motion twice","# than to type a 2 before it","return","(","motion_str",")","*","2","return","str","(","count",")","+","motion_str"],"url":"https:\/\/github.com\/danth\/pathfinder.vim\/blob\/4f67053cbea56a45020d004b6bd059e38934a21a\/pathfinder\/client\/output.py#L16-L27"}
21
+ {"nwo":"danth\/pathfinder.vim","sha":"4f67053cbea56a45020d004b6bd059e38934a21a","path":"pathfinder\/client\/output.py","language":"python","identifier":"compact_motions","parameters":"(motions)","argument_list":"","return_statement":"return \" \".join(\n [\n get_count(motion, len(list(group)))\n for motion, group in itertools.groupby(motions)\n ]\n )","docstring":"Return the given motion sequence in single-line form.\n\n e.g. 2* 5j $","docstring_summary":"Return the given motion sequence in single-line form.","docstring_tokens":["Return","the","given","motion","sequence","in","single","-","line","form","."],"function":"def compact_motions(motions):\n \"\"\"\n Return the given motion sequence in single-line form.\n\n e.g. 2* 5j $\n \"\"\"\n return \" \".join(\n [\n get_count(motion, len(list(group)))\n for motion, group in itertools.groupby(motions)\n ]\n )","function_tokens":["def","compact_motions","(","motions",")",":","return","\" \"",".","join","(","[","get_count","(","motion",",","len","(","list","(","group",")",")",")","for","motion",",","group","in","itertools",".","groupby","(","motions",")","]",")"],"url":"https:\/\/github.com\/danth\/pathfinder.vim\/blob\/4f67053cbea56a45020d004b6bd059e38934a21a\/pathfinder\/client\/output.py#L30-L41"}
22
+ {"nwo":"danth\/pathfinder.vim","sha":"4f67053cbea56a45020d004b6bd059e38934a21a","path":"pathfinder\/client\/output.py","language":"python","identifier":"explained_motions","parameters":"(motions)","argument_list":"","return_statement":"","docstring":"Yield each motion in the form \"motion <padding> help\"\n\n e.g. ['5j Down 5 lines', '$ To the end of the line']","docstring_summary":"Yield each motion in the form \"motion <padding> help\"","docstring_tokens":["Yield","each","motion","in","the","form","motion","<padding",">","help"],"function":"def explained_motions(motions):\n \"\"\"\n Yield each motion in the form \"motion <padding> help\"\n\n e.g. ['5j Down 5 lines', '$ To the end of the line']\n \"\"\"\n for motion, group in itertools.groupby(motions):\n repetitions = len(list(group))\n yield (\n get_count(motion, repetitions) + \" \" + get_description(motion, repetitions)\n )","function_tokens":["def","explained_motions","(","motions",")",":","for","motion",",","group","in","itertools",".","groupby","(","motions",")",":","repetitions","=","len","(","list","(","group",")",")","yield","(","get_count","(","motion",",","repetitions",")","+","\" \"","+","get_description","(","motion",",","repetitions",")",")"],"url":"https:\/\/github.com\/danth\/pathfinder.vim\/blob\/4f67053cbea56a45020d004b6bd059e38934a21a\/pathfinder\/client\/output.py#L52-L62"}
23
+ {"nwo":"danth\/pathfinder.vim","sha":"4f67053cbea56a45020d004b6bd059e38934a21a","path":"pathfinder\/client\/client.py","language":"python","identifier":"Client.open","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Launch and connect to the server Vim.","docstring_summary":"Launch and connect to the server Vim.","docstring_tokens":["Launch","and","connect","to","the","server","Vim","."],"function":"def open(self):\n \"\"\"Launch and connect to the server Vim.\"\"\"\n # Create a file used to communicate with the server\n self.file_path = os.path.join(\n tempfile.gettempdir(), \"pathfinder_vim_\" + vim.eval(\"getpid()\")\n )\n\n self.server_process = subprocess.Popen(\n self._build_server_cmd(), stdout=subprocess.PIPE, stderr=subprocess.PIPE\n )\n\n self.server_connection = None\n self.to_send = None","function_tokens":["def","open","(","self",")",":","# Create a file used to communicate with the server","self",".","file_path","=","os",".","path",".","join","(","tempfile",".","gettempdir","(",")",",","\"pathfinder_vim_\"","+","vim",".","eval","(","\"getpid()\"",")",")","self",".","server_process","=","subprocess",".","Popen","(","self",".","_build_server_cmd","(",")",",","stdout","=","subprocess",".","PIPE",",","stderr","=","subprocess",".","PIPE",")","self",".","server_connection","=","None","self",".","to_send","=","None"],"url":"https:\/\/github.com\/danth\/pathfinder.vim\/blob\/4f67053cbea56a45020d004b6bd059e38934a21a\/pathfinder\/client\/client.py#L26-L38"}
24
+ {"nwo":"danth\/pathfinder.vim","sha":"4f67053cbea56a45020d004b6bd059e38934a21a","path":"pathfinder\/client\/client.py","language":"python","identifier":"Client._build_server_cmd","parameters":"(self)","argument_list":"","return_statement":"return options","docstring":"Build the command used to launch the server Vim.","docstring_summary":"Build the command used to launch the server Vim.","docstring_tokens":["Build","the","command","used","to","launch","the","server","Vim","."],"function":"def _build_server_cmd(self):\n \"\"\"Build the command used to launch the server Vim.\"\"\"\n progpath = vim.eval(\"v:progpath\")\n\n options = [\n progpath,\n \"--clean\",\n \"--cmd\",\n f\"let g:pf_server_communication_file='{self.file_path}'\",\n \"-u\",\n os.path.normpath(\n # serverrc.vim in the root of this repository, instead of the user's\n # regular .vimrc or init.vim\n os.path.join(os.path.dirname(__file__), \"..\", \"..\", \"serverrc.vim\")\n ),\n ]\n\n if progpath.endswith(\"nvim\"):\n python3_host_prog = vim.eval(\"g:python3_host_prog\")\n options += [\n \"--headless\",\n \"--cmd\",\n f\"let g:python3_host_prog='{python3_host_prog}'\",\n ]\n else:\n options += [\"-v\", \"--not-a-term\"]\n\n return options","function_tokens":["def","_build_server_cmd","(","self",")",":","progpath","=","vim",".","eval","(","\"v:progpath\"",")","options","=","[","progpath",",","\"--clean\"",",","\"--cmd\"",",","f\"let g:pf_server_communication_file='{self.file_path}'\"",",","\"-u\"",",","os",".","path",".","normpath","(","# serverrc.vim in the root of this repository, instead of the user's","# regular .vimrc or init.vim","os",".","path",".","join","(","os",".","path",".","dirname","(","__file__",")",",","\"..\"",",","\"..\"",",","\"serverrc.vim\"",")",")",",","]","if","progpath",".","endswith","(","\"nvim\"",")",":","python3_host_prog","=","vim",".","eval","(","\"g:python3_host_prog\"",")","options","+=","[","\"--headless\"",",","\"--cmd\"",",","f\"let g:python3_host_prog='{python3_host_prog}'\"",",","]","else",":","options","+=","[","\"-v\"",",","\"--not-a-term\"","]","return","options"],"url":"https:\/\/github.com\/danth\/pathfinder.vim\/blob\/4f67053cbea56a45020d004b6bd059e38934a21a\/pathfinder\/client\/client.py#L40-L67"}
25
+ {"nwo":"danth\/pathfinder.vim","sha":"4f67053cbea56a45020d004b6bd059e38934a21a","path":"pathfinder\/client\/client.py","language":"python","identifier":"Client.close","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Shut down the server Vim.","docstring_summary":"Shut down the server Vim.","docstring_tokens":["Shut","down","the","server","Vim","."],"function":"def close(self):\n \"\"\"Shut down the server Vim.\"\"\"\n if self.server_connection is not None:\n # Server will shut down Vim gracefully when we disconnect\n self.server_connection.close()\n elif self.server_process is not None:\n # Not connected yet, terminate the process instead\n self.server_process.terminate()","function_tokens":["def","close","(","self",")",":","if","self",".","server_connection","is","not","None",":","# Server will shut down Vim gracefully when we disconnect","self",".","server_connection",".","close","(",")","elif","self",".","server_process","is","not","None",":","# Not connected yet, terminate the process instead","self",".","server_process",".","terminate","(",")"],"url":"https:\/\/github.com\/danth\/pathfinder.vim\/blob\/4f67053cbea56a45020d004b6bd059e38934a21a\/pathfinder\/client\/client.py#L69-L76"}
26
+ {"nwo":"danth\/pathfinder.vim","sha":"4f67053cbea56a45020d004b6bd059e38934a21a","path":"pathfinder\/client\/client.py","language":"python","identifier":"Client.connect","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Attempt to connect to the server.\n\n :returns: whether a connection is ready.","docstring_summary":"Attempt to connect to the server.","docstring_tokens":["Attempt","to","connect","to","the","server","."],"function":"def connect(self):\n \"\"\"\n Attempt to connect to the server.\n\n :returns: whether a connection is ready.\n \"\"\"\n if self.server_connection is not None:\n return True\n\n if self.server_process is None:\n # Server process has exited but we already raised an exception\n return False\n\n return_code = self.server_process.poll()\n if return_code is not None:\n # Server process has exited\n stdout, stderr = self.server_process.communicate()\n self.server_process = None\n raise Exception(\n f\"Pathfinding server process exited with return code {return_code}:\\n\"\n + stderr.decode()\n )\n\n try:\n # Attempt to connect\n self.server_connection = connection.Client(self.file_path)\n return True\n except FileNotFoundError:\n return False","function_tokens":["def","connect","(","self",")",":","if","self",".","server_connection","is","not","None",":","return","True","if","self",".","server_process","is","None",":","# Server process has exited but we already raised an exception","return","False","return_code","=","self",".","server_process",".","poll","(",")","if","return_code","is","not","None",":","# Server process has exited","stdout",",","stderr","=","self",".","server_process",".","communicate","(",")","self",".","server_process","=","None","raise","Exception","(","f\"Pathfinding server process exited with return code {return_code}:\\n\"","+","stderr",".","decode","(",")",")","try",":","# Attempt to connect","self",".","server_connection","=","connection",".","Client","(","self",".","file_path",")","return","True","except","FileNotFoundError",":","return","False"],"url":"https:\/\/github.com\/danth\/pathfinder.vim\/blob\/4f67053cbea56a45020d004b6bd059e38934a21a\/pathfinder\/client\/client.py#L93-L121"}
27
+ {"nwo":"danth\/pathfinder.vim","sha":"4f67053cbea56a45020d004b6bd059e38934a21a","path":"pathfinder\/client\/client.py","language":"python","identifier":"Client.handle_response","parameters":"(self, response_type, data)","argument_list":"","return_statement":"","docstring":"Process a response recieved from the server.\n\n This will be one of:\n - ``RESULT`` - A pathfinding result. Call the first queued callback.\n - ``ERROR`` - An unexpected exception was caught and the server has exited.\n Relay the traceback to the user for debugging.","docstring_summary":"Process a response recieved from the server.","docstring_tokens":["Process","a","response","recieved","from","the","server","."],"function":"def handle_response(self, response_type, data):\n \"\"\"\n Process a response recieved from the server.\n\n This will be one of:\n - ``RESULT`` - A pathfinding result. Call the first queued callback.\n - ``ERROR`` - An unexpected exception was caught and the server has exited.\n Relay the traceback to the user for debugging.\n \"\"\"\n if response_type == \"RESULT\":\n # Get the first callback function and pass the result to it\n self.callback(data)\n del self.callback\n elif response_type == \"ERROR\":\n raise Exception(\"Pathfinding server encountered an exception:\\n\" + data)\n else:\n raise Exception(\"Received an unexpected response \" + response_type)","function_tokens":["def","handle_response","(","self",",","response_type",",","data",")",":","if","response_type","==","\"RESULT\"",":","# Get the first callback function and pass the result to it","self",".","callback","(","data",")","del","self",".","callback","elif","response_type","==","\"ERROR\"",":","raise","Exception","(","\"Pathfinding server encountered an exception:\\n\"","+","data",")","else",":","raise","Exception","(","\"Received an unexpected response \"","+","response_type",")"],"url":"https:\/\/github.com\/danth\/pathfinder.vim\/blob\/4f67053cbea56a45020d004b6bd059e38934a21a\/pathfinder\/client\/client.py#L123-L139"}
28
+ {"nwo":"danth\/pathfinder.vim","sha":"4f67053cbea56a45020d004b6bd059e38934a21a","path":"pathfinder\/client\/client.py","language":"python","identifier":"Client.pathfind","parameters":"(self, buffer_contents, start_view, target_view, callback)","argument_list":"","return_statement":"","docstring":"Request a pathfinding result from the server.\n\n :param buffer_contents: List of lines we are pathfinding inside.\n :param start_view: The start position, in the current window.\n :param target_view: The target position, in the current window.\n :param callback: Function to be called once a path is found. Recieves a list\n of motions as a parameter.","docstring_summary":"Request a pathfinding result from the server.","docstring_tokens":["Request","a","pathfinding","result","from","the","server","."],"function":"def pathfind(self, buffer_contents, start_view, target_view, callback):\n \"\"\"\n Request a pathfinding result from the server.\n\n :param buffer_contents: List of lines we are pathfinding inside.\n :param start_view: The start position, in the current window.\n :param target_view: The target position, in the current window.\n :param callback: Function to be called once a path is found. Recieves a list\n of motions as a parameter.\n \"\"\"\n self.callback = callback\n\n min_line, max_line = get_line_limits(start_view, target_view)\n self.to_send = {\n \"start\": start_view,\n \"target\": target_view,\n \"min_line\": min_line,\n \"max_line\": max_line,\n \"size\": (\n # WindowTextWidth() - see plugin\/dimensions.vim\n vim.eval(\"WindowTextWidth()\"),\n vim.eval(\"winheight(0)\"),\n ),\n \"buffer\": buffer_contents,\n \"wrap\": vim.current.window.options[\"wrap\"],\n \"scrolloff\": vim.options[\"scrolloff\"],\n \"sidescrolloff\": vim.options[\"sidescrolloff\"],\n }","function_tokens":["def","pathfind","(","self",",","buffer_contents",",","start_view",",","target_view",",","callback",")",":","self",".","callback","=","callback","min_line",",","max_line","=","get_line_limits","(","start_view",",","target_view",")","self",".","to_send","=","{","\"start\"",":","start_view",",","\"target\"",":","target_view",",","\"min_line\"",":","min_line",",","\"max_line\"",":","max_line",",","\"size\"",":","(","# WindowTextWidth() - see plugin\/dimensions.vim","vim",".","eval","(","\"WindowTextWidth()\"",")",",","vim",".","eval","(","\"winheight(0)\"",")",",",")",",","\"buffer\"",":","buffer_contents",",","\"wrap\"",":","vim",".","current",".","window",".","options","[","\"wrap\"","]",",","\"scrolloff\"",":","vim",".","options","[","\"scrolloff\"","]",",","\"sidescrolloff\"",":","vim",".","options","[","\"sidescrolloff\"","]",",","}"],"url":"https:\/\/github.com\/danth\/pathfinder.vim\/blob\/4f67053cbea56a45020d004b6bd059e38934a21a\/pathfinder\/client\/client.py#L141-L168"}
29
+ {"nwo":"danth\/pathfinder.vim","sha":"4f67053cbea56a45020d004b6bd059e38934a21a","path":"pathfinder\/client\/popup.py","language":"python","identifier":"_neovim_popup","parameters":"(text, line_offset)","argument_list":"","return_statement":"","docstring":"Create a popup using Neovim 0.4+ floating windows.","docstring_summary":"Create a popup using Neovim 0.4+ floating windows.","docstring_tokens":["Create","a","popup","using","Neovim","0",".","4","+","floating","windows","."],"function":"def _neovim_popup(text, line_offset):\n \"\"\"Create a popup using Neovim 0.4+ floating windows.\"\"\"\n # Insert text into a scratch buffer\n buffer = vim.api.create_buf(False, True)\n vim.api.buf_set_lines(buffer, 0, -1, True, [f\" {text} \"])\n\n # Create a window containing the buffer\n window = vim.api.open_win(\n buffer,\n 0,\n {\n \"relative\": \"cursor\",\n \"row\": int(line_offset),\n \"col\": 0,\n \"style\": \"minimal\",\n \"focusable\": 0,\n \"height\": 1,\n \"width\": len(text) + 2,\n },\n )\n # Set the highlight of the window to match the cursor\n vim.api.win_set_option(window, \"winhl\", \"Normal:PathfinderPopup\")\n\n # Create a timer to close the window\n popup_time = int(vim.vars[\"pf_popup_time\"])\n vim.eval(f\"timer_start({popup_time}, {{-> nvim_win_close({window.handle}, 1)}})\")","function_tokens":["def","_neovim_popup","(","text",",","line_offset",")",":","# Insert text into a scratch buffer","buffer","=","vim",".","api",".","create_buf","(","False",",","True",")","vim",".","api",".","buf_set_lines","(","buffer",",","0",",","-","1",",","True",",","[","f\" {text} \"","]",")","# Create a window containing the buffer","window","=","vim",".","api",".","open_win","(","buffer",",","0",",","{","\"relative\"",":","\"cursor\"",",","\"row\"",":","int","(","line_offset",")",",","\"col\"",":","0",",","\"style\"",":","\"minimal\"",",","\"focusable\"",":","0",",","\"height\"",":","1",",","\"width\"",":","len","(","text",")","+","2",",","}",",",")","# Set the highlight of the window to match the cursor","vim",".","api",".","win_set_option","(","window",",","\"winhl\"",",","\"Normal:PathfinderPopup\"",")","# Create a timer to close the window","popup_time","=","int","(","vim",".","vars","[","\"pf_popup_time\"","]",")","vim",".","eval","(","f\"timer_start({popup_time}, {{-> nvim_win_close({window.handle}, 1)}})\"",")"],"url":"https:\/\/github.com\/danth\/pathfinder.vim\/blob\/4f67053cbea56a45020d004b6bd059e38934a21a\/pathfinder\/client\/popup.py#L6-L31"}
30
+ {"nwo":"danth\/pathfinder.vim","sha":"4f67053cbea56a45020d004b6bd059e38934a21a","path":"pathfinder\/client\/popup.py","language":"python","identifier":"_vim_popup","parameters":"(text, line_offset)","argument_list":"","return_statement":"","docstring":"Create a popup using Vim +popupwin.","docstring_summary":"Create a popup using Vim +popupwin.","docstring_tokens":["Create","a","popup","using","Vim","+","popupwin","."],"function":"def _vim_popup(text, line_offset):\n \"\"\"Create a popup using Vim +popupwin.\"\"\"\n vim.Function(\"popup_create\")(\n text,\n {\n \"line\": f\"cursor{line_offset}\",\n \"col\": \"cursor\",\n \"wrap\": False,\n \"padding\": (0, 1, 0, 1),\n \"highlight\": \"PathfinderPopup\",\n \"time\": int(vim.vars[\"pf_popup_time\"]),\n \"zindex\": 1000,\n },\n )","function_tokens":["def","_vim_popup","(","text",",","line_offset",")",":","vim",".","Function","(","\"popup_create\"",")","(","text",",","{","\"line\"",":","f\"cursor{line_offset}\"",",","\"col\"",":","\"cursor\"",",","\"wrap\"",":","False",",","\"padding\"",":","(","0",",","1",",","0",",","1",")",",","\"highlight\"",":","\"PathfinderPopup\"",",","\"time\"",":","int","(","vim",".","vars","[","\"pf_popup_time\"","]",")",",","\"zindex\"",":","1000",",","}",",",")"],"url":"https:\/\/github.com\/danth\/pathfinder.vim\/blob\/4f67053cbea56a45020d004b6bd059e38934a21a\/pathfinder\/client\/popup.py#L34-L47"}
31
+ {"nwo":"danth\/pathfinder.vim","sha":"4f67053cbea56a45020d004b6bd059e38934a21a","path":"pathfinder\/client\/plugin.py","language":"python","identifier":"Plugin._run","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Start calculating a path in the background.","docstring_summary":"Start calculating a path in the background.","docstring_tokens":["Start","calculating","a","path","in","the","background","."],"function":"def _run(self):\n \"\"\"Start calculating a path in the background.\"\"\"\n self.client.pathfind(\n self.state_tracker.start_state.lines,\n self.state_tracker.start_state.view,\n self.state_tracker.target_state.view,\n self.popup,\n )","function_tokens":["def","_run","(","self",")",":","self",".","client",".","pathfind","(","self",".","state_tracker",".","start_state",".","lines",",","self",".","state_tracker",".","start_state",".","view",",","self",".","state_tracker",".","target_state",".","view",",","self",".","popup",",",")"],"url":"https:\/\/github.com\/danth\/pathfinder.vim\/blob\/4f67053cbea56a45020d004b6bd059e38934a21a\/pathfinder\/client\/plugin.py#L19-L26"}
32
+ {"nwo":"danth\/pathfinder.vim","sha":"4f67053cbea56a45020d004b6bd059e38934a21a","path":"pathfinder\/client\/plugin.py","language":"python","identifier":"Plugin.autorun","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Called on a timer several times per second.","docstring_summary":"Called on a timer several times per second.","docstring_tokens":["Called","on","a","timer","several","times","per","second","."],"function":"def autorun(self):\n \"\"\"Called on a timer several times per second.\"\"\"\n if self.state_tracker.choose_action_using(choose_action) == \"pathfind\":\n if not cursor_in_same_position(\n self.state_tracker.start_state.view,\n self.state_tracker.target_state.view,\n ):\n self._run()\n self.state_tracker.reset()","function_tokens":["def","autorun","(","self",")",":","if","self",".","state_tracker",".","choose_action_using","(","choose_action",")","==","\"pathfind\"",":","if","not","cursor_in_same_position","(","self",".","state_tracker",".","start_state",".","view",",","self",".","state_tracker",".","target_state",".","view",",",")",":","self",".","_run","(",")","self",".","state_tracker",".","reset","(",")"],"url":"https:\/\/github.com\/danth\/pathfinder.vim\/blob\/4f67053cbea56a45020d004b6bd059e38934a21a\/pathfinder\/client\/plugin.py#L32-L40"}
33
+ {"nwo":"danth\/pathfinder.vim","sha":"4f67053cbea56a45020d004b6bd059e38934a21a","path":"pathfinder\/client\/plugin.py","language":"python","identifier":"Plugin.command_begin","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Called for the :PathfinderBegin command.","docstring_summary":"Called for the :PathfinderBegin command.","docstring_tokens":["Called","for","the",":","PathfinderBegin","command","."],"function":"def command_begin(self):\n \"\"\"Called for the :PathfinderBegin command.\"\"\"\n self.state_tracker.reset()","function_tokens":["def","command_begin","(","self",")",":","self",".","state_tracker",".","reset","(",")"],"url":"https:\/\/github.com\/danth\/pathfinder.vim\/blob\/4f67053cbea56a45020d004b6bd059e38934a21a\/pathfinder\/client\/plugin.py#L42-L44"}
34
+ {"nwo":"danth\/pathfinder.vim","sha":"4f67053cbea56a45020d004b6bd059e38934a21a","path":"pathfinder\/client\/plugin.py","language":"python","identifier":"Plugin.command_run","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Called for the :PathfinderRun command.","docstring_summary":"Called for the :PathfinderRun command.","docstring_tokens":["Called","for","the",":","PathfinderRun","command","."],"function":"def command_run(self):\n \"\"\"Called for the :PathfinderRun command.\"\"\"\n self.state_tracker.set_target()\n\n if cursor_in_same_position(\n self.state_tracker.start_state.view,\n self.state_tracker.target_state.view,\n ):\n print(\"You must move the cursor to a new location first!\")\n else:\n self._run()","function_tokens":["def","command_run","(","self",")",":","self",".","state_tracker",".","set_target","(",")","if","cursor_in_same_position","(","self",".","state_tracker",".","start_state",".","view",",","self",".","state_tracker",".","target_state",".","view",",",")",":","print","(","\"You must move the cursor to a new location first!\"",")","else",":","self",".","_run","(",")"],"url":"https:\/\/github.com\/danth\/pathfinder.vim\/blob\/4f67053cbea56a45020d004b6bd059e38934a21a\/pathfinder\/client\/plugin.py#L46-L56"}
35
+ {"nwo":"danth\/pathfinder.vim","sha":"4f67053cbea56a45020d004b6bd059e38934a21a","path":"pathfinder\/client\/plugin.py","language":"python","identifier":"Plugin.command_explain","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Called for the :PathfinderExplain command.","docstring_summary":"Called for the :PathfinderExplain command.","docstring_tokens":["Called","for","the",":","PathfinderExplain","command","."],"function":"def command_explain(self):\n \"\"\"Called for the :PathfinderExplain command.\"\"\"\n if self.last_output is None:\n print(\"No suggestion to explain.\")\n else:\n # explained_motions yields each line\n # sep tells print to put \\n between them rather than space\n print(*output.explained_motions(self.last_output), sep=\"\\n\")","function_tokens":["def","command_explain","(","self",")",":","if","self",".","last_output","is","None",":","print","(","\"No suggestion to explain.\"",")","else",":","# explained_motions yields each line","# sep tells print to put \\n between them rather than space","print","(","*","output",".","explained_motions","(","self",".","last_output",")",",","sep","=","\"\\n\"",")"],"url":"https:\/\/github.com\/danth\/pathfinder.vim\/blob\/4f67053cbea56a45020d004b6bd059e38934a21a\/pathfinder\/client\/plugin.py#L58-L65"}
36
+ {"nwo":"danth\/pathfinder.vim","sha":"4f67053cbea56a45020d004b6bd059e38934a21a","path":"pathfinder\/client\/plugin.py","language":"python","identifier":"Plugin.stop","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Called when Vim is about to shut down.","docstring_summary":"Called when Vim is about to shut down.","docstring_tokens":["Called","when","Vim","is","about","to","shut","down","."],"function":"def stop(self):\n \"\"\"Called when Vim is about to shut down.\"\"\"\n self.client.close()","function_tokens":["def","stop","(","self",")",":","self",".","client",".","close","(",")"],"url":"https:\/\/github.com\/danth\/pathfinder.vim\/blob\/4f67053cbea56a45020d004b6bd059e38934a21a\/pathfinder\/client\/plugin.py#L67-L69"}
37
+ {"nwo":"danth\/pathfinder.vim","sha":"4f67053cbea56a45020d004b6bd059e38934a21a","path":"pathfinder\/client\/autorun.py","language":"python","identifier":"choose_action","parameters":"(start_state, current_state, update_time)","argument_list":"","return_statement":"","docstring":"Select an action to take automatically.\n\n This is intended for use with StateTracker.choose_action_using().\n\n Returns one of:\n \"reset\" - Set start and target to the current state\n \"set_target\" - Set target to the current state\n \"pathfind\" - Start pathfinding, using the target from last time it was set\n None - Do nothing","docstring_summary":"Select an action to take automatically.","docstring_tokens":["Select","an","action","to","take","automatically","."],"function":"def choose_action(start_state, current_state, update_time):\n \"\"\"\n Select an action to take automatically.\n\n This is intended for use with StateTracker.choose_action_using().\n\n Returns one of:\n \"reset\" - Set start and target to the current state\n \"set_target\" - Set target to the current state\n \"pathfind\" - Start pathfinding, using the target from last time it was set\n None - Do nothing\n \"\"\"\n if (\n start_state.window != current_state.window\n or start_state.buffer != current_state.buffer\n ):\n # Reset to ensure the start or target view isn't set to a location\n # which is now impossible to access\n return \"reset\"\n\n delay = vim.vars[\"pf_autorun_delay\"]\n if delay > 0: # If delay <= 0, then the user disabled autorun\n if start_state.mode not in {\"n\", \"v\", \"V\", \"\u0016\"}:\n # Motions are not used in this mode, so pathfinding is useless\n return \"reset\"\n\n if (\n time.time() >= update_time + delay\n or start_state.mode != current_state.mode\n or start_state.lines != current_state.lines\n ):\n return \"pathfind\"\n else:\n return \"set_target\"","function_tokens":["def","choose_action","(","start_state",",","current_state",",","update_time",")",":","if","(","start_state",".","window","!=","current_state",".","window","or","start_state",".","buffer","!=","current_state",".","buffer",")",":","# Reset to ensure the start or target view isn't set to a location","# which is now impossible to access","return","\"reset\"","delay","=","vim",".","vars","[","\"pf_autorun_delay\"","]","if","delay",">","0",":","# If delay <= 0, then the user disabled autorun","if","start_state",".","mode","not","in","{","\"n\"",",","\"v\"",",","\"V\"",",","\"\u0016\"","}",":","# Motions are not used in this mode, so pathfinding is useless","return","\"reset\"","if","(","time",".","time","(",")",">=","update_time","+","delay","or","start_state",".","mode","!=","current_state",".","mode","or","start_state",".","lines","!=","current_state",".","lines",")",":","return","\"pathfind\"","else",":","return","\"set_target\""],"url":"https:\/\/github.com\/danth\/pathfinder.vim\/blob\/4f67053cbea56a45020d004b6bd059e38934a21a\/pathfinder\/client\/autorun.py#L6-L39"}
AlvarBer__Persimmon.jsonl ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {"nwo":"AlvarBer\/Persimmon","sha":"da08ed854dd0305d7e4684e97ee828acffd76b4d","path":"persimmon\/view\/blackboard.py","language":"python","identifier":"BlackBoard.execute_graph","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Tries to execute the graph, if some block is tainted it prevents\n the execution, if not it starts running the backend.","docstring_summary":"Tries to execute the graph, if some block is tainted it prevents\n the execution, if not it starts running the backend.","docstring_tokens":["Tries","to","execute","the","graph","if","some","block","is","tainted","it","prevents","the","execution","if","not","it","starts","running","the","backend","."],"function":"def execute_graph(self):\n \"\"\" Tries to execute the graph, if some block is tainted it prevents\n the execution, if not it starts running the backend. \"\"\"\n logger.debug('Checking taint')\n # Check if any block is tainted\n if any(map(lambda block: block.tainted, self.block_div.children)):\n # Get tainted block\n tainted_block = reduce(lambda l, r: l if l.tainted else r,\n self.block_div.children)\n logger.debug('Some block is tainted')\n Notification(title='Warning',\n message=tainted_block.tainted_msg).open()\n self.parent.on_graph_executed()\n else:\n logger.debug('No block is tainted')\n for block in self.block_div.children:\n if block.kindled:\n block.unkindle()\n self.backend.exec_graph(self.to_ir())","function_tokens":["def","execute_graph","(","self",")",":","logger",".","debug","(","'Checking taint'",")","# Check if any block is tainted","if","any","(","map","(","lambda","block",":","block",".","tainted",",","self",".","block_div",".","children",")",")",":","# Get tainted block","tainted_block","=","reduce","(","lambda","l",",","r",":","l","if","l",".","tainted","else","r",",","self",".","block_div",".","children",")","logger",".","debug","(","'Some block is tainted'",")","Notification","(","title","=","'Warning'",",","message","=","tainted_block",".","tainted_msg",")",".","open","(",")","self",".","parent",".","on_graph_executed","(",")","else",":","logger",".","debug","(","'No block is tainted'",")","for","block","in","self",".","block_div",".","children",":","if","block",".","kindled",":","block",".","unkindle","(",")","self",".","backend",".","exec_graph","(","self",".","to_ir","(",")",")"],"url":"https:\/\/github.com\/AlvarBer\/Persimmon\/blob\/da08ed854dd0305d7e4684e97ee828acffd76b4d\/persimmon\/view\/blackboard.py#L34-L52"}
2
+ {"nwo":"AlvarBer\/Persimmon","sha":"da08ed854dd0305d7e4684e97ee828acffd76b4d","path":"persimmon\/view\/blackboard.py","language":"python","identifier":"BlackBoard.get_relations","parameters":"(self)","argument_list":"","return_statement":"return ''.join(chain(ins, outs))","docstring":"Gets the relations between pins as a string.","docstring_summary":"Gets the relations between pins as a string.","docstring_tokens":["Gets","the","relations","between","pins","as","a","string","."],"function":"def get_relations(self) -> str:\n \"\"\" Gets the relations between pins as a string. \"\"\"\n # generator expressions are cool\n ins = ('{} -> {}\\n'.format(block.title, in_pin.origin.end.block.title)\n for block in self.block_div.children\n for in_pin in block.input_pins if in_pin.origin)\n outs = ('{} <- {}\\n'.format(block.title, destination.start.block.title)\n for block in self.block_div.children\n for out_pin in block.output_pins\n for destination in out_pin.destinations)\n\n return ''.join(chain(ins, outs))","function_tokens":["def","get_relations","(","self",")","->","str",":","# generator expressions are cool","ins","=","(","'{} -> {}\\n'",".","format","(","block",".","title",",","in_pin",".","origin",".","end",".","block",".","title",")","for","block","in","self",".","block_div",".","children","for","in_pin","in","block",".","input_pins","if","in_pin",".","origin",")","outs","=","(","'{} <- {}\\n'",".","format","(","block",".","title",",","destination",".","start",".","block",".","title",")","for","block","in","self",".","block_div",".","children","for","out_pin","in","block",".","output_pins","for","destination","in","out_pin",".","destinations",")","return","''",".","join","(","chain","(","ins",",","outs",")",")"],"url":"https:\/\/github.com\/AlvarBer\/Persimmon\/blob\/da08ed854dd0305d7e4684e97ee828acffd76b4d\/persimmon\/view\/blackboard.py#L54-L65"}
3
+ {"nwo":"AlvarBer\/Persimmon","sha":"da08ed854dd0305d7e4684e97ee828acffd76b4d","path":"persimmon\/view\/blackboard.py","language":"python","identifier":"BlackBoard.to_ir","parameters":"(self)","argument_list":"","return_statement":"return backend.IR(blocks=ir_blocks, inputs=ir_inputs, outputs=ir_outputs)","docstring":"Transforms the relations between blocks into an intermediate\n representation in O(n), n being the number of pins.","docstring_summary":"Transforms the relations between blocks into an intermediate\n representation in O(n), n being the number of pins.","docstring_tokens":["Transforms","the","relations","between","blocks","into","an","intermediate","representation","in","O","(","n",")","n","being","the","number","of","pins","."],"function":"def to_ir(self) -> IR:\n \"\"\" Transforms the relations between blocks into an intermediate\n representation in O(n), n being the number of pins. \"\"\"\n ir_blocks = {}\n ir_inputs = {}\n ir_outputs = {}\n logger.debug('Transforming to IR')\n for block in self.block_div.children:\n if block.is_orphan(): # Ignore orphaned blocks\n continue\n block_hash = id(block)\n block_inputs, block_outputs = [], []\n avoid = False\n for in_pin in block.input_pins:\n pin_hash = id(in_pin)\n block_inputs.append(pin_hash)\n other = id(in_pin.origin.end) # Always origin\n ir_inputs[pin_hash] = backend.InputEntry(origin=other,\n pin=in_pin,\n block=block_hash)\n for out_pin in block.output_pins:\n pin_hash = id(out_pin)\n block_outputs.append(pin_hash)\n dest = list(map(id, out_pin.destinations))\n ir_outputs[pin_hash] = backend.OutputEntry(destinations=dest,\n pin=out_pin,\n block=block_hash)\n ir_blocks[block_hash] = backend.BlockEntry(inputs=block_inputs,\n function=block.function,\n outputs=block_outputs)\n self.block_hashes = ir_blocks\n return backend.IR(blocks=ir_blocks, inputs=ir_inputs, outputs=ir_outputs)","function_tokens":["def","to_ir","(","self",")","->","IR",":","ir_blocks","=","{","}","ir_inputs","=","{","}","ir_outputs","=","{","}","logger",".","debug","(","'Transforming to IR'",")","for","block","in","self",".","block_div",".","children",":","if","block",".","is_orphan","(",")",":","# Ignore orphaned blocks","continue","block_hash","=","id","(","block",")","block_inputs",",","block_outputs","=","[","]",",","[","]","avoid","=","False","for","in_pin","in","block",".","input_pins",":","pin_hash","=","id","(","in_pin",")","block_inputs",".","append","(","pin_hash",")","other","=","id","(","in_pin",".","origin",".","end",")","# Always origin","ir_inputs","[","pin_hash","]","=","backend",".","InputEntry","(","origin","=","other",",","pin","=","in_pin",",","block","=","block_hash",")","for","out_pin","in","block",".","output_pins",":","pin_hash","=","id","(","out_pin",")","block_outputs",".","append","(","pin_hash",")","dest","=","list","(","map","(","id",",","out_pin",".","destinations",")",")","ir_outputs","[","pin_hash","]","=","backend",".","OutputEntry","(","destinations","=","dest",",","pin","=","out_pin",",","block","=","block_hash",")","ir_blocks","[","block_hash","]","=","backend",".","BlockEntry","(","inputs","=","block_inputs",",","function","=","block",".","function",",","outputs","=","block_outputs",")","self",".","block_hashes","=","ir_blocks","return","backend",".","IR","(","blocks","=","ir_blocks",",","inputs","=","ir_inputs",",","outputs","=","ir_outputs",")"],"url":"https:\/\/github.com\/AlvarBer\/Persimmon\/blob\/da08ed854dd0305d7e4684e97ee828acffd76b4d\/persimmon\/view\/blackboard.py#L67-L98"}
4
+ {"nwo":"AlvarBer\/Persimmon","sha":"da08ed854dd0305d7e4684e97ee828acffd76b4d","path":"persimmon\/view\/blackboard.py","language":"python","identifier":"BlackBoard.on_block_executed","parameters":"(self, block_hash: int)","argument_list":"","return_statement":"","docstring":"Callback that kindles a block, pulses future connections and\n stops the pulse of past connections.","docstring_summary":"Callback that kindles a block, pulses future connections and\n stops the pulse of past connections.","docstring_tokens":["Callback","that","kindles","a","block","pulses","future","connections","and","stops","the","pulse","of","past","connections","."],"function":"def on_block_executed(self, block_hash: int):\n \"\"\" Callback that kindles a block, pulses future connections and\n stops the pulse of past connections. \"\"\"\n block_idx = list(map(id, self.block_div.children)).index(block_hash)\n block = self.block_div.children[block_idx]\n block.kindle()\n logger.debug('Kindling block {}'.format(block.__class__.__name__))\n\n # Python list comprehensions can be nested forwards, but also backwards\n # http:\/\/rhodesmill.org\/brandon\/2009\/nested-comprehensions\/\n [connection.pulse() for out_pin in block.output_pins\n for connection in out_pin.destinations]\n [in_pin.origin.stop_pulse() for in_pin in block.input_pins]","function_tokens":["def","on_block_executed","(","self",",","block_hash",":","int",")",":","block_idx","=","list","(","map","(","id",",","self",".","block_div",".","children",")",")",".","index","(","block_hash",")","block","=","self",".","block_div",".","children","[","block_idx","]","block",".","kindle","(",")","logger",".","debug","(","'Kindling block {}'",".","format","(","block",".","__class__",".","__name__",")",")","# Python list comprehensions can be nested forwards, but also backwards","# http:\/\/rhodesmill.org\/brandon\/2009\/nested-comprehensions\/","[","connection",".","pulse","(",")","for","out_pin","in","block",".","output_pins","for","connection","in","out_pin",".","destinations","]","[","in_pin",".","origin",".","stop_pulse","(",")","for","in_pin","in","block",".","input_pins","]"],"url":"https:\/\/github.com\/AlvarBer\/Persimmon\/blob\/da08ed854dd0305d7e4684e97ee828acffd76b4d\/persimmon\/view\/blackboard.py#L101-L113"}
5
+ {"nwo":"AlvarBer\/Persimmon","sha":"da08ed854dd0305d7e4684e97ee828acffd76b4d","path":"persimmon\/view\/blackboard.py","language":"python","identifier":"BlackBoard.on_touch_up","parameters":"(self, touch: MotionEvent)","argument_list":"","return_statement":"return False","docstring":"Inherited from\n https:\/\/github.com\/kivy\/kivy\/blob\/master\/kivy\/uix\/scatter.py#L590.","docstring_summary":"Inherited from\n https:\/\/github.com\/kivy\/kivy\/blob\/master\/kivy\/uix\/scatter.py#L590.","docstring_tokens":["Inherited","from","https",":","\/\/","github",".","com","\/","kivy","\/","kivy","\/","blob","\/","master","\/","kivy","\/","uix","\/","scatter",".","py#L590","."],"function":"def on_touch_up(self, touch: MotionEvent) -> bool:\n \"\"\" Inherited from\n https:\/\/github.com\/kivy\/kivy\/blob\/master\/kivy\/uix\/scatter.py#L590. \"\"\"\n if self.disabled:\n return False\n\n x, y = touch.x, touch.y\n # if the touch isnt on the widget we do nothing, just try children\n if not touch.grab_current == self:\n touch.push()\n touch.apply_transform_2d(self.to_local)\n for child in self.children:\n if child.dispatch('on_touch_up', touch):\n touch.pop()\n return True\n touch.pop()\n\n # remove it from our saved touches\n if touch in self._touches and touch.grab_state:\n touch.ungrab(self)\n del self._last_touch_pos[touch]\n self._touches.remove(touch)\n\n # if no connection was made\n if 'cur_line' in touch.ud.keys() and touch.button == 'left':\n logger.info('Finish connection through smart bubble')\n connection = touch.ud['cur_line']\n if connection.forward:\n edge = connection.start\n else:\n edge = connection.end\n self.add_widget(blocks.SmartBubble(pos=touch.pos, backdrop=self, pin=edge))\n return True\n\n # stop propagating if its within our bounds\n if self.collide_point(x, y):\n return True\n return False","function_tokens":["def","on_touch_up","(","self",",","touch",":","MotionEvent",")","->","bool",":","if","self",".","disabled",":","return","False","x",",","y","=","touch",".","x",",","touch",".","y","# if the touch isnt on the widget we do nothing, just try children","if","not","touch",".","grab_current","==","self",":","touch",".","push","(",")","touch",".","apply_transform_2d","(","self",".","to_local",")","for","child","in","self",".","children",":","if","child",".","dispatch","(","'on_touch_up'",",","touch",")",":","touch",".","pop","(",")","return","True","touch",".","pop","(",")","# remove it from our saved touches","if","touch","in","self",".","_touches","and","touch",".","grab_state",":","touch",".","ungrab","(","self",")","del","self",".","_last_touch_pos","[","touch","]","self",".","_touches",".","remove","(","touch",")","# if no connection was made","if","'cur_line'","in","touch",".","ud",".","keys","(",")","and","touch",".","button","==","'left'",":","logger",".","info","(","'Finish connection through smart bubble'",")","connection","=","touch",".","ud","[","'cur_line'","]","if","connection",".","forward",":","edge","=","connection",".","start","else",":","edge","=","connection",".","end","self",".","add_widget","(","blocks",".","SmartBubble","(","pos","=","touch",".","pos",",","backdrop","=","self",",","pin","=","edge",")",")","return","True","# stop propagating if its within our bounds","if","self",".","collide_point","(","x",",","y",")",":","return","True","return","False"],"url":"https:\/\/github.com\/AlvarBer\/Persimmon\/blob\/da08ed854dd0305d7e4684e97ee828acffd76b4d\/persimmon\/view\/blackboard.py#L138-L175"}
6
+ {"nwo":"AlvarBer\/Persimmon","sha":"da08ed854dd0305d7e4684e97ee828acffd76b4d","path":"persimmon\/view\/blackboard.py","language":"python","identifier":"BlackBoard.in_block","parameters":"(self, x: float, y: float)","argument_list":"","return_statement":"return None","docstring":"Check if a position hits a block.","docstring_summary":"Check if a position hits a block.","docstring_tokens":["Check","if","a","position","hits","a","block","."],"function":"def in_block(self, x: float, y: float) -> Optional[blocks.Block]:\n \"\"\" Check if a position hits a block. \"\"\"\n for block in self.block_div.children:\n if block.collide_point(x, y):\n return block\n return None","function_tokens":["def","in_block","(","self",",","x",":","float",",","y",":","float",")","->","Optional","[","blocks",".","Block","]",":","for","block","in","self",".","block_div",".","children",":","if","block",".","collide_point","(","x",",","y",")",":","return","block","return","None"],"url":"https:\/\/github.com\/AlvarBer\/Persimmon\/blob\/da08ed854dd0305d7e4684e97ee828acffd76b4d\/persimmon\/view\/blackboard.py#L177-L182"}
7
+ {"nwo":"AlvarBer\/Persimmon","sha":"da08ed854dd0305d7e4684e97ee828acffd76b4d","path":"persimmon\/view\/blackboard.py","language":"python","identifier":"Blocks.add_widget","parameters":"(self, widget: Widget, index: int = 0, canvas: str = None)","argument_list":"","return_statement":"","docstring":"Add widget override.","docstring_summary":"Add widget override.","docstring_tokens":["Add","widget","override","."],"function":"def add_widget(self, widget: Widget, index: int = 0, canvas: str = None):\n \"\"\" Add widget override. \"\"\"\n if (widget.__class__ == blocks.PrintBlock and\n any(map(lambda w: w.__class__ == blocks.PrintBlock, self.children))):\n Notification(title='Warning',\n message='Only one print block allowed!').open()\n return\n if not self.children:\n self.parent.parent.parent.remove_hint()\n super().add_widget(widget, index, canvas)","function_tokens":["def","add_widget","(","self",",","widget",":","Widget",",","index",":","int","=","0",",","canvas",":","str","=","None",")",":","if","(","widget",".","__class__","==","blocks",".","PrintBlock","and","any","(","map","(","lambda","w",":","w",".","__class__","==","blocks",".","PrintBlock",",","self",".","children",")",")",")",":","Notification","(","title","=","'Warning'",",","message","=","'Only one print block allowed!'",")",".","open","(",")","return","if","not","self",".","children",":","self",".","parent",".","parent",".","parent",".","remove_hint","(",")","super","(",")",".","add_widget","(","widget",",","index",",","canvas",")"],"url":"https:\/\/github.com\/AlvarBer\/Persimmon\/blob\/da08ed854dd0305d7e4684e97ee828acffd76b4d\/persimmon\/view\/blackboard.py#L188-L197"}
8
+ {"nwo":"AlvarBer\/Persimmon","sha":"da08ed854dd0305d7e4684e97ee828acffd76b4d","path":"persimmon\/view\/blackboard.py","language":"python","identifier":"Blocks.remove_widget","parameters":"(self, widget: Widget)","argument_list":"","return_statement":"","docstring":"Remove widget override.","docstring_summary":"Remove widget override.","docstring_tokens":["Remove","widget","override","."],"function":"def remove_widget(self, widget: Widget):\n \"\"\" Remove widget override. \"\"\"\n super().remove_widget(widget)\n if not self.children:\n self.parent.parent.parent.add_hint()","function_tokens":["def","remove_widget","(","self",",","widget",":","Widget",")",":","super","(",")",".","remove_widget","(","widget",")","if","not","self",".","children",":","self",".","parent",".","parent",".","parent",".","add_hint","(",")"],"url":"https:\/\/github.com\/AlvarBer\/Persimmon\/blob\/da08ed854dd0305d7e4684e97ee828acffd76b4d\/persimmon\/view\/blackboard.py#L199-L203"}
9
+ {"nwo":"AlvarBer\/Persimmon","sha":"da08ed854dd0305d7e4684e97ee828acffd76b4d","path":"persimmon\/view\/util\/connection.py","language":"python","identifier":"Connection.__init__","parameters":"(self, **kwargs)","argument_list":"","return_statement":"","docstring":"On this initializer the connection has to check whether the\n connection is being made forward or backwards.","docstring_summary":"On this initializer the connection has to check whether the\n connection is being made forward or backwards.","docstring_tokens":["On","this","initializer","the","connection","has","to","check","whether","the","connection","is","being","made","forward","or","backwards","."],"function":"def __init__(self, **kwargs):\n \"\"\" On this initializer the connection has to check whether the\n connection is being made forward or backwards. \"\"\"\n super().__init__(**kwargs)\n if self.start:\n self.forward = True\n # The value is repeated for correctness sake\n self.bez_start, self.bez_end = [self.start.center] * 2\n with self.canvas.before:\n Color(*self.color)\n self.lin = Line(bezier=self.bez_start * 4, width=1.5)\n self._bind_pin(self.start)\n else:\n self.forward = False\n self.bez_start, self.bez_end = [self.end.center] * 2\n with self.canvas.before:\n Color(*self.color)\n self.lin = Line(bezier=self.bez_end * 4, width=1.5)\n self._bind_pin(self.end)\n self.warned = False\n self.info = Factory.Info(pos=self.bez_start)\n Window.add_widget(self.info)","function_tokens":["def","__init__","(","self",",","*","*","kwargs",")",":","super","(",")",".","__init__","(","*","*","kwargs",")","if","self",".","start",":","self",".","forward","=","True","# The value is repeated for correctness sake","self",".","bez_start",",","self",".","bez_end","=","[","self",".","start",".","center","]","*","2","with","self",".","canvas",".","before",":","Color","(","*","self",".","color",")","self",".","lin","=","Line","(","bezier","=","self",".","bez_start","*","4",",","width","=","1.5",")","self",".","_bind_pin","(","self",".","start",")","else",":","self",".","forward","=","False","self",".","bez_start",",","self",".","bez_end","=","[","self",".","end",".","center","]","*","2","with","self",".","canvas",".","before",":","Color","(","*","self",".","color",")","self",".","lin","=","Line","(","bezier","=","self",".","bez_end","*","4",",","width","=","1.5",")","self",".","_bind_pin","(","self",".","end",")","self",".","warned","=","False","self",".","info","=","Factory",".","Info","(","pos","=","self",".","bez_start",")","Window",".","add_widget","(","self",".","info",")"],"url":"https:\/\/github.com\/AlvarBer\/Persimmon\/blob\/da08ed854dd0305d7e4684e97ee828acffd76b4d\/persimmon\/view\/util\/connection.py#L52-L73"}
10
+ {"nwo":"AlvarBer\/Persimmon","sha":"da08ed854dd0305d7e4684e97ee828acffd76b4d","path":"persimmon\/view\/util\/connection.py","language":"python","identifier":"Connection.finish_connection","parameters":"(self, pin: 'Pin')","argument_list":"","return_statement":"","docstring":"This functions finishes a connection that has only start or end and\n is being currently dragged","docstring_summary":"This functions finishes a connection that has only start or end and\n is being currently dragged","docstring_tokens":["This","functions","finishes","a","connection","that","has","only","start","or","end","and","is","being","currently","dragged"],"function":"def finish_connection(self, pin: 'Pin'):\n \"\"\" This functions finishes a connection that has only start or end and\n is being currently dragged \"\"\"\n self.remove_info()\n if self.forward:\n self.end = pin\n self._bind_pin(self.end)\n else:\n self.start = pin\n self._bind_pin(self.start)","function_tokens":["def","finish_connection","(","self",",","pin",":","'Pin'",")",":","self",".","remove_info","(",")","if","self",".","forward",":","self",".","end","=","pin","self",".","_bind_pin","(","self",".","end",")","else",":","self",".","start","=","pin","self",".","_bind_pin","(","self",".","start",")"],"url":"https:\/\/github.com\/AlvarBer\/Persimmon\/blob\/da08ed854dd0305d7e4684e97ee828acffd76b4d\/persimmon\/view\/util\/connection.py#L75-L84"}
11
+ {"nwo":"AlvarBer\/Persimmon","sha":"da08ed854dd0305d7e4684e97ee828acffd76b4d","path":"persimmon\/view\/util\/connection.py","language":"python","identifier":"Connection.on_touch_down","parameters":"(self, touch: MotionEvent)","argument_list":"","return_statement":"","docstring":"On touch down on connection means we are modifying an already\n existing connection, not creating a new one.","docstring_summary":"On touch down on connection means we are modifying an already\n existing connection, not creating a new one.","docstring_tokens":["On","touch","down","on","connection","means","we","are","modifying","an","already","existing","connection","not","creating","a","new","one","."],"function":"def on_touch_down(self, touch: MotionEvent) -> bool:\n \"\"\" On touch down on connection means we are modifying an already\n existing connection, not creating a new one. \"\"\"\n # TODO: remove start check?\n if self.start and self.start.collide_point(*touch.pos):\n self.forward = False\n # Remove start edge\n self._unbind_pin(self.start)\n self.start.on_connection_delete(self)\n self.start = None\n # This signals that we are dragging a connection\n touch.ud['cur_line'] = self\n Window.add_widget(self.info)\n return True\n elif self.end and self.end.collide_point(*touch.pos):\n # Same as before but with the other edge\n self.forward = True\n self._unbind_pin(self.end)\n self.end.on_connection_delete(self)\n self.end = None\n touch.ud['cur_line'] = self\n Window.add_widget(self.info)\n return True\n else:\n return False","function_tokens":["def","on_touch_down","(","self",",","touch",":","MotionEvent",")","->","bool",":","# TODO: remove start check?","if","self",".","start","and","self",".","start",".","collide_point","(","*","touch",".","pos",")",":","self",".","forward","=","False","# Remove start edge","self",".","_unbind_pin","(","self",".","start",")","self",".","start",".","on_connection_delete","(","self",")","self",".","start","=","None","# This signals that we are dragging a connection","touch",".","ud","[","'cur_line'","]","=","self","Window",".","add_widget","(","self",".","info",")","return","True","elif","self",".","end","and","self",".","end",".","collide_point","(","*","touch",".","pos",")",":","# Same as before but with the other edge","self",".","forward","=","True","self",".","_unbind_pin","(","self",".","end",")","self",".","end",".","on_connection_delete","(","self",")","self",".","end","=","None","touch",".","ud","[","'cur_line'","]","=","self","Window",".","add_widget","(","self",".","info",")","return","True","else",":","return","False"],"url":"https:\/\/github.com\/AlvarBer\/Persimmon\/blob\/da08ed854dd0305d7e4684e97ee828acffd76b4d\/persimmon\/view\/util\/connection.py#L87-L111"}
12
+ {"nwo":"AlvarBer\/Persimmon","sha":"da08ed854dd0305d7e4684e97ee828acffd76b4d","path":"persimmon\/view\/util\/connection.py","language":"python","identifier":"Connection.follow_cursor","parameters":"(self, newpos, blackboard)","argument_list":"","return_statement":"","docstring":"This functions makes sure the current end being dragged follows the\n cursor. It also checks for type safety and changes the line color\n if needed.","docstring_summary":"This functions makes sure the current end being dragged follows the\n cursor. It also checks for type safety and changes the line color\n if needed.","docstring_tokens":["This","functions","makes","sure","the","current","end","being","dragged","follows","the","cursor",".","It","also","checks","for","type","safety","and","changes","the","line","color","if","needed","."],"function":"def follow_cursor(self, newpos, blackboard):\n \"\"\" This functions makes sure the current end being dragged follows the\n cursor. It also checks for type safety and changes the line color\n if needed.\"\"\"\n if self.forward:\n fixed_edge = self.start\n self.bez_end = [*newpos]\n self._rebezier()\n else:\n fixed_edge = self.end\n self.bez_start = [*newpos]\n self._rebezier()\n self.info.pos = [*newpos]\n # The conditionals are so complicated because it is necessary to check\n # whether or not a pin in a block has been touched, and then check\n # the typesafety.\n if (self._in_pin(blackboard, newpos) and\n not self._in_pin(blackboard, newpos).typesafe(fixed_edge)):\n # This conditional represents that the cursor stepped out the pin\n self.info.text = 'Connection is not possible'\n self._warn()\n elif (self._in_pin(blackboard, newpos) and\n self._in_pin(blackboard, newpos).typesafe(fixed_edge)):\n self.info.text = 'Connect'\n if self.warned:\n self._unwarn()\n else:\n self.info.text = 'Spawn new block'\n if self.warned:\n self._unwarn()","function_tokens":["def","follow_cursor","(","self",",","newpos",",","blackboard",")",":","if","self",".","forward",":","fixed_edge","=","self",".","start","self",".","bez_end","=","[","*","newpos","]","self",".","_rebezier","(",")","else",":","fixed_edge","=","self",".","end","self",".","bez_start","=","[","*","newpos","]","self",".","_rebezier","(",")","self",".","info",".","pos","=","[","*","newpos","]","# The conditionals are so complicated because it is necessary to check","# whether or not a pin in a block has been touched, and then check","# the typesafety.","if","(","self",".","_in_pin","(","blackboard",",","newpos",")","and","not","self",".","_in_pin","(","blackboard",",","newpos",")",".","typesafe","(","fixed_edge",")",")",":","# This conditional represents that the cursor stepped out the pin","self",".","info",".","text","=","'Connection is not possible'","self",".","_warn","(",")","elif","(","self",".","_in_pin","(","blackboard",",","newpos",")","and","self",".","_in_pin","(","blackboard",",","newpos",")",".","typesafe","(","fixed_edge",")",")",":","self",".","info",".","text","=","'Connect'","if","self",".","warned",":","self",".","_unwarn","(",")","else",":","self",".","info",".","text","=","'Spawn new block'","if","self",".","warned",":","self",".","_unwarn","(",")"],"url":"https:\/\/github.com\/AlvarBer\/Persimmon\/blob\/da08ed854dd0305d7e4684e97ee828acffd76b4d\/persimmon\/view\/util\/connection.py#L113-L142"}
13
+ {"nwo":"AlvarBer\/Persimmon","sha":"da08ed854dd0305d7e4684e97ee828acffd76b4d","path":"persimmon\/view\/util\/connection.py","language":"python","identifier":"Connection.delete_connection","parameters":"(self)","argument_list":"","return_statement":"","docstring":"This function deletes both ends (if they exist) and the connection\n itself.","docstring_summary":"This function deletes both ends (if they exist) and the connection\n itself.","docstring_tokens":["This","function","deletes","both","ends","(","if","they","exist",")","and","the","connection","itself","."],"function":"def delete_connection(self):\n \"\"\" This function deletes both ends (if they exist) and the connection\n itself. \"\"\"\n self.parent.remove_widget(self) # Self-destruct\n self.remove_info()\n if self.start:\n self._unbind_pin(self.start)\n self.start.on_connection_delete(self)\n if self.end:\n self._unbind_pin(self.end)\n self.end.on_connection_delete(self)","function_tokens":["def","delete_connection","(","self",")",":","self",".","parent",".","remove_widget","(","self",")","# Self-destruct","self",".","remove_info","(",")","if","self",".","start",":","self",".","_unbind_pin","(","self",".","start",")","self",".","start",".","on_connection_delete","(","self",")","if","self",".","end",":","self",".","_unbind_pin","(","self",".","end",")","self",".","end",".","on_connection_delete","(","self",")"],"url":"https:\/\/github.com\/AlvarBer\/Persimmon\/blob\/da08ed854dd0305d7e4684e97ee828acffd76b4d\/persimmon\/view\/util\/connection.py#L144-L154"}
14
+ {"nwo":"AlvarBer\/Persimmon","sha":"da08ed854dd0305d7e4684e97ee828acffd76b4d","path":"persimmon\/view\/util\/connection.py","language":"python","identifier":"Connection.pulse","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Makes a connection appear to pulse by modifying its width\n continuosly.","docstring_summary":"Makes a connection appear to pulse by modifying its width\n continuosly.","docstring_tokens":["Makes","a","connection","appear","to","pulse","by","modifying","its","width","continuosly","."],"function":"def pulse(self):\n \"\"\" Makes a connection appear to pulse by modifying its width\n continuosly. \"\"\"\n self.it = self._change_width()\n next(self.it)\n Clock.schedule_interval(lambda _: next(self.it), 0.05)","function_tokens":["def","pulse","(","self",")",":","self",".","it","=","self",".","_change_width","(",")","next","(","self",".","it",")","Clock",".","schedule_interval","(","lambda","_",":","next","(","self",".","it",")",",","0.05",")"],"url":"https:\/\/github.com\/AlvarBer\/Persimmon\/blob\/da08ed854dd0305d7e4684e97ee828acffd76b4d\/persimmon\/view\/util\/connection.py#L156-L161"}
15
+ {"nwo":"AlvarBer\/Persimmon","sha":"da08ed854dd0305d7e4684e97ee828acffd76b4d","path":"persimmon\/view\/util\/connection.py","language":"python","identifier":"Connection.stop_pulse","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Stops vibrating a connection. It will throw an execution if\n the connection is not pulsing right now.","docstring_summary":"Stops vibrating a connection. It will throw an execution if\n the connection is not pulsing right now.","docstring_tokens":["Stops","vibrating","a","connection",".","It","will","throw","an","execution","if","the","connection","is","not","pulsing","right","now","."],"function":"def stop_pulse(self):\n \"\"\" Stops vibrating a connection. It will throw an execution if\n the connection is not pulsing right now. \"\"\"\n self.it.throw(StopIteration)","function_tokens":["def","stop_pulse","(","self",")",":","self",".","it",".","throw","(","StopIteration",")"],"url":"https:\/\/github.com\/AlvarBer\/Persimmon\/blob\/da08ed854dd0305d7e4684e97ee828acffd76b4d\/persimmon\/view\/util\/connection.py#L163-L166"}
16
+ {"nwo":"AlvarBer\/Persimmon","sha":"da08ed854dd0305d7e4684e97ee828acffd76b4d","path":"persimmon\/view\/util\/connection.py","language":"python","identifier":"Connection._unbind_pin","parameters":"(self, pin: 'Pin')","argument_list":"","return_statement":"","docstring":"Undos pin's circle and line binding.","docstring_summary":"Undos pin's circle and line binding.","docstring_tokens":["Undos","pin","s","circle","and","line","binding","."],"function":"def _unbind_pin(self, pin: 'Pin'):\n \"\"\" Undos pin's circle and line binding. \"\"\"\n pin.funbind('pos', self._line_bind)","function_tokens":["def","_unbind_pin","(","self",",","pin",":","'Pin'",")",":","pin",".","funbind","(","'pos'",",","self",".","_line_bind",")"],"url":"https:\/\/github.com\/AlvarBer\/Persimmon\/blob\/da08ed854dd0305d7e4684e97ee828acffd76b4d\/persimmon\/view\/util\/connection.py#L181-L183"}
17
+ {"nwo":"AlvarBer\/Persimmon","sha":"da08ed854dd0305d7e4684e97ee828acffd76b4d","path":"persimmon\/view\/util\/connection.py","language":"python","identifier":"Connection._bind_pin","parameters":"(self, pin: 'Pin')","argument_list":"","return_statement":"","docstring":"Performs pin circle and line binding.","docstring_summary":"Performs pin circle and line binding.","docstring_tokens":["Performs","pin","circle","and","line","binding","."],"function":"def _bind_pin(self, pin: 'Pin'):\n \"\"\" Performs pin circle and line binding. \"\"\"\n pin.fbind('pos', self._line_bind)\n self._line_bind(pin, pin.pos)","function_tokens":["def","_bind_pin","(","self",",","pin",":","'Pin'",")",":","pin",".","fbind","(","'pos'",",","self",".","_line_bind",")","self",".","_line_bind","(","pin",",","pin",".","pos",")"],"url":"https:\/\/github.com\/AlvarBer\/Persimmon\/blob\/da08ed854dd0305d7e4684e97ee828acffd76b4d\/persimmon\/view\/util\/connection.py#L185-L188"}
18
+ {"nwo":"AlvarBer\/Persimmon","sha":"da08ed854dd0305d7e4684e97ee828acffd76b4d","path":"persimmon\/view\/util\/connection.py","language":"python","identifier":"Connection._change_width","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Ok, so let me explain what is going on, this generator\/coroutine\n changes the width of the line continuosly using the width_gen\n generator. We use it by calling it 20 times per second. The tricky\n part is stopping the scheduled calls. The way to tell Kivy to stop\n calling is to return a False value, and to do that we need to call\n this coroutine itself, which may be executing or not at that\n precise moment.\n\n That is where throw comes in, allowing for exceptions to be thrown\n on during the execution, hijacking the current execution (like a\n fast interruption), we need to return from this exception, in which\n we do not care about the value, and then return False on the\n regular execution in order to stop the calls.","docstring_summary":"Ok, so let me explain what is going on, this generator\/coroutine\n changes the width of the line continuosly using the width_gen\n generator. We use it by calling it 20 times per second. The tricky\n part is stopping the scheduled calls. The way to tell Kivy to stop\n calling is to return a False value, and to do that we need to call\n this coroutine itself, which may be executing or not at that\n precise moment.","docstring_tokens":["Ok","so","let","me","explain","what","is","going","on","this","generator","\/","coroutine","changes","the","width","of","the","line","continuosly","using","the","width_gen","generator",".","We","use","it","by","calling","it","20","times","per","second",".","The","tricky","part","is","stopping","the","scheduled","calls",".","The","way","to","tell","Kivy","to","stop","calling","is","to","return","a","False","value","and","to","do","that","we","need","to","call","this","coroutine","itself","which","may","be","executing","or","not","at","that","precise","moment","."],"function":"def _change_width(self):\n \"\"\" Ok, so let me explain what is going on, this generator\/coroutine\n changes the width of the line continuosly using the width_gen\n generator. We use it by calling it 20 times per second. The tricky\n part is stopping the scheduled calls. The way to tell Kivy to stop\n calling is to return a False value, and to do that we need to call\n this coroutine itself, which may be executing or not at that\n precise moment.\n\n That is where throw comes in, allowing for exceptions to be thrown\n on during the execution, hijacking the current execution (like a\n fast interruption), we need to return from this exception, in which\n we do not care about the value, and then return False on the\n regular execution in order to stop the calls.\"\"\"\n try:\n for value in self._width_gen():\n self.lin.width = value\n yield\n except StopIteration:\n self.lin.width = 2\n yield\n yield False","function_tokens":["def","_change_width","(","self",")",":","try",":","for","value","in","self",".","_width_gen","(",")",":","self",".","lin",".","width","=","value","yield","except","StopIteration",":","self",".","lin",".","width","=","2","yield","yield","False"],"url":"https:\/\/github.com\/AlvarBer\/Persimmon\/blob\/da08ed854dd0305d7e4684e97ee828acffd76b4d\/persimmon\/view\/util\/connection.py#L201-L222"}
19
+ {"nwo":"AlvarBer\/Persimmon","sha":"da08ed854dd0305d7e4684e97ee828acffd76b4d","path":"persimmon\/view\/util\/connection.py","language":"python","identifier":"Connection._width_gen","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Infinity oscillating generator (between 2 and 4)","docstring_summary":"Infinity oscillating generator (between 2 and 4)","docstring_tokens":["Infinity","oscillating","generator","(","between","2","and","4",")"],"function":"def _width_gen(self):\n \"\"\" Infinity oscillating generator (between 2 and 4) \"\"\"\n val = 0\n while True:\n yield np.sin(val) + 3\n val += pi \/ 20","function_tokens":["def","_width_gen","(","self",")",":","val","=","0","while","True",":","yield","np",".","sin","(","val",")","+","3","val","+=","pi","\/","20"],"url":"https:\/\/github.com\/AlvarBer\/Persimmon\/blob\/da08ed854dd0305d7e4684e97ee828acffd76b4d\/persimmon\/view\/util\/connection.py#L224-L229"}
20
+ {"nwo":"AlvarBer\/Persimmon","sha":"da08ed854dd0305d7e4684e97ee828acffd76b4d","path":"persimmon\/view\/util\/connection.py","language":"python","identifier":"Connection._warn","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Changes the current line to a red thick connection.","docstring_summary":"Changes the current line to a red thick connection.","docstring_tokens":["Changes","the","current","line","to","a","red","thick","connection","."],"function":"def _warn(self):\n \"\"\" Changes the current line to a red thick connection. \"\"\"\n self.warned = True\n self.canvas.before.remove(self.lin)\n with self.canvas.before:\n Color(1, 0, 0)\n self.lin = Line(points=self.lin.points, width=3)\n self._rebezier()","function_tokens":["def","_warn","(","self",")",":","self",".","warned","=","True","self",".","canvas",".","before",".","remove","(","self",".","lin",")","with","self",".","canvas",".","before",":","Color","(","1",",","0",",","0",")","self",".","lin","=","Line","(","points","=","self",".","lin",".","points",",","width","=","3",")","self",".","_rebezier","(",")"],"url":"https:\/\/github.com\/AlvarBer\/Persimmon\/blob\/da08ed854dd0305d7e4684e97ee828acffd76b4d\/persimmon\/view\/util\/connection.py#L232-L239"}
21
+ {"nwo":"AlvarBer\/Persimmon","sha":"da08ed854dd0305d7e4684e97ee828acffd76b4d","path":"persimmon\/view\/util\/connection.py","language":"python","identifier":"Connection._unwarn","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Returns the red thick connection to its normal state.","docstring_summary":"Returns the red thick connection to its normal state.","docstring_tokens":["Returns","the","red","thick","connection","to","its","normal","state","."],"function":"def _unwarn(self):\n \"\"\" Returns the red thick connection to its normal state. \"\"\"\n self.warned = False\n self.canvas.before.remove(self.lin)\n with self.canvas.before:\n Color(*self.color)\n self.lin = Line(points=self.lin.points, width=1.5)\n self._rebezier()","function_tokens":["def","_unwarn","(","self",")",":","self",".","warned","=","False","self",".","canvas",".","before",".","remove","(","self",".","lin",")","with","self",".","canvas",".","before",":","Color","(","*","self",".","color",")","self",".","lin","=","Line","(","points","=","self",".","lin",".","points",",","width","=","1.5",")","self",".","_rebezier","(",")"],"url":"https:\/\/github.com\/AlvarBer\/Persimmon\/blob\/da08ed854dd0305d7e4684e97ee828acffd76b4d\/persimmon\/view\/util\/connection.py#L241-L248"}
22
+ {"nwo":"AlvarBer\/Persimmon","sha":"da08ed854dd0305d7e4684e97ee828acffd76b4d","path":"persimmon\/view\/util\/connection.py","language":"python","identifier":"Connection._rebezier","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Refreshes bezier curve according to start and end.\n It uses the arctan to force the b\u00e8zier curve always going a bit\n forward before drifting.","docstring_summary":"Refreshes bezier curve according to start and end.\n It uses the arctan to force the b\u00e8zier curve always going a bit\n forward before drifting.","docstring_tokens":["Refreshes","bezier","curve","according","to","start","and","end",".","It","uses","the","arctan","to","force","the","b\u00e8zier","curve","always","going","a","bit","forward","before","drifting","."],"function":"def _rebezier(self):\n \"\"\" Refreshes bezier curve according to start and end.\n It uses the arctan to force the b\u00e8zier curve always going a bit\n forward before drifting.\"\"\"\n arc_tan = np.arctan2(self.bez_start[1] - self.bez_end[1],\n self.bez_start[0] - self.bez_end[0])\n abs_angle = np.abs(np.degrees(arc_tan))\n # We use the angle value plus a fixed amount to steer the line a bit\n start_right = [self.bez_start[0] - 5 - 0.6 * abs_angle,\n self.bez_start[1]]\n end_left = [self.bez_end[0] + 5 + 0.6 * abs_angle, self.bez_end[1]]\n # Y distance to mid point\n dist = (min(self.bez_start[0], self.bez_end[0]) +\n abs(self.bez_start[0] - self.bez_end[0]) \/ 2)\n # This updates the b\u00e8zier curve graphics\n self.lin.bezier = (self.bez_start + start_right +\n [dist, self.bez_start[1]] + [dist, self.bez_end[1]] +\n end_left + self.bez_end)","function_tokens":["def","_rebezier","(","self",")",":","arc_tan","=","np",".","arctan2","(","self",".","bez_start","[","1","]","-","self",".","bez_end","[","1","]",",","self",".","bez_start","[","0","]","-","self",".","bez_end","[","0","]",")","abs_angle","=","np",".","abs","(","np",".","degrees","(","arc_tan",")",")","# We use the angle value plus a fixed amount to steer the line a bit","start_right","=","[","self",".","bez_start","[","0","]","-","5","-","0.6","*","abs_angle",",","self",".","bez_start","[","1","]","]","end_left","=","[","self",".","bez_end","[","0","]","+","5","+","0.6","*","abs_angle",",","self",".","bez_end","[","1","]","]","# Y distance to mid point","dist","=","(","min","(","self",".","bez_start","[","0","]",",","self",".","bez_end","[","0","]",")","+","abs","(","self",".","bez_start","[","0","]","-","self",".","bez_end","[","0","]",")","\/","2",")","# This updates the b\u00e8zier curve graphics","self",".","lin",".","bezier","=","(","self",".","bez_start","+","start_right","+","[","dist",",","self",".","bez_start","[","1","]","]","+","[","dist",",","self",".","bez_end","[","1","]","]","+","end_left","+","self",".","bez_end",")"],"url":"https:\/\/github.com\/AlvarBer\/Persimmon\/blob\/da08ed854dd0305d7e4684e97ee828acffd76b4d\/persimmon\/view\/util\/connection.py#L251-L268"}
23
+ {"nwo":"AlvarBer\/Persimmon","sha":"da08ed854dd0305d7e4684e97ee828acffd76b4d","path":"persimmon\/view\/util\/play_button.py","language":"python","identifier":"PlayButton.on_angle","parameters":"(self, instance, values)","argument_list":"","return_statement":"","docstring":"Only needed so spinner goes after 360.","docstring_summary":"Only needed so spinner goes after 360.","docstring_tokens":["Only","needed","so","spinner","goes","after","360","."],"function":"def on_angle(self, instance, values):\n \"\"\" Only needed so spinner goes after 360. \"\"\"\n self.angle %= 360","function_tokens":["def","on_angle","(","self",",","instance",",","values",")",":","self",".","angle","%=","360"],"url":"https:\/\/github.com\/AlvarBer\/Persimmon\/blob\/da08ed854dd0305d7e4684e97ee828acffd76b4d\/persimmon\/view\/util\/play_button.py#L38-L40"}
24
+ {"nwo":"AlvarBer\/Persimmon","sha":"da08ed854dd0305d7e4684e97ee828acffd76b4d","path":"persimmon\/view\/pins\/pin.py","language":"python","identifier":"Pin.typesafe","parameters":"(self, other: 'Pin')","argument_list":"","return_statement":"","docstring":"Tells if a relation between two pins is typesafe.","docstring_summary":"Tells if a relation between two pins is typesafe.","docstring_tokens":["Tells","if","a","relation","between","two","pins","is","typesafe","."],"function":"def typesafe(self, other: 'Pin') -> bool:\n \"\"\" Tells if a relation between two pins is typesafe. \"\"\"\n if self.block == other.block or self.__class__ == other.__class__:\n return False\n elif self.type_ == Type.ANY or other.type_ == Type.ANY:\n return True # Anything is possible with ANY\n else:\n return self.type_ == other.type_","function_tokens":["def","typesafe","(","self",",","other",":","'Pin'",")","->","bool",":","if","self",".","block","==","other",".","block","or","self",".","__class__","==","other",".","__class__",":","return","False","elif","self",".","type_","==","Type",".","ANY","or","other",".","type_","==","Type",".","ANY",":","return","True","# Anything is possible with ANY","else",":","return","self",".","type_","==","other",".","type_"],"url":"https:\/\/github.com\/AlvarBer\/Persimmon\/blob\/da08ed854dd0305d7e4684e97ee828acffd76b4d\/persimmon\/view\/pins\/pin.py#L32-L39"}
25
+ {"nwo":"AlvarBer\/Persimmon","sha":"da08ed854dd0305d7e4684e97ee828acffd76b4d","path":"persimmon\/view\/pins\/pin.py","language":"python","identifier":"Pin.on_type_","parameters":"(self, instance: 'Pin', value: Type)","argument_list":"","return_statement":"","docstring":"If the kv lang was a bit smarted this would not be needed","docstring_summary":"If the kv lang was a bit smarted this would not be needed","docstring_tokens":["If","the","kv","lang","was","a","bit","smarted","this","would","not","be","needed"],"function":"def on_type_(self, instance: 'Pin', value: Type):\n \"\"\" If the kv lang was a bit smarted this would not be needed\n \"\"\"\n self.color = value.value","function_tokens":["def","on_type_","(","self",",","instance",":","'Pin'",",","value",":","Type",")",":","self",".","color","=","value",".","value"],"url":"https:\/\/github.com\/AlvarBer\/Persimmon\/blob\/da08ed854dd0305d7e4684e97ee828acffd76b4d\/persimmon\/view\/pins\/pin.py#L42-L45"}
26
+ {"nwo":"AlvarBer\/Persimmon","sha":"da08ed854dd0305d7e4684e97ee828acffd76b4d","path":"persimmon\/view\/blocks\/block.py","language":"python","identifier":"Block.is_orphan","parameters":"(self)","argument_list":"","return_statement":"return True","docstring":"Tells if a block is orphan, i.e. whether it has any connection","docstring_summary":"Tells if a block is orphan, i.e. whether it has any connection","docstring_tokens":["Tells","if","a","block","is","orphan","i",".","e",".","whether","it","has","any","connection"],"function":"def is_orphan(self) -> bool:\n \"\"\" Tells if a block is orphan, i.e. whether it has any connection \"\"\"\n for in_pin in self.input_pins:\n if in_pin.origin:\n return False\n for out_pin in self.output_pins:\n if out_pin.destinations:\n return False\n return True","function_tokens":["def","is_orphan","(","self",")","->","bool",":","for","in_pin","in","self",".","input_pins",":","if","in_pin",".","origin",":","return","False","for","out_pin","in","self",".","output_pins",":","if","out_pin",".","destinations",":","return","False","return","True"],"url":"https:\/\/github.com\/AlvarBer\/Persimmon\/blob\/da08ed854dd0305d7e4684e97ee828acffd76b4d\/persimmon\/view\/blocks\/block.py#L77-L85"}
27
+ {"nwo":"AlvarBer\/Persimmon","sha":"da08ed854dd0305d7e4684e97ee828acffd76b4d","path":"persimmon\/view\/blocks\/block.py","language":"python","identifier":"Block.in_pin","parameters":"(self, x: float, y: float)","argument_list":"","return_statement":"return None","docstring":"Checks if a position collides with any of the pins in the block.","docstring_summary":"Checks if a position collides with any of the pins in the block.","docstring_tokens":["Checks","if","a","position","collides","with","any","of","the","pins","in","the","block","."],"function":"def in_pin(self, x: float, y: float) -> Optional[Pin]:\n \"\"\" Checks if a position collides with any of the pins in the block.\n \"\"\"\n for pin in self.input_pins + self.output_pins:\n if pin.collide_point(x, y):\n return pin\n return None","function_tokens":["def","in_pin","(","self",",","x",":","float",",","y",":","float",")","->","Optional","[","Pin","]",":","for","pin","in","self",".","input_pins","+","self",".","output_pins",":","if","pin",".","collide_point","(","x",",","y",")",":","return","pin","return","None"],"url":"https:\/\/github.com\/AlvarBer\/Persimmon\/blob\/da08ed854dd0305d7e4684e97ee828acffd76b4d\/persimmon\/view\/blocks\/block.py#L87-L93"}
28
+ {"nwo":"AlvarBer\/Persimmon","sha":"da08ed854dd0305d7e4684e97ee828acffd76b4d","path":"persimmon\/view\/blocks\/block.py","language":"python","identifier":"Block.kindle","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Praise the sun \\[T]\/","docstring_summary":"Praise the sun \\[T]\/","docstring_tokens":["Praise","the","sun","\\","[","T","]","\/"],"function":"def kindle(self):\n \"\"\" Praise the sun \\[T]\/ \"\"\"\n with self.canvas.before:\n Color(1, 1, 1)\n self.kindled = BorderImage(pos=(self.x - 2, self.y - 2),\n size=(self.width + 4,\n self.height + 4),\n texture=self.border_texture)\n self.fbind('pos', self._bind_border)","function_tokens":["def","kindle","(","self",")",":","with","self",".","canvas",".","before",":","Color","(","1",",","1",",","1",")","self",".","kindled","=","BorderImage","(","pos","=","(","self",".","x","-","2",",","self",".","y","-","2",")",",","size","=","(","self",".","width","+","4",",","self",".","height","+","4",")",",","texture","=","self",".","border_texture",")","self",".","fbind","(","'pos'",",","self",".","_bind_border",")"],"url":"https:\/\/github.com\/AlvarBer\/Persimmon\/blob\/da08ed854dd0305d7e4684e97ee828acffd76b4d\/persimmon\/view\/blocks\/block.py#L115-L123"}
29
+ {"nwo":"AlvarBer\/Persimmon","sha":"da08ed854dd0305d7e4684e97ee828acffd76b4d","path":"persimmon\/view\/blocks\/block.py","language":"python","identifier":"Block.unkindle","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Reverts the border image.","docstring_summary":"Reverts the border image.","docstring_tokens":["Reverts","the","border","image","."],"function":"def unkindle(self):\n \"\"\" Reverts the border image. \"\"\"\n if self.kindled:\n self.canvas.before.remove(self.kindled)\n self.funbind('pos', self._bind_border)\n self.kindled = None\n else:\n logger.warning('Called unkindle on a block not kindled')","function_tokens":["def","unkindle","(","self",")",":","if","self",".","kindled",":","self",".","canvas",".","before",".","remove","(","self",".","kindled",")","self",".","funbind","(","'pos'",",","self",".","_bind_border",")","self",".","kindled","=","None","else",":","logger",".","warning","(","'Called unkindle on a block not kindled'",")"],"url":"https:\/\/github.com\/AlvarBer\/Persimmon\/blob\/da08ed854dd0305d7e4684e97ee828acffd76b4d\/persimmon\/view\/blocks\/block.py#L125-L132"}
30
+ {"nwo":"AlvarBer\/Persimmon","sha":"da08ed854dd0305d7e4684e97ee828acffd76b4d","path":"persimmon\/view\/blocks\/block.py","language":"python","identifier":"Block._bind_border","parameters":"(self, block: 'Block', new_pos: Tuple[float, float])","argument_list":"","return_statement":"","docstring":"Bind border to position.","docstring_summary":"Bind border to position.","docstring_tokens":["Bind","border","to","position","."],"function":"def _bind_border(self, block: 'Block', new_pos: Tuple[float, float]):\n \"\"\" Bind border to position. \"\"\"\n self.kindled.pos = new_pos[0] - 2, new_pos[1] - 2","function_tokens":["def","_bind_border","(","self",",","block",":","'Block'",",","new_pos",":","Tuple","[","float",",","float","]",")",":","self",".","kindled",".","pos","=","new_pos","[","0","]","-","2",",","new_pos","[","1","]","-","2"],"url":"https:\/\/github.com\/AlvarBer\/Persimmon\/blob\/da08ed854dd0305d7e4684e97ee828acffd76b4d\/persimmon\/view\/blocks\/block.py#L135-L137"}
31
+ {"nwo":"AlvarBer\/Persimmon","sha":"da08ed854dd0305d7e4684e97ee828acffd76b4d","path":"persimmon\/view\/blocks\/block.py","language":"python","identifier":"Block._bind_pin","parameters":"(self, block: 'Block', new_pos: Tuple[float, float],\n pin: Pin, i: int, output: bool)","argument_list":"","return_statement":"","docstring":"Keep pins on their respective places.","docstring_summary":"Keep pins on their respective places.","docstring_tokens":["Keep","pins","on","their","respective","places","."],"function":"def _bind_pin(self, block: 'Block', new_pos: Tuple[float, float],\n pin: Pin, i: int, output: bool):\n \"\"\" Keep pins on their respective places. \"\"\"\n pin.y = (block.y + (block.height - block.label.height) - i * self.gap +\n pin.height \/ 2)\n if output:\n pin.x = block.x + block.width - self.gap\n else:\n pin.x = block.x + 5","function_tokens":["def","_bind_pin","(","self",",","block",":","'Block'",",","new_pos",":","Tuple","[","float",",","float","]",",","pin",":","Pin",",","i",":","int",",","output",":","bool",")",":","pin",".","y","=","(","block",".","y","+","(","block",".","height","-","block",".","label",".","height",")","-","i","*","self",".","gap","+","pin",".","height","\/","2",")","if","output",":","pin",".","x","=","block",".","x","+","block",".","width","-","self",".","gap","else",":","pin",".","x","=","block",".","x","+","5"],"url":"https:\/\/github.com\/AlvarBer\/Persimmon\/blob\/da08ed854dd0305d7e4684e97ee828acffd76b4d\/persimmon\/view\/blocks\/block.py#L139-L147"}
32
+ {"nwo":"AlvarBer\/Persimmon","sha":"da08ed854dd0305d7e4684e97ee828acffd76b4d","path":"persimmon\/backend\/backend.py","language":"python","identifier":"Backend._exec_graph_parallel","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Execution algorithm, introduces all blocks on a set, when a block\n is executed it is taken out of the set until the set is empty.","docstring_summary":"Execution algorithm, introduces all blocks on a set, when a block\n is executed it is taken out of the set until the set is empty.","docstring_tokens":["Execution","algorithm","introduces","all","blocks","on","a","set","when","a","block","is","executed","it","is","taken","out","of","the","set","until","the","set","is","empty","."],"function":"def _exec_graph_parallel(self):\n \"\"\" Execution algorithm, introduces all blocks on a set, when a block\n is executed it is taken out of the set until the set is empty. \"\"\"\n unseen = set(self.ir.blocks.keys()) # All blocks are unseen at start\n # All output pins along their respectives values\n seen = {} # type: Dict[int, Any]\n while unseen:\n unseen, seen = self._exec_block(unseen.pop(), unseen, seen)\n logger.info('Execution done')\n self.emit('graph_executed')","function_tokens":["def","_exec_graph_parallel","(","self",")",":","unseen","=","set","(","self",".","ir",".","blocks",".","keys","(",")",")","# All blocks are unseen at start","# All output pins along their respectives values","seen","=","{","}","# type: Dict[int, Any]","while","unseen",":","unseen",",","seen","=","self",".","_exec_block","(","unseen",".","pop","(",")",",","unseen",",","seen",")","logger",".","info","(","'Execution done'",")","self",".","emit","(","'graph_executed'",")"],"url":"https:\/\/github.com\/AlvarBer\/Persimmon\/blob\/da08ed854dd0305d7e4684e97ee828acffd76b4d\/persimmon\/backend\/backend.py#L29-L38"}
33
+ {"nwo":"AlvarBer\/Persimmon","sha":"da08ed854dd0305d7e4684e97ee828acffd76b4d","path":"persimmon\/backend\/backend.py","language":"python","identifier":"Backend._exec_block","parameters":"(self, current: int, unseen: set,\n seen: Dict[int, Any])","argument_list":"","return_statement":"return unseen, seen","docstring":"Execute a block, if any dependency is not yet executed we\n recurse into it first.","docstring_summary":"Execute a block, if any dependency is not yet executed we\n recurse into it first.","docstring_tokens":["Execute","a","block","if","any","dependency","is","not","yet","executed","we","recurse","into","it","first","."],"function":"def _exec_block(self, current: int, unseen: set,\n seen: Dict[int, Any]) -> Tuple[set, Dict[int, Any]]:\n \"\"\" Execute a block, if any dependency is not yet executed we\n recurse into it first. \"\"\"\n logger.debug('Executing block {}'.format(current))\n current_block = self.ir.blocks[current]\n for in_pin in map(lambda x: self.ir.inputs[x], current_block.inputs):\n origin = in_pin.origin\n if origin not in seen:\n dependency = self.ir.outputs[origin].block\n unseen.remove(dependency)\n unseen, seen = self._exec_block(dependency, unseen, seen)\n in_pin.pin.val = seen[origin]\n\n current_block.function()\n self.emit('block_executed', current)\n logger.debug('Block {} executed'.format(current))\n\n for out_id in current_block.outputs:\n seen[out_id] = self.ir.outputs[out_id].pin.val\n return unseen, seen","function_tokens":["def","_exec_block","(","self",",","current",":","int",",","unseen",":","set",",","seen",":","Dict","[","int",",","Any","]",")","->","Tuple","[","set",",","Dict","[","int",",","Any","]","]",":","logger",".","debug","(","'Executing block {}'",".","format","(","current",")",")","current_block","=","self",".","ir",".","blocks","[","current","]","for","in_pin","in","map","(","lambda","x",":","self",".","ir",".","inputs","[","x","]",",","current_block",".","inputs",")",":","origin","=","in_pin",".","origin","if","origin","not","in","seen",":","dependency","=","self",".","ir",".","outputs","[","origin","]",".","block","unseen",".","remove","(","dependency",")","unseen",",","seen","=","self",".","_exec_block","(","dependency",",","unseen",",","seen",")","in_pin",".","pin",".","val","=","seen","[","origin","]","current_block",".","function","(",")","self",".","emit","(","'block_executed'",",","current",")","logger",".","debug","(","'Block {} executed'",".","format","(","current",")",")","for","out_id","in","current_block",".","outputs",":","seen","[","out_id","]","=","self",".","ir",".","outputs","[","out_id","]",".","pin",".","val","return","unseen",",","seen"],"url":"https:\/\/github.com\/AlvarBer\/Persimmon\/blob\/da08ed854dd0305d7e4684e97ee828acffd76b4d\/persimmon\/backend\/backend.py#L40-L60"}
AnasAboureada__Penetration-Testing-Study-Notes.jsonl ADDED
@@ -0,0 +1 @@
 
 
1
+ {"nwo":"AnasAboureada\/Penetration-Testing-Study-Notes","sha":"8152fd609cf818dba2f07e060738a24c56221687","path":"enumeration\/tools\/recon_scan\/samrdump.py","language":"python","identifier":"SAMRDump.dump","parameters":"(self, addr)","argument_list":"","return_statement":"","docstring":"Dumps the list of users and shares registered present at\n addr. Addr is a valid host name or IP address.","docstring_summary":"Dumps the list of users and shares registered present at\n addr. Addr is a valid host name or IP address.","docstring_tokens":["Dumps","the","list","of","users","and","shares","registered","present","at","addr",".","Addr","is","a","valid","host","name","or","IP","address","."],"function":"def dump(self, addr):\n \"\"\"Dumps the list of users and shares registered present at\n addr. Addr is a valid host name or IP address.\n \"\"\"\n\n encoding = sys.getdefaultencoding()\n\n print 'Retrieving endpoint list from %s' % addr\n\n # Try all requested protocols until one works.\n entries = []\n for protocol in self.__protocols:\n protodef = SAMRDump.KNOWN_PROTOCOLS[protocol]\n port = protodef[1]\n\n print \"Trying protocol %s...\" % protocol\n rpctransport = transport.SMBTransport(addr, port, r'\\samr', self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash)\n\n try:\n entries = self.__fetchList(rpctransport)\n except Exception, e:\n print 'Protocol failed: %s' % e\n raise\n else:\n # Got a response. No need for further iterations.\n break\n\n\n # Display results.\n\n for entry in entries:\n (username, uid, user) = entry\n base = \"%s (%d)\" % (username, uid)\n print base + '\/Enabled:', ('false', 'true')[user.is_enabled()]\n print base + '\/Last Logon:', user.get_logon_time()\n print base + '\/Last Logoff:', user.get_logoff_time()\n print base + '\/Kickoff:', user.get_kickoff_time()\n print base + '\/Last PWD Set:', user.get_pwd_last_set()\n print base + '\/PWD Can Change:', user.get_pwd_can_change()\n print base + '\/PWD Must Change:', user.get_pwd_must_change()\n print base + '\/Group id: %d' % user.get_group_id()\n print base + '\/Bad pwd count: %d' % user.get_bad_pwd_count()\n print base + '\/Logon count: %d' % user.get_logon_count()\n items = user.get_items()\n for i in samr.MSRPCUserInfo.ITEMS.keys():\n name = items[samr.MSRPCUserInfo.ITEMS[i]].get_name()\n name = name.encode(encoding, 'replace')\n print base + '\/' + i + ':', name\n\n if entries:\n num = len(entries)\n if 1 == num:\n print 'Received one entry.'\n else:\n print 'Received %d entries.' % num\n else:\n print 'No entries received.'","function_tokens":["def","dump","(","self",",","addr",")",":","encoding","=","sys",".","getdefaultencoding","(",")","print","'Retrieving endpoint list from %s'","%","addr","# Try all requested protocols until one works.","entries","=","[","]","for","protocol","in","self",".","__protocols",":","protodef","=","SAMRDump",".","KNOWN_PROTOCOLS","[","protocol","]","port","=","protodef","[","1","]","print","\"Trying protocol %s...\"","%","protocol","rpctransport","=","transport",".","SMBTransport","(","addr",",","port",",","r'\\samr'",",","self",".","__username",",","self",".","__password",",","self",".","__domain",",","self",".","__lmhash",",","self",".","__nthash",")","try",":","entries","=","self",".","__fetchList","(","rpctransport",")","except","Exception",",","e",":","print","'Protocol failed: %s'","%","e","raise","else",":","# Got a response. No need for further iterations.","break","# Display results.","for","entry","in","entries",":","(","username",",","uid",",","user",")","=","entry","base","=","\"%s (%d)\"","%","(","username",",","uid",")","print","base","+","'\/Enabled:'",",","(","'false'",",","'true'",")","[","user",".","is_enabled","(",")","]","print","base","+","'\/Last Logon:'",",","user",".","get_logon_time","(",")","print","base","+","'\/Last Logoff:'",",","user",".","get_logoff_time","(",")","print","base","+","'\/Kickoff:'",",","user",".","get_kickoff_time","(",")","print","base","+","'\/Last PWD Set:'",",","user",".","get_pwd_last_set","(",")","print","base","+","'\/PWD Can Change:'",",","user",".","get_pwd_can_change","(",")","print","base","+","'\/PWD Must Change:'",",","user",".","get_pwd_must_change","(",")","print","base","+","'\/Group id: %d'","%","user",".","get_group_id","(",")","print","base","+","'\/Bad pwd count: %d'","%","user",".","get_bad_pwd_count","(",")","print","base","+","'\/Logon count: %d'","%","user",".","get_logon_count","(",")","items","=","user",".","get_items","(",")","for","i","in","samr",".","MSRPCUserInfo",".","ITEMS",".","keys","(",")",":","name","=","items","[","samr",".","MSRPCUserInfo",".","ITEMS","[","i","]","]",".","get_name","(",")","name","=","name",".","encode","(","encoding",",","'replace'",")","print","base","+","'\/'","+","i","+","':'",",","name","if","entries",":","num","=","len","(","entries",")","if","1","==","num",":","print","'Received one entry.'","else",":","print","'Received %d entries.'","%","num","else",":","print","'No entries received.'"],"url":"https:\/\/github.com\/AnasAboureada\/Penetration-Testing-Study-Notes\/blob\/8152fd609cf818dba2f07e060738a24c56221687\/enumeration\/tools\/recon_scan\/samrdump.py#L54-L110"}
AonCyberLabs__EvilAbigail.jsonl ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {"nwo":"AonCyberLabs\/EvilAbigail","sha":"5bde1d49a76ef2e5a6e6bcda5b094441b41144ad","path":"evilmaid.py","language":"python","identifier":"UI.__init__","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Setup the main screen, progress bars and logging box","docstring_summary":"Setup the main screen, progress bars and logging box","docstring_tokens":["Setup","the","main","screen","progress","bars","and","logging","box"],"function":"def __init__(self):\n \"\"\"\n Setup the main screen, progress bars and logging box\n \"\"\"\n self.screen = curses.initscr()\n curses.curs_set(0)\n\n curses.start_color()\n curses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK)\n curses.init_pair(2, curses.COLOR_GREEN, curses.COLOR_BLACK)\n curses.init_pair(3, curses.COLOR_MAGENTA, curses.COLOR_BLACK)\n curses.init_pair(4, curses.COLOR_CYAN, curses.COLOR_BLACK)\n curses.init_pair(5, curses.COLOR_BLUE, curses.COLOR_BLACK)\n curses.init_pair(6, curses.COLOR_YELLOW, curses.COLOR_BLACK)\n\n self.height, self.width = self.screen.getmaxyx()\n self.screen.border()\n\n self.preptotal()\n self.prepcurrent()\n self.preplog()\n self.banner()\n self.sig()\n\n self.drives = len(glob.glob(\"\/dev\/sd?1\"))\n self.donedrives = 0\n self.prevprogress = 0\n self.loglines = []\n self.idx = 1","function_tokens":["def","__init__","(","self",")",":","self",".","screen","=","curses",".","initscr","(",")","curses",".","curs_set","(","0",")","curses",".","start_color","(",")","curses",".","init_pair","(","1",",","curses",".","COLOR_RED",",","curses",".","COLOR_BLACK",")","curses",".","init_pair","(","2",",","curses",".","COLOR_GREEN",",","curses",".","COLOR_BLACK",")","curses",".","init_pair","(","3",",","curses",".","COLOR_MAGENTA",",","curses",".","COLOR_BLACK",")","curses",".","init_pair","(","4",",","curses",".","COLOR_CYAN",",","curses",".","COLOR_BLACK",")","curses",".","init_pair","(","5",",","curses",".","COLOR_BLUE",",","curses",".","COLOR_BLACK",")","curses",".","init_pair","(","6",",","curses",".","COLOR_YELLOW",",","curses",".","COLOR_BLACK",")","self",".","height",",","self",".","width","=","self",".","screen",".","getmaxyx","(",")","self",".","screen",".","border","(",")","self",".","preptotal","(",")","self",".","prepcurrent","(",")","self",".","preplog","(",")","self",".","banner","(",")","self",".","sig","(",")","self",".","drives","=","len","(","glob",".","glob","(","\"\/dev\/sd?1\"",")",")","self",".","donedrives","=","0","self",".","prevprogress","=","0","self",".","loglines","=","[","]","self",".","idx","=","1"],"url":"https:\/\/github.com\/AonCyberLabs\/EvilAbigail\/blob\/5bde1d49a76ef2e5a6e6bcda5b094441b41144ad\/evilmaid.py#L129-L157"}
2
+ {"nwo":"AonCyberLabs\/EvilAbigail","sha":"5bde1d49a76ef2e5a6e6bcda5b094441b41144ad","path":"evilmaid.py","language":"python","identifier":"UI.banner","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Print the above banner and copyight notice","docstring_summary":"Print the above banner and copyight notice","docstring_tokens":["Print","the","above","banner","and","copyight","notice"],"function":"def banner(self):\n \"\"\"\n Print the above banner and copyight notice\n \"\"\"\n bannerlines = banner.split('\\n')\n for idx, line in enumerate(bannerlines):\n self.screen.addstr(2+idx, 1, line.center(self.width-2), curses.color_pair(3))\n start = bannerlines[2].center(self.width-2).index('|')+1\n self.screen.addstr(1+idx, start, copyrightlhs, curses.color_pair(1))\n self.screen.addstr(1+idx, start+len(copyrightlhs)+7, copyrightrhs, curses.color_pair(1))\n self.screen.addstr(2+idx, start, url.rjust(len(bannerlines[2])), curses.color_pair(4))","function_tokens":["def","banner","(","self",")",":","bannerlines","=","banner",".","split","(","'\\n'",")","for","idx",",","line","in","enumerate","(","bannerlines",")",":","self",".","screen",".","addstr","(","2","+","idx",",","1",",","line",".","center","(","self",".","width","-","2",")",",","curses",".","color_pair","(","3",")",")","start","=","bannerlines","[","2","]",".","center","(","self",".","width","-","2",")",".","index","(","'|'",")","+","1","self",".","screen",".","addstr","(","1","+","idx",",","start",",","copyrightlhs",",","curses",".","color_pair","(","1",")",")","self",".","screen",".","addstr","(","1","+","idx",",","start","+","len","(","copyrightlhs",")","+","7",",","copyrightrhs",",","curses",".","color_pair","(","1",")",")","self",".","screen",".","addstr","(","2","+","idx",",","start",",","url",".","rjust","(","len","(","bannerlines","[","2","]",")",")",",","curses",".","color_pair","(","4",")",")"],"url":"https:\/\/github.com\/AonCyberLabs\/EvilAbigail\/blob\/5bde1d49a76ef2e5a6e6bcda5b094441b41144ad\/evilmaid.py#L159-L169"}
3
+ {"nwo":"AonCyberLabs\/EvilAbigail","sha":"5bde1d49a76ef2e5a6e6bcda5b094441b41144ad","path":"evilmaid.py","language":"python","identifier":"UI.sig","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Print author signature","docstring_summary":"Print author signature","docstring_tokens":["Print","author","signature"],"function":"def sig(self):\n \"\"\"\n Print author signature\n \"\"\"\n self.sig = self.screen.subwin((self.height\/2)-6, (self.width-2)\/2, (self.height\/2)+6, ((self.width-2)\/2)+1)\n self.sig.border()\n self.sig.addstr(1, 1, \"Evil Abigail\".center(((self.width-2)\/2)-2), curses.color_pair(6))\n self.sig.addstr(2, 1, \"Rory McNamara\".center(((self.width-2)\/2)-2), curses.color_pair(6))\n self.sig.addstr(3, 1, \"rmcnamara@gdssecurity.com\".center(((self.width-2)\/2)-2), curses.color_pair(6))","function_tokens":["def","sig","(","self",")",":","self",".","sig","=","self",".","screen",".","subwin","(","(","self",".","height","\/","2",")","-","6",",","(","self",".","width","-","2",")","\/","2",",","(","self",".","height","\/","2",")","+","6",",","(","(","self",".","width","-","2",")","\/","2",")","+","1",")","self",".","sig",".","border","(",")","self",".","sig",".","addstr","(","1",",","1",",","\"Evil Abigail\"",".","center","(","(","(","self",".","width","-","2",")","\/","2",")","-","2",")",",","curses",".","color_pair","(","6",")",")","self",".","sig",".","addstr","(","2",",","1",",","\"Rory McNamara\"",".","center","(","(","(","self",".","width","-","2",")","\/","2",")","-","2",")",",","curses",".","color_pair","(","6",")",")","self",".","sig",".","addstr","(","3",",","1",",","\"rmcnamara@gdssecurity.com\"",".","center","(","(","(","self",".","width","-","2",")","\/","2",")","-","2",")",",","curses",".","color_pair","(","6",")",")"],"url":"https:\/\/github.com\/AonCyberLabs\/EvilAbigail\/blob\/5bde1d49a76ef2e5a6e6bcda5b094441b41144ad\/evilmaid.py#L171-L179"}
4
+ {"nwo":"AonCyberLabs\/EvilAbigail","sha":"5bde1d49a76ef2e5a6e6bcda5b094441b41144ad","path":"evilmaid.py","language":"python","identifier":"UI.preptotal","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Draw the total progress bar","docstring_summary":"Draw the total progress bar","docstring_tokens":["Draw","the","total","progress","bar"],"function":"def preptotal(self):\n \"\"\"\n Draw the total progress bar\n \"\"\"\n self.totalbar = self.screen.subwin(3, (self.width-2)\/2, (self.height\/2), ((self.width-2)\/2)+1)\n self.totalbar.erase()\n self.totalbar.border()\n self.screen.addstr((self.height\/2), ((self.width-2)\/2)+4, \"Total Progress\")","function_tokens":["def","preptotal","(","self",")",":","self",".","totalbar","=","self",".","screen",".","subwin","(","3",",","(","self",".","width","-","2",")","\/","2",",","(","self",".","height","\/","2",")",",","(","(","self",".","width","-","2",")","\/","2",")","+","1",")","self",".","totalbar",".","erase","(",")","self",".","totalbar",".","border","(",")","self",".","screen",".","addstr","(","(","self",".","height","\/","2",")",",","(","(","self",".","width","-","2",")","\/","2",")","+","4",",","\"Total Progress\"",")"],"url":"https:\/\/github.com\/AonCyberLabs\/EvilAbigail\/blob\/5bde1d49a76ef2e5a6e6bcda5b094441b41144ad\/evilmaid.py#L181-L188"}
5
+ {"nwo":"AonCyberLabs\/EvilAbigail","sha":"5bde1d49a76ef2e5a6e6bcda5b094441b41144ad","path":"evilmaid.py","language":"python","identifier":"UI.prepcurrent","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Draw the current progress bar","docstring_summary":"Draw the current progress bar","docstring_tokens":["Draw","the","current","progress","bar"],"function":"def prepcurrent(self):\n \"\"\"\n Draw the current progress bar\n \"\"\"\n self.currentbar = self.screen.subwin(3, (self.width-2)\/2, (self.height\/2)+3, ((self.width-2)\/2)+1)\n self.currentbar.erase()\n self.currentbar.border()\n self.screen.addstr((self.height\/2)+3, ((self.width-2)\/2)+4, \"Current Drive Progress\")","function_tokens":["def","prepcurrent","(","self",")",":","self",".","currentbar","=","self",".","screen",".","subwin","(","3",",","(","self",".","width","-","2",")","\/","2",",","(","self",".","height","\/","2",")","+","3",",","(","(","self",".","width","-","2",")","\/","2",")","+","1",")","self",".","currentbar",".","erase","(",")","self",".","currentbar",".","border","(",")","self",".","screen",".","addstr","(","(","self",".","height","\/","2",")","+","3",",","(","(","self",".","width","-","2",")","\/","2",")","+","4",",","\"Current Drive Progress\"",")"],"url":"https:\/\/github.com\/AonCyberLabs\/EvilAbigail\/blob\/5bde1d49a76ef2e5a6e6bcda5b094441b41144ad\/evilmaid.py#L190-L197"}
6
+ {"nwo":"AonCyberLabs\/EvilAbigail","sha":"5bde1d49a76ef2e5a6e6bcda5b094441b41144ad","path":"evilmaid.py","language":"python","identifier":"UI.preplog","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Draw the logging window","docstring_summary":"Draw the logging window","docstring_tokens":["Draw","the","logging","window"],"function":"def preplog(self):\n \"\"\"\n Draw the logging window\n \"\"\"\n self.log = self.screen.subwin((self.height\/2), (self.width-2)\/2, self.height\/2, 1)\n self.log.erase()\n self.log.border()\n self.screen.addstr((self.height\/2), 4, \"Log\")","function_tokens":["def","preplog","(","self",")",":","self",".","log","=","self",".","screen",".","subwin","(","(","self",".","height","\/","2",")",",","(","self",".","width","-","2",")","\/","2",",","self",".","height","\/","2",",","1",")","self",".","log",".","erase","(",")","self",".","log",".","border","(",")","self",".","screen",".","addstr","(","(","self",".","height","\/","2",")",",","4",",","\"Log\"",")"],"url":"https:\/\/github.com\/AonCyberLabs\/EvilAbigail\/blob\/5bde1d49a76ef2e5a6e6bcda5b094441b41144ad\/evilmaid.py#L199-L206"}
7
+ {"nwo":"AonCyberLabs\/EvilAbigail","sha":"5bde1d49a76ef2e5a6e6bcda5b094441b41144ad","path":"evilmaid.py","language":"python","identifier":"UI.logger","parameters":"(self, line, status, continuing = False)","argument_list":"","return_statement":"","docstring":"Log a line to the logging window. Autoscrolls\n A progress of 1.0 will fill the current bar accordingly (useful for 'continue')\n Auto splits and indents long lines","docstring_summary":"Log a line to the logging window. Autoscrolls\n A progress of 1.0 will fill the current bar accordingly (useful for 'continue')\n Auto splits and indents long lines","docstring_tokens":["Log","a","line","to","the","logging","window",".","Autoscrolls","A","progress","of","1",".","0","will","fill","the","current","bar","accordingly","(","useful","for","continue",")","Auto","splits","and","indents","long","lines"],"function":"def logger(self, line, status, continuing = False):\n \"\"\"\n Log a line to the logging window. Autoscrolls\n A progress of 1.0 will fill the current bar accordingly (useful for 'continue')\n Auto splits and indents long lines\n \"\"\"\n statuses = {\n \"ERROR\": curses.color_pair(1),\n \"INFO\": curses.color_pair(2)\n }\n if status == \"ERROR\" and not continuing:\n progress = 1.0\n else:\n progress = self.idx\/self.items\n self.idx += 1\n first = True\n while line:\n if first:\n first = False\n self.loglines.append((line[:37], status))\n line = line[37:]\n else:\n self.loglines.append((' '+line[:35], status))\n line = line[35:]\n self.preplog()\n for idx, line in enumerate(self.loglines[-((self.height\/2)-3):]):\n self.log.addstr(idx+1, 1, line[0], statuses[line[1]])\n if progress:\n self.plot(progress)\n self.refresh()","function_tokens":["def","logger","(","self",",","line",",","status",",","continuing","=","False",")",":","statuses","=","{","\"ERROR\"",":","curses",".","color_pair","(","1",")",",","\"INFO\"",":","curses",".","color_pair","(","2",")","}","if","status","==","\"ERROR\"","and","not","continuing",":","progress","=","1.0","else",":","progress","=","self",".","idx","\/","self",".","items","self",".","idx","+=","1","first","=","True","while","line",":","if","first",":","first","=","False","self",".","loglines",".","append","(","(","line","[",":","37","]",",","status",")",")","line","=","line","[","37",":","]","else",":","self",".","loglines",".","append","(","(","' '","+","line","[",":","35","]",",","status",")",")","line","=","line","[","35",":","]","self",".","preplog","(",")","for","idx",",","line","in","enumerate","(","self",".","loglines","[","-","(","(","self",".","height","\/","2",")","-","3",")",":","]",")",":","self",".","log",".","addstr","(","idx","+","1",",","1",",","line","[","0","]",",","statuses","[","line","[","1","]","]",")","if","progress",":","self",".","plot","(","progress",")","self",".","refresh","(",")"],"url":"https:\/\/github.com\/AonCyberLabs\/EvilAbigail\/blob\/5bde1d49a76ef2e5a6e6bcda5b094441b41144ad\/evilmaid.py#L208-L237"}
8
+ {"nwo":"AonCyberLabs\/EvilAbigail","sha":"5bde1d49a76ef2e5a6e6bcda5b094441b41144ad","path":"evilmaid.py","language":"python","identifier":"UI.nextdrive","parameters":"(self, items)","argument_list":"","return_statement":"","docstring":"Signifies the start of the next drive for the current progress bar\n Items is how many logging evens we expect to see on the main path","docstring_summary":"Signifies the start of the next drive for the current progress bar\n Items is how many logging evens we expect to see on the main path","docstring_tokens":["Signifies","the","start","of","the","next","drive","for","the","current","progress","bar","Items","is","how","many","logging","evens","we","expect","to","see","on","the","main","path"],"function":"def nextdrive(self, items):\n \"\"\"\n Signifies the start of the next drive for the current progress bar\n Items is how many logging evens we expect to see on the main path\n \"\"\"\n self.idx = 1\n self.items = float(items)","function_tokens":["def","nextdrive","(","self",",","items",")",":","self",".","idx","=","1","self",".","items","=","float","(","items",")"],"url":"https:\/\/github.com\/AonCyberLabs\/EvilAbigail\/blob\/5bde1d49a76ef2e5a6e6bcda5b094441b41144ad\/evilmaid.py#L239-L245"}
9
+ {"nwo":"AonCyberLabs\/EvilAbigail","sha":"5bde1d49a76ef2e5a6e6bcda5b094441b41144ad","path":"evilmaid.py","language":"python","identifier":"UI.incritems","parameters":"(self, items)","argument_list":"","return_statement":"","docstring":"Allows adding to how many steps we expect to see\n For branch based differences","docstring_summary":"Allows adding to how many steps we expect to see\n For branch based differences","docstring_tokens":["Allows","adding","to","how","many","steps","we","expect","to","see","For","branch","based","differences"],"function":"def incritems(self, items):\n \"\"\"\n Allows adding to how many steps we expect to see\n For branch based differences\n \"\"\"\n self.items += items","function_tokens":["def","incritems","(","self",",","items",")",":","self",".","items","+=","items"],"url":"https:\/\/github.com\/AonCyberLabs\/EvilAbigail\/blob\/5bde1d49a76ef2e5a6e6bcda5b094441b41144ad\/evilmaid.py#L247-L252"}
10
+ {"nwo":"AonCyberLabs\/EvilAbigail","sha":"5bde1d49a76ef2e5a6e6bcda5b094441b41144ad","path":"evilmaid.py","language":"python","identifier":"UI.plot","parameters":"(self, progress)","argument_list":"","return_statement":"","docstring":"Actually fill the progress bars accordingly","docstring_summary":"Actually fill the progress bars accordingly","docstring_tokens":["Actually","fill","the","progress","bars","accordingly"],"function":"def plot(self, progress):\n \"\"\"\n Actually fill the progress bars accordingly\n \"\"\"\n if progress < self.prevprogress:\n self.donedrives += 1\n self.prevprogress = progress\n\n progress = progress + self.donedrives\n totalbar = int((progress\/self.drives)*((self.width-2)\/2))\n currentbar = int(progress*((self.width-2)\/2)) % (self.width\/2)\n\n self.preptotal()\n self.prepcurrent()\n\n self.totalbar.addstr(1, 1, \"-\"*(totalbar-2), curses.color_pair(2))\n self.currentbar.addstr(1, 1, \"-\"*(currentbar-2), curses.color_pair(2))\n\n self.refresh()","function_tokens":["def","plot","(","self",",","progress",")",":","if","progress","<","self",".","prevprogress",":","self",".","donedrives","+=","1","self",".","prevprogress","=","progress","progress","=","progress","+","self",".","donedrives","totalbar","=","int","(","(","progress","\/","self",".","drives",")","*","(","(","self",".","width","-","2",")","\/","2",")",")","currentbar","=","int","(","progress","*","(","(","self",".","width","-","2",")","\/","2",")",")","%","(","self",".","width","\/","2",")","self",".","preptotal","(",")","self",".","prepcurrent","(",")","self",".","totalbar",".","addstr","(","1",",","1",",","\"-\"","*","(","totalbar","-","2",")",",","curses",".","color_pair","(","2",")",")","self",".","currentbar",".","addstr","(","1",",","1",",","\"-\"","*","(","currentbar","-","2",")",",","curses",".","color_pair","(","2",")",")","self",".","refresh","(",")"],"url":"https:\/\/github.com\/AonCyberLabs\/EvilAbigail\/blob\/5bde1d49a76ef2e5a6e6bcda5b094441b41144ad\/evilmaid.py#L254-L272"}
11
+ {"nwo":"AonCyberLabs\/EvilAbigail","sha":"5bde1d49a76ef2e5a6e6bcda5b094441b41144ad","path":"evilmaid.py","language":"python","identifier":"UI.refresh","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Refresh the screen in order","docstring_summary":"Refresh the screen in order","docstring_tokens":["Refresh","the","screen","in","order"],"function":"def refresh(self):\n \"\"\"\n Refresh the screen in order\n \"\"\"\n self.totalbar.refresh()\n self.currentbar.refresh()\n self.log.refresh()\n self.screen.refresh()","function_tokens":["def","refresh","(","self",")",":","self",".","totalbar",".","refresh","(",")","self",".","currentbar",".","refresh","(",")","self",".","log",".","refresh","(",")","self",".","screen",".","refresh","(",")"],"url":"https:\/\/github.com\/AonCyberLabs\/EvilAbigail\/blob\/5bde1d49a76ef2e5a6e6bcda5b094441b41144ad\/evilmaid.py#L274-L281"}
12
+ {"nwo":"AonCyberLabs\/EvilAbigail","sha":"5bde1d49a76ef2e5a6e6bcda5b094441b41144ad","path":"evilmaid.py","language":"python","identifier":"UI.destroy","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Clear screen and exit","docstring_summary":"Clear screen and exit","docstring_tokens":["Clear","screen","and","exit"],"function":"def destroy(self):\n \"\"\"\n Clear screen and exit\n \"\"\"\n self.screen.erase()\n self.refresh()\n curses.endwin()","function_tokens":["def","destroy","(","self",")",":","self",".","screen",".","erase","(",")","self",".","refresh","(",")","curses",".","endwin","(",")"],"url":"https:\/\/github.com\/AonCyberLabs\/EvilAbigail\/blob\/5bde1d49a76ef2e5a6e6bcda5b094441b41144ad\/evilmaid.py#L283-L289"}
Ape__samsungctl.jsonl ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {"nwo":"Ape\/samsungctl","sha":"81cf14aa138c32ff10aaa424864d6fc92b987322","path":"samsungctl\/remote_websocket.py","language":"python","identifier":"RemoteWebsocket.close","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Close the connection.","docstring_summary":"Close the connection.","docstring_tokens":["Close","the","connection","."],"function":"def close(self):\n \"\"\"Close the connection.\"\"\"\n if self.connection:\n self.connection.close()\n self.connection = None\n logging.debug(\"Connection closed.\")","function_tokens":["def","close","(","self",")",":","if","self",".","connection",":","self",".","connection",".","close","(",")","self",".","connection","=","None","logging",".","debug","(","\"Connection closed.\"",")"],"url":"https:\/\/github.com\/Ape\/samsungctl\/blob\/81cf14aa138c32ff10aaa424864d6fc92b987322\/samsungctl\/remote_websocket.py#L38-L43"}
2
+ {"nwo":"Ape\/samsungctl","sha":"81cf14aa138c32ff10aaa424864d6fc92b987322","path":"samsungctl\/remote_websocket.py","language":"python","identifier":"RemoteWebsocket.control","parameters":"(self, key)","argument_list":"","return_statement":"","docstring":"Send a control command.","docstring_summary":"Send a control command.","docstring_tokens":["Send","a","control","command","."],"function":"def control(self, key):\n \"\"\"Send a control command.\"\"\"\n if not self.connection:\n raise exceptions.ConnectionClosed()\n\n payload = json.dumps({\n \"method\": \"ms.remote.control\",\n \"params\": {\n \"Cmd\": \"Click\",\n \"DataOfCmd\": key,\n \"Option\": \"false\",\n \"TypeOfRemote\": \"SendRemoteKey\"\n }\n })\n\n logging.info(\"Sending control command: %s\", key)\n self.connection.send(payload)\n time.sleep(self._key_interval)","function_tokens":["def","control","(","self",",","key",")",":","if","not","self",".","connection",":","raise","exceptions",".","ConnectionClosed","(",")","payload","=","json",".","dumps","(","{","\"method\"",":","\"ms.remote.control\"",",","\"params\"",":","{","\"Cmd\"",":","\"Click\"",",","\"DataOfCmd\"",":","key",",","\"Option\"",":","\"false\"",",","\"TypeOfRemote\"",":","\"SendRemoteKey\"","}","}",")","logging",".","info","(","\"Sending control command: %s\"",",","key",")","self",".","connection",".","send","(","payload",")","time",".","sleep","(","self",".","_key_interval",")"],"url":"https:\/\/github.com\/Ape\/samsungctl\/blob\/81cf14aa138c32ff10aaa424864d6fc92b987322\/samsungctl\/remote_websocket.py#L45-L62"}
3
+ {"nwo":"Ape\/samsungctl","sha":"81cf14aa138c32ff10aaa424864d6fc92b987322","path":"samsungctl\/remote_legacy.py","language":"python","identifier":"RemoteLegacy.__init__","parameters":"(self, config)","argument_list":"","return_statement":"","docstring":"Make a new connection.","docstring_summary":"Make a new connection.","docstring_tokens":["Make","a","new","connection","."],"function":"def __init__(self, config):\n if not config[\"port\"]:\n config[\"port\"] = 55000\n\n \"\"\"Make a new connection.\"\"\"\n self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n if config[\"timeout\"]:\n self.connection.settimeout(config[\"timeout\"])\n\n self.connection.connect((config[\"host\"], config[\"port\"]))\n\n payload = b\"\\x64\\x00\" \\\n + self._serialize_string(config[\"description\"]) \\\n + self._serialize_string(config[\"id\"]) \\\n + self._serialize_string(config[\"name\"])\n packet = b\"\\x00\\x00\\x00\" + self._serialize_string(payload, True)\n\n logging.info(\"Sending handshake.\")\n self.connection.send(packet)\n self._read_response(True)","function_tokens":["def","__init__","(","self",",","config",")",":","if","not","config","[","\"port\"","]",":","config","[","\"port\"","]","=","55000","self",".","connection","=","socket",".","socket","(","socket",".","AF_INET",",","socket",".","SOCK_STREAM",")","if","config","[","\"timeout\"","]",":","self",".","connection",".","settimeout","(","config","[","\"timeout\"","]",")","self",".","connection",".","connect","(","(","config","[","\"host\"","]",",","config","[","\"port\"","]",")",")","payload","=","b\"\\x64\\x00\"","+","self",".","_serialize_string","(","config","[","\"description\"","]",")","+","self",".","_serialize_string","(","config","[","\"id\"","]",")","+","self",".","_serialize_string","(","config","[","\"name\"","]",")","packet","=","b\"\\x00\\x00\\x00\"","+","self",".","_serialize_string","(","payload",",","True",")","logging",".","info","(","\"Sending handshake.\"",")","self",".","connection",".","send","(","packet",")","self",".","_read_response","(","True",")"],"url":"https:\/\/github.com\/Ape\/samsungctl\/blob\/81cf14aa138c32ff10aaa424864d6fc92b987322\/samsungctl\/remote_legacy.py#L12-L32"}
4
+ {"nwo":"Ape\/samsungctl","sha":"81cf14aa138c32ff10aaa424864d6fc92b987322","path":"samsungctl\/remote_legacy.py","language":"python","identifier":"RemoteLegacy.close","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Close the connection.","docstring_summary":"Close the connection.","docstring_tokens":["Close","the","connection","."],"function":"def close(self):\n \"\"\"Close the connection.\"\"\"\n if self.connection:\n self.connection.close()\n self.connection = None\n logging.debug(\"Connection closed.\")","function_tokens":["def","close","(","self",")",":","if","self",".","connection",":","self",".","connection",".","close","(",")","self",".","connection","=","None","logging",".","debug","(","\"Connection closed.\"",")"],"url":"https:\/\/github.com\/Ape\/samsungctl\/blob\/81cf14aa138c32ff10aaa424864d6fc92b987322\/samsungctl\/remote_legacy.py#L40-L45"}
5
+ {"nwo":"Ape\/samsungctl","sha":"81cf14aa138c32ff10aaa424864d6fc92b987322","path":"samsungctl\/remote_legacy.py","language":"python","identifier":"RemoteLegacy.control","parameters":"(self, key)","argument_list":"","return_statement":"","docstring":"Send a control command.","docstring_summary":"Send a control command.","docstring_tokens":["Send","a","control","command","."],"function":"def control(self, key):\n \"\"\"Send a control command.\"\"\"\n if not self.connection:\n raise exceptions.ConnectionClosed()\n\n payload = b\"\\x00\\x00\\x00\" + self._serialize_string(key)\n packet = b\"\\x00\\x00\\x00\" + self._serialize_string(payload, True)\n\n logging.info(\"Sending control command: %s\", key)\n self.connection.send(packet)\n self._read_response()\n time.sleep(self._key_interval)","function_tokens":["def","control","(","self",",","key",")",":","if","not","self",".","connection",":","raise","exceptions",".","ConnectionClosed","(",")","payload","=","b\"\\x00\\x00\\x00\"","+","self",".","_serialize_string","(","key",")","packet","=","b\"\\x00\\x00\\x00\"","+","self",".","_serialize_string","(","payload",",","True",")","logging",".","info","(","\"Sending control command: %s\"",",","key",")","self",".","connection",".","send","(","packet",")","self",".","_read_response","(",")","time",".","sleep","(","self",".","_key_interval",")"],"url":"https:\/\/github.com\/Ape\/samsungctl\/blob\/81cf14aa138c32ff10aaa424864d6fc92b987322\/samsungctl\/remote_legacy.py#L47-L58"}
6
+ {"nwo":"Ape\/samsungctl","sha":"81cf14aa138c32ff10aaa424864d6fc92b987322","path":"samsungctl\/interactive.py","language":"python","identifier":"run","parameters":"(remote)","argument_list":"","return_statement":"","docstring":"Run interactive remote control application.","docstring_summary":"Run interactive remote control application.","docstring_tokens":["Run","interactive","remote","control","application","."],"function":"def run(remote):\n \"\"\"Run interactive remote control application.\"\"\"\n curses.wrapper(_control, remote)","function_tokens":["def","run","(","remote",")",":","curses",".","wrapper","(","_control",",","remote",")"],"url":"https:\/\/github.com\/Ape\/samsungctl\/blob\/81cf14aa138c32ff10aaa424864d6fc92b987322\/samsungctl\/interactive.py#L45-L47"}
Azelphur__pyPushBullet.jsonl ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {"nwo":"Azelphur\/pyPushBullet","sha":"d230d80419f105367dade9337539dd112d574869","path":"pushbullet\/pushbullet.py","language":"python","identifier":"PushBullet.addDevice","parameters":"(self, device_name)","argument_list":"","return_statement":"return self._request(\"POST\", HOST + \"\/devices\", data)","docstring":"Push a note\n https:\/\/docs.pushbullet.com\/v2\/pushes\n\n Arguments:\n device_name -- Human readable name for device\n type -- stream, thats all there is currently","docstring_summary":"Push a note\n https:\/\/docs.pushbullet.com\/v2\/pushes","docstring_tokens":["Push","a","note","https",":","\/\/","docs",".","pushbullet",".","com","\/","v2","\/","pushes"],"function":"def addDevice(self, device_name):\n \"\"\" Push a note\n https:\/\/docs.pushbullet.com\/v2\/pushes\n\n Arguments:\n device_name -- Human readable name for device\n type -- stream, thats all there is currently\n\n \"\"\"\n\n data = {\"nickname\": device_name,\n \"type\": \"stream\"\n }\n return self._request(\"POST\", HOST + \"\/devices\", data)","function_tokens":["def","addDevice","(","self",",","device_name",")",":","data","=","{","\"nickname\"",":","device_name",",","\"type\"",":","\"stream\"","}","return","self",".","_request","(","\"POST\"",",","HOST","+","\"\/devices\"",",","data",")"],"url":"https:\/\/github.com\/Azelphur\/pyPushBullet\/blob\/d230d80419f105367dade9337539dd112d574869\/pushbullet\/pushbullet.py#L46-L59"}
2
+ {"nwo":"Azelphur\/pyPushBullet","sha":"d230d80419f105367dade9337539dd112d574869","path":"pushbullet\/pushbullet.py","language":"python","identifier":"PushBullet.getDevices","parameters":"(self)","argument_list":"","return_statement":"return self._request(\"GET\", HOST + \"\/devices\")[\"devices\"]","docstring":"Get devices\n https:\/\/docs.pushbullet.com\/v2\/devices\n\n Get a list of devices, and data about them.","docstring_summary":"Get devices\n https:\/\/docs.pushbullet.com\/v2\/devices","docstring_tokens":["Get","devices","https",":","\/\/","docs",".","pushbullet",".","com","\/","v2","\/","devices"],"function":"def getDevices(self):\n \"\"\" Get devices\n https:\/\/docs.pushbullet.com\/v2\/devices\n\n Get a list of devices, and data about them.\n \"\"\"\n\n return self._request(\"GET\", HOST + \"\/devices\")[\"devices\"]","function_tokens":["def","getDevices","(","self",")",":","return","self",".","_request","(","\"GET\"",",","HOST","+","\"\/devices\"",")","[","\"devices\"","]"],"url":"https:\/\/github.com\/Azelphur\/pyPushBullet\/blob\/d230d80419f105367dade9337539dd112d574869\/pushbullet\/pushbullet.py#L61-L68"}
3
+ {"nwo":"Azelphur\/pyPushBullet","sha":"d230d80419f105367dade9337539dd112d574869","path":"pushbullet\/pushbullet.py","language":"python","identifier":"PushBullet.deleteDevice","parameters":"(self, device_iden)","argument_list":"","return_statement":"return self._request(\"DELETE\", HOST + \"\/devices\/\" + device_iden)","docstring":"Delete a device\n https:\/\/docs.pushbullet.com\/v2\/devices\n\n Arguments:\n device_iden -- iden of device to push to","docstring_summary":"Delete a device\n https:\/\/docs.pushbullet.com\/v2\/devices","docstring_tokens":["Delete","a","device","https",":","\/\/","docs",".","pushbullet",".","com","\/","v2","\/","devices"],"function":"def deleteDevice(self, device_iden):\n \"\"\" Delete a device\n https:\/\/docs.pushbullet.com\/v2\/devices\n\n Arguments:\n device_iden -- iden of device to push to\n \"\"\"\n\n return self._request(\"DELETE\", HOST + \"\/devices\/\" + device_iden)","function_tokens":["def","deleteDevice","(","self",",","device_iden",")",":","return","self",".","_request","(","\"DELETE\"",",","HOST","+","\"\/devices\/\"","+","device_iden",")"],"url":"https:\/\/github.com\/Azelphur\/pyPushBullet\/blob\/d230d80419f105367dade9337539dd112d574869\/pushbullet\/pushbullet.py#L70-L78"}
4
+ {"nwo":"Azelphur\/pyPushBullet","sha":"d230d80419f105367dade9337539dd112d574869","path":"pushbullet\/pushbullet.py","language":"python","identifier":"PushBullet.pushNote","parameters":"(self, recipient, title, body, recipient_type=\"device_iden\")","argument_list":"","return_statement":"return self._request(\"POST\", HOST + \"\/pushes\", data)","docstring":"Push a note\n https:\/\/docs.pushbullet.com\/v2\/pushes\n\n Arguments:\n recipient -- a recipient\n title -- a title for the note\n body -- the body of the note\n recipient_type -- a type of recipient (device, email, channel or client)","docstring_summary":"Push a note\n https:\/\/docs.pushbullet.com\/v2\/pushes","docstring_tokens":["Push","a","note","https",":","\/\/","docs",".","pushbullet",".","com","\/","v2","\/","pushes"],"function":"def pushNote(self, recipient, title, body, recipient_type=\"device_iden\"):\n \"\"\" Push a note\n https:\/\/docs.pushbullet.com\/v2\/pushes\n\n Arguments:\n recipient -- a recipient\n title -- a title for the note\n body -- the body of the note\n recipient_type -- a type of recipient (device, email, channel or client)\n \"\"\"\n\n data = {\"type\": \"note\",\n \"title\": title,\n \"body\": body}\n\n data[recipient_type] = recipient\n\n return self._request(\"POST\", HOST + \"\/pushes\", data)","function_tokens":["def","pushNote","(","self",",","recipient",",","title",",","body",",","recipient_type","=","\"device_iden\"",")",":","data","=","{","\"type\"",":","\"note\"",",","\"title\"",":","title",",","\"body\"",":","body","}","data","[","recipient_type","]","=","recipient","return","self",".","_request","(","\"POST\"",",","HOST","+","\"\/pushes\"",",","data",")"],"url":"https:\/\/github.com\/Azelphur\/pyPushBullet\/blob\/d230d80419f105367dade9337539dd112d574869\/pushbullet\/pushbullet.py#L80-L97"}
5
+ {"nwo":"Azelphur\/pyPushBullet","sha":"d230d80419f105367dade9337539dd112d574869","path":"pushbullet\/pushbullet.py","language":"python","identifier":"PushBullet.pushAddress","parameters":"(self, recipient, name, address, recipient_type=\"device_iden\")","argument_list":"","return_statement":"return self._request(\"POST\", HOST + \"\/pushes\", data)","docstring":"Push an address\n https:\/\/docs.pushbullet.com\/v2\/pushes\n\n Arguments:\n recipient -- a recipient\n name -- name for the address, eg \"Bobs house\"\n address -- address of the address\n recipient_type -- a type of recipient (device, email, channel or client)","docstring_summary":"Push an address\n https:\/\/docs.pushbullet.com\/v2\/pushes","docstring_tokens":["Push","an","address","https",":","\/\/","docs",".","pushbullet",".","com","\/","v2","\/","pushes"],"function":"def pushAddress(self, recipient, name, address, recipient_type=\"device_iden\"):\n \"\"\" Push an address\n https:\/\/docs.pushbullet.com\/v2\/pushes\n\n Arguments:\n recipient -- a recipient\n name -- name for the address, eg \"Bobs house\"\n address -- address of the address\n recipient_type -- a type of recipient (device, email, channel or client)\n \"\"\"\n\n data = {\"type\": \"address\",\n \"name\": name,\n \"address\": address}\n\t\t\t\t\n data[recipient_type] = recipient\n\t\t\t\t\n return self._request(\"POST\", HOST + \"\/pushes\", data)","function_tokens":["def","pushAddress","(","self",",","recipient",",","name",",","address",",","recipient_type","=","\"device_iden\"",")",":","data","=","{","\"type\"",":","\"address\"",",","\"name\"",":","name",",","\"address\"",":","address","}","data","[","recipient_type","]","=","recipient","return","self",".","_request","(","\"POST\"",",","HOST","+","\"\/pushes\"",",","data",")"],"url":"https:\/\/github.com\/Azelphur\/pyPushBullet\/blob\/d230d80419f105367dade9337539dd112d574869\/pushbullet\/pushbullet.py#L99-L116"}
6
+ {"nwo":"Azelphur\/pyPushBullet","sha":"d230d80419f105367dade9337539dd112d574869","path":"pushbullet\/pushbullet.py","language":"python","identifier":"PushBullet.pushList","parameters":"(self, recipient, title, items, recipient_type=\"device_iden\")","argument_list":"","return_statement":"return self._request(\"POST\", HOST + \"\/pushes\", data)","docstring":"Push a list\n https:\/\/docs.pushbullet.com\/v2\/pushes\n\n Arguments:\n recipient -- a recipient\n title -- a title for the list\n items -- a list of items\n recipient_type -- a type of recipient (device, email, channel or client)","docstring_summary":"Push a list\n https:\/\/docs.pushbullet.com\/v2\/pushes","docstring_tokens":["Push","a","list","https",":","\/\/","docs",".","pushbullet",".","com","\/","v2","\/","pushes"],"function":"def pushList(self, recipient, title, items, recipient_type=\"device_iden\"):\n \"\"\" Push a list\n https:\/\/docs.pushbullet.com\/v2\/pushes\n\n Arguments:\n recipient -- a recipient\n title -- a title for the list\n items -- a list of items\n recipient_type -- a type of recipient (device, email, channel or client)\n \"\"\"\n\n data = {\"type\": \"list\",\n \"title\": title,\n \"items\": items}\n\t\t\t\t\n data[recipient_type] = recipient\n\n return self._request(\"POST\", HOST + \"\/pushes\", data)","function_tokens":["def","pushList","(","self",",","recipient",",","title",",","items",",","recipient_type","=","\"device_iden\"",")",":","data","=","{","\"type\"",":","\"list\"",",","\"title\"",":","title",",","\"items\"",":","items","}","data","[","recipient_type","]","=","recipient","return","self",".","_request","(","\"POST\"",",","HOST","+","\"\/pushes\"",",","data",")"],"url":"https:\/\/github.com\/Azelphur\/pyPushBullet\/blob\/d230d80419f105367dade9337539dd112d574869\/pushbullet\/pushbullet.py#L118-L135"}
7
+ {"nwo":"Azelphur\/pyPushBullet","sha":"d230d80419f105367dade9337539dd112d574869","path":"pushbullet\/pushbullet.py","language":"python","identifier":"PushBullet.pushLink","parameters":"(self, recipient, title, url, recipient_type=\"device_iden\")","argument_list":"","return_statement":"return self._request(\"POST\", HOST + \"\/pushes\", data)","docstring":"Push a link\n https:\/\/docs.pushbullet.com\/v2\/pushes\n\n Arguments:\n recipient -- a recipient\n title -- link title\n url -- link url\n recipient_type -- a type of recipient (device, email, channel or client)","docstring_summary":"Push a link\n https:\/\/docs.pushbullet.com\/v2\/pushes","docstring_tokens":["Push","a","link","https",":","\/\/","docs",".","pushbullet",".","com","\/","v2","\/","pushes"],"function":"def pushLink(self, recipient, title, url, recipient_type=\"device_iden\"):\n \"\"\" Push a link\n https:\/\/docs.pushbullet.com\/v2\/pushes\n\n Arguments:\n recipient -- a recipient\n title -- link title\n url -- link url\n recipient_type -- a type of recipient (device, email, channel or client)\n \"\"\"\n\n data = {\"type\": \"link\",\n \"title\": title,\n \"url\": url}\n\t\t\t\t\n data[recipient_type] = recipient\n\t\t\t\t\n return self._request(\"POST\", HOST + \"\/pushes\", data)","function_tokens":["def","pushLink","(","self",",","recipient",",","title",",","url",",","recipient_type","=","\"device_iden\"",")",":","data","=","{","\"type\"",":","\"link\"",",","\"title\"",":","title",",","\"url\"",":","url","}","data","[","recipient_type","]","=","recipient","return","self",".","_request","(","\"POST\"",",","HOST","+","\"\/pushes\"",",","data",")"],"url":"https:\/\/github.com\/Azelphur\/pyPushBullet\/blob\/d230d80419f105367dade9337539dd112d574869\/pushbullet\/pushbullet.py#L137-L154"}
8
+ {"nwo":"Azelphur\/pyPushBullet","sha":"d230d80419f105367dade9337539dd112d574869","path":"pushbullet\/pushbullet.py","language":"python","identifier":"PushBullet.pushFile","parameters":"(self, recipient, file_name, body, file, file_type=None, recipient_type=\"device_iden\")","argument_list":"","return_statement":"return self._request(\"POST\", HOST + \"\/pushes\", data)","docstring":"Push a file\n https:\/\/docs.pushbullet.com\/v2\/pushes\n https:\/\/docs.pushbullet.com\/v2\/upload-request\n\n Arguments:\n recipient -- a recipient\n file_name -- name of the file\n file -- a file object\n file_type -- file mimetype, if not set, python-magic will be used\n recipient_type -- a type of recipient (device, email, channel or client)","docstring_summary":"Push a file\n https:\/\/docs.pushbullet.com\/v2\/pushes\n https:\/\/docs.pushbullet.com\/v2\/upload-request","docstring_tokens":["Push","a","file","https",":","\/\/","docs",".","pushbullet",".","com","\/","v2","\/","pushes","https",":","\/\/","docs",".","pushbullet",".","com","\/","v2","\/","upload","-","request"],"function":"def pushFile(self, recipient, file_name, body, file, file_type=None, recipient_type=\"device_iden\"):\n \"\"\" Push a file\n https:\/\/docs.pushbullet.com\/v2\/pushes\n https:\/\/docs.pushbullet.com\/v2\/upload-request\n\n Arguments:\n recipient -- a recipient\n file_name -- name of the file\n file -- a file object\n file_type -- file mimetype, if not set, python-magic will be used\n recipient_type -- a type of recipient (device, email, channel or client)\n \"\"\"\n\n if not file_type:\n try:\n import magic\n except ImportError:\n raise Exception(\"No file_type given and python-magic isn't installed\")\n\n # Unfortunately there's two libraries called magic, both of which do\n # the exact same thing but have different conventions for doing so\n if hasattr(magic, \"from_buffer\"):\n file_type = magic.from_buffer(file.read(1024))\n else:\n _magic = magic.open(magic.MIME_TYPE)\n _magic.compile(None)\n\n file_type = _magic.file(file_name)\n\n _magic.close()\n\n file.seek(0)\n\n data = {\"file_name\": file_name,\n \"file_type\": file_type}\n\n upload_request = self._request(\"GET\",\n HOST + \"\/upload-request\",\n None,\n data)\n\n upload = requests.post(upload_request[\"upload_url\"],\n data=upload_request[\"data\"],\n files={\"file\": file},\n headers={\"User-Agent\": \"pyPushBullet\"})\n\n upload.raise_for_status()\n\n data = {\"type\": \"file\",\n \"file_name\": file_name,\n \"file_type\": file_type,\n \"file_url\": upload_request[\"file_url\"],\n \"body\": body}\n\t\t\t\t\n data[recipient_type] = recipient\n\n return self._request(\"POST\", HOST + \"\/pushes\", data)","function_tokens":["def","pushFile","(","self",",","recipient",",","file_name",",","body",",","file",",","file_type","=","None",",","recipient_type","=","\"device_iden\"",")",":","if","not","file_type",":","try",":","import","magic","except","ImportError",":","raise","Exception","(","\"No file_type given and python-magic isn't installed\"",")","# Unfortunately there's two libraries called magic, both of which do","# the exact same thing but have different conventions for doing so","if","hasattr","(","magic",",","\"from_buffer\"",")",":","file_type","=","magic",".","from_buffer","(","file",".","read","(","1024",")",")","else",":","_magic","=","magic",".","open","(","magic",".","MIME_TYPE",")","_magic",".","compile","(","None",")","file_type","=","_magic",".","file","(","file_name",")","_magic",".","close","(",")","file",".","seek","(","0",")","data","=","{","\"file_name\"",":","file_name",",","\"file_type\"",":","file_type","}","upload_request","=","self",".","_request","(","\"GET\"",",","HOST","+","\"\/upload-request\"",",","None",",","data",")","upload","=","requests",".","post","(","upload_request","[","\"upload_url\"","]",",","data","=","upload_request","[","\"data\"","]",",","files","=","{","\"file\"",":","file","}",",","headers","=","{","\"User-Agent\"",":","\"pyPushBullet\"","}",")","upload",".","raise_for_status","(",")","data","=","{","\"type\"",":","\"file\"",",","\"file_name\"",":","file_name",",","\"file_type\"",":","file_type",",","\"file_url\"",":","upload_request","[","\"file_url\"","]",",","\"body\"",":","body","}","data","[","recipient_type","]","=","recipient","return","self",".","_request","(","\"POST\"",",","HOST","+","\"\/pushes\"",",","data",")"],"url":"https:\/\/github.com\/Azelphur\/pyPushBullet\/blob\/d230d80419f105367dade9337539dd112d574869\/pushbullet\/pushbullet.py#L156-L212"}
9
+ {"nwo":"Azelphur\/pyPushBullet","sha":"d230d80419f105367dade9337539dd112d574869","path":"pushbullet\/pushbullet.py","language":"python","identifier":"PushBullet.getPushHistory","parameters":"(self, modified_after=0, cursor=None)","argument_list":"","return_statement":"return self._request(\"GET\", HOST + \"\/pushes\", None, data)[\"pushes\"]","docstring":"Get Push History\n https:\/\/docs.pushbullet.com\/v2\/pushes\n\n Returns a list of pushes\n\n Arguments:\n modified_after -- Request pushes modified after this timestamp\n cursor -- Request another page of pushes (if necessary)","docstring_summary":"Get Push History\n https:\/\/docs.pushbullet.com\/v2\/pushes","docstring_tokens":["Get","Push","History","https",":","\/\/","docs",".","pushbullet",".","com","\/","v2","\/","pushes"],"function":"def getPushHistory(self, modified_after=0, cursor=None):\n \"\"\" Get Push History\n https:\/\/docs.pushbullet.com\/v2\/pushes\n\n Returns a list of pushes\n\n Arguments:\n modified_after -- Request pushes modified after this timestamp\n cursor -- Request another page of pushes (if necessary)\n \"\"\"\n data = {\"modified_after\": modified_after}\n if cursor:\n data[\"cursor\"] = cursor\n return self._request(\"GET\", HOST + \"\/pushes\", None, data)[\"pushes\"]","function_tokens":["def","getPushHistory","(","self",",","modified_after","=","0",",","cursor","=","None",")",":","data","=","{","\"modified_after\"",":","modified_after","}","if","cursor",":","data","[","\"cursor\"","]","=","cursor","return","self",".","_request","(","\"GET\"",",","HOST","+","\"\/pushes\"",",","None",",","data",")","[","\"pushes\"","]"],"url":"https:\/\/github.com\/Azelphur\/pyPushBullet\/blob\/d230d80419f105367dade9337539dd112d574869\/pushbullet\/pushbullet.py#L214-L227"}
10
+ {"nwo":"Azelphur\/pyPushBullet","sha":"d230d80419f105367dade9337539dd112d574869","path":"pushbullet\/pushbullet.py","language":"python","identifier":"PushBullet.deletePush","parameters":"(self, push_iden)","argument_list":"","return_statement":"return self._request(\"DELETE\", HOST + \"\/pushes\/\" + push_iden)","docstring":"Delete push\n https:\/\/docs.pushbullet.com\/v2\/pushes\n\n Arguments:\n push_iden -- the iden of the push to delete","docstring_summary":"Delete push\n https:\/\/docs.pushbullet.com\/v2\/pushes","docstring_tokens":["Delete","push","https",":","\/\/","docs",".","pushbullet",".","com","\/","v2","\/","pushes"],"function":"def deletePush(self, push_iden):\n \"\"\" Delete push\n https:\/\/docs.pushbullet.com\/v2\/pushes\n\n Arguments:\n push_iden -- the iden of the push to delete\n \"\"\"\n return self._request(\"DELETE\", HOST + \"\/pushes\/\" + push_iden)","function_tokens":["def","deletePush","(","self",",","push_iden",")",":","return","self",".","_request","(","\"DELETE\"",",","HOST","+","\"\/pushes\/\"","+","push_iden",")"],"url":"https:\/\/github.com\/Azelphur\/pyPushBullet\/blob\/d230d80419f105367dade9337539dd112d574869\/pushbullet\/pushbullet.py#L229-L236"}
11
+ {"nwo":"Azelphur\/pyPushBullet","sha":"d230d80419f105367dade9337539dd112d574869","path":"pushbullet\/pushbullet.py","language":"python","identifier":"PushBullet.getContacts","parameters":"(self)","argument_list":"","return_statement":"return self._request(\"GET\", HOST + \"\/contacts\")[\"contacts\"]","docstring":"Gets your contacts\n https:\/\/docs.pushbullet.com\/v2\/contacts\n\n returns a list of contacts","docstring_summary":"Gets your contacts\n https:\/\/docs.pushbullet.com\/v2\/contacts","docstring_tokens":["Gets","your","contacts","https",":","\/\/","docs",".","pushbullet",".","com","\/","v2","\/","contacts"],"function":"def getContacts(self):\n \"\"\" Gets your contacts\n https:\/\/docs.pushbullet.com\/v2\/contacts\n\n returns a list of contacts\n \"\"\"\n return self._request(\"GET\", HOST + \"\/contacts\")[\"contacts\"]","function_tokens":["def","getContacts","(","self",")",":","return","self",".","_request","(","\"GET\"",",","HOST","+","\"\/contacts\"",")","[","\"contacts\"","]"],"url":"https:\/\/github.com\/Azelphur\/pyPushBullet\/blob\/d230d80419f105367dade9337539dd112d574869\/pushbullet\/pushbullet.py#L238-L244"}
12
+ {"nwo":"Azelphur\/pyPushBullet","sha":"d230d80419f105367dade9337539dd112d574869","path":"pushbullet\/pushbullet.py","language":"python","identifier":"PushBullet.deleteContact","parameters":"(self, contact_iden)","argument_list":"","return_statement":"return self._request(\"DELETE\", HOST + \"\/contacts\/\" + contact_iden)","docstring":"Delete a contact\n https:\/\/docs.pushbullet.com\/v2\/contacts\n\n Arguments:\n contact_iden -- the iden of the contact to delete","docstring_summary":"Delete a contact\n https:\/\/docs.pushbullet.com\/v2\/contacts","docstring_tokens":["Delete","a","contact","https",":","\/\/","docs",".","pushbullet",".","com","\/","v2","\/","contacts"],"function":"def deleteContact(self, contact_iden):\n \"\"\" Delete a contact\n https:\/\/docs.pushbullet.com\/v2\/contacts\n\n Arguments:\n contact_iden -- the iden of the contact to delete\n \"\"\"\n return self._request(\"DELETE\", HOST + \"\/contacts\/\" + contact_iden)","function_tokens":["def","deleteContact","(","self",",","contact_iden",")",":","return","self",".","_request","(","\"DELETE\"",",","HOST","+","\"\/contacts\/\"","+","contact_iden",")"],"url":"https:\/\/github.com\/Azelphur\/pyPushBullet\/blob\/d230d80419f105367dade9337539dd112d574869\/pushbullet\/pushbullet.py#L246-L253"}
13
+ {"nwo":"Azelphur\/pyPushBullet","sha":"d230d80419f105367dade9337539dd112d574869","path":"pushbullet\/pushbullet.py","language":"python","identifier":"PushBullet.getUser","parameters":"(self)","argument_list":"","return_statement":"return self._request(\"GET\", HOST + \"\/users\/me\")","docstring":"Get this users information\n https:\/\/docs.pushbullet.com\/v2\/users","docstring_summary":"Get this users information\n https:\/\/docs.pushbullet.com\/v2\/users","docstring_tokens":["Get","this","users","information","https",":","\/\/","docs",".","pushbullet",".","com","\/","v2","\/","users"],"function":"def getUser(self):\n \"\"\" Get this users information\n https:\/\/docs.pushbullet.com\/v2\/users\n \"\"\"\n return self._request(\"GET\", HOST + \"\/users\/me\")","function_tokens":["def","getUser","(","self",")",":","return","self",".","_request","(","\"GET\"",",","HOST","+","\"\/users\/me\"",")"],"url":"https:\/\/github.com\/Azelphur\/pyPushBullet\/blob\/d230d80419f105367dade9337539dd112d574869\/pushbullet\/pushbullet.py#L255-L259"}
14
+ {"nwo":"Azelphur\/pyPushBullet","sha":"d230d80419f105367dade9337539dd112d574869","path":"pushbullet\/pushbullet.py","language":"python","identifier":"PushBullet.dismissEphemeral","parameters":"(self, notification_id, notification_tag, package_name, source_user_iden)","argument_list":"","return_statement":"return self._request(\"POST\", HOST + \"\/ephemerals\", data)","docstring":"Marks an ephemeral notification as dismissed\n https:\/\/docs.pushbullet.com\/v2\/pushes\n\n Arguments:\n notification_id -- the id of the notification to dismiss\n notification_tag -- the tag of the notification\n package_name -- the name of the package that made the notification\n source_user_iden -- the identifier for the user that made the notification","docstring_summary":"Marks an ephemeral notification as dismissed\n https:\/\/docs.pushbullet.com\/v2\/pushes","docstring_tokens":["Marks","an","ephemeral","notification","as","dismissed","https",":","\/\/","docs",".","pushbullet",".","com","\/","v2","\/","pushes"],"function":"def dismissEphemeral(self, notification_id, notification_tag, package_name, source_user_iden):\n \"\"\" Marks an ephemeral notification as dismissed\n https:\/\/docs.pushbullet.com\/v2\/pushes\n\n Arguments:\n notification_id -- the id of the notification to dismiss\n notification_tag -- the tag of the notification\n package_name -- the name of the package that made the notification\n source_user_iden -- the identifier for the user that made the notification\n \"\"\"\n data = {\"push\": {\"notification_id\": notification_id,\n \"notification_tag\": notification_tag,\n \"package_name\": package_name,\n \"source_user_iden\": source_user_iden,\n \"type\": \"dismissal\"},\n \"type\": \"push\"}\n\n return self._request(\"POST\", HOST + \"\/ephemerals\", data)","function_tokens":["def","dismissEphemeral","(","self",",","notification_id",",","notification_tag",",","package_name",",","source_user_iden",")",":","data","=","{","\"push\"",":","{","\"notification_id\"",":","notification_id",",","\"notification_tag\"",":","notification_tag",",","\"package_name\"",":","package_name",",","\"source_user_iden\"",":","source_user_iden",",","\"type\"",":","\"dismissal\"","}",",","\"type\"",":","\"push\"","}","return","self",".","_request","(","\"POST\"",",","HOST","+","\"\/ephemerals\"",",","data",")"],"url":"https:\/\/github.com\/Azelphur\/pyPushBullet\/blob\/d230d80419f105367dade9337539dd112d574869\/pushbullet\/pushbullet.py#L261-L278"}
15
+ {"nwo":"Azelphur\/pyPushBullet","sha":"d230d80419f105367dade9337539dd112d574869","path":"pushbullet\/pushbullet.py","language":"python","identifier":"PushBullet.realtime","parameters":"(self, callback)","argument_list":"","return_statement":"","docstring":"Opens a Realtime Event Stream\n https:\/\/docs.pushbullet.com\/stream\n\n callback will be called with one argument, the JSON response\n from the server, nop messages are filtered.\n\n Arguments:\n callback -- The function to call on activity","docstring_summary":"Opens a Realtime Event Stream\n https:\/\/docs.pushbullet.com\/stream","docstring_tokens":["Opens","a","Realtime","Event","Stream","https",":","\/\/","docs",".","pushbullet",".","com","\/","stream"],"function":"def realtime(self, callback):\n \"\"\" Opens a Realtime Event Stream\n https:\/\/docs.pushbullet.com\/stream\n\n callback will be called with one argument, the JSON response\n from the server, nop messages are filtered.\n\n Arguments:\n callback -- The function to call on activity\n \"\"\"\n\n url = \"wss:\/\/stream.pushbullet.com\/websocket\/\" + self.apiKey\n ws = create_connection(url)\n while 1:\n data = ws.recv()\n data = json.loads(data)\n if data[\"type\"] != \"nop\":\n callback(data)","function_tokens":["def","realtime","(","self",",","callback",")",":","url","=","\"wss:\/\/stream.pushbullet.com\/websocket\/\"","+","self",".","apiKey","ws","=","create_connection","(","url",")","while","1",":","data","=","ws",".","recv","(",")","data","=","json",".","loads","(","data",")","if","data","[","\"type\"","]","!=","\"nop\"",":","callback","(","data",")"],"url":"https:\/\/github.com\/Azelphur\/pyPushBullet\/blob\/d230d80419f105367dade9337539dd112d574869\/pushbullet\/pushbullet.py#L280-L297"}
BIGBALLON__CIFAR-ZOO.jsonl ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {"nwo":"BIGBALLON\/CIFAR-ZOO","sha":"94b4c75e02d0c62ec1c7ce862863b0a810d9d0a5","path":"utils.py","language":"python","identifier":"mixup_data","parameters":"(x, y, alpha, device)","argument_list":"","return_statement":"return mixed_x, y_a, y_b, lam","docstring":"Returns mixed inputs, pairs of targets, and lambda","docstring_summary":"Returns mixed inputs, pairs of targets, and lambda","docstring_tokens":["Returns","mixed","inputs","pairs","of","targets","and","lambda"],"function":"def mixup_data(x, y, alpha, device):\n \"\"\"Returns mixed inputs, pairs of targets, and lambda\"\"\"\n if alpha > 0:\n lam = np.random.beta(alpha, alpha)\n else:\n lam = 1\n\n batch_size = x.size()[0]\n index = torch.randperm(batch_size).to(device)\n\n mixed_x = lam * x + (1 - lam) * x[index, :]\n y_a, y_b = y, y[index]\n return mixed_x, y_a, y_b, lam","function_tokens":["def","mixup_data","(","x",",","y",",","alpha",",","device",")",":","if","alpha",">","0",":","lam","=","np",".","random",".","beta","(","alpha",",","alpha",")","else",":","lam","=","1","batch_size","=","x",".","size","(",")","[","0","]","index","=","torch",".","randperm","(","batch_size",")",".","to","(","device",")","mixed_x","=","lam","*","x","+","(","1","-","lam",")","*","x","[","index",",",":","]","y_a",",","y_b","=","y",",","y","[","index","]","return","mixed_x",",","y_a",",","y_b",",","lam"],"url":"https:\/\/github.com\/BIGBALLON\/CIFAR-ZOO\/blob\/94b4c75e02d0c62ec1c7ce862863b0a810d9d0a5\/utils.py#L147-L159"}
2
+ {"nwo":"BIGBALLON\/CIFAR-ZOO","sha":"94b4c75e02d0c62ec1c7ce862863b0a810d9d0a5","path":"models\/sknet.py","language":"python","identifier":"SKConv.__init__","parameters":"(self, features, M, G, r, stride=1, L=32)","argument_list":"","return_statement":"","docstring":"Constructor\n Args:\n features: input channel dimensionality.\n M: the number of branchs.\n G: num of convolution groups.\n r: the radio for compute d, the length of z.\n stride: stride, default 1.\n L: the minimum dim of the vector z in paper, default 32.","docstring_summary":"Constructor\n Args:\n features: input channel dimensionality.\n M: the number of branchs.\n G: num of convolution groups.\n r: the radio for compute d, the length of z.\n stride: stride, default 1.\n L: the minimum dim of the vector z in paper, default 32.","docstring_tokens":["Constructor","Args",":","features",":","input","channel","dimensionality",".","M",":","the","number","of","branchs",".","G",":","num","of","convolution","groups",".","r",":","the","radio","for","compute","d","the","length","of","z",".","stride",":","stride","default","1",".","L",":","the","minimum","dim","of","the","vector","z","in","paper","default","32","."],"function":"def __init__(self, features, M, G, r, stride=1, L=32):\n \"\"\" Constructor\n Args:\n features: input channel dimensionality.\n M: the number of branchs.\n G: num of convolution groups.\n r: the radio for compute d, the length of z.\n stride: stride, default 1.\n L: the minimum dim of the vector z in paper, default 32.\n \"\"\"\n super(SKConv, self).__init__()\n d = max(int(features \/ r), L)\n self.convs = nn.ModuleList([])\n for i in range(M):\n self.convs.append(\n nn.Sequential(\n nn.Conv2d(\n features,\n features,\n kernel_size=1 + i * 2,\n stride=stride,\n padding=i,\n groups=G,\n ),\n nn.BatchNorm2d(features),\n nn.ReLU(inplace=False),\n )\n )\n self.gap = nn.AdaptiveAvgPool2d(1)\n self.fc = nn.Linear(features, d)\n self.fcs = nn.ModuleList([])\n for i in range(M):\n self.fcs.append(nn.Linear(d, features))\n self.softmax = nn.Softmax(dim=1)","function_tokens":["def","__init__","(","self",",","features",",","M",",","G",",","r",",","stride","=","1",",","L","=","32",")",":","super","(","SKConv",",","self",")",".","__init__","(",")","d","=","max","(","int","(","features","\/","r",")",",","L",")","self",".","convs","=","nn",".","ModuleList","(","[","]",")","for","i","in","range","(","M",")",":","self",".","convs",".","append","(","nn",".","Sequential","(","nn",".","Conv2d","(","features",",","features",",","kernel_size","=","1","+","i","*","2",",","stride","=","stride",",","padding","=","i",",","groups","=","G",",",")",",","nn",".","BatchNorm2d","(","features",")",",","nn",".","ReLU","(","inplace","=","False",")",",",")",")","self",".","gap","=","nn",".","AdaptiveAvgPool2d","(","1",")","self",".","fc","=","nn",".","Linear","(","features",",","d",")","self",".","fcs","=","nn",".","ModuleList","(","[","]",")","for","i","in","range","(","M",")",":","self",".","fcs",".","append","(","nn",".","Linear","(","d",",","features",")",")","self",".","softmax","=","nn",".","Softmax","(","dim","=","1",")"],"url":"https:\/\/github.com\/BIGBALLON\/CIFAR-ZOO\/blob\/94b4c75e02d0c62ec1c7ce862863b0a810d9d0a5\/models\/sknet.py#L10-L43"}
3
+ {"nwo":"BIGBALLON\/CIFAR-ZOO","sha":"94b4c75e02d0c62ec1c7ce862863b0a810d9d0a5","path":"models\/resnext.py","language":"python","identifier":"ResNeXt.__init__","parameters":"(self, cardinality, depth, num_classes, base_width, expansion=4)","argument_list":"","return_statement":"","docstring":"Constructor\n Args:\n cardinality: number of convolution groups.\n depth: number of layers.\n num_classes: number of classes\n base_width: base number of channels in each group.\n expansion: factor to adjust the channel dimensionality","docstring_summary":"Constructor\n Args:\n cardinality: number of convolution groups.\n depth: number of layers.\n num_classes: number of classes\n base_width: base number of channels in each group.\n expansion: factor to adjust the channel dimensionality","docstring_tokens":["Constructor","Args",":","cardinality",":","number","of","convolution","groups",".","depth",":","number","of","layers",".","num_classes",":","number","of","classes","base_width",":","base","number","of","channels","in","each","group",".","expansion",":","factor","to","adjust","the","channel","dimensionality"],"function":"def __init__(self, cardinality, depth, num_classes, base_width, expansion=4):\n \"\"\" Constructor\n Args:\n cardinality: number of convolution groups.\n depth: number of layers.\n num_classes: number of classes\n base_width: base number of channels in each group.\n expansion: factor to adjust the channel dimensionality\n \"\"\"\n super(ResNeXt, self).__init__()\n self.cardinality = cardinality\n self.depth = depth\n self.block_depth = (self.depth - 2) \/\/ 9\n self.base_width = base_width\n self.expansion = expansion\n self.num_classes = num_classes\n self.output_size = 64\n self.stages = [\n 64,\n 64 * self.expansion,\n 128 * self.expansion,\n 256 * self.expansion,\n ]\n\n self.conv_1_3x3 = nn.Conv2d(3, 64, 3, 1, 1, bias=False)\n self.bn_1 = nn.BatchNorm2d(64)\n self.stage_1 = self.block(\"stage_1\", self.stages[0], self.stages[1], 1)\n self.stage_2 = self.block(\"stage_2\", self.stages[1], self.stages[2], 2)\n self.stage_3 = self.block(\"stage_3\", self.stages[2], self.stages[3], 2)\n self.fc = nn.Linear(self.stages[3], num_classes)\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n nn.init.kaiming_normal_(m.weight.data)\n elif isinstance(m, nn.BatchNorm2d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()","function_tokens":["def","__init__","(","self",",","cardinality",",","depth",",","num_classes",",","base_width",",","expansion","=","4",")",":","super","(","ResNeXt",",","self",")",".","__init__","(",")","self",".","cardinality","=","cardinality","self",".","depth","=","depth","self",".","block_depth","=","(","self",".","depth","-","2",")","\/\/","9","self",".","base_width","=","base_width","self",".","expansion","=","expansion","self",".","num_classes","=","num_classes","self",".","output_size","=","64","self",".","stages","=","[","64",",","64","*","self",".","expansion",",","128","*","self",".","expansion",",","256","*","self",".","expansion",",","]","self",".","conv_1_3x3","=","nn",".","Conv2d","(","3",",","64",",","3",",","1",",","1",",","bias","=","False",")","self",".","bn_1","=","nn",".","BatchNorm2d","(","64",")","self",".","stage_1","=","self",".","block","(","\"stage_1\"",",","self",".","stages","[","0","]",",","self",".","stages","[","1","]",",","1",")","self",".","stage_2","=","self",".","block","(","\"stage_2\"",",","self",".","stages","[","1","]",",","self",".","stages","[","2","]",",","2",")","self",".","stage_3","=","self",".","block","(","\"stage_3\"",",","self",".","stages","[","2","]",",","self",".","stages","[","3","]",",","2",")","self",".","fc","=","nn",".","Linear","(","self",".","stages","[","3","]",",","num_classes",")","for","m","in","self",".","modules","(",")",":","if","isinstance","(","m",",","nn",".","Conv2d",")",":","nn",".","init",".","kaiming_normal_","(","m",".","weight",".","data",")","elif","isinstance","(","m",",","nn",".","BatchNorm2d",")",":","m",".","weight",".","data",".","fill_","(","1",")","m",".","bias",".","data",".","zero_","(",")"],"url":"https:\/\/github.com\/BIGBALLON\/CIFAR-ZOO\/blob\/94b4c75e02d0c62ec1c7ce862863b0a810d9d0a5\/models\/resnext.py#L70-L105"}
4
+ {"nwo":"BIGBALLON\/CIFAR-ZOO","sha":"94b4c75e02d0c62ec1c7ce862863b0a810d9d0a5","path":"models\/preresnet.py","language":"python","identifier":"conv3x3","parameters":"(in_planes, out_planes, stride=1)","argument_list":"","return_statement":"return nn.Conv2d(\n in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False\n )","docstring":"3x3 convolution with padding","docstring_summary":"3x3 convolution with padding","docstring_tokens":["3x3","convolution","with","padding"],"function":"def conv3x3(in_planes, out_planes, stride=1):\n \"3x3 convolution with padding\"\n return nn.Conv2d(\n in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False\n )","function_tokens":["def","conv3x3","(","in_planes",",","out_planes",",","stride","=","1",")",":","return","nn",".","Conv2d","(","in_planes",",","out_planes",",","kernel_size","=","3",",","stride","=","stride",",","padding","=","1",",","bias","=","False",")"],"url":"https:\/\/github.com\/BIGBALLON\/CIFAR-ZOO\/blob\/94b4c75e02d0c62ec1c7ce862863b0a810d9d0a5\/models\/preresnet.py#L15-L19"}
5
+ {"nwo":"BIGBALLON\/CIFAR-ZOO","sha":"94b4c75e02d0c62ec1c7ce862863b0a810d9d0a5","path":"models\/resnet.py","language":"python","identifier":"conv3x3","parameters":"(in_planes, out_planes, stride=1)","argument_list":"","return_statement":"return nn.Conv2d(\n in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False\n )","docstring":"3x3 convolution with padding","docstring_summary":"3x3 convolution with padding","docstring_tokens":["3x3","convolution","with","padding"],"function":"def conv3x3(in_planes, out_planes, stride=1):\n \"3x3 convolution with padding\"\n return nn.Conv2d(\n in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False\n )","function_tokens":["def","conv3x3","(","in_planes",",","out_planes",",","stride","=","1",")",":","return","nn",".","Conv2d","(","in_planes",",","out_planes",",","kernel_size","=","3",",","stride","=","stride",",","padding","=","1",",","bias","=","False",")"],"url":"https:\/\/github.com\/BIGBALLON\/CIFAR-ZOO\/blob\/94b4c75e02d0c62ec1c7ce862863b0a810d9d0a5\/models\/resnet.py#L8-L12"}
Befzz__blender3d_import_psk_psa.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
Behappy123__market-maker.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
Billwilliams1952__PiCameraApp.jsonl ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {"nwo":"Billwilliams1952\/PiCameraApp","sha":"61802b367d620aafb6b4e0bb84ea1ebd0dbd42c0","path":"Source\/BasicControls.py","language":"python","identifier":"BasicControls.BuildPage","parameters":"( self )","argument_list":"","return_statement":"","docstring":"Add additional controls if JPG is selected\n\t\t\t\tCertain file formats accept additional options which can be specified as keyword\n\t\t\t\targuments. Currently, only the 'jpeg' encoder accepts additional options, which are:\n\n\t\t\t\tquality - Defines the quality of the JPEG encoder as an integer ranging from 1 to 100.\n\t\t\t\t\t\t\t Defaults to 85. Please note that JPEG quality is not a percentage and\n\t\t\t\t\t\t\t definitions of quality vary widely.\n\t\t\t\trestart - Defines the restart interval for the JPEG encoder as a number of JPEG MCUs.\n\t\t\t\t\t\t\t The actual restart interval used will be a multiple of the number of MCUs per row in the resulting image.\n\t\t\t\tthumbnail - Defines the size and quality of the thumbnail to embed in the Exif\n\t\t\t\t\t\t\t\tmetadata. Specifying None disables thumbnail generation. Otherwise,\n\t\t\t\t\t\t\t\tspecify a tuple of (width, height, quality). Defaults to (64, 48, 35).\n\t\t\t\tbayer - If True, the raw bayer data from the camera\u2019s sensor is included in the\n\t\t\t\t\t\t\tExif metadata.","docstring_summary":"Add additional controls if JPG is selected\n\t\t\t\tCertain file formats accept additional options which can be specified as keyword\n\t\t\t\targuments. Currently, only the 'jpeg' encoder accepts additional options, which are:","docstring_tokens":["Add","additional","controls","if","JPG","is","selected","Certain","file","formats","accept","additional","options","which","can","be","specified","as","keyword","arguments",".","Currently","only","the","jpeg","encoder","accepts","additional","options","which","are",":"],"function":"def BuildPage ( self ):\n\t\t#### TODO: \tAdd Rotation. Cleanup and organize controls\n\t\t#\t\t\tAdd handling of Image Effect Params\n\n\t\t#----------- Select port for image captures ------------\n\t\tf1 = MyLabelFrame(self,'Select port for image captures',0,0,span=2)\n\t\tself.UseVidPort = MyBooleanVar(False)\n\t\tself.UseRadio = MyRadio(f1,'Use Still Port',False,self.UseVidPort,\n\t\t\t\t\tself.UseVideoPort,0,0,'W',tip=100)\n\t\tMyRadio(f1,'Use Video Port',True,self.UseVidPort,\n\t\t\t\t\tself.UseVideoPort,0,1,'W',tip=101)\n\t\tf2 = ttk.Frame(f1)\t\t\t# Sub frame\n\t\tf2.grid(row=1,column=0,columnspan=4,sticky='NSEW')\n\t\tself.VideoDenoise = MyBooleanVar(True)\n\t\tb = ttk.Checkbutton(f2,text='Video denoise',variable=self.VideoDenoise,\n\t\t\tcommand=self.VideoDenoiseChecked)\n\t\tb.grid(row=1,column=0,sticky='NW',padx=5)\n\t\tToolTip(b,msg=103)\n\t\tself.VideoStab = MyBooleanVar(False)\n\t\tb = ttk.Checkbutton(f2,text='Video stabilization',variable=self.VideoStab,\n\t\t\tcommand=self.VideoStabChecked)\n\t\tb.grid(row=1,column=1,sticky='NW')\n\t\tToolTip(b, msg=105)\n\t\tself.ImageDenoise = MyBooleanVar(True)\n\t\tb = ttk.Checkbutton(f2,text='Image denoise',variable=self.ImageDenoise,\n\t\t\tcommand=self.ImageDenoiseChecked)\n\t\tb.grid(row=1,column=2,sticky='NW',padx=10)\n\t\tToolTip(b, msg=104)\n\n\t\t#--------------- Picture\/Video Capture Size ---------------\n\t\tf = MyLabelFrame(self,'Picture\/Video capture size in pixels',1,0)\n\t\t#f.columnconfigure(0,weight=1)\n\t\tf1 = ttk.Frame(f)\t\t\t# Sub frames to frame f\n\t\tf1.grid(row=1,column=0,sticky='NSEW')\n\t\tf1.columnconfigure(1,weight=1)\n\t\tself.UseFixedResolutions = BooleanVar()\n\t\tself.UseFixedResolutions.set(True)\n\t\tself.UseFixedResRadio = ttk.Radiobutton(f1,text='Use fixed:',\n\t\t\tvariable=self.UseFixedResolutions,\n\t\t\tvalue=True,command=self.UseFixedResRadios,padding=(5,5,5,5))\n\t\tToolTip(self.UseFixedResRadio,120)\n\t\tself.UseFixedResRadio.grid(row=0,column=0,sticky='NW')\n\t\tself.FixedResolutionsCombo = Combobox(f1,state='readonly',width=25)\n\t\tself.FixedResolutionsCombo.bind('<<ComboboxSelected>>',\n\t\t\tself.FixedResolutionChanged)\n\t\tself.FixedResolutionsCombo.grid(row=0,column=1,columnspan=3,sticky='W')\n\t\tToolTip(self.FixedResolutionsCombo,121)\n\t\t#------------ Capture Width and Height ----------------\n\t\t# OrderedDict is used to ensure the keys stay in the same order as\n\t\t# entered. I want the combobox to display in this order\n\t\t#### TODO: \tMust check resolution and framerate and disable the Video\n\t\t# \t\t\tbutton if we exceed limits of the modes\n\t\t# Framerate 1-30 fps up to 1920x1080\t\t16:9 aspect ratio\n\t\t# Framerate 1-15 fps up to 2592 x 1944\t\t 4:3 aspect ratio\n\t\t# Framerate 0.1666 to 1 fps up to 2592 x 1944 4:3 aspect ratio\n\t\t# Framerate 1-42 fps up t0 1296 x 972 \t\t 4:3 aspect ratio\n\t\t# Framerate 1-49 fps up to 1296 x 730\t\t16:9 aspect ratio\n\t\t# Framerate 42.1 - 60 fps to 640 x 480\t\t 4:3 aspect ratio\n\t\t# Framerate 60.1 - 90 fps to 640 x 480\t\t 4:3 aspect ratio\n\t\tself.StandardResolutions = OrderedDict([ \\\n\t\t\t('CGA', (320,200)),\t\t\t('QVGA', (320,240)),\n\t\t\t('VGA', (640,480)),\t\t\t('PAL', (768,576)),\n\t\t\t('480p', (720,480)),\t\t('576p', (720,576)),\n\t\t\t('WVGA', (800,480)),\t\t('SVGA', (800,600)),\n\t\t\t('FWVGA', (854,480)),\t\t('WSVGA', (1024,600)),\n\t\t\t('XGA', (1024,768)),\t\t('HD 720', (1280,720)),\n\t\t\t('WXGA_1', (1280,768)),\t\t('WXGA_2', (1280,800)),\n\t\t\t('SXGA', (1280,1024)),\t\t('SXGA+', (1400,1050)),\n\t\t\t('UXGA', (1600,1200)),\t\t('WSXGA+', (1680,1050)),\n\t\t\t('HD 1080', (1920,1080)), \t('WUXGA', (1920,1200)),\n\t\t\t('2K', (2048,1080)),\t\t('QXGA', (2048, 1536)),\n\t\t\t('WQXGA', (2560,1600)),\t\t('MAX Resolution', (2592,1944)),\n\t\t ])\n\t\tvals = []\n\t\tfor key in self.StandardResolutions.keys():\n\t\t\tvals.append('%s: (%dx%d)' % (key, # Tabs not working?!!\n\t\t\t\t\t\t\tself.StandardResolutions[key][0],\n\t\t\t\t\t\t\tself.StandardResolutions[key][1]))\n\t\tself.FixedResolutionsCombo['values'] = vals\n\t\tself.FixedResolutionsCombo.current(10)\n\n\t\tf2 = ttk.Frame(f)\t\t# subframe to frame f\n\t\tf2.grid(row=2,column=0,sticky='NSEW')\n\t\tf2.columnconfigure(2,weight=1)\n\t\tf2.columnconfigure(4,weight=1)\n\t\tb2 = ttk.Radiobutton(f2,text='Roll your own:',\n\t\t\tvariable=self.UseFixedResolutions,\n\t\t\tvalue=False,command=self.UseFixedResRadios,padding=(5,5,5,5))\n\t\tb2.grid(row=1,column=0,sticky='NW')\n\t\tToolTip(b2,122)\n\n\t\tLabel(f2,text=\"Width:\",anchor=E).grid(column=1,row=1,sticky='E',ipadx=3,ipady=3)\n\t\tWidths = []\n\t\tfor i in range(1,82):\n\t\t\tWidths.append(32 * i) # Widths can be in 32 byte increments\n\t\tself.cb = MyComboBox ( f2, Widths, current=10,\n\t\t\tcallback=self.ResolutionChanged, width=5, row=1, col=2,\n\t\t\tsticky='W', state='disabled', tip=123)\n\n\t\tLabel(f2,text=\"Height:\",anchor=E).grid(column=3,row=1,sticky='W',ipadx=5,ipady=3)\n\t\tHeights = []\n\t\tfor i in range(1,123):\n\t\t\tHeights.append(16 * i)\t# heights in 16 byte increments\n\t\tself.cb1 = MyComboBox ( f2, Heights, current=10,\n\t\t\tcallback=self.ResolutionChanged, width=5, row=1, col=4,\n\t\t\tsticky='W', state='disabled', tip=124)\n\n\t\tttk.Label(f2,text='Actual:').grid(row=2,column=1,sticky='E')\n\t\tself.WidthLabel = ttk.Label(f2,style='DataLabel.TLabel')\n\t\tself.WidthLabel.grid(row=2,column=2,sticky='W')\n\t\tToolTip(self.WidthLabel,125)\n\t\tttk.Label(f2,text='Actual:').grid(row=2,column=3,sticky='E')\n\t\tself.HeightLabel = ttk.Label(f2,style='DataLabel.TLabel')\n\t\tself.HeightLabel.grid(row=2,column=4,sticky='W')\n\t\tToolTip(self.HeightLabel,126)\n\n\t\tSeparator(f,orient=HORIZONTAL).grid(pady=5,row=3,column=0,\n\t\t\tcolumnspan=4,sticky='EW')\n\n\t\t#--------------- Zoom Region Before ----------------\n\t\tf4 = MyLabelFrame(f,'Zoom region of interest before taking '+\n\t\t\t'picture\/video',4,0)\n\t\t#f4.columnconfigure(1,weight=1)\n\t\t#f4.columnconfigure(3,weight=1)\n\t\tLabel(f4,text='X:').grid(row=0,column=0,sticky='E')\n\t\tself.Xzoom = ttk.Scale(f4,from_=0.0,to=0.94,orient='horizontal')\n\t\tself.Xzoom.grid(row=0,column=1,sticky='W',padx=5,pady=3)\n\t\tself.Xzoom.set(0.0)\n\t\tToolTip(self.Xzoom,130)\n\t\tLabel(f4,text='Y:').grid(row=0,column=2,sticky='E')\n\t\tself.Yzoom = ttk.Scale(f4,from_=0.0,to=0.94,orient='horizontal')\n\t\tself.Yzoom.grid(row=0,column=3,sticky='W',padx=5,pady=3)\n\t\tself.Yzoom.set(0.0)\n\t\tToolTip(self.Yzoom,131)\n\t\tLabel(f4,text='Width:').grid(row=1,column=0,sticky='E')\n\t\tself.Widthzoom = ttk.Scale(f4,from_=0.05,to=1.0,orient='horizontal')\n\t\tself.Widthzoom.grid(row=1,column=1,sticky='W',padx=5,pady=3)\n\t\tself.Widthzoom.set(1.0)\n\t\tToolTip(self.Widthzoom,132)\n\t\tLabel(f4,text='Height:').grid(row=1,column=2,sticky='E')\n\t\tself.Heightzoom = ttk.Scale(f4,from_=0.05,to=1.0,orient='horizontal')\n\t\tself.Heightzoom.grid(row=1,column=3,sticky='W',padx=5,pady=3)\n\t\tself.Heightzoom.set(1.0)\n\t\tToolTip(self.Heightzoom,133)\n\t\t# WLW THIS IS A PROBLEM\n\t\timage = PIL.Image.open('Assets\/reset.png') #.resize((16,16))\n\t\tself.resetImage = GetPhotoImage(image.resize((16,16)))\n\t\tself.ResetZoomButton = ttk.Button(f4,image=self.resetImage,\n\t\t\tcommand=self.ZoomReset)\n\t\tself.ResetZoomButton.grid(row=0,column=4,rowspan=2,sticky='W')\n\t\tToolTip(self.ResetZoomButton,134)\n\n\t\tself.Xzoom.config(command=lambda newval,\n\t\t\twidget=self.Xzoom:self.Zoom(newval,widget))\n\t\tself.Yzoom.config(command=lambda newval,\n\t\t\twidget=self.Yzoom:self.Zoom(newval,widget))\n\t\tself.Widthzoom.config(command=lambda newval,\n\t\t\twidget=self.Widthzoom:self.Zoom(newval,widget))\n\t\tself.Heightzoom.config(command=lambda newval,\n\t\t\twidget=self.Heightzoom:self.Zoom(newval,widget))\n\n\t\tSeparator(f,orient=HORIZONTAL).grid(pady=5,row=5,column=0,\n\t\t\tcolumnspan=3,sticky='EW')\n\n\t\t#--------------- Resize Image After ----------------\n\t\tf4 = MyLabelFrame(f,'Resize image after taking picture\/video',6,0)\n\t\t#f4.columnconfigure(3,weight=1)\n\t\t#f4.columnconfigure(5,weight=1)\n\n\t\tb = MyBooleanVar(False)\n\t\tself.ResizeAfterNone = MyRadio(f4,'None (Default)',False,b,\n\t\t\tself.AllowImageResizeAfter,0,0,'W',pad=(0,5,0,5), tip=140)\n\t\tMyRadio(f4,'Resize',True,b,self.AllowImageResizeAfter,\n\t\t\t\t\t0,1,'W',pad=(5,5,0,5),tip=141)\n\n\t\tLabel(f4,text=\"Width:\",anchor=E).grid(column=2,row=0,sticky='E',ipadx=3,ipady=3)\n\t\tself.resizeWidthAfterCombo = MyComboBox ( f4, Widths, current=10,\n\t\t\tcallback=self.ResizeAfterChanged, width=5, row=0, col=3,\n\t\t\tsticky='W', state='disabled', tip=142)\n\n\t\tLabel(f4,text=\"Height:\",anchor=E).grid(column=4,row=0,sticky='W',ipadx=5,ipady=3)\n\t\tself.resizeHeightAfterCombo = MyComboBox ( f4, Heights, current=10,\n\t\t\tcallback=self.ResizeAfterChanged, width=5, row=0, col=5,\n\t\t\tsticky='W', state='disabled', tip=143)\n\n\t\tself.resizeAfter = None\n\n\t\t#--------------- Quick Adjustments ----------------\n\t\tf = MyLabelFrame(self,'Quick adjustments',2,0)\n\t\t#f.columnconfigure(2,weight=1)\n\t\t#-Brightness\n\t\tself.brightLabel, self.brightness, val = \\\n\t\t\tself.SetupLabelCombo(f,'Brightness:',0,0,0, 100,\n\t\t\t\tself.CameraBrightnessChanged, self.camera.brightness )\n\t\tself.CameraBrightnessChanged(val)\n\t\tToolTip(self.brightness,msg=150)\n\t\t#-Contrast\n\t\tself.contrastLabel, self.contrast, val = \\\n\t\t\tself.SetupLabelCombo(f,'Contrast:',0,3,-100, 100,\n\t\t\t\tself.ContrastChanged, self.camera.contrast )\n\t\tself.ContrastChanged(val)\n\t\tToolTip(self.contrast,msg=151)\n\t\t#-Saturation\n\t\tself.saturationLabel, self.saturation, val = \\\n\t\t\tself.SetupLabelCombo(f,'Saturation:',1,0,-100, 100,\n\t\t\t\tself.SaturationChanged, self.camera.saturation, label='Sat' )\n\t\tself.SaturationChanged(val)\n\t\tToolTip(self.saturation,msg=152)\n\t\t#-Sharpness\n\t\tself.sharpnessLabel, self.sharpness, val = \\\n\t\t\tself.SetupLabelCombo(f,'Sharpness:',1,3,-100, 100,\n\t\t\t\tself.SharpnessChanged, self.camera.sharpness )\n\t\tself.SharpnessChanged(val)\n\t\tToolTip(self.sharpness,msg=153)\n\t\t#-Reset\n\t\t#self.ResetGeneralButton = Button(f,image=self.resetImage,width=5,\n\t\t\t#command=self.ResetGeneralSliders)\n\t\t#self.ResetGeneralButton.grid(row=4,column=2,sticky='W',padx=5)\n\t\t#ToolTip(self.ResetGeneralButton,msg=154)\n\n\t\t#--------------- Image Effects ----------------\n\t\tf = MyLabelFrame(self,'Preprogrammed image effects',3,0)\n\t\t#f.columnconfigure(2,weight=1)\n\n\t\tv = MyBooleanVar(False)\n\t\tself.NoEffectsRadio = MyRadio(f,'None (Default)',False,v,\n\t\t\tself.EffectsChecked,0,0,'W',tip=160)\n\t\tMyRadio(f,'Select effect:',True,v,self.EffectsChecked,0,1,'W',\n\t\t\ttip=161)\n\n\t\tself.effects = Combobox(f,height=15,width=10,state='readonly')#,width=15)\n\t\tself.effects.grid(row=0,column=2,sticky='W')\n\t\teffects = list(self.camera.IMAGE_EFFECTS.keys())\t# python 3 workaround\n\t\teffects.remove('none')\n\t\teffects.sort() #cmp=lambda x,y: cmp(x.lower(),y.lower())) # not python 3\n\t\tself.effects['values'] = effects\n\t\tself.effects.current(0)\n\t\tself.effects.bind('<<ComboboxSelected>>',self.EffectsChanged)\n\t\tToolTip(self.effects, msg=162)\n\n\t\tself.ModParams = ttk.Button(f,text='Params...',\n\t\t\tcommand=self.ModifyEffectsParamsPressed,underline=0,padding=(5,3,5,3),width=8)\n\t\tself.ModParams.grid(row=0,column=3,sticky=EW,padx=5)\n\t\tToolTip(self.ModParams, msg=163)\n\t\tself.EffectsChecked(False)\n\t\t'''\n\t\t\t\tAdd additional controls if JPG is selected\n\t\t\t\tCertain file formats accept additional options which can be specified as keyword\n\t\t\t\targuments. Currently, only the 'jpeg' encoder accepts additional options, which are:\n\n\t\t\t\tquality - Defines the quality of the JPEG encoder as an integer ranging from 1 to 100.\n\t\t\t\t\t\t\t Defaults to 85. Please note that JPEG quality is not a percentage and\n\t\t\t\t\t\t\t definitions of quality vary widely.\n\t\t\t\trestart - Defines the restart interval for the JPEG encoder as a number of JPEG MCUs.\n\t\t\t\t\t\t\t The actual restart interval used will be a multiple of the number of MCUs per row in the resulting image.\n\t\t\t\tthumbnail - Defines the size and quality of the thumbnail to embed in the Exif\n\t\t\t\t\t\t\t\tmetadata. Specifying None disables thumbnail generation. Otherwise,\n\t\t\t\t\t\t\t\tspecify a tuple of (width, height, quality). Defaults to (64, 48, 35).\n\t\t\t\tbayer - If True, the raw bayer data from the camera\u2019s sensor is included in the\n\t\t\t\t\t\t\tExif metadata.\n\t\t'''\n\t\t#--------------- Flash Mode ---------------\n\t\tf = MyLabelFrame(self,'LED and Flash mode',4,0,span=4)\n\t\t#f.columnconfigure(3,weight=1)\n\t\tself.LedOn = MyBooleanVar(True)\n\t\tself.LedButton = ttk.Checkbutton(f,text='Led On (via GPIO pins)',\n\t\t\tvariable=self.LedOn, command=self.LedOnChecked)\n\t\tself.LedButton.grid(row=0,column=0,sticky='NW',pady=5, columnspan=2)\n\t\tToolTip(self.LedButton,msg=102)\n\t\tLabel(f,text='Flash Mode:').grid(row=1,column=0,sticky='W')\n\t\tb = MyStringVar('off')\n\t\tself.FlashModeOffRadio = MyRadio(f,'Off (Default)','off',b,\n\t\t\tself.FlashModeButton,1,1,'W',tip=180)\n\t\tMyRadio(f,'Auto','auto',b,self.FlashModeButton,1,2,'W',tip=181)\n\t\tMyRadio(f,'Select:','set',b,self.FlashModeButton,1,3,'W',tip=182)\n\t\t# Use invoke() on radio button to force a command\n\t\tself.FlashModeCombo = Combobox(f,state='readonly',width=10)\n\t\tself.FlashModeCombo.grid(row=1,column=4,sticky='W')\n\t\tself.FlashModeCombo.bind('<<ComboboxSelected>>',self.FlashModeChanged)\n\t\tmodes = list(self.camera.FLASH_MODES.keys())\n\t\tmodes.remove('off')\t\t# these two are handled by radio buttons\n\t\tmodes.remove('auto')\n\t\tmodes.sort() #cmp=lambda x,y: cmp(x.lower(),y.lower()))\n\t\tself.FlashModeCombo['values'] = modes\n\t\tself.FlashModeCombo.current(0)\n\t\tself.FlashModeCombo.config(state='disabled')\n\t\tToolTip(self.FlashModeCombo,183)\n\n\t\tself.FixedResolutionChanged(None)","function_tokens":["def","BuildPage","(","self",")",":","#### TODO: \tAdd Rotation. Cleanup and organize controls","#\t\t\tAdd handling of Image Effect Params","#----------- Select port for image captures ------------","f1","=","MyLabelFrame","(","self",",","'Select port for image captures'",",","0",",","0",",","span","=","2",")","self",".","UseVidPort","=","MyBooleanVar","(","False",")","self",".","UseRadio","=","MyRadio","(","f1",",","'Use Still Port'",",","False",",","self",".","UseVidPort",",","self",".","UseVideoPort",",","0",",","0",",","'W'",",","tip","=","100",")","MyRadio","(","f1",",","'Use Video Port'",",","True",",","self",".","UseVidPort",",","self",".","UseVideoPort",",","0",",","1",",","'W'",",","tip","=","101",")","f2","=","ttk",".","Frame","(","f1",")","# Sub frame","f2",".","grid","(","row","=","1",",","column","=","0",",","columnspan","=","4",",","sticky","=","'NSEW'",")","self",".","VideoDenoise","=","MyBooleanVar","(","True",")","b","=","ttk",".","Checkbutton","(","f2",",","text","=","'Video denoise'",",","variable","=","self",".","VideoDenoise",",","command","=","self",".","VideoDenoiseChecked",")","b",".","grid","(","row","=","1",",","column","=","0",",","sticky","=","'NW'",",","padx","=","5",")","ToolTip","(","b",",","msg","=","103",")","self",".","VideoStab","=","MyBooleanVar","(","False",")","b","=","ttk",".","Checkbutton","(","f2",",","text","=","'Video stabilization'",",","variable","=","self",".","VideoStab",",","command","=","self",".","VideoStabChecked",")","b",".","grid","(","row","=","1",",","column","=","1",",","sticky","=","'NW'",")","ToolTip","(","b",",","msg","=","105",")","self",".","ImageDenoise","=","MyBooleanVar","(","True",")","b","=","ttk",".","Checkbutton","(","f2",",","text","=","'Image denoise'",",","variable","=","self",".","ImageDenoise",",","command","=","self",".","ImageDenoiseChecked",")","b",".","grid","(","row","=","1",",","column","=","2",",","sticky","=","'NW'",",","padx","=","10",")","ToolTip","(","b",",","msg","=","104",")","#--------------- Picture\/Video Capture Size ---------------","f","=","MyLabelFrame","(","self",",","'Picture\/Video capture size in pixels'",",","1",",","0",")","#f.columnconfigure(0,weight=1)","f1","=","ttk",".","Frame","(","f",")","# Sub frames to frame f","f1",".","grid","(","row","=","1",",","column","=","0",",","sticky","=","'NSEW'",")","f1",".","columnconfigure","(","1",",","weight","=","1",")","self",".","UseFixedResolutions","=","BooleanVar","(",")","self",".","UseFixedResolutions",".","set","(","True",")","self",".","UseFixedResRadio","=","ttk",".","Radiobutton","(","f1",",","text","=","'Use fixed:'",",","variable","=","self",".","UseFixedResolutions",",","value","=","True",",","command","=","self",".","UseFixedResRadios",",","padding","=","(","5",",","5",",","5",",","5",")",")","ToolTip","(","self",".","UseFixedResRadio",",","120",")","self",".","UseFixedResRadio",".","grid","(","row","=","0",",","column","=","0",",","sticky","=","'NW'",")","self",".","FixedResolutionsCombo","=","Combobox","(","f1",",","state","=","'readonly'",",","width","=","25",")","self",".","FixedResolutionsCombo",".","bind","(","'<<ComboboxSelected>>'",",","self",".","FixedResolutionChanged",")","self",".","FixedResolutionsCombo",".","grid","(","row","=","0",",","column","=","1",",","columnspan","=","3",",","sticky","=","'W'",")","ToolTip","(","self",".","FixedResolutionsCombo",",","121",")","#------------ Capture Width and Height ----------------","# OrderedDict is used to ensure the keys stay in the same order as","# entered. I want the combobox to display in this order","#### TODO: \tMust check resolution and framerate and disable the Video","# \t\t\tbutton if we exceed limits of the modes","# Framerate 1-30 fps up to 1920x1080\t\t16:9 aspect ratio","# Framerate 1-15 fps up to 2592 x 1944\t\t 4:3 aspect ratio","# Framerate 0.1666 to 1 fps up to 2592 x 1944 4:3 aspect ratio","# Framerate 1-42 fps up t0 1296 x 972 \t\t 4:3 aspect ratio","# Framerate 1-49 fps up to 1296 x 730\t\t16:9 aspect ratio","# Framerate 42.1 - 60 fps to 640 x 480\t\t 4:3 aspect ratio","# Framerate 60.1 - 90 fps to 640 x 480\t\t 4:3 aspect ratio","self",".","StandardResolutions","=","OrderedDict","(","[","(","'CGA'",",","(","320",",","200",")",")",",","(","'QVGA'",",","(","320",",","240",")",")",",","(","'VGA'",",","(","640",",","480",")",")",",","(","'PAL'",",","(","768",",","576",")",")",",","(","'480p'",",","(","720",",","480",")",")",",","(","'576p'",",","(","720",",","576",")",")",",","(","'WVGA'",",","(","800",",","480",")",")",",","(","'SVGA'",",","(","800",",","600",")",")",",","(","'FWVGA'",",","(","854",",","480",")",")",",","(","'WSVGA'",",","(","1024",",","600",")",")",",","(","'XGA'",",","(","1024",",","768",")",")",",","(","'HD 720'",",","(","1280",",","720",")",")",",","(","'WXGA_1'",",","(","1280",",","768",")",")",",","(","'WXGA_2'",",","(","1280",",","800",")",")",",","(","'SXGA'",",","(","1280",",","1024",")",")",",","(","'SXGA+'",",","(","1400",",","1050",")",")",",","(","'UXGA'",",","(","1600",",","1200",")",")",",","(","'WSXGA+'",",","(","1680",",","1050",")",")",",","(","'HD 1080'",",","(","1920",",","1080",")",")",",","(","'WUXGA'",",","(","1920",",","1200",")",")",",","(","'2K'",",","(","2048",",","1080",")",")",",","(","'QXGA'",",","(","2048",",","1536",")",")",",","(","'WQXGA'",",","(","2560",",","1600",")",")",",","(","'MAX Resolution'",",","(","2592",",","1944",")",")",",","]",")","vals","=","[","]","for","key","in","self",".","StandardResolutions",".","keys","(",")",":","vals",".","append","(","'%s: (%dx%d)'","%","(","key",",","# Tabs not working?!!","self",".","StandardResolutions","[","key","]","[","0","]",",","self",".","StandardResolutions","[","key","]","[","1","]",")",")","self",".","FixedResolutionsCombo","[","'values'","]","=","vals","self",".","FixedResolutionsCombo",".","current","(","10",")","f2","=","ttk",".","Frame","(","f",")","# subframe to frame f","f2",".","grid","(","row","=","2",",","column","=","0",",","sticky","=","'NSEW'",")","f2",".","columnconfigure","(","2",",","weight","=","1",")","f2",".","columnconfigure","(","4",",","weight","=","1",")","b2","=","ttk",".","Radiobutton","(","f2",",","text","=","'Roll your own:'",",","variable","=","self",".","UseFixedResolutions",",","value","=","False",",","command","=","self",".","UseFixedResRadios",",","padding","=","(","5",",","5",",","5",",","5",")",")","b2",".","grid","(","row","=","1",",","column","=","0",",","sticky","=","'NW'",")","ToolTip","(","b2",",","122",")","Label","(","f2",",","text","=","\"Width:\"",",","anchor","=","E",")",".","grid","(","column","=","1",",","row","=","1",",","sticky","=","'E'",",","ipadx","=","3",",","ipady","=","3",")","Widths","=","[","]","for","i","in","range","(","1",",","82",")",":","Widths",".","append","(","32","*","i",")","# Widths can be in 32 byte increments","self",".","cb","=","MyComboBox","(","f2",",","Widths",",","current","=","10",",","callback","=","self",".","ResolutionChanged",",","width","=","5",",","row","=","1",",","col","=","2",",","sticky","=","'W'",",","state","=","'disabled'",",","tip","=","123",")","Label","(","f2",",","text","=","\"Height:\"",",","anchor","=","E",")",".","grid","(","column","=","3",",","row","=","1",",","sticky","=","'W'",",","ipadx","=","5",",","ipady","=","3",")","Heights","=","[","]","for","i","in","range","(","1",",","123",")",":","Heights",".","append","(","16","*","i",")","# heights in 16 byte increments","self",".","cb1","=","MyComboBox","(","f2",",","Heights",",","current","=","10",",","callback","=","self",".","ResolutionChanged",",","width","=","5",",","row","=","1",",","col","=","4",",","sticky","=","'W'",",","state","=","'disabled'",",","tip","=","124",")","ttk",".","Label","(","f2",",","text","=","'Actual:'",")",".","grid","(","row","=","2",",","column","=","1",",","sticky","=","'E'",")","self",".","WidthLabel","=","ttk",".","Label","(","f2",",","style","=","'DataLabel.TLabel'",")","self",".","WidthLabel",".","grid","(","row","=","2",",","column","=","2",",","sticky","=","'W'",")","ToolTip","(","self",".","WidthLabel",",","125",")","ttk",".","Label","(","f2",",","text","=","'Actual:'",")",".","grid","(","row","=","2",",","column","=","3",",","sticky","=","'E'",")","self",".","HeightLabel","=","ttk",".","Label","(","f2",",","style","=","'DataLabel.TLabel'",")","self",".","HeightLabel",".","grid","(","row","=","2",",","column","=","4",",","sticky","=","'W'",")","ToolTip","(","self",".","HeightLabel",",","126",")","Separator","(","f",",","orient","=","HORIZONTAL",")",".","grid","(","pady","=","5",",","row","=","3",",","column","=","0",",","columnspan","=","4",",","sticky","=","'EW'",")","#--------------- Zoom Region Before ----------------","f4","=","MyLabelFrame","(","f",",","'Zoom region of interest before taking '","+","'picture\/video'",",","4",",","0",")","#f4.columnconfigure(1,weight=1)","#f4.columnconfigure(3,weight=1)","Label","(","f4",",","text","=","'X:'",")",".","grid","(","row","=","0",",","column","=","0",",","sticky","=","'E'",")","self",".","Xzoom","=","ttk",".","Scale","(","f4",",","from_","=","0.0",",","to","=","0.94",",","orient","=","'horizontal'",")","self",".","Xzoom",".","grid","(","row","=","0",",","column","=","1",",","sticky","=","'W'",",","padx","=","5",",","pady","=","3",")","self",".","Xzoom",".","set","(","0.0",")","ToolTip","(","self",".","Xzoom",",","130",")","Label","(","f4",",","text","=","'Y:'",")",".","grid","(","row","=","0",",","column","=","2",",","sticky","=","'E'",")","self",".","Yzoom","=","ttk",".","Scale","(","f4",",","from_","=","0.0",",","to","=","0.94",",","orient","=","'horizontal'",")","self",".","Yzoom",".","grid","(","row","=","0",",","column","=","3",",","sticky","=","'W'",",","padx","=","5",",","pady","=","3",")","self",".","Yzoom",".","set","(","0.0",")","ToolTip","(","self",".","Yzoom",",","131",")","Label","(","f4",",","text","=","'Width:'",")",".","grid","(","row","=","1",",","column","=","0",",","sticky","=","'E'",")","self",".","Widthzoom","=","ttk",".","Scale","(","f4",",","from_","=","0.05",",","to","=","1.0",",","orient","=","'horizontal'",")","self",".","Widthzoom",".","grid","(","row","=","1",",","column","=","1",",","sticky","=","'W'",",","padx","=","5",",","pady","=","3",")","self",".","Widthzoom",".","set","(","1.0",")","ToolTip","(","self",".","Widthzoom",",","132",")","Label","(","f4",",","text","=","'Height:'",")",".","grid","(","row","=","1",",","column","=","2",",","sticky","=","'E'",")","self",".","Heightzoom","=","ttk",".","Scale","(","f4",",","from_","=","0.05",",","to","=","1.0",",","orient","=","'horizontal'",")","self",".","Heightzoom",".","grid","(","row","=","1",",","column","=","3",",","sticky","=","'W'",",","padx","=","5",",","pady","=","3",")","self",".","Heightzoom",".","set","(","1.0",")","ToolTip","(","self",".","Heightzoom",",","133",")","# WLW THIS IS A PROBLEM","image","=","PIL",".","Image",".","open","(","'Assets\/reset.png'",")","#.resize((16,16))","self",".","resetImage","=","GetPhotoImage","(","image",".","resize","(","(","16",",","16",")",")",")","self",".","ResetZoomButton","=","ttk",".","Button","(","f4",",","image","=","self",".","resetImage",",","command","=","self",".","ZoomReset",")","self",".","ResetZoomButton",".","grid","(","row","=","0",",","column","=","4",",","rowspan","=","2",",","sticky","=","'W'",")","ToolTip","(","self",".","ResetZoomButton",",","134",")","self",".","Xzoom",".","config","(","command","=","lambda","newval",",","widget","=","self",".","Xzoom",":","self",".","Zoom","(","newval",",","widget",")",")","self",".","Yzoom",".","config","(","command","=","lambda","newval",",","widget","=","self",".","Yzoom",":","self",".","Zoom","(","newval",",","widget",")",")","self",".","Widthzoom",".","config","(","command","=","lambda","newval",",","widget","=","self",".","Widthzoom",":","self",".","Zoom","(","newval",",","widget",")",")","self",".","Heightzoom",".","config","(","command","=","lambda","newval",",","widget","=","self",".","Heightzoom",":","self",".","Zoom","(","newval",",","widget",")",")","Separator","(","f",",","orient","=","HORIZONTAL",")",".","grid","(","pady","=","5",",","row","=","5",",","column","=","0",",","columnspan","=","3",",","sticky","=","'EW'",")","#--------------- Resize Image After ----------------","f4","=","MyLabelFrame","(","f",",","'Resize image after taking picture\/video'",",","6",",","0",")","#f4.columnconfigure(3,weight=1)","#f4.columnconfigure(5,weight=1)","b","=","MyBooleanVar","(","False",")","self",".","ResizeAfterNone","=","MyRadio","(","f4",",","'None (Default)'",",","False",",","b",",","self",".","AllowImageResizeAfter",",","0",",","0",",","'W'",",","pad","=","(","0",",","5",",","0",",","5",")",",","tip","=","140",")","MyRadio","(","f4",",","'Resize'",",","True",",","b",",","self",".","AllowImageResizeAfter",",","0",",","1",",","'W'",",","pad","=","(","5",",","5",",","0",",","5",")",",","tip","=","141",")","Label","(","f4",",","text","=","\"Width:\"",",","anchor","=","E",")",".","grid","(","column","=","2",",","row","=","0",",","sticky","=","'E'",",","ipadx","=","3",",","ipady","=","3",")","self",".","resizeWidthAfterCombo","=","MyComboBox","(","f4",",","Widths",",","current","=","10",",","callback","=","self",".","ResizeAfterChanged",",","width","=","5",",","row","=","0",",","col","=","3",",","sticky","=","'W'",",","state","=","'disabled'",",","tip","=","142",")","Label","(","f4",",","text","=","\"Height:\"",",","anchor","=","E",")",".","grid","(","column","=","4",",","row","=","0",",","sticky","=","'W'",",","ipadx","=","5",",","ipady","=","3",")","self",".","resizeHeightAfterCombo","=","MyComboBox","(","f4",",","Heights",",","current","=","10",",","callback","=","self",".","ResizeAfterChanged",",","width","=","5",",","row","=","0",",","col","=","5",",","sticky","=","'W'",",","state","=","'disabled'",",","tip","=","143",")","self",".","resizeAfter","=","None","#--------------- Quick Adjustments ----------------","f","=","MyLabelFrame","(","self",",","'Quick adjustments'",",","2",",","0",")","#f.columnconfigure(2,weight=1)","#-Brightness","self",".","brightLabel",",","self",".","brightness",",","val","=","self",".","SetupLabelCombo","(","f",",","'Brightness:'",",","0",",","0",",","0",",","100",",","self",".","CameraBrightnessChanged",",","self",".","camera",".","brightness",")","self",".","CameraBrightnessChanged","(","val",")","ToolTip","(","self",".","brightness",",","msg","=","150",")","#-Contrast","self",".","contrastLabel",",","self",".","contrast",",","val","=","self",".","SetupLabelCombo","(","f",",","'Contrast:'",",","0",",","3",",","-","100",",","100",",","self",".","ContrastChanged",",","self",".","camera",".","contrast",")","self",".","ContrastChanged","(","val",")","ToolTip","(","self",".","contrast",",","msg","=","151",")","#-Saturation","self",".","saturationLabel",",","self",".","saturation",",","val","=","self",".","SetupLabelCombo","(","f",",","'Saturation:'",",","1",",","0",",","-","100",",","100",",","self",".","SaturationChanged",",","self",".","camera",".","saturation",",","label","=","'Sat'",")","self",".","SaturationChanged","(","val",")","ToolTip","(","self",".","saturation",",","msg","=","152",")","#-Sharpness","self",".","sharpnessLabel",",","self",".","sharpness",",","val","=","self",".","SetupLabelCombo","(","f",",","'Sharpness:'",",","1",",","3",",","-","100",",","100",",","self",".","SharpnessChanged",",","self",".","camera",".","sharpness",")","self",".","SharpnessChanged","(","val",")","ToolTip","(","self",".","sharpness",",","msg","=","153",")","#-Reset","#self.ResetGeneralButton = Button(f,image=self.resetImage,width=5,","#command=self.ResetGeneralSliders)","#self.ResetGeneralButton.grid(row=4,column=2,sticky='W',padx=5)","#ToolTip(self.ResetGeneralButton,msg=154)","#--------------- Image Effects ----------------","f","=","MyLabelFrame","(","self",",","'Preprogrammed image effects'",",","3",",","0",")","#f.columnconfigure(2,weight=1)","v","=","MyBooleanVar","(","False",")","self",".","NoEffectsRadio","=","MyRadio","(","f",",","'None (Default)'",",","False",",","v",",","self",".","EffectsChecked",",","0",",","0",",","'W'",",","tip","=","160",")","MyRadio","(","f",",","'Select effect:'",",","True",",","v",",","self",".","EffectsChecked",",","0",",","1",",","'W'",",","tip","=","161",")","self",".","effects","=","Combobox","(","f",",","height","=","15",",","width","=","10",",","state","=","'readonly'",")","#,width=15)","self",".","effects",".","grid","(","row","=","0",",","column","=","2",",","sticky","=","'W'",")","effects","=","list","(","self",".","camera",".","IMAGE_EFFECTS",".","keys","(",")",")","# python 3 workaround","effects",".","remove","(","'none'",")","effects",".","sort","(",")","#cmp=lambda x,y: cmp(x.lower(),y.lower())) # not python 3","self",".","effects","[","'values'","]","=","effects","self",".","effects",".","current","(","0",")","self",".","effects",".","bind","(","'<<ComboboxSelected>>'",",","self",".","EffectsChanged",")","ToolTip","(","self",".","effects",",","msg","=","162",")","self",".","ModParams","=","ttk",".","Button","(","f",",","text","=","'Params...'",",","command","=","self",".","ModifyEffectsParamsPressed",",","underline","=","0",",","padding","=","(","5",",","3",",","5",",","3",")",",","width","=","8",")","self",".","ModParams",".","grid","(","row","=","0",",","column","=","3",",","sticky","=","EW",",","padx","=","5",")","ToolTip","(","self",".","ModParams",",","msg","=","163",")","self",".","EffectsChecked","(","False",")","#--------------- Flash Mode ---------------","f","=","MyLabelFrame","(","self",",","'LED and Flash mode'",",","4",",","0",",","span","=","4",")","#f.columnconfigure(3,weight=1)","self",".","LedOn","=","MyBooleanVar","(","True",")","self",".","LedButton","=","ttk",".","Checkbutton","(","f",",","text","=","'Led On (via GPIO pins)'",",","variable","=","self",".","LedOn",",","command","=","self",".","LedOnChecked",")","self",".","LedButton",".","grid","(","row","=","0",",","column","=","0",",","sticky","=","'NW'",",","pady","=","5",",","columnspan","=","2",")","ToolTip","(","self",".","LedButton",",","msg","=","102",")","Label","(","f",",","text","=","'Flash Mode:'",")",".","grid","(","row","=","1",",","column","=","0",",","sticky","=","'W'",")","b","=","MyStringVar","(","'off'",")","self",".","FlashModeOffRadio","=","MyRadio","(","f",",","'Off (Default)'",",","'off'",",","b",",","self",".","FlashModeButton",",","1",",","1",",","'W'",",","tip","=","180",")","MyRadio","(","f",",","'Auto'",",","'auto'",",","b",",","self",".","FlashModeButton",",","1",",","2",",","'W'",",","tip","=","181",")","MyRadio","(","f",",","'Select:'",",","'set'",",","b",",","self",".","FlashModeButton",",","1",",","3",",","'W'",",","tip","=","182",")","# Use invoke() on radio button to force a command","self",".","FlashModeCombo","=","Combobox","(","f",",","state","=","'readonly'",",","width","=","10",")","self",".","FlashModeCombo",".","grid","(","row","=","1",",","column","=","4",",","sticky","=","'W'",")","self",".","FlashModeCombo",".","bind","(","'<<ComboboxSelected>>'",",","self",".","FlashModeChanged",")","modes","=","list","(","self",".","camera",".","FLASH_MODES",".","keys","(",")",")","modes",".","remove","(","'off'",")","# these two are handled by radio buttons","modes",".","remove","(","'auto'",")","modes",".","sort","(",")","#cmp=lambda x,y: cmp(x.lower(),y.lower()))","self",".","FlashModeCombo","[","'values'","]","=","modes","self",".","FlashModeCombo",".","current","(","0",")","self",".","FlashModeCombo",".","config","(","state","=","'disabled'",")","ToolTip","(","self",".","FlashModeCombo",",","183",")","self",".","FixedResolutionChanged","(","None",")"],"url":"https:\/\/github.com\/Billwilliams1952\/PiCameraApp\/blob\/61802b367d620aafb6b4e0bb84ea1ebd0dbd42c0\/Source\/BasicControls.py#L52-L340"}
2
+ {"nwo":"Billwilliams1952\/PiCameraApp","sha":"61802b367d620aafb6b4e0bb84ea1ebd0dbd42c0","path":"Source\/Exposure.py","language":"python","identifier":"Exposure.ValidateEntry","parameters":"( self, entry, minVal, maxVal )","argument_list":"","return_statement":"return num","docstring":"Change how the edit fields work. Allow a '\/' in the edit field to\n\t\tdenote a fraction.\n\t\tSplit on '\/' and evaluate each side. Note, if '<num> \/' then\n\t\tnum is evalulated since 'den' is empty","docstring_summary":"Change how the edit fields work. Allow a '\/' in the edit field to\n\t\tdenote a fraction.\n\t\tSplit on '\/' and evaluate each side. Note, if '<num> \/' then\n\t\tnum is evalulated since 'den' is empty","docstring_tokens":["Change","how","the","edit","fields","work",".","Allow","a","\/","in","the","edit","field","to","denote","a","fraction",".","Split","on","\/","and","evaluate","each","side",".","Note","if","<num",">","\/","then","num","is","evalulated","since","den","is","empty"],"function":"def ValidateEntry ( self, entry, minVal, maxVal ):\n\t\t'''\n\t\tChange how the edit fields work. Allow a '\/' in the edit field to\n\t\tdenote a fraction.\n\t\tSplit on '\/' and evaluate each side. Note, if '<num> \/' then\n\t\tnum is evalulated since 'den' is empty\n\t\t'''\n\t\tvals = entry.split('\/',1)\t# entry is text\n\t\tval = vals[0].strip()\n\t\ttry:\t\tnum = float(val)\n\t\texcept:\tnum = None\n\t\telse:\n\t\t\tif len(vals) > 1:\n\t\t\t\tval = vals[1].strip()\n\t\t\t\tif val:\n\t\t\t\t\ttry:\t\t\tden = float(val)\n\t\t\t\t\texcept:\t\tnum = None\n\t\t\t\t\telse:\n\t\t\t\t\t\tif den > 0:\tnum = num \/ den\n\t\t\t\t\t\telse:\t\t\tnum = None\n\t\tif num is not None:\n\t\t\tnum = num if num >= minVal and num <= maxVal else None\n\t\tself.FrameRate.config(style='RedMessage.TLabel' if num is None \\\n\t\t\t\t\t\t\t\t\t else 'DataLabel.TLabel')\n\t\treturn num","function_tokens":["def","ValidateEntry","(","self",",","entry",",","minVal",",","maxVal",")",":","vals","=","entry",".","split","(","'\/'",",","1",")","# entry is text","val","=","vals","[","0","]",".","strip","(",")","try",":","num","=","float","(","val",")","except",":","num","=","None","else",":","if","len","(","vals",")",">","1",":","val","=","vals","[","1","]",".","strip","(",")","if","val",":","try",":","den","=","float","(","val",")","except",":","num","=","None","else",":","if","den",">","0",":","num","=","num","\/","den","else",":","num","=","None","if","num","is","not","None",":","num","=","num","if","num",">=","minVal","and","num","<=","maxVal","else","None","self",".","FrameRate",".","config","(","style","=","'RedMessage.TLabel'","if","num","is","None","else","'DataLabel.TLabel'",")","return","num"],"url":"https:\/\/github.com\/Billwilliams1952\/PiCameraApp\/blob\/61802b367d620aafb6b4e0bb84ea1ebd0dbd42c0\/Source\/Exposure.py#L473-L497"}
3
+ {"nwo":"Billwilliams1952\/PiCameraApp","sha":"61802b367d620aafb6b4e0bb84ea1ebd0dbd42c0","path":"Source\/Tooltip.py","language":"python","identifier":"ToolTip.__init__","parameters":"( self, wdgt, msg=None, msgFunc=None, follow=1 )","argument_list":"","return_statement":"","docstring":"Initialize the ToolTip\n\t\tArguments:\n\t\t\twdgt: The widget to which this ToolTip is assigned\n\t\t\tmsg: A static string message assigned to the ToolTip\n\t\t\t\t\tif msg istype integer - search for text in TipLines\n\t\t\tmsgFunc: A function that retrieves a string to use as the ToolTip text\n\t\t\tdelay: The delay in seconds before the ToolTip appears(may be float)\n\t\t\tfollow: If True, the ToolTip follows motion, otherwise hides","docstring_summary":"Initialize the ToolTip\n\t\tArguments:\n\t\t\twdgt: The widget to which this ToolTip is assigned\n\t\t\tmsg: A static string message assigned to the ToolTip\n\t\t\t\t\tif msg istype integer - search for text in TipLines\n\t\t\tmsgFunc: A function that retrieves a string to use as the ToolTip text\n\t\t\tdelay: The delay in seconds before the ToolTip appears(may be float)\n\t\t\tfollow: If True, the ToolTip follows motion, otherwise hides","docstring_tokens":["Initialize","the","ToolTip","Arguments",":","wdgt",":","The","widget","to","which","this","ToolTip","is","assigned","msg",":","A","static","string","message","assigned","to","the","ToolTip","if","msg","istype","integer","-","search","for","text","in","TipLines","msgFunc",":","A","function","that","retrieves","a","string","to","use","as","the","ToolTip","text","delay",":","The","delay","in","seconds","before","the","ToolTip","appears","(","may","be","float",")","follow",":","If","True","the","ToolTip","follows","motion","otherwise","hides"],"function":"def __init__( self, wdgt, msg=None, msgFunc=None, follow=1 ):\n\t\t\"\"\"\n\t\tInitialize the ToolTip\n\t\tArguments:\n\t\t\twdgt: The widget to which this ToolTip is assigned\n\t\t\tmsg: A static string message assigned to the ToolTip\n\t\t\t\t\tif msg istype integer - search for text in TipLines\n\t\t\tmsgFunc: A function that retrieves a string to use as the ToolTip text\n\t\t\tdelay: The delay in seconds before the ToolTip appears(may be float)\n\t\t\tfollow: If True, the ToolTip follows motion, otherwise hides\n\t\t\"\"\"\n\t\tself.wdgt = wdgt\n\t\t# The parent of the ToolTip is the parent of the ToolTips widget\n\t\tself.parent = self.wdgt.master\n\t\t# Initalise the Toplevel\n\t\tToplevel.__init__( self, self.parent, bg='black', padx=1, pady=1 )\n\t\tself.withdraw() # Hide initially\n\t\t# The ToolTip Toplevel should have no frame or title bar\n\t\tself.overrideredirect( True )\n\t\t# The msgVar will contain the text displayed by the ToolTip\n\t\tself.msgVar = StringVar()\n\t\tself.TipID = None\n\t\tself.TipNumText = \"\"\n\t\ttry:\n\t\t\tif msg is None:\n\t\t\t\tself.msgVar.set('No tooltip provided')\n\t\t\telif type(msg) is int:\t# lookup tooltip text in file\n\t\t\t\tself.TipID = msg\n\t\t\t\tself.msgVar.set(ToolTip.GetTooltipText(msg))\n\t\t\t\tself.TipNumText = \"Tip number %d\\n\\n\" % self.TipID\n\t\t\telse:\t# assume a string is passed\n\t\t\t\tself.msgVar.set( msg )\n\t\texcept:\n\t\t\tself.msgVar.set('ERROR getting tooltip')\n\t\tself.msgFunc = msgFunc\t\t# call this function to return tip text\n\t\tself.follow = follow\t\t\t# move tip if mouse moves\n\t\tself.visible = 0\n\t\tself.lastMotion = 0\n\t\t# The test of the ToolTip is displayed in a Message widget\n\t\tMessage( self, textvariable=self.msgVar, bg='#FFFFDD',\n\t\t\t\t\taspect=250 ).grid()\n\t\t# Add bindings to the widget. This will NOT override bindings\n\t\t# that the widget already has\n\t\tself.wdgt.bind( '<Enter>', self.spawn, '+' )\n\t\tself.wdgt.bind( '<Leave>', self.hide, '+' )\n\t\tself.wdgt.bind( '<Motion>', self.move, '+' )","function_tokens":["def","__init__","(","self",",","wdgt",",","msg","=","None",",","msgFunc","=","None",",","follow","=","1",")",":","self",".","wdgt","=","wdgt","# The parent of the ToolTip is the parent of the ToolTips widget","self",".","parent","=","self",".","wdgt",".","master","# Initalise the Toplevel","Toplevel",".","__init__","(","self",",","self",".","parent",",","bg","=","'black'",",","padx","=","1",",","pady","=","1",")","self",".","withdraw","(",")","# Hide initially","# The ToolTip Toplevel should have no frame or title bar","self",".","overrideredirect","(","True",")","# The msgVar will contain the text displayed by the ToolTip","self",".","msgVar","=","StringVar","(",")","self",".","TipID","=","None","self",".","TipNumText","=","\"\"","try",":","if","msg","is","None",":","self",".","msgVar",".","set","(","'No tooltip provided'",")","elif","type","(","msg",")","is","int",":","# lookup tooltip text in file","self",".","TipID","=","msg","self",".","msgVar",".","set","(","ToolTip",".","GetTooltipText","(","msg",")",")","self",".","TipNumText","=","\"Tip number %d\\n\\n\"","%","self",".","TipID","else",":","# assume a string is passed","self",".","msgVar",".","set","(","msg",")","except",":","self",".","msgVar",".","set","(","'ERROR getting tooltip'",")","self",".","msgFunc","=","msgFunc","# call this function to return tip text","self",".","follow","=","follow","# move tip if mouse moves","self",".","visible","=","0","self",".","lastMotion","=","0","# The test of the ToolTip is displayed in a Message widget","Message","(","self",",","textvariable","=","self",".","msgVar",",","bg","=","'#FFFFDD'",",","aspect","=","250",")",".","grid","(",")","# Add bindings to the widget. This will NOT override bindings","# that the widget already has","self",".","wdgt",".","bind","(","'<Enter>'",",","self",".","spawn",",","'+'",")","self",".","wdgt",".","bind","(","'<Leave>'",",","self",".","hide",",","'+'",")","self",".","wdgt",".","bind","(","'<Motion>'",",","self",".","move",",","'+'",")"],"url":"https:\/\/github.com\/Billwilliams1952\/PiCameraApp\/blob\/61802b367d620aafb6b4e0bb84ea1ebd0dbd42c0\/Source\/Tooltip.py#L102-L147"}
4
+ {"nwo":"Billwilliams1952\/PiCameraApp","sha":"61802b367d620aafb6b4e0bb84ea1ebd0dbd42c0","path":"Source\/Tooltip.py","language":"python","identifier":"ToolTip.spawn","parameters":"( self, event=None )","argument_list":"","return_statement":"","docstring":"Spawn the ToolTip. This simply makes the ToolTip eligible for display.\n\t\tUsually this is caused by entering the widget\n\t\tArguments:\n\t\t\tevent: The event that called this funciton","docstring_summary":"Spawn the ToolTip. This simply makes the ToolTip eligible for display.\n\t\tUsually this is caused by entering the widget\n\t\tArguments:\n\t\t\tevent: The event that called this funciton","docstring_tokens":["Spawn","the","ToolTip",".","This","simply","makes","the","ToolTip","eligible","for","display",".","Usually","this","is","caused","by","entering","the","widget","Arguments",":","event",":","The","event","that","called","this","funciton"],"function":"def spawn( self, event=None ):\n\t\t\"\"\"\n\t\tSpawn the ToolTip. This simply makes the ToolTip eligible for display.\n\t\tUsually this is caused by entering the widget\n\t\tArguments:\n\t\t\tevent: The event that called this funciton\n\t\t\"\"\"\n\t\tself.visible = 1\n\t\t# The after function takes a time argument in miliseconds\n\t\tself.after( int( ToolTip.ShowTipDelay * 1000 ), self.show )","function_tokens":["def","spawn","(","self",",","event","=","None",")",":","self",".","visible","=","1","# The after function takes a time argument in miliseconds","self",".","after","(","int","(","ToolTip",".","ShowTipDelay","*","1000",")",",","self",".","show",")"],"url":"https:\/\/github.com\/Billwilliams1952\/PiCameraApp\/blob\/61802b367d620aafb6b4e0bb84ea1ebd0dbd42c0\/Source\/Tooltip.py#L149-L158"}
5
+ {"nwo":"Billwilliams1952\/PiCameraApp","sha":"61802b367d620aafb6b4e0bb84ea1ebd0dbd42c0","path":"Source\/Tooltip.py","language":"python","identifier":"ToolTip.show","parameters":"( self )","argument_list":"","return_statement":"","docstring":"Displays the ToolTip if the time delay has been long enough","docstring_summary":"Displays the ToolTip if the time delay has been long enough","docstring_tokens":["Displays","the","ToolTip","if","the","time","delay","has","been","long","enough"],"function":"def show( self ):\n\t\t\"\"\"\n\t\tDisplays the ToolTip if the time delay has been long enough\n\t\t\"\"\"\n\t\tif ToolTip.ShowToolTips is False: return\n\t\ttext = self.msgVar.get()\n\t\tif ToolTip.ShowTipNumber is True and self.TipID is not None:\n\t\t\t# check if text is not there, if so add it\n\t\t\tif self.TipNumText not in text:\n\t\t\t\tself.msgVar.set(self.TipNumText+text)\n\t\telse:\n\t\t\ttext.replace(self.TipNumText,\"\")\n\t\t\tself.msgVar.set(text)\n\n\t\tif self.visible == 1 and time() - self.lastMotion > ToolTip.ShowTipDelay:\n\t\t\tself.visible = 2\n\t\tif self.visible == 2:\n\t\t\tself.deiconify()","function_tokens":["def","show","(","self",")",":","if","ToolTip",".","ShowToolTips","is","False",":","return","text","=","self",".","msgVar",".","get","(",")","if","ToolTip",".","ShowTipNumber","is","True","and","self",".","TipID","is","not","None",":","# check if text is not there, if so add it","if","self",".","TipNumText","not","in","text",":","self",".","msgVar",".","set","(","self",".","TipNumText","+","text",")","else",":","text",".","replace","(","self",".","TipNumText",",","\"\"",")","self",".","msgVar",".","set","(","text",")","if","self",".","visible","==","1","and","time","(",")","-","self",".","lastMotion",">","ToolTip",".","ShowTipDelay",":","self",".","visible","=","2","if","self",".","visible","==","2",":","self",".","deiconify","(",")"],"url":"https:\/\/github.com\/Billwilliams1952\/PiCameraApp\/blob\/61802b367d620aafb6b4e0bb84ea1ebd0dbd42c0\/Source\/Tooltip.py#L160-L177"}
6
+ {"nwo":"Billwilliams1952\/PiCameraApp","sha":"61802b367d620aafb6b4e0bb84ea1ebd0dbd42c0","path":"Source\/Tooltip.py","language":"python","identifier":"ToolTip.move","parameters":"( self, event )","argument_list":"","return_statement":"","docstring":"Processes motion within the widget.\n\t\tArguments:\n\t\tevent: The event that called this function","docstring_summary":"Processes motion within the widget.\n\t\tArguments:\n\t\tevent: The event that called this function","docstring_tokens":["Processes","motion","within","the","widget",".","Arguments",":","event",":","The","event","that","called","this","function"],"function":"def move( self, event ):\n\t\t\"\"\"\n\t\tProcesses motion within the widget.\n\t\tArguments:\n\t\tevent: The event that called this function\n\t\t\"\"\"\n\t\tself.lastMotion = time()\n\t\t# If the follow flag is not set, motion within the widget will\n\t\t# make the ToolTip dissapear\n\t\tif self.follow == False:\n\t\t\tself.withdraw()\n\t\t\tself.visible = 1\n\t\t# Offset the ToolTip 10x10 pixels southeast of the pointer\n\t\tself.geometry( '+%i+%i' % ( event.x_root+10, event.y_root+10 ) )\n\t\t# Try to call the message function. Will not change the message\n\t\t# if the message function is None or the message function fails\n\t\ttry:\t\tself.msgVar.set( self.msgFunc() )\n\t\texcept:\tpass\n\t\tself.after( int( ToolTip.ShowTipDelay * 1000 ), self.show )","function_tokens":["def","move","(","self",",","event",")",":","self",".","lastMotion","=","time","(",")","# If the follow flag is not set, motion within the widget will","# make the ToolTip dissapear","if","self",".","follow","==","False",":","self",".","withdraw","(",")","self",".","visible","=","1","# Offset the ToolTip 10x10 pixels southeast of the pointer","self",".","geometry","(","'+%i+%i'","%","(","event",".","x_root","+","10",",","event",".","y_root","+","10",")",")","# Try to call the message function. Will not change the message","# if the message function is None or the message function fails","try",":","self",".","msgVar",".","set","(","self",".","msgFunc","(",")",")","except",":","pass","self",".","after","(","int","(","ToolTip",".","ShowTipDelay","*","1000",")",",","self",".","show",")"],"url":"https:\/\/github.com\/Billwilliams1952\/PiCameraApp\/blob\/61802b367d620aafb6b4e0bb84ea1ebd0dbd42c0\/Source\/Tooltip.py#L179-L197"}
7
+ {"nwo":"Billwilliams1952\/PiCameraApp","sha":"61802b367d620aafb6b4e0bb84ea1ebd0dbd42c0","path":"Source\/Tooltip.py","language":"python","identifier":"ToolTip.hide","parameters":"( self, event=None )","argument_list":"","return_statement":"","docstring":"Hides the ToolTip. Usually this is caused by leaving the widget\n\t\tArguments:\n\t\t\tevent: The event that called this function","docstring_summary":"Hides the ToolTip. Usually this is caused by leaving the widget\n\t\tArguments:\n\t\t\tevent: The event that called this function","docstring_tokens":["Hides","the","ToolTip",".","Usually","this","is","caused","by","leaving","the","widget","Arguments",":","event",":","The","event","that","called","this","function"],"function":"def hide( self, event=None ):\n\t\t\"\"\"\n\t\tHides the ToolTip. Usually this is caused by leaving the widget\n\t\tArguments:\n\t\t\tevent: The event that called this function\n\t\t\"\"\"\n\t\tself.visible = 0\n\t\tself.withdraw()","function_tokens":["def","hide","(","self",",","event","=","None",")",":","self",".","visible","=","0","self",".","withdraw","(",")"],"url":"https:\/\/github.com\/Billwilliams1952\/PiCameraApp\/blob\/61802b367d620aafb6b4e0bb84ea1ebd0dbd42c0\/Source\/Tooltip.py#L199-L206"}
8
+ {"nwo":"Billwilliams1952\/PiCameraApp","sha":"61802b367d620aafb6b4e0bb84ea1ebd0dbd42c0","path":"Source\/Mapping.py","language":"python","identifier":"ControlMapping.SetControlMapping","parameters":"( self )","argument_list":"","return_statement":"","docstring":"Can't seem to get a foucs highlight around some of the controls.\n\t\tSo I'm using color changes to show focus\/tab stops.\n\t\tAlso, the Scale does not seem to get focus by clicking on it\n\t\tNeed to force focus when the user clicks on it","docstring_summary":"Can't seem to get a foucs highlight around some of the controls.\n\t\tSo I'm using color changes to show focus\/tab stops.\n\t\tAlso, the Scale does not seem to get focus by clicking on it\n\t\tNeed to force focus when the user clicks on it","docstring_tokens":["Can","t","seem","to","get","a","foucs","highlight","around","some","of","the","controls",".","So","I","m","using","color","changes","to","show","focus","\/","tab","stops",".","Also","the","Scale","does","not","seem","to","get","focus","by","clicking","on","it","Need","to","force","focus","when","the","user","clicks","on","it"],"function":"def SetControlMapping ( self ):\n\t\t#Style().configure('.', font=('Helvetica', 12)) # all\n\t\tStyle().configure('RedMessage.TLabel',font=('Arial',10,\"italic\"),foreground='red')\n\t\t# These dont work since they're overriden by the map later on... ???\n\t\tStyle().configure('Error.TEntry',background='red',foreground='white')\n\t\tStyle().configure('OK.TEntry',background='white',foreground='black')\n\t\tStyle().configure('DataLabel.TLabel',foreground='blue',font=('Arial',10))\n\t\tStyle().configure('StatusBar.TLabel',background=self.FocusColor,relief=SUNKEN)\n\t\tStyle().configure('TMenu',background='white',activeforeground='lightblue')\n\t\t'''\n\t\tCan't seem to get a foucs highlight around some of the controls.\n\t\tSo I'm using color changes to show focus\/tab stops.\n\t\tAlso, the Scale does not seem to get focus by clicking on it\n\t\tNeed to force focus when the user clicks on it\n\t\t'''\n\t\tStyle().map('TPanedwindow',\n\t\t\tbackground = [\n\t\t\t\t\t\t\t\t('!active','#f0f0ff'),\n\t\t\t\t\t\t\t ],\n\t\t\t)\n\t\tStyle().map('TCombobox',\n\t\t\tfieldbackground = [\n\t\t\t\t\t\t\t ('focus','!disabled',self.FocusColor),\n\t\t\t\t\t\t\t ('!focus','active','!disabled',self.NoFocusMouseOverColor),\n\t\t\t\t\t\t\t ('!focus','!active','!disabled',self.NoFocusNoMouseOverColor),\n\t\t\t\t\t\t\t #('disabled','lightgray'), # Use foreground\n\t\t\t\t\t\t\t ],\n\t\t\tforeground = [\n\t\t\t\t\t\t ('disabled','gray'),\n\t\t\t\t\t\t ('!disabled', 'black')\n\t\t\t\t\t\t ],\n\t\t\tselectbackground = [\n\t\t\t\t\t\t\t ('focus','!disabled',self.FocusColor),\n\t\t\t\t\t\t\t ('!focus','active','!disabled',self.NoFocusMouseOverColor),\n\t\t\t\t\t\t\t ('!focus','!active','!disabled',self.NoFocusNoMouseOverColor),\n\t\t\t\t\t\t\t #('disabled','lightgray'),\n\t\t\t\t\t\t\t ],\n\t\t\tselectforeground = [\n\t\t\t\t\t\t\t ('!focus','black'),\n\t\t\t\t\t\t\t ('readonly','black'),\n\t\t\t\t\t\t\t ('focus','black'),\n\t\t\t\t\t\t\t ('disabled','black'),\n\t\t\t\t\t\t\t ('!disabled', 'black')\n\t\t\t\t\t\t\t ],\n\t\t\t\t )\t# close map\n\n\t\tStyle().map('TEntry',# This one is just for 'look and feel'\n\t\t\tfieldbackground = [\n\t\t\t\t\t\t\t ('focus','!disabled', '!invalid' ,self.FocusColor),\n\t\t\t\t\t\t\t ('!focus','active','!disabled','!invalid', self.NoFocusMouseOverColor),\n\t\t\t\t\t\t\t ('!focus','!active','!disabled','!invalid',self.NoFocusNoMouseOverColor),\n\t\t\t\t\t\t\t ('invalid', '#FF0000')\n\t\t\t\t\t\t\t #('disabled','lightgray'),\n\t\t\t\t\t\t\t ],\n\t\t\tforeground = [\n\t\t\t\t\t\t ('disabled', '!invalid', 'gray'),\n\t\t\t\t\t\t ('!disabled', '!invalid', 'black')\n\t\t\t\t\t\t #('invalid', self.NoFocusNoMouseOverColor)\n\t\t\t\t\t\t ],\n\t\t\t#background = [\n\t\t\t\t\t\t #('focus','!disabled',self.FocusColor),\n\t\t\t\t\t\t #('!focus','active','!disabled',self.NoFocusMouseOverColor'),\n\t\t\t\t\t\t #('!focus','!active','!disabled',self.NoFocusNoMouseOverColor),\n\t\t\t\t\t\t ##('disabled','lightgray'),\n\t\t\t\t\t\t #],\n\t\t\t#selectbackground = [\n\t\t\t\t\t\t\t #('focus','!disabled',self.FocusColor),\n\t\t\t\t\t\t\t #('!focus','active','!disabled',self.NoFocusMouseOverColor),\n\t\t\t\t\t\t\t #('!focus','!active','!disabled',self.NoFocusNoMouseOverColor).\n\t\t\t\t\t\t\t ##('disabled','lightgray'),\n\t\t\t\t\t\t\t #],\n\t\t\tselectforeground = [\n\t\t\t\t\t\t\t ('!focus','black'),\n\t\t\t\t\t\t\t ('focus','white'),\n\t\t\t\t\t\t\t ],\n\t\t\t\t ) # close map\n\n\t\t#Style().map('TMenubutton',# This one is just for 'look and feel'\n\t\t\t#fieldbackground = [\n\t\t\t\t\t\t\t #('focus','!disabled',self.FocusColor),\n\t\t\t\t\t\t\t #('!focus','active','!disabled',self.NoFocusMouseOverColor),\n\t\t\t\t\t\t\t #('!focus','!active','!disabled',self.NoFocusNoMouseOverColor),\n\t\t\t\t\t\t\t ##('disabled','lightgray'),\n\t\t\t\t\t\t\t #],\n\t\t\t#foreground = [\n\t\t\t\t\t\t #('disabled','gray'),\n\t\t\t\t\t\t #('!disabled', 'black')\n\t\t\t\t\t\t #],\n\t\t\t#background = [\n\t\t\t\t\t\t #('focus','!disabled',self.FocusColor),\n\t\t\t\t\t\t #('!focus','active','!disabled',self.NoFocusMouseOverColor),\n\t\t\t\t\t\t #('!focus','!active','!disabled',self.NoFocusNoMouseOverColor),\n\t\t\t\t\t\t ##('disabled','lightgray'),\n\t\t\t\t\t\t #],\n\t\t\t#selectbackground = [\n\t\t\t\t\t\t\t #('focus','!disabled',self.FocusColor),\n\t\t\t\t\t\t\t #('!focus','active','!disabled',self.NoFocusMouseOverColor),\n\t\t\t\t\t\t\t #('!focus','!active','!disabled',self.NoFocusNoMouseOverColor),\n\t\t\t\t\t\t\t ##('disabled','lightgray'),\n\t\t\t\t\t\t\t #],\n\t\t\t#selectforeground = [\n\t\t\t\t\t\t\t #('!focus','black'),\n\t\t\t\t\t\t\t #('focus','white'),\n\t\t\t\t\t\t\t #],\n\t\t\t\t #) # close map\n\n\t\tStyle().map(\"Horizontal.TScale\",\n\t\t\ttroughcolor = [\n\t\t\t\t\t\t ('focus','!disabled',self.FocusColor),\n\t\t\t\t\t\t ('!focus','active','!disabled',self.NoFocusMouseOverColor),\n\t\t\t\t\t\t ('!focus','!active','!disabled',self.NoFocusNoMouseOverColor),\n\t\t\t\t\t\t ('disabled','lightgray'),\n\t\t\t\t\t\t ],\n\t\t\t\t ) # close map\n\n\t\tStyle().map(\"Vertical.TScale\",\n\t\t\ttroughcolor = [\n\t\t\t\t\t\t ('focus','!disabled',self.FocusColor),\n\t\t\t\t\t\t ('!focus','active','!disabled',self.NoFocusMouseOverColor),\n\t\t\t\t\t\t ('!focus','!active','!disabled',self.NoFocusNoMouseOverColor),\n\t\t\t\t\t\t ('disabled','lightgray'),\n\t\t\t\t\t\t ],\n\t\t\t\t ) # close map\n\n\t\tStyle().map(\"TMenu\",\n\t\t\tbackground = [\n\t\t\t\t\t\t ('focus','!disabled',self.FocusColor),\n\t\t\t\t\t\t ('!focus','active','!disabled',self.NoFocusMouseOverColor),\n\t\t\t\t\t\t ('!focus','!active','!disabled',self.NoFocusNoMouseOverColor),\n\t\t\t\t\t\t ('disabled','lightgray'),\n\t\t\t\t\t\t ],\n\t\t\t\t )","function_tokens":["def","SetControlMapping","(","self",")",":","#Style().configure('.', font=('Helvetica', 12)) # all","Style","(",")",".","configure","(","'RedMessage.TLabel'",",","font","=","(","'Arial'",",","10",",","\"italic\"",")",",","foreground","=","'red'",")","# These dont work since they're overriden by the map later on... ???","Style","(",")",".","configure","(","'Error.TEntry'",",","background","=","'red'",",","foreground","=","'white'",")","Style","(",")",".","configure","(","'OK.TEntry'",",","background","=","'white'",",","foreground","=","'black'",")","Style","(",")",".","configure","(","'DataLabel.TLabel'",",","foreground","=","'blue'",",","font","=","(","'Arial'",",","10",")",")","Style","(",")",".","configure","(","'StatusBar.TLabel'",",","background","=","self",".","FocusColor",",","relief","=","SUNKEN",")","Style","(",")",".","configure","(","'TMenu'",",","background","=","'white'",",","activeforeground","=","'lightblue'",")","Style","(",")",".","map","(","'TPanedwindow'",",","background","=","[","(","'!active'",",","'#f0f0ff'",")",",","]",",",")","Style","(",")",".","map","(","'TCombobox'",",","fieldbackground","=","[","(","'focus'",",","'!disabled'",",","self",".","FocusColor",")",",","(","'!focus'",",","'active'",",","'!disabled'",",","self",".","NoFocusMouseOverColor",")",",","(","'!focus'",",","'!active'",",","'!disabled'",",","self",".","NoFocusNoMouseOverColor",")",",","#('disabled','lightgray'), # Use foreground","]",",","foreground","=","[","(","'disabled'",",","'gray'",")",",","(","'!disabled'",",","'black'",")","]",",","selectbackground","=","[","(","'focus'",",","'!disabled'",",","self",".","FocusColor",")",",","(","'!focus'",",","'active'",",","'!disabled'",",","self",".","NoFocusMouseOverColor",")",",","(","'!focus'",",","'!active'",",","'!disabled'",",","self",".","NoFocusNoMouseOverColor",")",",","#('disabled','lightgray'),","]",",","selectforeground","=","[","(","'!focus'",",","'black'",")",",","(","'readonly'",",","'black'",")",",","(","'focus'",",","'black'",")",",","(","'disabled'",",","'black'",")",",","(","'!disabled'",",","'black'",")","]",",",")","# close map","Style","(",")",".","map","(","'TEntry'",",","# This one is just for 'look and feel'","fieldbackground","=","[","(","'focus'",",","'!disabled'",",","'!invalid'",",","self",".","FocusColor",")",",","(","'!focus'",",","'active'",",","'!disabled'",",","'!invalid'",",","self",".","NoFocusMouseOverColor",")",",","(","'!focus'",",","'!active'",",","'!disabled'",",","'!invalid'",",","self",".","NoFocusNoMouseOverColor",")",",","(","'invalid'",",","'#FF0000'",")","#('disabled','lightgray'),","]",",","foreground","=","[","(","'disabled'",",","'!invalid'",",","'gray'",")",",","(","'!disabled'",",","'!invalid'",",","'black'",")","#('invalid', self.NoFocusNoMouseOverColor)","]",",","#background = [","#('focus','!disabled',self.FocusColor),","#('!focus','active','!disabled',self.NoFocusMouseOverColor'),","#('!focus','!active','!disabled',self.NoFocusNoMouseOverColor),","##('disabled','lightgray'),","#],","#selectbackground = [","#('focus','!disabled',self.FocusColor),","#('!focus','active','!disabled',self.NoFocusMouseOverColor),","#('!focus','!active','!disabled',self.NoFocusNoMouseOverColor).","##('disabled','lightgray'),","#],","selectforeground","=","[","(","'!focus'",",","'black'",")",",","(","'focus'",",","'white'",")",",","]",",",")","# close map","#Style().map('TMenubutton',# This one is just for 'look and feel'","#fieldbackground = [","#('focus','!disabled',self.FocusColor),","#('!focus','active','!disabled',self.NoFocusMouseOverColor),","#('!focus','!active','!disabled',self.NoFocusNoMouseOverColor),","##('disabled','lightgray'),","#],","#foreground = [","#('disabled','gray'),","#('!disabled', 'black')","#],","#background = [","#('focus','!disabled',self.FocusColor),","#('!focus','active','!disabled',self.NoFocusMouseOverColor),","#('!focus','!active','!disabled',self.NoFocusNoMouseOverColor),","##('disabled','lightgray'),","#],","#selectbackground = [","#('focus','!disabled',self.FocusColor),","#('!focus','active','!disabled',self.NoFocusMouseOverColor),","#('!focus','!active','!disabled',self.NoFocusNoMouseOverColor),","##('disabled','lightgray'),","#],","#selectforeground = [","#('!focus','black'),","#('focus','white'),","#],","#) # close map","Style","(",")",".","map","(","\"Horizontal.TScale\"",",","troughcolor","=","[","(","'focus'",",","'!disabled'",",","self",".","FocusColor",")",",","(","'!focus'",",","'active'",",","'!disabled'",",","self",".","NoFocusMouseOverColor",")",",","(","'!focus'",",","'!active'",",","'!disabled'",",","self",".","NoFocusNoMouseOverColor",")",",","(","'disabled'",",","'lightgray'",")",",","]",",",")","# close map","Style","(",")",".","map","(","\"Vertical.TScale\"",",","troughcolor","=","[","(","'focus'",",","'!disabled'",",","self",".","FocusColor",")",",","(","'!focus'",",","'active'",",","'!disabled'",",","self",".","NoFocusMouseOverColor",")",",","(","'!focus'",",","'!active'",",","'!disabled'",",","self",".","NoFocusNoMouseOverColor",")",",","(","'disabled'",",","'lightgray'",")",",","]",",",")","# close map","Style","(",")",".","map","(","\"TMenu\"",",","background","=","[","(","'focus'",",","'!disabled'",",","self",".","FocusColor",")",",","(","'!focus'",",","'active'",",","'!disabled'",",","self",".","NoFocusMouseOverColor",")",",","(","'!focus'",",","'!active'",",","'!disabled'",",","self",".","NoFocusNoMouseOverColor",")",",","(","'disabled'",",","'lightgray'",")",",","]",",",")"],"url":"https:\/\/github.com\/Billwilliams1952\/PiCameraApp\/blob\/61802b367d620aafb6b4e0bb84ea1ebd0dbd42c0\/Source\/Mapping.py#L52-L183"}
9
+ {"nwo":"Billwilliams1952\/PiCameraApp","sha":"61802b367d620aafb6b4e0bb84ea1ebd0dbd42c0","path":"Source\/PiCameraApp.py","language":"python","identifier":"PiCameraApp.LoadImageFromStream","parameters":"( self, zoom )","argument_list":"","return_statement":"","docstring":"Implement Record Sequence","docstring_summary":"Implement Record Sequence","docstring_tokens":["Implement","Record","Sequence"],"function":"def LoadImageFromStream ( self, zoom ):\n\t\tif self.photo: del self.photo\n\n\t\tself.pictureStream.seek(0)\n\t\tself.CurrentImage = PIL.Image.open(self.pictureStream)\n\t\t# https:\/\/pillow.readthedocs.io\/en\/3.1.x\/reference\/Image.html#the-image-class\n\t\tself.RawEXIFData = None\n\t\tif PreferencesDialog.DefaultPhotoFormat == 'jpeg':\n\t\t\tself.RawEXIFData = self.CurrentImage.info['exif']\t# Works!!!!\n\t\t\t#print ( self.RawEXIFData )\n\t\tself.CameraUtils.AddEXIFTags(self.CurrentImage)\n\t\tself.ShowHideImageAttributesPane(self.viewImageAttributesPane.get())\n\n\t\t# resize what's displayed if user used Ctrl+mousewheel\n\t\tsize = self.CurrentImage.size\n\t\tif size[0] <= 1024 and size[1] <= 768:\t# hold max zoom level\n\t\t\twidth = int(zoom*size[0])\n\t\t\theight = int(zoom*size[1])\n\t\t\tif width <= 1024 and height <= 768:\n\t\t\t\tself.CurrentImage = self.CurrentImage.resize((width,height),PIL.Image.ANTIALIAS)\n\t\tself.CurrentImageSize = self.CurrentImage.size\n\n\t\t# Convert to canvas compatible format and store on canvas\n\t\tself.photo = ImageTk.PhotoImage(self.CurrentImage)\n\t\tself.photoCanvas.delete(\"pic\")\n\t\tself.photoCanvas.create_image(0,0,image=self.photo,anchor='nw',tags=('pic'))\n\t\tself.photoCanvas.config(scrollregion=self.photoCanvas.bbox(ALL))\n\t\tself.photoCanvas.tag_raise(\"objs\") # raise Z order of cursors to topmost\n\t\t'''\n\t\t\tImplement Record Sequence\n\t\t'''","function_tokens":["def","LoadImageFromStream","(","self",",","zoom",")",":","if","self",".","photo",":","del","self",".","photo","self",".","pictureStream",".","seek","(","0",")","self",".","CurrentImage","=","PIL",".","Image",".","open","(","self",".","pictureStream",")","# https:\/\/pillow.readthedocs.io\/en\/3.1.x\/reference\/Image.html#the-image-class","self",".","RawEXIFData","=","None","if","PreferencesDialog",".","DefaultPhotoFormat","==","'jpeg'",":","self",".","RawEXIFData","=","self",".","CurrentImage",".","info","[","'exif'","]","# Works!!!!","#print ( self.RawEXIFData )","self",".","CameraUtils",".","AddEXIFTags","(","self",".","CurrentImage",")","self",".","ShowHideImageAttributesPane","(","self",".","viewImageAttributesPane",".","get","(",")",")","# resize what's displayed if user used Ctrl+mousewheel","size","=","self",".","CurrentImage",".","size","if","size","[","0","]","<=","1024","and","size","[","1","]","<=","768",":","# hold max zoom level","width","=","int","(","zoom","*","size","[","0","]",")","height","=","int","(","zoom","*","size","[","1","]",")","if","width","<=","1024","and","height","<=","768",":","self",".","CurrentImage","=","self",".","CurrentImage",".","resize","(","(","width",",","height",")",",","PIL",".","Image",".","ANTIALIAS",")","self",".","CurrentImageSize","=","self",".","CurrentImage",".","size","# Convert to canvas compatible format and store on canvas","self",".","photo","=","ImageTk",".","PhotoImage","(","self",".","CurrentImage",")","self",".","photoCanvas",".","delete","(","\"pic\"",")","self",".","photoCanvas",".","create_image","(","0",",","0",",","image","=","self",".","photo",",","anchor","=","'nw'",",","tags","=","(","'pic'",")",")","self",".","photoCanvas",".","config","(","scrollregion","=","self",".","photoCanvas",".","bbox","(","ALL",")",")","self",".","photoCanvas",".","tag_raise","(","\"objs\"",")","# raise Z order of cursors to topmost"],"url":"https:\/\/github.com\/Billwilliams1952\/PiCameraApp\/blob\/61802b367d620aafb6b4e0bb84ea1ebd0dbd42c0\/Source\/PiCameraApp.py#L755-L785"}
10
+ {"nwo":"Billwilliams1952\/PiCameraApp","sha":"61802b367d620aafb6b4e0bb84ea1ebd0dbd42c0","path":"Source\/PiCameraApp.py","language":"python","identifier":"PiCameraApp.LoseFocus","parameters":"( self, event )","argument_list":"","return_statement":"","docstring":"The Combobox is a problem.\n\t\tCould save last two entries... if Combobox, Labelframe, Tk...\n\t\tNO! this could be the Topwindow losing focus while the\n\t\tCombobox has the focus. The same effect\n\t\tAlso, the nesting may vary based on where the Combobox is in\n\t\tthe hierarcy. What I really want is to capture the <B1-Motion>\n\t\ton the TopWindow titlebar - OR - get the widget ID to the\n\t\tCombobox Toplevel dropdown window.","docstring_summary":"The Combobox is a problem.\n\t\tCould save last two entries... if Combobox, Labelframe, Tk...\n\t\tNO! this could be the Topwindow losing focus while the\n\t\tCombobox has the focus. The same effect\n\t\tAlso, the nesting may vary based on where the Combobox is in\n\t\tthe hierarcy. What I really want is to capture the <B1-Motion>\n\t\ton the TopWindow titlebar - OR - get the widget ID to the\n\t\tCombobox Toplevel dropdown window.","docstring_tokens":["The","Combobox","is","a","problem",".","Could","save","last","two","entries","...","if","Combobox","Labelframe","Tk","...","NO!","this","could","be","the","Topwindow","losing","focus","while","the","Combobox","has","the","focus",".","The","same","effect","Also","the","nesting","may","vary","based","on","where","the","Combobox","is","in","the","hierarcy",".","What","I","really","want","is","to","capture","the","<B1","-","Motion",">","on","the","TopWindow","titlebar","-","OR","-","get","the","widget","ID","to","the","Combobox","Toplevel","dropdown","window","."],"function":"def LoseFocus ( self, event ):\n\t\t'''\n\t\t\t\t\t\t\tThe Combobox is a problem.\n\t\tCould save last two entries... if Combobox, Labelframe, Tk...\n\t\tNO! this could be the Topwindow losing focus while the\n\t\tCombobox has the focus. The same effect\n\t\tAlso, the nesting may vary based on where the Combobox is in\n\t\tthe hierarcy. What I really want is to capture the <B1-Motion>\n\t\ton the TopWindow titlebar - OR - get the widget ID to the\n\t\tCombobox Toplevel dropdown window.\n\t\t'''\n\t\tif self.camera.preview and not self.AlwaysPreview and \\\n\t\t\tevent.widget.winfo_class().lower() == 'tk' and \\\n\t\t\tself.root.attributes(\"-topmost\") == 0: # TopMost window hack\n\t\t\tif self.ShowOnScreen.get() == False:\n\t\t\t\tself.camera.preview.alpha = 0\n\t\t\tself.ImageCanvas.itemconfigure('nopreview',state='normal')","function_tokens":["def","LoseFocus","(","self",",","event",")",":","if","self",".","camera",".","preview","and","not","self",".","AlwaysPreview","and","event",".","widget",".","winfo_class","(",")",".","lower","(",")","==","'tk'","and","self",".","root",".","attributes","(","\"-topmost\"",")","==","0",":","# TopMost window hack","if","self",".","ShowOnScreen",".","get","(",")","==","False",":","self",".","camera",".","preview",".","alpha","=","0","self",".","ImageCanvas",".","itemconfigure","(","'nopreview'",",","state","=","'normal'",")"],"url":"https:\/\/github.com\/Billwilliams1952\/PiCameraApp\/blob\/61802b367d620aafb6b4e0bb84ea1ebd0dbd42c0\/Source\/PiCameraApp.py#L967-L983"}
11
+ {"nwo":"Billwilliams1952\/PiCameraApp","sha":"61802b367d620aafb6b4e0bb84ea1ebd0dbd42c0","path":"Source\/PreferencesDialog.py","language":"python","identifier":"General.BuildPage","parameters":"( self )","argument_list":"","return_statement":"","docstring":"Configuration files in python\n\t\tThere are several ways to do this depending on the file format required.\n\t\tConfigParser [.ini format]\n\t\tWrite a file like so:\n\t\t\tfrom ConfigParser import SafeConfigParser\n\t\t\tconfig = SafeConfigParser()\n\t\t\tconfig.read('config.ini')\n\t\t\tconfig.add_section('main')\n\t\t\tconfig.set('main', 'key1', 'value1')\n\t\t\tconfig.set('main', 'key2', 'value2')\n\t\t\tconfig.set('main', 'key3', 'value3')","docstring_summary":"Configuration files in python\n\t\tThere are several ways to do this depending on the file format required.\n\t\tConfigParser [.ini format]\n\t\tWrite a file like so:\n\t\t\tfrom ConfigParser import SafeConfigParser\n\t\t\tconfig = SafeConfigParser()\n\t\t\tconfig.read('config.ini')\n\t\t\tconfig.add_section('main')\n\t\t\tconfig.set('main', 'key1', 'value1')\n\t\t\tconfig.set('main', 'key2', 'value2')\n\t\t\tconfig.set('main', 'key3', 'value3')","docstring_tokens":["Configuration","files","in","python","There","are","several","ways","to","do","this","depending","on","the","file","format","required",".","ConfigParser","[",".","ini","format","]","Write","a","file","like","so",":","from","ConfigParser","import","SafeConfigParser","config","=","SafeConfigParser","()","config",".","read","(","config",".","ini",")","config",".","add_section","(","main",")","config",".","set","(","main","key1","value1",")","config",".","set","(","main","key2","value2",")","config",".","set","(","main","key3","value3",")"],"function":"def BuildPage ( self ):\n\t\t# Setup default folder to save pictures and videos\n\t\tf = MyLabelFrame(self,'Set default directories',0,0)\n\n\t\tself.iconCameraBig = PIL.Image.open('Assets\/camera-icon.png')\n\t\tself.iconCameraBig = ImageTk.PhotoImage(self.iconCameraBig.resize((22,22),Image.ANTIALIAS))\n\t\tself.iconVideoBig = PIL.Image.open('Assets\/video-icon-b.png')\n\t\tself.iconVideoBig = ImageTk.PhotoImage(self.iconVideoBig.resize((22,22),Image.ANTIALIAS))\n\t\tself.iconFiles = PIL.Image.open('Assets\/files.png')\n\t\tself.iconFiles = ImageTk.PhotoImage(self.iconFiles.resize((22,22),Image.ANTIALIAS))\n\n\t\tb = ttk.Button(f,text=\"Photos...\",image=self.iconCameraBig,compound='left',\n\t\t\tcommand=self.SelectPhotoDirectory,width=7)\n\t\tb.grid(row=0,column=0,sticky='W',pady=(5,5))\n\t\tToolTip(b,6000)\n\t\tself.PhotoDirLabel = Label(f,foreground='#0000FF',\n\t\t\ttext=PreferencesDialog.DefaultPhotoDir,anchor=W)\n\t\tself.PhotoDirLabel.grid(row=0,column=1,sticky='EW',padx=10);\n\t\tToolTip(self.PhotoDirLabel,6001)\n\n\t\tb = ttk.Button(f,text=\"Videos...\",image=self.iconVideoBig,compound='left',\n\t\t\tcommand=self.SelectVideoDirectory,width=7)\n\t\tb.grid(row=1,column=0,sticky='W')\n\t\tToolTip(b,6002)\n\t\tself.VideoDirLabel = Label(f,foreground='#0000FF',\n\t\t\ttext=PreferencesDialog.DefaultVideoDir,anchor=W)\n\t\tself.VideoDirLabel.grid(row=1,column=1,sticky='EW',padx=10);\n\t\tToolTip(self.VideoDirLabel,6003)\n\n\t\tb = ttk.Button(f,text=\"Files...\",image=self.iconFiles,compound='left',\n\t\t\tcommand=self.SelectFilesDirectory,width=7)\n\t\tb.grid(row=2,column=0,sticky='W',pady=(5,5))\n\t\tToolTip(b,6004)\n\t\tself.FilesDirLabel = Label(f,foreground='#0000FF',\n\t\t\ttext=PreferencesDialog.DefaultFilesDir,anchor=W)\n\t\tself.FilesDirLabel.grid(row=2,column=1,sticky='EW',padx=10);\n\t\tToolTip(self.FilesDirLabel,6005)\n\n\t\tf = MyLabelFrame(self,'Photo\/Video capture formats',1,0)\n\n\t\tttk.Label(f,text='Photo capture format',padding=(5,5,5,5)) \\\n\t\t\t.grid(row=0,column=0,sticky='W')\n\t\tself.photoCaptureFormatCombo = Combobox(f,height=15,width=8,\n\t\t\tstate='readonly')#,width=15)\n\t\tself.photoCaptureFormatCombo.grid(row=0,column=1,sticky='EW')\n\t\tself.photoFormats = ['jpeg','png','bmp',\n\t\t\t'gif','yuv','rgb','rgba','bgr','bgra','raw']\n\t\tself.photoCaptureFormatCombo['values'] = self.photoFormats\n\t\tself.photoCaptureFormatCombo.current( \\\n\t\t\tself.photoFormats.index(PreferencesDialog.DefaultPhotoFormat))\n\t\tself.photoCaptureFormatCombo.bind('<<ComboboxSelected>>',\n\t\t\tself.photoCaptureFormatChanged)\n\t\tToolTip(self.photoCaptureFormatCombo, msg=6010)\n\t\tself.ModFormatParams = ttk.Button(f,text='Params...',\n\t\t\tcommand=self.ModifyFormatParamPressed,\n\t\t\tunderline=0,padding=(5,3,5,3),width=8)\n\t\tself.ModFormatParams.grid(row=0,column=2,sticky='W',padx=5)\n\t\tToolTip(self.ModFormatParams, msg=6011)\n\n\t\tttk.Label(f,text='Video capture format',padding=(5,5,5,5)) \\\n\t\t\t.grid(row=1,column=0,sticky='W')\n\t\tself.VideoCaptureFormatCombo = Combobox(f,height=15,width=8,\n\t\t\tstate='readonly')#,width=15)\n\t\tself.VideoCaptureFormatCombo.grid(row=1,column=1,sticky='EW')\n\t\tself.videoFormats = ['h264','mjpeg','yuv',\n\t\t\t'rgb','rgba','bgr','bgra']\n\t\tself.VideoCaptureFormatCombo['values'] = self.videoFormats\n\t\tself.VideoCaptureFormatCombo.current( \\\n\t\t\tself.videoFormats.index(PreferencesDialog.DefaultVideoFormat))\n\t\tself.VideoCaptureFormatCombo.bind('<<ComboboxSelected>>',\n\t\t\tself.VideoCaptureFormatChanged)\n\t\tToolTip(self.VideoCaptureFormatCombo,6020)\n\t\tself.ModVideoFormatParams = ttk.Button(f,text='Params...',\n\t\t\tcommand=self.ModifyVideoFormatParamPressed,\n\t\t\tunderline=0,padding=(5,3,5,3),width=8)\n\t\tself.ModVideoFormatParams.grid(row=1,column=2,sticky='W',padx=5)\n\t\tToolTip(self.ModVideoFormatParams,6021)\n\t\t# Save \/ Restore camera settings? This may be a bit to do\n\n\t\tf = MyLabelFrame(self,'Photo\/Video naming',2,0)\n\t\tLabel(f,text='Timestamp format:') \\\n\t\t\t.grid(row=0,column=0,sticky='W')\n\t\tokCmd = (self.register(self.ValidateTimestamp),'%P')\n\t\tself.TimeStamp = MyStringVar(PreferencesDialog.DefaultTimestampFormat)\n\t\te = Entry(f,width=20,validate='all',\n\t\t\ttextvariable=self.TimeStamp)\n\t\te.grid(row=0,column=1,sticky='W')\n\t\tToolTip(e,6050)\n\n\t\timage = PIL.Image.open('Assets\/help.png')\n\t\tself.helpimage = ImageTk.PhotoImage(image.resize((16,16)))\n\t\tb = ttk.Button(f,image=self.helpimage,width=10,\n\t\t\tcommand=self.FormatHelp,padding=(2,2,2,2))\n\t\tb.grid(row=0,column=2,padx=5)\n\t\tToolTip(b,6052)\n\n\t\tLabel(f,text='Sample timestamp:').grid(row=1,column=0,sticky='W')\n\t\tself.TimestampLabel = MyStringVar(datetime.datetime.now() \\\n\t\t\t.strftime(PreferencesDialog.DefaultTimestampFormat))\n\t\tself.tsl = Label(f,textvariable=self.TimestampLabel,foreground='#0000FF')\n\t\tself.tsl.grid(row=1,column=1,columnspan=2,sticky='W')\n\t\tToolTip(self.tsl,6051)\n\t\tself.after(1000,self.UpdateTimestamp)\n\n\t\tself.PhotoTimestampVar = MyBooleanVar(PreferencesDialog.PhotoTimestamp)\n\t\tself.PhotoTimestamp = Checkbutton(f,text='Include timestamp in photo name',\n\t\t\tvariable=self.PhotoTimestampVar, command=self.PhotoTimestampChecked)\n\t\tself.PhotoTimestamp.grid(row=2,column=0,columnspan=2,sticky='W')\n\t\tToolTip(self.PhotoTimestamp,6060)\n\n\t\tself.VideoTimestampVar = MyBooleanVar(PreferencesDialog.VideoTimestamp)\n\t\tself.VideoTimestamp = Checkbutton(f,text='Include timestamp in video name',\n\t\t\tvariable=self.VideoTimestampVar, command=self.VideoTimestampChecked)\n\t\tself.VideoTimestamp.grid(row=3,column=0,columnspan=2,sticky='W')\n\t\tToolTip(self.VideoTimestamp,6061)\n\n\t\te.config(validatecommand=okCmd)\n\t\t'''\n\t\tConfiguration files in python\n\t\tThere are several ways to do this depending on the file format required.\n\t\tConfigParser [.ini format]\n\t\tWrite a file like so:\n\t\t\tfrom ConfigParser import SafeConfigParser\n\t\t\tconfig = SafeConfigParser()\n\t\t\tconfig.read('config.ini')\n\t\t\tconfig.add_section('main')\n\t\t\tconfig.set('main', 'key1', 'value1')\n\t\t\tconfig.set('main', 'key2', 'value2')\n\t\t\tconfig.set('main', 'key3', 'value3')\n\t\t'''\n\t\tself.photoCaptureFormatChanged(None)\n\t\tself.VideoCaptureFormatChanged(None)","function_tokens":["def","BuildPage","(","self",")",":","# Setup default folder to save pictures and videos","f","=","MyLabelFrame","(","self",",","'Set default directories'",",","0",",","0",")","self",".","iconCameraBig","=","PIL",".","Image",".","open","(","'Assets\/camera-icon.png'",")","self",".","iconCameraBig","=","ImageTk",".","PhotoImage","(","self",".","iconCameraBig",".","resize","(","(","22",",","22",")",",","Image",".","ANTIALIAS",")",")","self",".","iconVideoBig","=","PIL",".","Image",".","open","(","'Assets\/video-icon-b.png'",")","self",".","iconVideoBig","=","ImageTk",".","PhotoImage","(","self",".","iconVideoBig",".","resize","(","(","22",",","22",")",",","Image",".","ANTIALIAS",")",")","self",".","iconFiles","=","PIL",".","Image",".","open","(","'Assets\/files.png'",")","self",".","iconFiles","=","ImageTk",".","PhotoImage","(","self",".","iconFiles",".","resize","(","(","22",",","22",")",",","Image",".","ANTIALIAS",")",")","b","=","ttk",".","Button","(","f",",","text","=","\"Photos...\"",",","image","=","self",".","iconCameraBig",",","compound","=","'left'",",","command","=","self",".","SelectPhotoDirectory",",","width","=","7",")","b",".","grid","(","row","=","0",",","column","=","0",",","sticky","=","'W'",",","pady","=","(","5",",","5",")",")","ToolTip","(","b",",","6000",")","self",".","PhotoDirLabel","=","Label","(","f",",","foreground","=","'#0000FF'",",","text","=","PreferencesDialog",".","DefaultPhotoDir",",","anchor","=","W",")","self",".","PhotoDirLabel",".","grid","(","row","=","0",",","column","=","1",",","sticky","=","'EW'",",","padx","=","10",")","ToolTip","(","self",".","PhotoDirLabel",",","6001",")","b","=","ttk",".","Button","(","f",",","text","=","\"Videos...\"",",","image","=","self",".","iconVideoBig",",","compound","=","'left'",",","command","=","self",".","SelectVideoDirectory",",","width","=","7",")","b",".","grid","(","row","=","1",",","column","=","0",",","sticky","=","'W'",")","ToolTip","(","b",",","6002",")","self",".","VideoDirLabel","=","Label","(","f",",","foreground","=","'#0000FF'",",","text","=","PreferencesDialog",".","DefaultVideoDir",",","anchor","=","W",")","self",".","VideoDirLabel",".","grid","(","row","=","1",",","column","=","1",",","sticky","=","'EW'",",","padx","=","10",")","ToolTip","(","self",".","VideoDirLabel",",","6003",")","b","=","ttk",".","Button","(","f",",","text","=","\"Files...\"",",","image","=","self",".","iconFiles",",","compound","=","'left'",",","command","=","self",".","SelectFilesDirectory",",","width","=","7",")","b",".","grid","(","row","=","2",",","column","=","0",",","sticky","=","'W'",",","pady","=","(","5",",","5",")",")","ToolTip","(","b",",","6004",")","self",".","FilesDirLabel","=","Label","(","f",",","foreground","=","'#0000FF'",",","text","=","PreferencesDialog",".","DefaultFilesDir",",","anchor","=","W",")","self",".","FilesDirLabel",".","grid","(","row","=","2",",","column","=","1",",","sticky","=","'EW'",",","padx","=","10",")","ToolTip","(","self",".","FilesDirLabel",",","6005",")","f","=","MyLabelFrame","(","self",",","'Photo\/Video capture formats'",",","1",",","0",")","ttk",".","Label","(","f",",","text","=","'Photo capture format'",",","padding","=","(","5",",","5",",","5",",","5",")",")",".","grid","(","row","=","0",",","column","=","0",",","sticky","=","'W'",")","self",".","photoCaptureFormatCombo","=","Combobox","(","f",",","height","=","15",",","width","=","8",",","state","=","'readonly'",")","#,width=15)","self",".","photoCaptureFormatCombo",".","grid","(","row","=","0",",","column","=","1",",","sticky","=","'EW'",")","self",".","photoFormats","=","[","'jpeg'",",","'png'",",","'bmp'",",","'gif'",",","'yuv'",",","'rgb'",",","'rgba'",",","'bgr'",",","'bgra'",",","'raw'","]","self",".","photoCaptureFormatCombo","[","'values'","]","=","self",".","photoFormats","self",".","photoCaptureFormatCombo",".","current","(","self",".","photoFormats",".","index","(","PreferencesDialog",".","DefaultPhotoFormat",")",")","self",".","photoCaptureFormatCombo",".","bind","(","'<<ComboboxSelected>>'",",","self",".","photoCaptureFormatChanged",")","ToolTip","(","self",".","photoCaptureFormatCombo",",","msg","=","6010",")","self",".","ModFormatParams","=","ttk",".","Button","(","f",",","text","=","'Params...'",",","command","=","self",".","ModifyFormatParamPressed",",","underline","=","0",",","padding","=","(","5",",","3",",","5",",","3",")",",","width","=","8",")","self",".","ModFormatParams",".","grid","(","row","=","0",",","column","=","2",",","sticky","=","'W'",",","padx","=","5",")","ToolTip","(","self",".","ModFormatParams",",","msg","=","6011",")","ttk",".","Label","(","f",",","text","=","'Video capture format'",",","padding","=","(","5",",","5",",","5",",","5",")",")",".","grid","(","row","=","1",",","column","=","0",",","sticky","=","'W'",")","self",".","VideoCaptureFormatCombo","=","Combobox","(","f",",","height","=","15",",","width","=","8",",","state","=","'readonly'",")","#,width=15)","self",".","VideoCaptureFormatCombo",".","grid","(","row","=","1",",","column","=","1",",","sticky","=","'EW'",")","self",".","videoFormats","=","[","'h264'",",","'mjpeg'",",","'yuv'",",","'rgb'",",","'rgba'",",","'bgr'",",","'bgra'","]","self",".","VideoCaptureFormatCombo","[","'values'","]","=","self",".","videoFormats","self",".","VideoCaptureFormatCombo",".","current","(","self",".","videoFormats",".","index","(","PreferencesDialog",".","DefaultVideoFormat",")",")","self",".","VideoCaptureFormatCombo",".","bind","(","'<<ComboboxSelected>>'",",","self",".","VideoCaptureFormatChanged",")","ToolTip","(","self",".","VideoCaptureFormatCombo",",","6020",")","self",".","ModVideoFormatParams","=","ttk",".","Button","(","f",",","text","=","'Params...'",",","command","=","self",".","ModifyVideoFormatParamPressed",",","underline","=","0",",","padding","=","(","5",",","3",",","5",",","3",")",",","width","=","8",")","self",".","ModVideoFormatParams",".","grid","(","row","=","1",",","column","=","2",",","sticky","=","'W'",",","padx","=","5",")","ToolTip","(","self",".","ModVideoFormatParams",",","6021",")","# Save \/ Restore camera settings? This may be a bit to do","f","=","MyLabelFrame","(","self",",","'Photo\/Video naming'",",","2",",","0",")","Label","(","f",",","text","=","'Timestamp format:'",")",".","grid","(","row","=","0",",","column","=","0",",","sticky","=","'W'",")","okCmd","=","(","self",".","register","(","self",".","ValidateTimestamp",")",",","'%P'",")","self",".","TimeStamp","=","MyStringVar","(","PreferencesDialog",".","DefaultTimestampFormat",")","e","=","Entry","(","f",",","width","=","20",",","validate","=","'all'",",","textvariable","=","self",".","TimeStamp",")","e",".","grid","(","row","=","0",",","column","=","1",",","sticky","=","'W'",")","ToolTip","(","e",",","6050",")","image","=","PIL",".","Image",".","open","(","'Assets\/help.png'",")","self",".","helpimage","=","ImageTk",".","PhotoImage","(","image",".","resize","(","(","16",",","16",")",")",")","b","=","ttk",".","Button","(","f",",","image","=","self",".","helpimage",",","width","=","10",",","command","=","self",".","FormatHelp",",","padding","=","(","2",",","2",",","2",",","2",")",")","b",".","grid","(","row","=","0",",","column","=","2",",","padx","=","5",")","ToolTip","(","b",",","6052",")","Label","(","f",",","text","=","'Sample timestamp:'",")",".","grid","(","row","=","1",",","column","=","0",",","sticky","=","'W'",")","self",".","TimestampLabel","=","MyStringVar","(","datetime",".","datetime",".","now","(",")",".","strftime","(","PreferencesDialog",".","DefaultTimestampFormat",")",")","self",".","tsl","=","Label","(","f",",","textvariable","=","self",".","TimestampLabel",",","foreground","=","'#0000FF'",")","self",".","tsl",".","grid","(","row","=","1",",","column","=","1",",","columnspan","=","2",",","sticky","=","'W'",")","ToolTip","(","self",".","tsl",",","6051",")","self",".","after","(","1000",",","self",".","UpdateTimestamp",")","self",".","PhotoTimestampVar","=","MyBooleanVar","(","PreferencesDialog",".","PhotoTimestamp",")","self",".","PhotoTimestamp","=","Checkbutton","(","f",",","text","=","'Include timestamp in photo name'",",","variable","=","self",".","PhotoTimestampVar",",","command","=","self",".","PhotoTimestampChecked",")","self",".","PhotoTimestamp",".","grid","(","row","=","2",",","column","=","0",",","columnspan","=","2",",","sticky","=","'W'",")","ToolTip","(","self",".","PhotoTimestamp",",","6060",")","self",".","VideoTimestampVar","=","MyBooleanVar","(","PreferencesDialog",".","VideoTimestamp",")","self",".","VideoTimestamp","=","Checkbutton","(","f",",","text","=","'Include timestamp in video name'",",","variable","=","self",".","VideoTimestampVar",",","command","=","self",".","VideoTimestampChecked",")","self",".","VideoTimestamp",".","grid","(","row","=","3",",","column","=","0",",","columnspan","=","2",",","sticky","=","'W'",")","ToolTip","(","self",".","VideoTimestamp",",","6061",")","e",".","config","(","validatecommand","=","okCmd",")","self",".","photoCaptureFormatChanged","(","None",")","self",".","VideoCaptureFormatChanged","(","None",")"],"url":"https:\/\/github.com\/Billwilliams1952\/PiCameraApp\/blob\/61802b367d620aafb6b4e0bb84ea1ebd0dbd42c0\/Source\/PreferencesDialog.py#L111-L242"}
BishopFox__rickmote.jsonl ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {"nwo":"BishopFox\/rickmote","sha":"2a8469657f9de7d6ee1d4cc65ce83235c1e582d9","path":"rickmote.py","language":"python","identifier":"matching_line","parameters":"(lines, keyword)","argument_list":"","return_statement":"return None","docstring":"Returns the first matching line in a list of lines. See match()","docstring_summary":"Returns the first matching line in a list of lines. See match()","docstring_tokens":["Returns","the","first","matching","line","in","a","list","of","lines",".","See","match","()"],"function":"def matching_line(lines, keyword):\n \"\"\"Returns the first matching line in a list of lines. See match()\"\"\"\n for line in lines:\n matching=match(line,keyword)\n if matching!=None:\n return matching\n return None","function_tokens":["def","matching_line","(","lines",",","keyword",")",":","for","line","in","lines",":","matching","=","match","(","line",",","keyword",")","if","matching","!=","None",":","return","matching","return","None"],"url":"https:\/\/github.com\/BishopFox\/rickmote\/blob\/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9\/rickmote.py#L68-L74"}
2
+ {"nwo":"BishopFox\/rickmote","sha":"2a8469657f9de7d6ee1d4cc65ce83235c1e582d9","path":"rickmote.py","language":"python","identifier":"match","parameters":"(line,keyword)","argument_list":"","return_statement":"","docstring":"If the first part of line (modulo blanks) matches keyword,\n returns the end of that line. Otherwise returns None","docstring_summary":"If the first part of line (modulo blanks) matches keyword,\n returns the end of that line. Otherwise returns None","docstring_tokens":["If","the","first","part","of","line","(","modulo","blanks",")","matches","keyword","returns","the","end","of","that","line",".","Otherwise","returns","None"],"function":"def match(line,keyword):\n \"\"\"If the first part of line (modulo blanks) matches keyword,\n returns the end of that line. Otherwise returns None\"\"\"\n line=line.lstrip()\n length=len(keyword)\n if line[:length] == keyword:\n return line[length:]\n else:\n return None","function_tokens":["def","match","(","line",",","keyword",")",":","line","=","line",".","lstrip","(",")","length","=","len","(","keyword",")","if","line","[",":","length","]","==","keyword",":","return","line","[","length",":","]","else",":","return","None"],"url":"https:\/\/github.com\/BishopFox\/rickmote\/blob\/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9\/rickmote.py#L76-L84"}
3
+ {"nwo":"BishopFox\/rickmote","sha":"2a8469657f9de7d6ee1d4cc65ce83235c1e582d9","path":"rickmote.py","language":"python","identifier":"parse_cell","parameters":"(cell)","argument_list":"","return_statement":"return parsed_cell","docstring":"Applies the rules to the bunch of text describing a cell and returns the\n corresponding dictionary","docstring_summary":"Applies the rules to the bunch of text describing a cell and returns the\n corresponding dictionary","docstring_tokens":["Applies","the","rules","to","the","bunch","of","text","describing","a","cell","and","returns","the","corresponding","dictionary"],"function":"def parse_cell(cell):\n \"\"\"Applies the rules to the bunch of text describing a cell and returns the\n corresponding dictionary\"\"\"\n parsed_cell={}\n for key in rules:\n rule=rules[key]\n parsed_cell.update({key:rule(cell)})\n return parsed_cell","function_tokens":["def","parse_cell","(","cell",")",":","parsed_cell","=","{","}","for","key","in","rules",":","rule","=","rules","[","key","]","parsed_cell",".","update","(","{","key",":","rule","(","cell",")","}",")","return","parsed_cell"],"url":"https:\/\/github.com\/BishopFox\/rickmote\/blob\/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9\/rickmote.py#L86-L93"}
4
+ {"nwo":"BishopFox\/rickmote","sha":"2a8469657f9de7d6ee1d4cc65ce83235c1e582d9","path":"pychromecast\/dial.py","language":"python","identifier":"start_app","parameters":"(host, app_id, data=None)","argument_list":"","return_statement":"","docstring":"Starts an application.\n\n If your TV is not on will turn it on unless app_id == APP_ID_HOME.","docstring_summary":"Starts an application.","docstring_tokens":["Starts","an","application","."],"function":"def start_app(host, app_id, data=None):\n \"\"\" Starts an application.\n\n If your TV is not on will turn it on unless app_id == APP_ID_HOME. \"\"\"\n\n if data is None:\n data = {\"\": \"\"}\n\n CC_SESSION.post(_craft_app_url(host, app_id), data=data)","function_tokens":["def","start_app","(","host",",","app_id",",","data","=","None",")",":","if","data","is","None",":","data","=","{","\"\"",":","\"\"","}","CC_SESSION",".","post","(","_craft_app_url","(","host",",","app_id",")",",","data","=","data",")"],"url":"https:\/\/github.com\/BishopFox\/rickmote\/blob\/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9\/pychromecast\/dial.py#L21-L29"}
5
+ {"nwo":"BishopFox\/rickmote","sha":"2a8469657f9de7d6ee1d4cc65ce83235c1e582d9","path":"pychromecast\/dial.py","language":"python","identifier":"quit_app","parameters":"(host, app_id=None)","argument_list":"","return_statement":"","docstring":"Quits specified application if it is running.\n If no app_id specified will quit current running app.","docstring_summary":"Quits specified application if it is running.\n If no app_id specified will quit current running app.","docstring_tokens":["Quits","specified","application","if","it","is","running",".","If","no","app_id","specified","will","quit","current","running","app","."],"function":"def quit_app(host, app_id=None):\n \"\"\" Quits specified application if it is running.\n If no app_id specified will quit current running app. \"\"\"\n\n if not app_id:\n status = get_app_status(host)\n\n if status:\n app_id = status.app_id\n\n if app_id:\n CC_SESSION.delete(_craft_app_url(host, app_id))","function_tokens":["def","quit_app","(","host",",","app_id","=","None",")",":","if","not","app_id",":","status","=","get_app_status","(","host",")","if","status",":","app_id","=","status",".","app_id","if","app_id",":","CC_SESSION",".","delete","(","_craft_app_url","(","host",",","app_id",")",")"],"url":"https:\/\/github.com\/BishopFox\/rickmote\/blob\/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9\/pychromecast\/dial.py#L32-L43"}
6
+ {"nwo":"BishopFox\/rickmote","sha":"2a8469657f9de7d6ee1d4cc65ce83235c1e582d9","path":"pychromecast\/dial.py","language":"python","identifier":"reboot","parameters":"(host)","argument_list":"","return_statement":"","docstring":"Reboots the chromecast.","docstring_summary":"Reboots the chromecast.","docstring_tokens":["Reboots","the","chromecast","."],"function":"def reboot(host):\n \"\"\" Reboots the chromecast. \"\"\"\n CC_SESSION.post(FORMAT_BASE_URL.format(host) + \"\/setup\/reboot\",\n data='{\"params\":\"now\"}')","function_tokens":["def","reboot","(","host",")",":","CC_SESSION",".","post","(","FORMAT_BASE_URL",".","format","(","host",")","+","\"\/setup\/reboot\"",",","data","=","'{\"params\":\"now\"}'",")"],"url":"https:\/\/github.com\/BishopFox\/rickmote\/blob\/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9\/pychromecast\/dial.py#L46-L49"}
7
+ {"nwo":"BishopFox\/rickmote","sha":"2a8469657f9de7d6ee1d4cc65ce83235c1e582d9","path":"pychromecast\/dial.py","language":"python","identifier":"get_device_status","parameters":"(host)","argument_list":"","return_statement":"","docstring":"Returns the device status as a named tuple.","docstring_summary":"Returns the device status as a named tuple.","docstring_tokens":["Returns","the","device","status","as","a","named","tuple","."],"function":"def get_device_status(host):\n \"\"\" Returns the device status as a named tuple. \"\"\"\n\n try:\n req = CC_SESSION.get(\n FORMAT_BASE_URL.format(host) + \"\/ssdp\/device-desc.xml\")\n\n status_el = ET.fromstring(req.text.encode(\"UTF-8\"))\n\n device_info_el = status_el.find(XML_NS_UPNP_DEVICE + \"device\")\n api_version_el = status_el.find(XML_NS_UPNP_DEVICE + \"specVersion\")\n\n friendly_name = _read_xml_element(device_info_el, XML_NS_UPNP_DEVICE,\n \"friendlyName\", \"Unknown Chromecast\")\n model_name = _read_xml_element(device_info_el, XML_NS_UPNP_DEVICE,\n \"modelName\", \"Unknown model name\")\n manufacturer = _read_xml_element(device_info_el, XML_NS_UPNP_DEVICE,\n \"manufacturer\",\n \"Unknown manufacturer\")\n\n api_version = (int(_read_xml_element(api_version_el,\n XML_NS_UPNP_DEVICE, \"major\", -1)),\n int(_read_xml_element(api_version_el,\n XML_NS_UPNP_DEVICE, \"minor\", -1)))\n\n return DeviceStatus(friendly_name, model_name, manufacturer,\n api_version)\n\n except (requests.exceptions.RequestException, ET.ParseError):\n return None","function_tokens":["def","get_device_status","(","host",")",":","try",":","req","=","CC_SESSION",".","get","(","FORMAT_BASE_URL",".","format","(","host",")","+","\"\/ssdp\/device-desc.xml\"",")","status_el","=","ET",".","fromstring","(","req",".","text",".","encode","(","\"UTF-8\"",")",")","device_info_el","=","status_el",".","find","(","XML_NS_UPNP_DEVICE","+","\"device\"",")","api_version_el","=","status_el",".","find","(","XML_NS_UPNP_DEVICE","+","\"specVersion\"",")","friendly_name","=","_read_xml_element","(","device_info_el",",","XML_NS_UPNP_DEVICE",",","\"friendlyName\"",",","\"Unknown Chromecast\"",")","model_name","=","_read_xml_element","(","device_info_el",",","XML_NS_UPNP_DEVICE",",","\"modelName\"",",","\"Unknown model name\"",")","manufacturer","=","_read_xml_element","(","device_info_el",",","XML_NS_UPNP_DEVICE",",","\"manufacturer\"",",","\"Unknown manufacturer\"",")","api_version","=","(","int","(","_read_xml_element","(","api_version_el",",","XML_NS_UPNP_DEVICE",",","\"major\"",",","-","1",")",")",",","int","(","_read_xml_element","(","api_version_el",",","XML_NS_UPNP_DEVICE",",","\"minor\"",",","-","1",")",")",")","return","DeviceStatus","(","friendly_name",",","model_name",",","manufacturer",",","api_version",")","except","(","requests",".","exceptions",".","RequestException",",","ET",".","ParseError",")",":","return","None"],"url":"https:\/\/github.com\/BishopFox\/rickmote\/blob\/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9\/pychromecast\/dial.py#L52-L81"}
8
+ {"nwo":"BishopFox\/rickmote","sha":"2a8469657f9de7d6ee1d4cc65ce83235c1e582d9","path":"pychromecast\/dial.py","language":"python","identifier":"get_app_status","parameters":"(host, app_id=None)","argument_list":"","return_statement":"","docstring":"Returns the status of the specified app\n or else the current running app.","docstring_summary":"Returns the status of the specified app\n or else the current running app.","docstring_tokens":["Returns","the","status","of","the","specified","app","or","else","the","current","running","app","."],"function":"def get_app_status(host, app_id=None):\n \"\"\" Returns the status of the specified app\n or else the current running app. \"\"\"\n # \/apps\/ will redirect to the active app\n url = (FORMAT_APP_PATH.format(host, app_id) if app_id\n else FORMAT_BASE_URL.format(host) + \"\/apps\/\")\n\n try:\n req = CC_SESSION.get(url)\n\n if req.status_code == 204:\n return None\n\n status_el = ET.fromstring(req.text.encode(\"UTF-8\"))\n options = status_el.find(XML_NS_DIAL + \"options\").attrib\n\n app_id = _read_xml_element(status_el, XML_NS_DIAL,\n \"name\", \"Unknown application\")\n\n state = _read_xml_element(status_el, XML_NS_DIAL,\n \"state\", \"unknown\")\n\n service_el = status_el.find(XML_NS_CAST + \"servicedata\")\n\n if service_el is not None:\n service_url = _read_xml_element(service_el, XML_NS_CAST,\n \"connectionSvcURL\", None)\n\n protocols_el = service_el.find(XML_NS_CAST + \"protocols\")\n\n if protocols_el is not None:\n protocols = [el.text for el in protocols_el]\n else:\n protocols = []\n\n else:\n service_url = None\n protocols = []\n\n activity_el = status_el.find(XML_NS_CAST + \"activity-status\")\n\n if activity_el is not None:\n description = _read_xml_element(activity_el, XML_NS_CAST,\n \"description\", app_id)\n else:\n description = app_id\n\n return AppStatus(app_id, description, state,\n options, service_url, protocols)\n\n except (requests.exceptions.RequestException, ET.ParseError):\n return None","function_tokens":["def","get_app_status","(","host",",","app_id","=","None",")",":","# \/apps\/ will redirect to the active app","url","=","(","FORMAT_APP_PATH",".","format","(","host",",","app_id",")","if","app_id","else","FORMAT_BASE_URL",".","format","(","host",")","+","\"\/apps\/\"",")","try",":","req","=","CC_SESSION",".","get","(","url",")","if","req",".","status_code","==","204",":","return","None","status_el","=","ET",".","fromstring","(","req",".","text",".","encode","(","\"UTF-8\"",")",")","options","=","status_el",".","find","(","XML_NS_DIAL","+","\"options\"",")",".","attrib","app_id","=","_read_xml_element","(","status_el",",","XML_NS_DIAL",",","\"name\"",",","\"Unknown application\"",")","state","=","_read_xml_element","(","status_el",",","XML_NS_DIAL",",","\"state\"",",","\"unknown\"",")","service_el","=","status_el",".","find","(","XML_NS_CAST","+","\"servicedata\"",")","if","service_el","is","not","None",":","service_url","=","_read_xml_element","(","service_el",",","XML_NS_CAST",",","\"connectionSvcURL\"",",","None",")","protocols_el","=","service_el",".","find","(","XML_NS_CAST","+","\"protocols\"",")","if","protocols_el","is","not","None",":","protocols","=","[","el",".","text","for","el","in","protocols_el","]","else",":","protocols","=","[","]","else",":","service_url","=","None","protocols","=","[","]","activity_el","=","status_el",".","find","(","XML_NS_CAST","+","\"activity-status\"",")","if","activity_el","is","not","None",":","description","=","_read_xml_element","(","activity_el",",","XML_NS_CAST",",","\"description\"",",","app_id",")","else",":","description","=","app_id","return","AppStatus","(","app_id",",","description",",","state",",","options",",","service_url",",","protocols",")","except","(","requests",".","exceptions",".","RequestException",",","ET",".","ParseError",")",":","return","None"],"url":"https:\/\/github.com\/BishopFox\/rickmote\/blob\/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9\/pychromecast\/dial.py#L84-L135"}
9
+ {"nwo":"BishopFox\/rickmote","sha":"2a8469657f9de7d6ee1d4cc65ce83235c1e582d9","path":"pychromecast\/dial.py","language":"python","identifier":"_craft_app_url","parameters":"(host, app_id=None)","argument_list":"","return_statement":"return (FORMAT_APP_PATH.format(host, app_id) if app_id\n else FORMAT_BASE_URL.format(host))","docstring":"Helper method to create a ChromeCast url given\n a host and an optional app_id.","docstring_summary":"Helper method to create a ChromeCast url given\n a host and an optional app_id.","docstring_tokens":["Helper","method","to","create","a","ChromeCast","url","given","a","host","and","an","optional","app_id","."],"function":"def _craft_app_url(host, app_id=None):\n \"\"\" Helper method to create a ChromeCast url given\n a host and an optional app_id. \"\"\"\n return (FORMAT_APP_PATH.format(host, app_id) if app_id\n else FORMAT_BASE_URL.format(host))","function_tokens":["def","_craft_app_url","(","host",",","app_id","=","None",")",":","return","(","FORMAT_APP_PATH",".","format","(","host",",","app_id",")","if","app_id","else","FORMAT_BASE_URL",".","format","(","host",")",")"],"url":"https:\/\/github.com\/BishopFox\/rickmote\/blob\/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9\/pychromecast\/dial.py#L138-L142"}
10
+ {"nwo":"BishopFox\/rickmote","sha":"2a8469657f9de7d6ee1d4cc65ce83235c1e582d9","path":"pychromecast\/dial.py","language":"python","identifier":"_read_xml_element","parameters":"(element, xml_ns, tag_name, default=\"\")","argument_list":"","return_statement":"","docstring":"Helper method to read text from an element.","docstring_summary":"Helper method to read text from an element.","docstring_tokens":["Helper","method","to","read","text","from","an","element","."],"function":"def _read_xml_element(element, xml_ns, tag_name, default=\"\"):\n \"\"\" Helper method to read text from an element. \"\"\"\n try:\n return element.find(xml_ns + tag_name).text\n\n except AttributeError:\n return default","function_tokens":["def","_read_xml_element","(","element",",","xml_ns",",","tag_name",",","default","=","\"\"",")",":","try",":","return","element",".","find","(","xml_ns","+","tag_name",")",".","text","except","AttributeError",":","return","default"],"url":"https:\/\/github.com\/BishopFox\/rickmote\/blob\/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9\/pychromecast\/dial.py#L145-L151"}
11
+ {"nwo":"BishopFox\/rickmote","sha":"2a8469657f9de7d6ee1d4cc65ce83235c1e582d9","path":"pychromecast\/upnp.py","language":"python","identifier":"discover_chromecasts","parameters":"(max_devices=None, timeout=DISCOVER_TIMEOUT)","argument_list":"","return_statement":"return ips","docstring":"Sends a message over the network to discover Chromecasts and returns\n a list of found IP addresses.\n\n Inspired by Crimsdings\n https:\/\/github.com\/crimsdings\/ChromeCast\/blob\/master\/cc_discovery.py","docstring_summary":"Sends a message over the network to discover Chromecasts and returns\n a list of found IP addresses.","docstring_tokens":["Sends","a","message","over","the","network","to","discover","Chromecasts","and","returns","a","list","of","found","IP","addresses","."],"function":"def discover_chromecasts(max_devices=None, timeout=DISCOVER_TIMEOUT):\n \"\"\"\n Sends a message over the network to discover Chromecasts and returns\n a list of found IP addresses.\n\n Inspired by Crimsdings\n https:\/\/github.com\/crimsdings\/ChromeCast\/blob\/master\/cc_discovery.py\n \"\"\"\n ips = []\n\n calc_now = dt.datetime.now\n start = calc_now()\n\n try:\n sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n\n sock.sendto(SSDP_REQUEST.encode(\"ascii\"), (SSDP_ADDR, SSDP_PORT))\n\n sock.setblocking(0)\n\n while True:\n time_diff = calc_now() - start\n\n seconds_left = timeout - time_diff.seconds\n\n if seconds_left <= 0:\n return ips\n\n ready = select.select([sock], [], [], seconds_left)[0]\n\n if ready:\n response = sock.recv(1024).decode(\"ascii\")\n\n found_ip = found_st = None\n\n headers = response.split(\"\\r\\n\\r\\n\", 1)[0]\n\n for header in headers.split(\"\\r\\n\"):\n parts = header.split(\": \", 1)\n\n # Headers start with something like 'HTTP\/1.1 200 OK'\n # We cannot split that up in key-value pair, so skip\n if len(parts) != 2:\n continue\n\n key, value = parts\n\n if key == \"LOCATION\":\n url = urlparse.urlparse(value)\n\n found_ip = url.hostname\n\n elif key == \"ST\":\n found_st = value\n\n if found_st == SSDP_ST and found_ip:\n ips.append(found_ip)\n\n if max_devices and len(ips) == max_devices:\n return ips\n\n except socket.error:\n logging.getLogger(__name__).exception(\n \"Socket error while discovering Chromecasts\")\n\n finally:\n sock.close()\n\n return ips","function_tokens":["def","discover_chromecasts","(","max_devices","=","None",",","timeout","=","DISCOVER_TIMEOUT",")",":","ips","=","[","]","calc_now","=","dt",".","datetime",".","now","start","=","calc_now","(",")","try",":","sock","=","socket",".","socket","(","socket",".","AF_INET",",","socket",".","SOCK_DGRAM",")","sock",".","sendto","(","SSDP_REQUEST",".","encode","(","\"ascii\"",")",",","(","SSDP_ADDR",",","SSDP_PORT",")",")","sock",".","setblocking","(","0",")","while","True",":","time_diff","=","calc_now","(",")","-","start","seconds_left","=","timeout","-","time_diff",".","seconds","if","seconds_left","<=","0",":","return","ips","ready","=","select",".","select","(","[","sock","]",",","[","]",",","[","]",",","seconds_left",")","[","0","]","if","ready",":","response","=","sock",".","recv","(","1024",")",".","decode","(","\"ascii\"",")","found_ip","=","found_st","=","None","headers","=","response",".","split","(","\"\\r\\n\\r\\n\"",",","1",")","[","0","]","for","header","in","headers",".","split","(","\"\\r\\n\"",")",":","parts","=","header",".","split","(","\": \"",",","1",")","# Headers start with something like 'HTTP\/1.1 200 OK'","# We cannot split that up in key-value pair, so skip","if","len","(","parts",")","!=","2",":","continue","key",",","value","=","parts","if","key","==","\"LOCATION\"",":","url","=","urlparse",".","urlparse","(","value",")","found_ip","=","url",".","hostname","elif","key","==","\"ST\"",":","found_st","=","value","if","found_st","==","SSDP_ST","and","found_ip",":","ips",".","append","(","found_ip",")","if","max_devices","and","len","(","ips",")","==","max_devices",":","return","ips","except","socket",".","error",":","logging",".","getLogger","(","__name__",")",".","exception","(","\"Socket error while discovering Chromecasts\"",")","finally",":","sock",".","close","(",")","return","ips"],"url":"https:\/\/github.com\/BishopFox\/rickmote\/blob\/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9\/pychromecast\/upnp.py#L30-L98"}
12
+ {"nwo":"BishopFox\/rickmote","sha":"2a8469657f9de7d6ee1d4cc65ce83235c1e582d9","path":"pychromecast\/config.py","language":"python","identifier":"get_possible_app_ids","parameters":"()","argument_list":"","return_statement":"","docstring":"Returns all possible app ids.","docstring_summary":"Returns all possible app ids.","docstring_tokens":["Returns","all","possible","app","ids","."],"function":"def get_possible_app_ids():\n \"\"\" Returns all possible app ids. \"\"\"\n\n try:\n req = requests.get(\n \"https:\/\/clients3.google.com\/cast\/chromecast\/device\/baseconfig\")\n data = json.loads(req.text[4:])\n\n return [app['app_id'] for app in data['applications']] + \\\n data[\"enabled_app_ids\"]\n\n except ValueError:\n # If json fails to parse\n return []","function_tokens":["def","get_possible_app_ids","(",")",":","try",":","req","=","requests",".","get","(","\"https:\/\/clients3.google.com\/cast\/chromecast\/device\/baseconfig\"",")","data","=","json",".","loads","(","req",".","text","[","4",":","]",")","return","[","app","[","'app_id'","]","for","app","in","data","[","'applications'","]","]","+","data","[","\"enabled_app_ids\"","]","except","ValueError",":","# If json fails to parse","return","[","]"],"url":"https:\/\/github.com\/BishopFox\/rickmote\/blob\/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9\/pychromecast\/config.py#L34-L47"}
13
+ {"nwo":"BishopFox\/rickmote","sha":"2a8469657f9de7d6ee1d4cc65ce83235c1e582d9","path":"pychromecast\/config.py","language":"python","identifier":"get_app_config","parameters":"(app_id)","argument_list":"","return_statement":"","docstring":"Get specific configuration for 'app_id'.","docstring_summary":"Get specific configuration for 'app_id'.","docstring_tokens":["Get","specific","configuration","for","app_id","."],"function":"def get_app_config(app_id):\n \"\"\" Get specific configuration for 'app_id'. \"\"\"\n try:\n req = requests.get(\n (\"https:\/\/clients3.google.com\/\"\n \"cast\/chromecast\/device\/app?a={}\").format(app_id))\n\n return json.loads(req.text[4:]) if req.status_code == 200 else {}\n\n except ValueError:\n # If json fails to parse\n return {}","function_tokens":["def","get_app_config","(","app_id",")",":","try",":","req","=","requests",".","get","(","(","\"https:\/\/clients3.google.com\/\"","\"cast\/chromecast\/device\/app?a={}\"",")",".","format","(","app_id",")",")","return","json",".","loads","(","req",".","text","[","4",":","]",")","if","req",".","status_code","==","200","else","{","}","except","ValueError",":","# If json fails to parse","return","{","}"],"url":"https:\/\/github.com\/BishopFox\/rickmote\/blob\/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9\/pychromecast\/config.py#L50-L61"}
14
+ {"nwo":"BishopFox\/rickmote","sha":"2a8469657f9de7d6ee1d4cc65ce83235c1e582d9","path":"pychromecast\/websocket.py","language":"python","identifier":"create_websocket_client","parameters":"(app_status)","argument_list":"","return_statement":"return client","docstring":"Creates and returns a RAMP client based on the supplied app status.\n Will return None if RAMP client is not supported.\n Will raise ValueError if unable to retrieve the websocket url.","docstring_summary":"Creates and returns a RAMP client based on the supplied app status.\n Will return None if RAMP client is not supported.\n Will raise ValueError if unable to retrieve the websocket url.","docstring_tokens":["Creates","and","returns","a","RAMP","client","based","on","the","supplied","app","status",".","Will","return","None","if","RAMP","client","is","not","supported",".","Will","raise","ValueError","if","unable","to","retrieve","the","websocket","url","."],"function":"def create_websocket_client(app_status):\n \"\"\"\n Creates and returns a RAMP client based on the supplied app status.\n Will return None if RAMP client is not supported.\n Will raise ValueError if unable to retrieve the websocket url.\n \"\"\"\n\n # Check if current app has no service url or no protocols.\n if not app_status.service_url or not app_status.service_protocols:\n return None\n\n req = requests.post(app_status.service_url,\n data=\"{}\".encode(\"ascii\"),\n headers={\"Content-Type\": \"application\/json\"})\n\n if req.status_code != 200:\n raise error.ConnectionError(\n \"Could not retrieve websocket url ({}).\".format(req.status_code))\n\n conn_data = json.loads(req.text)\n\n client = ChromecastWebSocketClient(conn_data['URL'],\n app_status.service_protocols)\n\n client.connect()\n\n atexit.register(_clean_open_clients)\n\n return client","function_tokens":["def","create_websocket_client","(","app_status",")",":","# Check if current app has no service url or no protocols.","if","not","app_status",".","service_url","or","not","app_status",".","service_protocols",":","return","None","req","=","requests",".","post","(","app_status",".","service_url",",","data","=","\"{}\"",".","encode","(","\"ascii\"",")",",","headers","=","{","\"Content-Type\"",":","\"application\/json\"","}",")","if","req",".","status_code","!=","200",":","raise","error",".","ConnectionError","(","\"Could not retrieve websocket url ({}).\"",".","format","(","req",".","status_code",")",")","conn_data","=","json",".","loads","(","req",".","text",")","client","=","ChromecastWebSocketClient","(","conn_data","[","'URL'","]",",","app_status",".","service_protocols",")","client",".","connect","(",")","atexit",".","register","(","_clean_open_clients",")","return","client"],"url":"https:\/\/github.com\/BishopFox\/rickmote\/blob\/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9\/pychromecast\/websocket.py#L87-L115"}
15
+ {"nwo":"BishopFox\/rickmote","sha":"2a8469657f9de7d6ee1d4cc65ce83235c1e582d9","path":"pychromecast\/websocket.py","language":"python","identifier":"_clean_open_clients","parameters":"()","argument_list":"","return_statement":"","docstring":"Called on exit of Python to close open clients.","docstring_summary":"Called on exit of Python to close open clients.","docstring_tokens":["Called","on","exit","of","Python","to","close","open","clients","."],"function":"def _clean_open_clients():\n \"\"\" Called on exit of Python to close open clients. \"\"\"\n for client_weakref in list(_OPEN_CLIENTS):\n client = client_weakref()\n\n if client and not client.terminated:\n client.close_connection()","function_tokens":["def","_clean_open_clients","(",")",":","for","client_weakref","in","list","(","_OPEN_CLIENTS",")",":","client","=","client_weakref","(",")","if","client","and","not","client",".","terminated",":","client",".","close_connection","(",")"],"url":"https:\/\/github.com\/BishopFox\/rickmote\/blob\/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9\/pychromecast\/websocket.py#L118-L124"}
16
+ {"nwo":"BishopFox\/rickmote","sha":"2a8469657f9de7d6ee1d4cc65ce83235c1e582d9","path":"pychromecast\/websocket.py","language":"python","identifier":"ChromecastWebSocketClient.opened","parameters":"(self)","argument_list":"","return_statement":"","docstring":"When connection is opened initiate the protocol handlers.","docstring_summary":"When connection is opened initiate the protocol handlers.","docstring_tokens":["When","connection","is","opened","initiate","the","protocol","handlers","."],"function":"def opened(self):\n \"\"\" When connection is opened initiate the protocol handlers. \"\"\"\n _OPEN_CLIENTS.append(self._weakref)\n\n self.handlers[PROTOCOL_COMMAND] = CommandSubprotocol(self)\n\n _known_prot = KNOWN_PROTOCOLS\n\n # Instantiate supported subprotocols.\n for protocol in self.supported_protocols:\n handler = _known_prot.get(protocol)\n\n if handler:\n self.handlers[protocol] = handler(self)\n else:\n self.logger.warning(\n \"Unsupported protocol: {}\".format(protocol))","function_tokens":["def","opened","(","self",")",":","_OPEN_CLIENTS",".","append","(","self",".","_weakref",")","self",".","handlers","[","PROTOCOL_COMMAND","]","=","CommandSubprotocol","(","self",")","_known_prot","=","KNOWN_PROTOCOLS","# Instantiate supported subprotocols.","for","protocol","in","self",".","supported_protocols",":","handler","=","_known_prot",".","get","(","protocol",")","if","handler",":","self",".","handlers","[","protocol","]","=","handler","(","self",")","else",":","self",".","logger",".","warning","(","\"Unsupported protocol: {}\"",".","format","(","protocol",")",")"],"url":"https:\/\/github.com\/BishopFox\/rickmote\/blob\/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9\/pychromecast\/websocket.py#L139-L155"}
17
+ {"nwo":"BishopFox\/rickmote","sha":"2a8469657f9de7d6ee1d4cc65ce83235c1e582d9","path":"pychromecast\/websocket.py","language":"python","identifier":"ChromecastWebSocketClient.closed","parameters":"(self, code, reason=None)","argument_list":"","return_statement":"","docstring":"Clear protocol handlers when connection is lost.","docstring_summary":"Clear protocol handlers when connection is lost.","docstring_tokens":["Clear","protocol","handlers","when","connection","is","lost","."],"function":"def closed(self, code, reason=None):\n \"\"\" Clear protocol handlers when connection is lost. \"\"\"\n # Clear reference to client\n _OPEN_CLIENTS.remove(self._weakref)\n\n for handler in self.handlers.values():\n handler.client = None\n\n self.handlers.clear()","function_tokens":["def","closed","(","self",",","code",",","reason","=","None",")",":","# Clear reference to client","_OPEN_CLIENTS",".","remove","(","self",".","_weakref",")","for","handler","in","self",".","handlers",".","values","(",")",":","handler",".","client","=","None","self",".","handlers",".","clear","(",")"],"url":"https:\/\/github.com\/BishopFox\/rickmote\/blob\/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9\/pychromecast\/websocket.py#L157-L165"}
18
+ {"nwo":"BishopFox\/rickmote","sha":"2a8469657f9de7d6ee1d4cc65ce83235c1e582d9","path":"pychromecast\/websocket.py","language":"python","identifier":"ChromecastWebSocketClient.received_message","parameters":"(self, message)","argument_list":"","return_statement":"","docstring":"When a new message is received.","docstring_summary":"When a new message is received.","docstring_tokens":["When","a","new","message","is","received","."],"function":"def received_message(self, message):\n \"\"\" When a new message is received. \"\"\"\n\n # We do not support binary message\n if message.is_binary:\n return False\n\n try:\n protocol, data = json.loads(message.data.decode('utf8'))\n except ValueError:\n # If error while parsing JSON\n # if unpack error: more then 2 items in the list\n logging.getLogger(__name__).exception(\n \"Error parsing incoming message: {}\".format(\n message.data.decode(\"utf8\")))\n\n return\n\n if _DEBUG:\n logging.getLogger(__name__).info(\"Receiving {}\".format(data))\n\n handler = self.handlers.get(protocol)\n\n if handler:\n handler._receive_protocol(data) # pylint: disable=protected-access\n else:\n logging.getLogger(__name__).warning(\n \"Unknown protocol received: {}, {}\".format(protocol, data))","function_tokens":["def","received_message","(","self",",","message",")",":","# We do not support binary message","if","message",".","is_binary",":","return","False","try",":","protocol",",","data","=","json",".","loads","(","message",".","data",".","decode","(","'utf8'",")",")","except","ValueError",":","# If error while parsing JSON","# if unpack error: more then 2 items in the list","logging",".","getLogger","(","__name__",")",".","exception","(","\"Error parsing incoming message: {}\"",".","format","(","message",".","data",".","decode","(","\"utf8\"",")",")",")","return","if","_DEBUG",":","logging",".","getLogger","(","__name__",")",".","info","(","\"Receiving {}\"",".","format","(","data",")",")","handler","=","self",".","handlers",".","get","(","protocol",")","if","handler",":","handler",".","_receive_protocol","(","data",")","# pylint: disable=protected-access","else",":","logging",".","getLogger","(","__name__",")",".","warning","(","\"Unknown protocol received: {}, {}\"",".","format","(","protocol",",","data",")",")"],"url":"https:\/\/github.com\/BishopFox\/rickmote\/blob\/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9\/pychromecast\/websocket.py#L167-L194"}
19
+ {"nwo":"BishopFox\/rickmote","sha":"2a8469657f9de7d6ee1d4cc65ce83235c1e582d9","path":"pychromecast\/websocket.py","language":"python","identifier":"BaseSubprotocol._send_protocol","parameters":"(self, data)","argument_list":"","return_statement":"","docstring":"Default handler for sending messages as subprotocol.","docstring_summary":"Default handler for sending messages as subprotocol.","docstring_tokens":["Default","handler","for","sending","messages","as","subprotocol","."],"function":"def _send_protocol(self, data):\n \"\"\" Default handler for sending messages as subprotocol. \"\"\"\n if _DEBUG:\n self.logger.info(\"Sending {}\".format(data))\n\n if not self.client:\n raise error.ConnectionError(\"Not connected to Chromecast\")\n\n try:\n self.client.send(json.dumps([self.protocol, data]).encode(\"utf8\"))\n\n except socket.error:\n # if an error occured sending data over the socket\n raise error.ConnectionError(\"Error communicating with Chromecast\")","function_tokens":["def","_send_protocol","(","self",",","data",")",":","if","_DEBUG",":","self",".","logger",".","info","(","\"Sending {}\"",".","format","(","data",")",")","if","not","self",".","client",":","raise","error",".","ConnectionError","(","\"Not connected to Chromecast\"",")","try",":","self",".","client",".","send","(","json",".","dumps","(","[","self",".","protocol",",","data","]",")",".","encode","(","\"utf8\"",")",")","except","socket",".","error",":","# if an error occured sending data over the socket","raise","error",".","ConnectionError","(","\"Error communicating with Chromecast\"",")"],"url":"https:\/\/github.com\/BishopFox\/rickmote\/blob\/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9\/pychromecast\/websocket.py#L206-L219"}
20
+ {"nwo":"BishopFox\/rickmote","sha":"2a8469657f9de7d6ee1d4cc65ce83235c1e582d9","path":"pychromecast\/websocket.py","language":"python","identifier":"BaseSubprotocol._receive_protocol","parameters":"(self, data)","argument_list":"","return_statement":"","docstring":"Default handler for receiving messages as subprotocol.","docstring_summary":"Default handler for receiving messages as subprotocol.","docstring_tokens":["Default","handler","for","receiving","messages","as","subprotocol","."],"function":"def _receive_protocol(self, data):\n \"\"\" Default handler for receiving messages as subprotocol. \"\"\"\n self.logger.warning(\n \"Unhandled {} message: {}\".format(self.protocol, data))","function_tokens":["def","_receive_protocol","(","self",",","data",")",":","self",".","logger",".","warning","(","\"Unhandled {} message: {}\"",".","format","(","self",".","protocol",",","data",")",")"],"url":"https:\/\/github.com\/BishopFox\/rickmote\/blob\/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9\/pychromecast\/websocket.py#L221-L224"}
21
+ {"nwo":"BishopFox\/rickmote","sha":"2a8469657f9de7d6ee1d4cc65ce83235c1e582d9","path":"pychromecast\/websocket.py","language":"python","identifier":"BaseSubprotocol.is_active","parameters":"(self)","argument_list":"","return_statement":"return not self.client.terminated","docstring":"Returns if this subprotocol is active.","docstring_summary":"Returns if this subprotocol is active.","docstring_tokens":["Returns","if","this","subprotocol","is","active","."],"function":"def is_active(self):\n \"\"\" Returns if this subprotocol is active. \"\"\"\n return not self.client.terminated","function_tokens":["def","is_active","(","self",")",":","return","not","self",".","client",".","terminated"],"url":"https:\/\/github.com\/BishopFox\/rickmote\/blob\/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9\/pychromecast\/websocket.py#L227-L229"}
22
+ {"nwo":"BishopFox\/rickmote","sha":"2a8469657f9de7d6ee1d4cc65ce83235c1e582d9","path":"pychromecast\/websocket.py","language":"python","identifier":"CommandSubprotocol._receive_protocol","parameters":"(self, data)","argument_list":"","return_statement":"","docstring":"Handles an incoming COMMAND message.","docstring_summary":"Handles an incoming COMMAND message.","docstring_tokens":["Handles","an","incoming","COMMAND","message","."],"function":"def _receive_protocol(self, data):\n \"\"\" Handles an incoming COMMAND message. \"\"\"\n\n if data[COMMAND_ATTR_TYPE] == COMMAND_TYPE_PING:\n self._send_protocol({COMMAND_ATTR_TYPE: COMMAND_TYPE_PONG})\n else:\n BaseSubprotocol._receive_protocol(self, data)","function_tokens":["def","_receive_protocol","(","self",",","data",")",":","if","data","[","COMMAND_ATTR_TYPE","]","==","COMMAND_TYPE_PING",":","self",".","_send_protocol","(","{","COMMAND_ATTR_TYPE",":","COMMAND_TYPE_PONG","}",")","else",":","BaseSubprotocol",".","_receive_protocol","(","self",",","data",")"],"url":"https:\/\/github.com\/BishopFox\/rickmote\/blob\/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9\/pychromecast\/websocket.py#L238-L244"}
23
+ {"nwo":"BishopFox\/rickmote","sha":"2a8469657f9de7d6ee1d4cc65ce83235c1e582d9","path":"pychromecast\/websocket.py","language":"python","identifier":"RampSubprotocol._receive_protocol","parameters":"(self, data)","argument_list":"","return_statement":"","docstring":"Handles an incoming Ramp message.","docstring_summary":"Handles an incoming Ramp message.","docstring_tokens":["Handles","an","incoming","Ramp","message","."],"function":"def _receive_protocol(self, data):\n \"\"\" Handles an incoming Ramp message. \"\"\"\n message_type = data[RAMP_ATTR_TYPE]\n\n if message_type == RAMP_TYPE_STATUS:\n self._update_status(data[RAMP_ATTR_STATUS])\n\n elif message_type == RAMP_TYPE_RESPONSE:\n # Match it with the command that we send\n try:\n cmd_type, cmd_event = \\\n self.commands.pop(data[RAMP_ATTR_CMD_ID])\n\n except KeyError:\n # If CMD_ID did not exist or we do not recognize command\n return\n\n # Handle response, currently no response handlers\n if cmd_type in (RAMP_TYPE_PLAY, RAMP_TYPE_VOLUME,\n RAMP_TYPE_INFO):\n\n self._update_status(data[RAMP_ATTR_STATUS])\n\n else:\n self.logger.warning(\n \"Unhandled response for command {}: {}\".format(\n cmd_type, data))\n\n # Alert code that is waiting for this command to get response\n if cmd_event:\n cmd_event.set()\n\n else:\n BaseSubprotocol._receive_protocol(self, data)","function_tokens":["def","_receive_protocol","(","self",",","data",")",":","message_type","=","data","[","RAMP_ATTR_TYPE","]","if","message_type","==","RAMP_TYPE_STATUS",":","self",".","_update_status","(","data","[","RAMP_ATTR_STATUS","]",")","elif","message_type","==","RAMP_TYPE_RESPONSE",":","# Match it with the command that we send","try",":","cmd_type",",","cmd_event","=","self",".","commands",".","pop","(","data","[","RAMP_ATTR_CMD_ID","]",")","except","KeyError",":","# If CMD_ID did not exist or we do not recognize command","return","# Handle response, currently no response handlers","if","cmd_type","in","(","RAMP_TYPE_PLAY",",","RAMP_TYPE_VOLUME",",","RAMP_TYPE_INFO",")",":","self",".","_update_status","(","data","[","RAMP_ATTR_STATUS","]",")","else",":","self",".","logger",".","warning","(","\"Unhandled response for command {}: {}\"",".","format","(","cmd_type",",","data",")",")","# Alert code that is waiting for this command to get response","if","cmd_event",":","cmd_event",".","set","(",")","else",":","BaseSubprotocol",".","_receive_protocol","(","self",",","data",")"],"url":"https:\/\/github.com\/BishopFox\/rickmote\/blob\/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9\/pychromecast\/websocket.py#L259-L292"}
24
+ {"nwo":"BishopFox\/rickmote","sha":"2a8469657f9de7d6ee1d4cc65ce83235c1e582d9","path":"pychromecast\/websocket.py","language":"python","identifier":"RampSubprotocol._send_ramp","parameters":"(self, data, blocking=False)","argument_list":"","return_statement":"","docstring":"Sends a RAMP message.\n Set blocking=True to wait till the Chromecast sends a response\n to the command.","docstring_summary":"Sends a RAMP message.\n Set blocking=True to wait till the Chromecast sends a response\n to the command.","docstring_tokens":["Sends","a","RAMP","message",".","Set","blocking","=","True","to","wait","till","the","Chromecast","sends","a","response","to","the","command","."],"function":"def _send_ramp(self, data, blocking=False):\n \"\"\"\n Sends a RAMP message.\n Set blocking=True to wait till the Chromecast sends a response\n to the command.\n \"\"\"\n data[RAMP_ATTR_CMD_ID] = self.command_id\n\n event = threading.Event() if blocking else None\n\n # Save type to match later with response\n self.commands[self.command_id] = (data[RAMP_ATTR_TYPE], event)\n\n self._send_protocol(data)\n\n self.command_id += 1\n\n if blocking:\n event.wait()","function_tokens":["def","_send_ramp","(","self",",","data",",","blocking","=","False",")",":","data","[","RAMP_ATTR_CMD_ID","]","=","self",".","command_id","event","=","threading",".","Event","(",")","if","blocking","else","None","# Save type to match later with response","self",".","commands","[","self",".","command_id","]","=","(","data","[","RAMP_ATTR_TYPE","]",",","event",")","self",".","_send_protocol","(","data",")","self",".","command_id","+=","1","if","blocking",":","event",".","wait","(",")"],"url":"https:\/\/github.com\/BishopFox\/rickmote\/blob\/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9\/pychromecast\/websocket.py#L295-L313"}
25
+ {"nwo":"BishopFox\/rickmote","sha":"2a8469657f9de7d6ee1d4cc65ce83235c1e582d9","path":"pychromecast\/websocket.py","language":"python","identifier":"RampSubprotocol.is_playing","parameters":"(self)","argument_list":"","return_statement":"return self.is_active and self.state == RAMP_STATE_PLAYING","docstring":"Property that represents if content is being played.","docstring_summary":"Property that represents if content is being played.","docstring_tokens":["Property","that","represents","if","content","is","being","played","."],"function":"def is_playing(self):\n \"\"\" Property that represents if content is being played. \"\"\"\n return self.is_active and self.state == RAMP_STATE_PLAYING","function_tokens":["def","is_playing","(","self",")",":","return","self",".","is_active","and","self",".","state","==","RAMP_STATE_PLAYING"],"url":"https:\/\/github.com\/BishopFox\/rickmote\/blob\/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9\/pychromecast\/websocket.py#L316-L318"}
26
+ {"nwo":"BishopFox\/rickmote","sha":"2a8469657f9de7d6ee1d4cc65ce83235c1e582d9","path":"pychromecast\/websocket.py","language":"python","identifier":"RampSubprotocol.play","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Send the PLAY-command to the RAMP-target.","docstring_summary":"Send the PLAY-command to the RAMP-target.","docstring_tokens":["Send","the","PLAY","-","command","to","the","RAMP","-","target","."],"function":"def play(self):\n \"\"\" Send the PLAY-command to the RAMP-target. \"\"\"\n self._send_ramp({RAMP_ATTR_TYPE: RAMP_TYPE_PLAY})","function_tokens":["def","play","(","self",")",":","self",".","_send_ramp","(","{","RAMP_ATTR_TYPE",":","RAMP_TYPE_PLAY","}",")"],"url":"https:\/\/github.com\/BishopFox\/rickmote\/blob\/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9\/pychromecast\/websocket.py#L320-L322"}
27
+ {"nwo":"BishopFox\/rickmote","sha":"2a8469657f9de7d6ee1d4cc65ce83235c1e582d9","path":"pychromecast\/websocket.py","language":"python","identifier":"RampSubprotocol.pause","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Send the PAUSE-command to the RAMP-target.","docstring_summary":"Send the PAUSE-command to the RAMP-target.","docstring_tokens":["Send","the","PAUSE","-","command","to","the","RAMP","-","target","."],"function":"def pause(self):\n \"\"\" Send the PAUSE-command to the RAMP-target. \"\"\"\n # The STOP command actually pauses the media\n self._send_ramp({RAMP_ATTR_TYPE: RAMP_TYPE_STOP})","function_tokens":["def","pause","(","self",")",":","# The STOP command actually pauses the media","self",".","_send_ramp","(","{","RAMP_ATTR_TYPE",":","RAMP_TYPE_STOP","}",")"],"url":"https:\/\/github.com\/BishopFox\/rickmote\/blob\/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9\/pychromecast\/websocket.py#L324-L327"}
28
+ {"nwo":"BishopFox\/rickmote","sha":"2a8469657f9de7d6ee1d4cc65ce83235c1e582d9","path":"pychromecast\/websocket.py","language":"python","identifier":"RampSubprotocol.playpause","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Plays if paused, pauses if playing.","docstring_summary":"Plays if paused, pauses if playing.","docstring_tokens":["Plays","if","paused","pauses","if","playing","."],"function":"def playpause(self):\n \"\"\" Plays if paused, pauses if playing. \"\"\"\n if self.state == RAMP_STATE_PLAYING:\n self.pause()\n else:\n self.play()","function_tokens":["def","playpause","(","self",")",":","if","self",".","state","==","RAMP_STATE_PLAYING",":","self",".","pause","(",")","else",":","self",".","play","(",")"],"url":"https:\/\/github.com\/BishopFox\/rickmote\/blob\/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9\/pychromecast\/websocket.py#L329-L334"}
29
+ {"nwo":"BishopFox\/rickmote","sha":"2a8469657f9de7d6ee1d4cc65ce83235c1e582d9","path":"pychromecast\/websocket.py","language":"python","identifier":"RampSubprotocol.seek","parameters":"(self, seconds)","argument_list":"","return_statement":"","docstring":"Seek within the content played at RAMP-target.","docstring_summary":"Seek within the content played at RAMP-target.","docstring_tokens":["Seek","within","the","content","played","at","RAMP","-","target","."],"function":"def seek(self, seconds):\n \"\"\" Seek within the content played at RAMP-target. \"\"\"\n self._send_ramp({RAMP_ATTR_TYPE: RAMP_TYPE_PLAY,\n RAMP_ATTR_POSITION: seconds})","function_tokens":["def","seek","(","self",",","seconds",")",":","self",".","_send_ramp","(","{","RAMP_ATTR_TYPE",":","RAMP_TYPE_PLAY",",","RAMP_ATTR_POSITION",":","seconds","}",")"],"url":"https:\/\/github.com\/BishopFox\/rickmote\/blob\/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9\/pychromecast\/websocket.py#L336-L339"}
30
+ {"nwo":"BishopFox\/rickmote","sha":"2a8469657f9de7d6ee1d4cc65ce83235c1e582d9","path":"pychromecast\/websocket.py","language":"python","identifier":"RampSubprotocol.rewind","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Rewinds current media item.","docstring_summary":"Rewinds current media item.","docstring_tokens":["Rewinds","current","media","item","."],"function":"def rewind(self):\n \"\"\" Rewinds current media item. \"\"\"\n self.seek(0)","function_tokens":["def","rewind","(","self",")",":","self",".","seek","(","0",")"],"url":"https:\/\/github.com\/BishopFox\/rickmote\/blob\/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9\/pychromecast\/websocket.py#L341-L343"}
31
+ {"nwo":"BishopFox\/rickmote","sha":"2a8469657f9de7d6ee1d4cc65ce83235c1e582d9","path":"pychromecast\/websocket.py","language":"python","identifier":"RampSubprotocol.next","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Skip to the next content at the RAMP-target.","docstring_summary":"Skip to the next content at the RAMP-target.","docstring_tokens":["Skip","to","the","next","content","at","the","RAMP","-","target","."],"function":"def next(self):\n \"\"\" Skip to the next content at the RAMP-target. \"\"\"\n if self.duration != 0:\n self.seek(self.duration-.1)","function_tokens":["def","next","(","self",")",":","if","self",".","duration","!=","0",":","self",".","seek","(","self",".","duration","-",".1",")"],"url":"https:\/\/github.com\/BishopFox\/rickmote\/blob\/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9\/pychromecast\/websocket.py#L345-L348"}
32
+ {"nwo":"BishopFox\/rickmote","sha":"2a8469657f9de7d6ee1d4cc65ce83235c1e582d9","path":"pychromecast\/websocket.py","language":"python","identifier":"RampSubprotocol.set_volume","parameters":"(self, volume)","argument_list":"","return_statement":"","docstring":"Set volume at the RAMP-target.","docstring_summary":"Set volume at the RAMP-target.","docstring_tokens":["Set","volume","at","the","RAMP","-","target","."],"function":"def set_volume(self, volume):\n \"\"\" Set volume at the RAMP-target. \"\"\"\n # volume is double between 0 and 1\n self._send_ramp({RAMP_ATTR_TYPE: RAMP_TYPE_VOLUME,\n RAMP_ATTR_VOLUME: volume})","function_tokens":["def","set_volume","(","self",",","volume",")",":","# volume is double between 0 and 1","self",".","_send_ramp","(","{","RAMP_ATTR_TYPE",":","RAMP_TYPE_VOLUME",",","RAMP_ATTR_VOLUME",":","volume","}",")"],"url":"https:\/\/github.com\/BishopFox\/rickmote\/blob\/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9\/pychromecast\/websocket.py#L350-L354"}
33
+ {"nwo":"BishopFox\/rickmote","sha":"2a8469657f9de7d6ee1d4cc65ce83235c1e582d9","path":"pychromecast\/websocket.py","language":"python","identifier":"RampSubprotocol.volume_up","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Increases volume.","docstring_summary":"Increases volume.","docstring_tokens":["Increases","volume","."],"function":"def volume_up(self):\n \"\"\" Increases volume. \"\"\"\n if self.volume < 1:\n self.set_volume(min(self.volume+.1, 1))","function_tokens":["def","volume_up","(","self",")",":","if","self",".","volume","<","1",":","self",".","set_volume","(","min","(","self",".","volume","+",".1",",","1",")",")"],"url":"https:\/\/github.com\/BishopFox\/rickmote\/blob\/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9\/pychromecast\/websocket.py#L356-L359"}
34
+ {"nwo":"BishopFox\/rickmote","sha":"2a8469657f9de7d6ee1d4cc65ce83235c1e582d9","path":"pychromecast\/websocket.py","language":"python","identifier":"RampSubprotocol.volume_down","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Decreases volume.","docstring_summary":"Decreases volume.","docstring_tokens":["Decreases","volume","."],"function":"def volume_down(self):\n \"\"\" Decreases volume. \"\"\"\n if self.volume > 0:\n self.set_volume(max(self.volume-.1, 0))","function_tokens":["def","volume_down","(","self",")",":","if","self",".","volume",">","0",":","self",".","set_volume","(","max","(","self",".","volume","-",".1",",","0",")",")"],"url":"https:\/\/github.com\/BishopFox\/rickmote\/blob\/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9\/pychromecast\/websocket.py#L361-L364"}
35
+ {"nwo":"BishopFox\/rickmote","sha":"2a8469657f9de7d6ee1d4cc65ce83235c1e582d9","path":"pychromecast\/websocket.py","language":"python","identifier":"RampSubprotocol.refresh","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Refresh data at the RAMP-target.","docstring_summary":"Refresh data at the RAMP-target.","docstring_tokens":["Refresh","data","at","the","RAMP","-","target","."],"function":"def refresh(self):\n \"\"\" Refresh data at the RAMP-target. \"\"\"\n self._send_ramp({RAMP_ATTR_TYPE: RAMP_TYPE_INFO})","function_tokens":["def","refresh","(","self",")",":","self",".","_send_ramp","(","{","RAMP_ATTR_TYPE",":","RAMP_TYPE_INFO","}",")"],"url":"https:\/\/github.com\/BishopFox\/rickmote\/blob\/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9\/pychromecast\/websocket.py#L366-L368"}
36
+ {"nwo":"BishopFox\/rickmote","sha":"2a8469657f9de7d6ee1d4cc65ce83235c1e582d9","path":"pychromecast\/websocket.py","language":"python","identifier":"RampSubprotocol._update_status","parameters":"(self, status)","argument_list":"","return_statement":"","docstring":"Updates the RAMP status.","docstring_summary":"Updates the RAMP status.","docstring_tokens":["Updates","the","RAMP","status","."],"function":"def _update_status(self, status):\n \"\"\" Updates the RAMP status. \"\"\"\n con_inf = status.get(RAMP_ATTR_CONTENT_INFO, {})\n\n self.state = status.get(RAMP_STATUS_ATTR_STATE, 0)\n self.volume = status.get(RAMP_STATUS_ATTR_VOLUME, 1)\n self.muted = status.get(RAMP_STATUS_ATTR_MUTED, False)\n self.content_id = status.get(RAMP_STATUS_ATTR_CONTENT_ID)\n self.title = status.get(RAMP_STATUS_ATTR_TITLE)\n self.artist = con_inf.get(RAMP_STATUS_CONTENT_INFO_ATTR_ARTIST)\n self.album = con_inf.get(RAMP_STATUS_CONTENT_INFO_ATTR_ALBUM_TITLE)\n self._current_time = status.get(RAMP_STATUS_ATTR_CURRENT_TIME, 0)\n self.duration = status.get(RAMP_STATUS_ATTR_DURATION, 0)\n self.image_url = status.get(RAMP_STATUS_ATTR_IMAGE_URL)\n self.time_progress = status.get(RAMP_ATTR_TIME_PROGRESS, False)\n\n self.last_updated = dt.datetime.now()","function_tokens":["def","_update_status","(","self",",","status",")",":","con_inf","=","status",".","get","(","RAMP_ATTR_CONTENT_INFO",",","{","}",")","self",".","state","=","status",".","get","(","RAMP_STATUS_ATTR_STATE",",","0",")","self",".","volume","=","status",".","get","(","RAMP_STATUS_ATTR_VOLUME",",","1",")","self",".","muted","=","status",".","get","(","RAMP_STATUS_ATTR_MUTED",",","False",")","self",".","content_id","=","status",".","get","(","RAMP_STATUS_ATTR_CONTENT_ID",")","self",".","title","=","status",".","get","(","RAMP_STATUS_ATTR_TITLE",")","self",".","artist","=","con_inf",".","get","(","RAMP_STATUS_CONTENT_INFO_ATTR_ARTIST",")","self",".","album","=","con_inf",".","get","(","RAMP_STATUS_CONTENT_INFO_ATTR_ALBUM_TITLE",")","self",".","_current_time","=","status",".","get","(","RAMP_STATUS_ATTR_CURRENT_TIME",",","0",")","self",".","duration","=","status",".","get","(","RAMP_STATUS_ATTR_DURATION",",","0",")","self",".","image_url","=","status",".","get","(","RAMP_STATUS_ATTR_IMAGE_URL",")","self",".","time_progress","=","status",".","get","(","RAMP_ATTR_TIME_PROGRESS",",","False",")","self",".","last_updated","=","dt",".","datetime",".","now","(",")"],"url":"https:\/\/github.com\/BishopFox\/rickmote\/blob\/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9\/pychromecast\/websocket.py#L370-L386"}
37
+ {"nwo":"BishopFox\/rickmote","sha":"2a8469657f9de7d6ee1d4cc65ce83235c1e582d9","path":"pychromecast\/websocket.py","language":"python","identifier":"RampSubprotocol.current_time","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Returns current time of the content.","docstring_summary":"Returns current time of the content.","docstring_tokens":["Returns","current","time","of","the","content","."],"function":"def current_time(self):\n \"\"\" Returns current time of the content. \"\"\"\n\n # If time is progressing we have to calculate the current time based on\n # time the status was retrieved and the then current time.\n if self.time_progress:\n timediff = dt.datetime.now() - self.last_updated\n\n return min(self._current_time + timediff.seconds, self.duration)\n\n else:\n return self._current_time","function_tokens":["def","current_time","(","self",")",":","# If time is progressing we have to calculate the current time based on","# time the status was retrieved and the then current time.","if","self",".","time_progress",":","timediff","=","dt",".","datetime",".","now","(",")","-","self",".","last_updated","return","min","(","self",".","_current_time","+","timediff",".","seconds",",","self",".","duration",")","else",":","return","self",".","_current_time"],"url":"https:\/\/github.com\/BishopFox\/rickmote\/blob\/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9\/pychromecast\/websocket.py#L389-L400"}
38
+ {"nwo":"BishopFox\/rickmote","sha":"2a8469657f9de7d6ee1d4cc65ce83235c1e582d9","path":"pychromecast\/__init__.py","language":"python","identifier":"play_youtube_video","parameters":"(video_id, host=None)","argument_list":"","return_statement":"","docstring":"Starts the YouTube app if it is not running and plays\n specified video.","docstring_summary":"Starts the YouTube app if it is not running and plays\n specified video.","docstring_tokens":["Starts","the","YouTube","app","if","it","is","not","running","and","plays","specified","video","."],"function":"def play_youtube_video(video_id, host=None):\n \"\"\" Starts the YouTube app if it is not running and plays\n specified video. \"\"\"\n\n if not host:\n host = _auto_select_chromecast()\n\n start_app(host, APP_ID[\"YOUTUBE\"], {\"v\": video_id})","function_tokens":["def","play_youtube_video","(","video_id",",","host","=","None",")",":","if","not","host",":","host","=","_auto_select_chromecast","(",")","start_app","(","host",",","APP_ID","[","\"YOUTUBE\"","]",",","{","\"v\"",":","video_id","}",")"],"url":"https:\/\/github.com\/BishopFox\/rickmote\/blob\/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9\/pychromecast\/__init__.py#L17-L24"}
39
+ {"nwo":"BishopFox\/rickmote","sha":"2a8469657f9de7d6ee1d4cc65ce83235c1e582d9","path":"pychromecast\/__init__.py","language":"python","identifier":"play_youtube_playlist","parameters":"(playlist_id, host=None)","argument_list":"","return_statement":"","docstring":"Starts the YouTube app if it is not running and plays\n specified playlist.","docstring_summary":"Starts the YouTube app if it is not running and plays\n specified playlist.","docstring_tokens":["Starts","the","YouTube","app","if","it","is","not","running","and","plays","specified","playlist","."],"function":"def play_youtube_playlist(playlist_id, host=None):\n \"\"\" Starts the YouTube app if it is not running and plays\n specified playlist. \"\"\"\n\n if not host:\n host = _auto_select_chromecast()\n\n start_app(host, APP_ID[\"YOUTUBE\"],\n {\"listType\": \"playlist\", \"list\": playlist_id})","function_tokens":["def","play_youtube_playlist","(","playlist_id",",","host","=","None",")",":","if","not","host",":","host","=","_auto_select_chromecast","(",")","start_app","(","host",",","APP_ID","[","\"YOUTUBE\"","]",",","{","\"listType\"",":","\"playlist\"",",","\"list\"",":","playlist_id","}",")"],"url":"https:\/\/github.com\/BishopFox\/rickmote\/blob\/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9\/pychromecast\/__init__.py#L27-L35"}
40
+ {"nwo":"BishopFox\/rickmote","sha":"2a8469657f9de7d6ee1d4cc65ce83235c1e582d9","path":"pychromecast\/__init__.py","language":"python","identifier":"_auto_select_chromecast","parameters":"()","argument_list":"","return_statement":"","docstring":"Discovers local Chromecasts and returns first one found.\n Raises exception if none can be found.","docstring_summary":"Discovers local Chromecasts and returns first one found.\n Raises exception if none can be found.","docstring_tokens":["Discovers","local","Chromecasts","and","returns","first","one","found",".","Raises","exception","if","none","can","be","found","."],"function":"def _auto_select_chromecast():\n \"\"\"\n Discovers local Chromecasts and returns first one found.\n Raises exception if none can be found.\n \"\"\"\n ips = discover_chromecasts(1)\n\n if ips:\n return ips[0]\n else:\n raise NoChromecastFoundError(\"Unable to detect Chromecast\")","function_tokens":["def","_auto_select_chromecast","(",")",":","ips","=","discover_chromecasts","(","1",")","if","ips",":","return","ips","[","0","]","else",":","raise","NoChromecastFoundError","(","\"Unable to detect Chromecast\"",")"],"url":"https:\/\/github.com\/BishopFox\/rickmote\/blob\/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9\/pychromecast\/__init__.py#L38-L48"}
41
+ {"nwo":"BishopFox\/rickmote","sha":"2a8469657f9de7d6ee1d4cc65ce83235c1e582d9","path":"pychromecast\/__init__.py","language":"python","identifier":"PyChromecast.app_id","parameters":"(self)","argument_list":"","return_statement":"return self.app.app_id if self.app else None","docstring":"Returns the current app_id.","docstring_summary":"Returns the current app_id.","docstring_tokens":["Returns","the","current","app_id","."],"function":"def app_id(self):\n \"\"\" Returns the current app_id. \"\"\"\n return self.app.app_id if self.app else None","function_tokens":["def","app_id","(","self",")",":","return","self",".","app",".","app_id","if","self",".","app","else","None"],"url":"https:\/\/github.com\/BishopFox\/rickmote\/blob\/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9\/pychromecast\/__init__.py#L73-L75"}
42
+ {"nwo":"BishopFox\/rickmote","sha":"2a8469657f9de7d6ee1d4cc65ce83235c1e582d9","path":"pychromecast\/__init__.py","language":"python","identifier":"PyChromecast.app_description","parameters":"(self)","argument_list":"","return_statement":"return self.app.description if self.app else None","docstring":"Returns the name of the current running app.","docstring_summary":"Returns the name of the current running app.","docstring_tokens":["Returns","the","name","of","the","current","running","app","."],"function":"def app_description(self):\n \"\"\" Returns the name of the current running app. \"\"\"\n return self.app.description if self.app else None","function_tokens":["def","app_description","(","self",")",":","return","self",".","app",".","description","if","self",".","app","else","None"],"url":"https:\/\/github.com\/BishopFox\/rickmote\/blob\/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9\/pychromecast\/__init__.py#L78-L80"}
43
+ {"nwo":"BishopFox\/rickmote","sha":"2a8469657f9de7d6ee1d4cc65ce83235c1e582d9","path":"pychromecast\/__init__.py","language":"python","identifier":"PyChromecast.get_protocol","parameters":"(self, protocol)","argument_list":"","return_statement":"","docstring":"Returns the current RAMP content info and controls.","docstring_summary":"Returns the current RAMP content info and controls.","docstring_tokens":["Returns","the","current","RAMP","content","info","and","controls","."],"function":"def get_protocol(self, protocol):\n \"\"\" Returns the current RAMP content info and controls. \"\"\"\n if self.websocket_client:\n return self.websocket_client.handlers.get(protocol)\n else:\n return None","function_tokens":["def","get_protocol","(","self",",","protocol",")",":","if","self",".","websocket_client",":","return","self",".","websocket_client",".","handlers",".","get","(","protocol",")","else",":","return","None"],"url":"https:\/\/github.com\/BishopFox\/rickmote\/blob\/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9\/pychromecast\/__init__.py#L82-L87"}
44
+ {"nwo":"BishopFox\/rickmote","sha":"2a8469657f9de7d6ee1d4cc65ce83235c1e582d9","path":"pychromecast\/__init__.py","language":"python","identifier":"PyChromecast.refresh","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Queries the Chromecast for the current status.\n Starts a websocket client if possible.","docstring_summary":"Queries the Chromecast for the current status.\n Starts a websocket client if possible.","docstring_tokens":["Queries","the","Chromecast","for","the","current","status",".","Starts","a","websocket","client","if","possible","."],"function":"def refresh(self):\n \"\"\"\n Queries the Chromecast for the current status.\n Starts a websocket client if possible.\n \"\"\"\n self.logger.info(\"Refreshing app status\")\n\n # If we are refreshing but a refresh was planned, cancel that one\n with self._refresh_lock:\n if self._refresh_timer:\n self._refresh_timer.cancel()\n self._refresh_timer = None\n\n cur_app = self.app\n cur_ws = self.websocket_client\n\n self.app = app = get_app_status(self.host)\n\n # If no previous app and no new app there is nothing to do\n if not cur_app and not app:\n is_diff_app = False\n else:\n is_diff_app = (not cur_app and app or cur_app and not app or\n cur_app.app_id != app.app_id)\n\n # Clean up websocket if:\n # - there is a different app and a connection exists\n # - if it is the same app but the connection is terminated\n if cur_ws and (is_diff_app or cur_ws.terminated):\n\n if not cur_ws.terminated:\n cur_ws.close_connection()\n\n self.websocket_client = cur_ws = None\n\n # Create a new websocket client if there is no connection\n if not cur_ws and app:\n\n try:\n # If the current app is not capable of a websocket client\n # This method will return None so nothing is lost\n self.websocket_client = cur_ws = create_websocket_client(app)\n\n except ConnectionError:\n pass\n\n # Ramp service does not always immediately show up in the app\n # status. If we do not have a websocket client but the app is\n # known to be RAMP controllable, then plan refresh.\n if not cur_ws and app.app_id in RAMP_ENABLED:\n self._delayed_refresh()","function_tokens":["def","refresh","(","self",")",":","self",".","logger",".","info","(","\"Refreshing app status\"",")","# If we are refreshing but a refresh was planned, cancel that one","with","self",".","_refresh_lock",":","if","self",".","_refresh_timer",":","self",".","_refresh_timer",".","cancel","(",")","self",".","_refresh_timer","=","None","cur_app","=","self",".","app","cur_ws","=","self",".","websocket_client","self",".","app","=","app","=","get_app_status","(","self",".","host",")","# If no previous app and no new app there is nothing to do","if","not","cur_app","and","not","app",":","is_diff_app","=","False","else",":","is_diff_app","=","(","not","cur_app","and","app","or","cur_app","and","not","app","or","cur_app",".","app_id","!=","app",".","app_id",")","# Clean up websocket if:","# - there is a different app and a connection exists","# - if it is the same app but the connection is terminated","if","cur_ws","and","(","is_diff_app","or","cur_ws",".","terminated",")",":","if","not","cur_ws",".","terminated",":","cur_ws",".","close_connection","(",")","self",".","websocket_client","=","cur_ws","=","None","# Create a new websocket client if there is no connection","if","not","cur_ws","and","app",":","try",":","# If the current app is not capable of a websocket client","# This method will return None so nothing is lost","self",".","websocket_client","=","cur_ws","=","create_websocket_client","(","app",")","except","ConnectionError",":","pass","# Ramp service does not always immediately show up in the app","# status. If we do not have a websocket client but the app is","# known to be RAMP controllable, then plan refresh.","if","not","cur_ws","and","app",".","app_id","in","RAMP_ENABLED",":","self",".","_delayed_refresh","(",")"],"url":"https:\/\/github.com\/BishopFox\/rickmote\/blob\/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9\/pychromecast\/__init__.py#L89-L139"}
45
+ {"nwo":"BishopFox\/rickmote","sha":"2a8469657f9de7d6ee1d4cc65ce83235c1e582d9","path":"pychromecast\/__init__.py","language":"python","identifier":"PyChromecast.start_app","parameters":"(self, app_id, data=None)","argument_list":"","return_statement":"","docstring":"Start an app on the Chromecast.","docstring_summary":"Start an app on the Chromecast.","docstring_tokens":["Start","an","app","on","the","Chromecast","."],"function":"def start_app(self, app_id, data=None):\n \"\"\" Start an app on the Chromecast. \"\"\"\n self.logger.info(\"Starting app {}\".format(app_id))\n\n # data parameter has to contain atleast 1 key\n # or else some apps won't show\n start_app(self.host, app_id, data)\n\n self._delayed_refresh()","function_tokens":["def","start_app","(","self",",","app_id",",","data","=","None",")",":","self",".","logger",".","info","(","\"Starting app {}\"",".","format","(","app_id",")",")","# data parameter has to contain atleast 1 key","# or else some apps won't show","start_app","(","self",".","host",",","app_id",",","data",")","self",".","_delayed_refresh","(",")"],"url":"https:\/\/github.com\/BishopFox\/rickmote\/blob\/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9\/pychromecast\/__init__.py#L141-L149"}
46
+ {"nwo":"BishopFox\/rickmote","sha":"2a8469657f9de7d6ee1d4cc65ce83235c1e582d9","path":"pychromecast\/__init__.py","language":"python","identifier":"PyChromecast.quit_app","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Tells the Chromecast to quit current app_id.","docstring_summary":"Tells the Chromecast to quit current app_id.","docstring_tokens":["Tells","the","Chromecast","to","quit","current","app_id","."],"function":"def quit_app(self):\n \"\"\" Tells the Chromecast to quit current app_id. \"\"\"\n self.logger.info(\"Quiting current app\")\n\n quit_app(self.host)\n\n self._delayed_refresh()","function_tokens":["def","quit_app","(","self",")",":","self",".","logger",".","info","(","\"Quiting current app\"",")","quit_app","(","self",".","host",")","self",".","_delayed_refresh","(",")"],"url":"https:\/\/github.com\/BishopFox\/rickmote\/blob\/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9\/pychromecast\/__init__.py#L151-L157"}
47
+ {"nwo":"BishopFox\/rickmote","sha":"2a8469657f9de7d6ee1d4cc65ce83235c1e582d9","path":"pychromecast\/__init__.py","language":"python","identifier":"PyChromecast._delayed_refresh","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Give the ChromeCast time to start the app, then refresh app.","docstring_summary":"Give the ChromeCast time to start the app, then refresh app.","docstring_tokens":["Give","the","ChromeCast","time","to","start","the","app","then","refresh","app","."],"function":"def _delayed_refresh(self):\n \"\"\" Give the ChromeCast time to start the app, then refresh app. \"\"\"\n with self._refresh_lock:\n if self._refresh_timer:\n self._refresh_timer.cancel()\n\n self._refresh_timer = threading.Timer(5, self.refresh)\n self._refresh_timer.start()","function_tokens":["def","_delayed_refresh","(","self",")",":","with","self",".","_refresh_lock",":","if","self",".","_refresh_timer",":","self",".","_refresh_timer",".","cancel","(",")","self",".","_refresh_timer","=","threading",".","Timer","(","5",",","self",".","refresh",")","self",".","_refresh_timer",".","start","(",")"],"url":"https:\/\/github.com\/BishopFox\/rickmote\/blob\/2a8469657f9de7d6ee1d4cc65ce83235c1e582d9\/pychromecast\/__init__.py#L159-L166"}
Blockstream__satellite.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
BoboTiG__python-mss.jsonl ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/windows.py","language":"python","identifier":"MSS.__init__","parameters":"(self, **_)","argument_list":"","return_statement":"","docstring":"Windows initialisations.","docstring_summary":"Windows initialisations.","docstring_tokens":["Windows","initialisations","."],"function":"def __init__(self, **_):\n # type: (Any) -> None\n \"\"\" Windows initialisations. \"\"\"\n\n super().__init__()\n\n self.user32 = ctypes.WinDLL(\"user32\")\n self.gdi32 = ctypes.WinDLL(\"gdi32\")\n self._set_cfunctions()\n self._set_dpi_awareness()\n\n self._bbox = {\"height\": 0, \"width\": 0}\n self._data = ctypes.create_string_buffer(0) # type: ctypes.Array[ctypes.c_char]\n\n srcdc = self._get_srcdc()\n if not MSS.memdc:\n MSS.memdc = self.gdi32.CreateCompatibleDC(srcdc)\n\n bmi = BITMAPINFO()\n bmi.bmiHeader.biSize = ctypes.sizeof(BITMAPINFOHEADER)\n bmi.bmiHeader.biPlanes = 1 # Always 1\n bmi.bmiHeader.biBitCount = 32 # See grab.__doc__ [2]\n bmi.bmiHeader.biCompression = 0 # 0 = BI_RGB (no compression)\n bmi.bmiHeader.biClrUsed = 0 # See grab.__doc__ [3]\n bmi.bmiHeader.biClrImportant = 0 # See grab.__doc__ [3]\n self._bmi = bmi","function_tokens":["def","__init__","(","self",",","*","*","_",")",":","# type: (Any) -> None","super","(",")",".","__init__","(",")","self",".","user32","=","ctypes",".","WinDLL","(","\"user32\"",")","self",".","gdi32","=","ctypes",".","WinDLL","(","\"gdi32\"",")","self",".","_set_cfunctions","(",")","self",".","_set_dpi_awareness","(",")","self",".","_bbox","=","{","\"height\"",":","0",",","\"width\"",":","0","}","self",".","_data","=","ctypes",".","create_string_buffer","(","0",")","# type: ctypes.Array[ctypes.c_char]","srcdc","=","self",".","_get_srcdc","(",")","if","not","MSS",".","memdc",":","MSS",".","memdc","=","self",".","gdi32",".","CreateCompatibleDC","(","srcdc",")","bmi","=","BITMAPINFO","(",")","bmi",".","bmiHeader",".","biSize","=","ctypes",".","sizeof","(","BITMAPINFOHEADER",")","bmi",".","bmiHeader",".","biPlanes","=","1","# Always 1","bmi",".","bmiHeader",".","biBitCount","=","32","# See grab.__doc__ [2]","bmi",".","bmiHeader",".","biCompression","=","0","# 0 = BI_RGB (no compression)","bmi",".","bmiHeader",".","biClrUsed","=","0","# See grab.__doc__ [3]","bmi",".","bmiHeader",".","biClrImportant","=","0","# See grab.__doc__ [3]","self",".","_bmi","=","bmi"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/windows.py#L111-L136"}
2
+ {"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/windows.py","language":"python","identifier":"MSS._set_cfunctions","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Set all ctypes functions and attach them to attributes.","docstring_summary":"Set all ctypes functions and attach them to attributes.","docstring_tokens":["Set","all","ctypes","functions","and","attach","them","to","attributes","."],"function":"def _set_cfunctions(self):\n \"\"\" Set all ctypes functions and attach them to attributes. \"\"\"\n\n cfactory = self._cfactory\n attrs = {\n \"gdi32\": self.gdi32,\n \"user32\": self.user32,\n }\n for func, (attr, argtypes, restype) in CFUNCTIONS.items():\n cfactory(\n attr=attrs[attr],\n func=func,\n argtypes=argtypes,\n restype=restype,\n )","function_tokens":["def","_set_cfunctions","(","self",")",":","cfactory","=","self",".","_cfactory","attrs","=","{","\"gdi32\"",":","self",".","gdi32",",","\"user32\"",":","self",".","user32",",","}","for","func",",","(","attr",",","argtypes",",","restype",")","in","CFUNCTIONS",".","items","(",")",":","cfactory","(","attr","=","attrs","[","attr","]",",","func","=","func",",","argtypes","=","argtypes",",","restype","=","restype",",",")"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/windows.py#L138-L152"}
3
+ {"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/windows.py","language":"python","identifier":"MSS._set_dpi_awareness","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Set DPI awareness to capture full screen on Hi-DPI monitors.","docstring_summary":"Set DPI awareness to capture full screen on Hi-DPI monitors.","docstring_tokens":["Set","DPI","awareness","to","capture","full","screen","on","Hi","-","DPI","monitors","."],"function":"def _set_dpi_awareness(self):\n \"\"\" Set DPI awareness to capture full screen on Hi-DPI monitors. \"\"\"\n\n version = sys.getwindowsversion()[:2] # pylint: disable=no-member\n if version >= (6, 3):\n # Windows 8.1+\n # Here 2 = PROCESS_PER_MONITOR_DPI_AWARE, which means:\n # per monitor DPI aware. This app checks for the DPI when it is\n # created and adjusts the scale factor whenever the DPI changes.\n # These applications are not automatically scaled by the system.\n ctypes.windll.shcore.SetProcessDpiAwareness(2)\n elif (6, 0) <= version < (6, 3):\n # Windows Vista, 7, 8 and Server 2012\n self.user32.SetProcessDPIAware()","function_tokens":["def","_set_dpi_awareness","(","self",")",":","version","=","sys",".","getwindowsversion","(",")","[",":","2","]","# pylint: disable=no-member","if","version",">=","(","6",",","3",")",":","# Windows 8.1+","# Here 2 = PROCESS_PER_MONITOR_DPI_AWARE, which means:","# per monitor DPI aware. This app checks for the DPI when it is","# created and adjusts the scale factor whenever the DPI changes.","# These applications are not automatically scaled by the system.","ctypes",".","windll",".","shcore",".","SetProcessDpiAwareness","(","2",")","elif","(","6",",","0",")","<=","version","<","(","6",",","3",")",":","# Windows Vista, 7, 8 and Server 2012","self",".","user32",".","SetProcessDPIAware","(",")"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/windows.py#L154-L167"}
4
+ {"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/windows.py","language":"python","identifier":"MSS._get_srcdc","parameters":"(self)","argument_list":"","return_statement":"return srcdc","docstring":"Retrieve a thread-safe HDC from GetWindowDC().\n In multithreading, if the thread that creates *srcdc* is dead, *srcdc* will\n no longer be valid to grab the screen. The *srcdc* attribute is replaced\n with *_srcdc_dict* to maintain the *srcdc* values in multithreading.\n Since the current thread and main thread are always alive, reuse their *srcdc* value first.","docstring_summary":"Retrieve a thread-safe HDC from GetWindowDC().\n In multithreading, if the thread that creates *srcdc* is dead, *srcdc* will\n no longer be valid to grab the screen. The *srcdc* attribute is replaced\n with *_srcdc_dict* to maintain the *srcdc* values in multithreading.\n Since the current thread and main thread are always alive, reuse their *srcdc* value first.","docstring_tokens":["Retrieve","a","thread","-","safe","HDC","from","GetWindowDC","()",".","In","multithreading","if","the","thread","that","creates","*","srcdc","*","is","dead","*","srcdc","*","will","no","longer","be","valid","to","grab","the","screen",".","The","*","srcdc","*","attribute","is","replaced","with","*","_srcdc_dict","*","to","maintain","the","*","srcdc","*","values","in","multithreading",".","Since","the","current","thread","and","main","thread","are","always","alive","reuse","their","*","srcdc","*","value","first","."],"function":"def _get_srcdc(self):\n \"\"\"\n Retrieve a thread-safe HDC from GetWindowDC().\n In multithreading, if the thread that creates *srcdc* is dead, *srcdc* will\n no longer be valid to grab the screen. The *srcdc* attribute is replaced\n with *_srcdc_dict* to maintain the *srcdc* values in multithreading.\n Since the current thread and main thread are always alive, reuse their *srcdc* value first.\n \"\"\"\n cur_thread, main_thread = threading.current_thread(), threading.main_thread()\n srcdc = MSS._srcdc_dict.get(cur_thread) or MSS._srcdc_dict.get(main_thread)\n if not srcdc:\n srcdc = MSS._srcdc_dict[cur_thread] = self.user32.GetWindowDC(0)\n return srcdc","function_tokens":["def","_get_srcdc","(","self",")",":","cur_thread",",","main_thread","=","threading",".","current_thread","(",")",",","threading",".","main_thread","(",")","srcdc","=","MSS",".","_srcdc_dict",".","get","(","cur_thread",")","or","MSS",".","_srcdc_dict",".","get","(","main_thread",")","if","not","srcdc",":","srcdc","=","MSS",".","_srcdc_dict","[","cur_thread","]","=","self",".","user32",".","GetWindowDC","(","0",")","return","srcdc"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/windows.py#L169-L181"}
5
+ {"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/windows.py","language":"python","identifier":"MSS._monitors_impl","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Get positions of monitors. It will populate self._monitors.","docstring_summary":"Get positions of monitors. It will populate self._monitors.","docstring_tokens":["Get","positions","of","monitors",".","It","will","populate","self",".","_monitors","."],"function":"def _monitors_impl(self):\n # type: () -> None\n \"\"\" Get positions of monitors. It will populate self._monitors. \"\"\"\n\n int_ = int\n user32 = self.user32\n get_system_metrics = user32.GetSystemMetrics\n\n # All monitors\n self._monitors.append(\n {\n \"left\": int_(get_system_metrics(76)), # SM_XVIRTUALSCREEN\n \"top\": int_(get_system_metrics(77)), # SM_YVIRTUALSCREEN\n \"width\": int_(get_system_metrics(78)), # SM_CXVIRTUALSCREEN\n \"height\": int_(get_system_metrics(79)), # SM_CYVIRTUALSCREEN\n }\n )\n\n # Each monitor\n def _callback(monitor, data, rect, dc_):\n # types: (int, HDC, LPRECT, LPARAM) -> int\n \"\"\"\n Callback for monitorenumproc() function, it will return\n a RECT with appropriate values.\n \"\"\"\n # pylint: disable=unused-argument\n\n rct = rect.contents\n self._monitors.append(\n {\n \"left\": int_(rct.left),\n \"top\": int_(rct.top),\n \"width\": int_(rct.right - rct.left),\n \"height\": int_(rct.bottom - rct.top),\n }\n )\n return 1\n\n callback = MONITORNUMPROC(_callback)\n user32.EnumDisplayMonitors(0, 0, callback, 0)","function_tokens":["def","_monitors_impl","(","self",")",":","# type: () -> None","int_","=","int","user32","=","self",".","user32","get_system_metrics","=","user32",".","GetSystemMetrics","# All monitors","self",".","_monitors",".","append","(","{","\"left\"",":","int_","(","get_system_metrics","(","76",")",")",",","# SM_XVIRTUALSCREEN","\"top\"",":","int_","(","get_system_metrics","(","77",")",")",",","# SM_YVIRTUALSCREEN","\"width\"",":","int_","(","get_system_metrics","(","78",")",")",",","# SM_CXVIRTUALSCREEN","\"height\"",":","int_","(","get_system_metrics","(","79",")",")",",","# SM_CYVIRTUALSCREEN","}",")","# Each monitor","def","_callback","(","monitor",",","data",",","rect",",","dc_",")",":","# types: (int, HDC, LPRECT, LPARAM) -> int","\"\"\"\n Callback for monitorenumproc() function, it will return\n a RECT with appropriate values.\n \"\"\"","# pylint: disable=unused-argument","rct","=","rect",".","contents","self",".","_monitors",".","append","(","{","\"left\"",":","int_","(","rct",".","left",")",",","\"top\"",":","int_","(","rct",".","top",")",",","\"width\"",":","int_","(","rct",".","right","-","rct",".","left",")",",","\"height\"",":","int_","(","rct",".","bottom","-","rct",".","top",")",",","}",")","return","1","callback","=","MONITORNUMPROC","(","_callback",")","user32",".","EnumDisplayMonitors","(","0",",","0",",","callback",",","0",")"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/windows.py#L183-L222"}
6
+ {"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/windows.py","language":"python","identifier":"MSS._grab_impl","parameters":"(self, monitor)","argument_list":"","return_statement":"return self.cls_image(bytearray(self._data), monitor)","docstring":"Retrieve all pixels from a monitor. Pixels have to be RGB.\n\n In the code, there are a few interesting things:\n\n [1] bmi.bmiHeader.biHeight = -height\n\n A bottom-up DIB is specified by setting the height to a\n positive number, while a top-down DIB is specified by\n setting the height to a negative number.\n https:\/\/msdn.microsoft.com\/en-us\/library\/ms787796.aspx\n https:\/\/msdn.microsoft.com\/en-us\/library\/dd144879%28v=vs.85%29.aspx\n\n\n [2] bmi.bmiHeader.biBitCount = 32\n image_data = create_string_buffer(height * width * 4)\n\n We grab the image in RGBX mode, so that each word is 32bit\n and we have no striding.\n Inspired by https:\/\/github.com\/zoofIO\/flexx\n\n\n [3] bmi.bmiHeader.biClrUsed = 0\n bmi.bmiHeader.biClrImportant = 0\n\n When biClrUsed and biClrImportant are set to zero, there\n is \"no\" color table, so we can read the pixels of the bitmap\n retrieved by gdi32.GetDIBits() as a sequence of RGB values.\n Thanks to http:\/\/stackoverflow.com\/a\/3688682","docstring_summary":"Retrieve all pixels from a monitor. Pixels have to be RGB.","docstring_tokens":["Retrieve","all","pixels","from","a","monitor",".","Pixels","have","to","be","RGB","."],"function":"def _grab_impl(self, monitor):\n # type: (Monitor) -> ScreenShot\n \"\"\"\n Retrieve all pixels from a monitor. Pixels have to be RGB.\n\n In the code, there are a few interesting things:\n\n [1] bmi.bmiHeader.biHeight = -height\n\n A bottom-up DIB is specified by setting the height to a\n positive number, while a top-down DIB is specified by\n setting the height to a negative number.\n https:\/\/msdn.microsoft.com\/en-us\/library\/ms787796.aspx\n https:\/\/msdn.microsoft.com\/en-us\/library\/dd144879%28v=vs.85%29.aspx\n\n\n [2] bmi.bmiHeader.biBitCount = 32\n image_data = create_string_buffer(height * width * 4)\n\n We grab the image in RGBX mode, so that each word is 32bit\n and we have no striding.\n Inspired by https:\/\/github.com\/zoofIO\/flexx\n\n\n [3] bmi.bmiHeader.biClrUsed = 0\n bmi.bmiHeader.biClrImportant = 0\n\n When biClrUsed and biClrImportant are set to zero, there\n is \"no\" color table, so we can read the pixels of the bitmap\n retrieved by gdi32.GetDIBits() as a sequence of RGB values.\n Thanks to http:\/\/stackoverflow.com\/a\/3688682\n \"\"\"\n\n srcdc, memdc = self._get_srcdc(), MSS.memdc\n width, height = monitor[\"width\"], monitor[\"height\"]\n\n if (self._bbox[\"height\"], self._bbox[\"width\"]) != (height, width):\n self._bbox = monitor\n self._bmi.bmiHeader.biWidth = width\n self._bmi.bmiHeader.biHeight = -height # Why minus? [1]\n self._data = ctypes.create_string_buffer(width * height * 4) # [2]\n if MSS.bmp:\n self.gdi32.DeleteObject(MSS.bmp)\n MSS.bmp = self.gdi32.CreateCompatibleBitmap(srcdc, width, height)\n self.gdi32.SelectObject(memdc, MSS.bmp)\n\n self.gdi32.BitBlt(\n memdc,\n 0,\n 0,\n width,\n height,\n srcdc,\n monitor[\"left\"],\n monitor[\"top\"],\n SRCCOPY | CAPTUREBLT,\n )\n bits = self.gdi32.GetDIBits(\n memdc, MSS.bmp, 0, height, self._data, self._bmi, DIB_RGB_COLORS\n )\n if bits != height:\n raise ScreenShotError(\"gdi32.GetDIBits() failed.\")\n\n return self.cls_image(bytearray(self._data), monitor)","function_tokens":["def","_grab_impl","(","self",",","monitor",")",":","# type: (Monitor) -> ScreenShot","srcdc",",","memdc","=","self",".","_get_srcdc","(",")",",","MSS",".","memdc","width",",","height","=","monitor","[","\"width\"","]",",","monitor","[","\"height\"","]","if","(","self",".","_bbox","[","\"height\"","]",",","self",".","_bbox","[","\"width\"","]",")","!=","(","height",",","width",")",":","self",".","_bbox","=","monitor","self",".","_bmi",".","bmiHeader",".","biWidth","=","width","self",".","_bmi",".","bmiHeader",".","biHeight","=","-","height","# Why minus? [1]","self",".","_data","=","ctypes",".","create_string_buffer","(","width","*","height","*","4",")","# [2]","if","MSS",".","bmp",":","self",".","gdi32",".","DeleteObject","(","MSS",".","bmp",")","MSS",".","bmp","=","self",".","gdi32",".","CreateCompatibleBitmap","(","srcdc",",","width",",","height",")","self",".","gdi32",".","SelectObject","(","memdc",",","MSS",".","bmp",")","self",".","gdi32",".","BitBlt","(","memdc",",","0",",","0",",","width",",","height",",","srcdc",",","monitor","[","\"left\"","]",",","monitor","[","\"top\"","]",",","SRCCOPY","|","CAPTUREBLT",",",")","bits","=","self",".","gdi32",".","GetDIBits","(","memdc",",","MSS",".","bmp",",","0",",","height",",","self",".","_data",",","self",".","_bmi",",","DIB_RGB_COLORS",")","if","bits","!=","height",":","raise","ScreenShotError","(","\"gdi32.GetDIBits() failed.\"",")","return","self",".","cls_image","(","bytearray","(","self",".","_data",")",",","monitor",")"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/windows.py#L224-L287"}
7
+ {"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/screenshot.py","language":"python","identifier":"ScreenShot.__array_interface__","parameters":"(self)","argument_list":"","return_statement":"return {\n \"version\": 3,\n \"shape\": (self.height, self.width, 4),\n \"typestr\": \"|u1\",\n \"data\": self.raw,\n }","docstring":"Numpy array interface support.\n It uses raw data in BGRA form.\n\n See https:\/\/docs.scipy.org\/doc\/numpy\/reference\/arrays.interface.html","docstring_summary":"Numpy array interface support.\n It uses raw data in BGRA form.","docstring_tokens":["Numpy","array","interface","support",".","It","uses","raw","data","in","BGRA","form","."],"function":"def __array_interface__(self):\n # type: () -> Dict[str, Any]\n \"\"\"\n Numpy array interface support.\n It uses raw data in BGRA form.\n\n See https:\/\/docs.scipy.org\/doc\/numpy\/reference\/arrays.interface.html\n \"\"\"\n\n return {\n \"version\": 3,\n \"shape\": (self.height, self.width, 4),\n \"typestr\": \"|u1\",\n \"data\": self.raw,\n }","function_tokens":["def","__array_interface__","(","self",")",":","# type: () -> Dict[str, Any]","return","{","\"version\"",":","3",",","\"shape\"",":","(","self",".","height",",","self",".","width",",","4",")",",","\"typestr\"",":","\"|u1\"",",","\"data\"",":","self",".","raw",",","}"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/screenshot.py#L54-L68"}
8
+ {"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/screenshot.py","language":"python","identifier":"ScreenShot.from_size","parameters":"(cls, data, width, height)","argument_list":"","return_statement":"return cls(data, monitor)","docstring":"Instantiate a new class given only screen shot's data and size.","docstring_summary":"Instantiate a new class given only screen shot's data and size.","docstring_tokens":["Instantiate","a","new","class","given","only","screen","shot","s","data","and","size","."],"function":"def from_size(cls, data, width, height):\n # type: (bytearray, int, int) -> ScreenShot\n \"\"\" Instantiate a new class given only screen shot's data and size. \"\"\"\n\n monitor = {\"left\": 0, \"top\": 0, \"width\": width, \"height\": height}\n return cls(data, monitor)","function_tokens":["def","from_size","(","cls",",","data",",","width",",","height",")",":","# type: (bytearray, int, int) -> ScreenShot","monitor","=","{","\"left\"",":","0",",","\"top\"",":","0",",","\"width\"",":","width",",","\"height\"",":","height","}","return","cls","(","data",",","monitor",")"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/screenshot.py#L71-L76"}
9
+ {"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/screenshot.py","language":"python","identifier":"ScreenShot.bgra","parameters":"(self)","argument_list":"","return_statement":"return bytes(self.raw)","docstring":"BGRA values from the BGRA raw pixels.","docstring_summary":"BGRA values from the BGRA raw pixels.","docstring_tokens":["BGRA","values","from","the","BGRA","raw","pixels","."],"function":"def bgra(self):\n # type: () -> bytes\n \"\"\" BGRA values from the BGRA raw pixels. \"\"\"\n return bytes(self.raw)","function_tokens":["def","bgra","(","self",")",":","# type: () -> bytes","return","bytes","(","self",".","raw",")"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/screenshot.py#L79-L82"}
10
+ {"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/screenshot.py","language":"python","identifier":"ScreenShot.height","parameters":"(self)","argument_list":"","return_statement":"return self.size.height","docstring":"Convenient accessor to the height size.","docstring_summary":"Convenient accessor to the height size.","docstring_tokens":["Convenient","accessor","to","the","height","size","."],"function":"def height(self):\n # type: () -> int\n \"\"\" Convenient accessor to the height size. \"\"\"\n return self.size.height","function_tokens":["def","height","(","self",")",":","# type: () -> int","return","self",".","size",".","height"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/screenshot.py#L85-L88"}
11
+ {"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/screenshot.py","language":"python","identifier":"ScreenShot.left","parameters":"(self)","argument_list":"","return_statement":"return self.pos.left","docstring":"Convenient accessor to the left position.","docstring_summary":"Convenient accessor to the left position.","docstring_tokens":["Convenient","accessor","to","the","left","position","."],"function":"def left(self):\n # type: () -> int\n \"\"\" Convenient accessor to the left position. \"\"\"\n return self.pos.left","function_tokens":["def","left","(","self",")",":","# type: () -> int","return","self",".","pos",".","left"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/screenshot.py#L91-L94"}
12
+ {"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/screenshot.py","language":"python","identifier":"ScreenShot.pixels","parameters":"(self)","argument_list":"","return_statement":"return self.__pixels","docstring":":return list: RGB tuples.","docstring_summary":":return list: RGB tuples.","docstring_tokens":[":","return","list",":","RGB","tuples","."],"function":"def pixels(self):\n # type: () -> Pixels\n \"\"\"\n :return list: RGB tuples.\n \"\"\"\n\n if not self.__pixels:\n rgb_tuples = zip(\n self.raw[2::4], self.raw[1::4], self.raw[0::4]\n ) # type: Iterator[Pixel]\n self.__pixels = list(zip(*[iter(rgb_tuples)] * self.width)) # type: ignore\n\n return self.__pixels","function_tokens":["def","pixels","(","self",")",":","# type: () -> Pixels","if","not","self",".","__pixels",":","rgb_tuples","=","zip","(","self",".","raw","[","2",":",":","4","]",",","self",".","raw","[","1",":",":","4","]",",","self",".","raw","[","0",":",":","4","]",")","# type: Iterator[Pixel]","self",".","__pixels","=","list","(","zip","(","*","[","iter","(","rgb_tuples",")","]","*","self",".","width",")",")","# type: ignore","return","self",".","__pixels"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/screenshot.py#L97-L109"}
13
+ {"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/screenshot.py","language":"python","identifier":"ScreenShot.rgb","parameters":"(self)","argument_list":"","return_statement":"return self.__rgb","docstring":"Compute RGB values from the BGRA raw pixels.\n\n :return bytes: RGB pixels.","docstring_summary":"Compute RGB values from the BGRA raw pixels.","docstring_tokens":["Compute","RGB","values","from","the","BGRA","raw","pixels","."],"function":"def rgb(self):\n # type: () -> bytes\n \"\"\"\n Compute RGB values from the BGRA raw pixels.\n\n :return bytes: RGB pixels.\n \"\"\"\n\n if not self.__rgb:\n rgb = bytearray(self.height * self.width * 3)\n raw = self.raw\n rgb[0::3] = raw[2::4]\n rgb[1::3] = raw[1::4]\n rgb[2::3] = raw[0::4]\n self.__rgb = bytes(rgb)\n\n return self.__rgb","function_tokens":["def","rgb","(","self",")",":","# type: () -> bytes","if","not","self",".","__rgb",":","rgb","=","bytearray","(","self",".","height","*","self",".","width","*","3",")","raw","=","self",".","raw","rgb","[","0",":",":","3","]","=","raw","[","2",":",":","4","]","rgb","[","1",":",":","3","]","=","raw","[","1",":",":","4","]","rgb","[","2",":",":","3","]","=","raw","[","0",":",":","4","]","self",".","__rgb","=","bytes","(","rgb",")","return","self",".","__rgb"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/screenshot.py#L112-L128"}
14
+ {"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/screenshot.py","language":"python","identifier":"ScreenShot.top","parameters":"(self)","argument_list":"","return_statement":"return self.pos.top","docstring":"Convenient accessor to the top position.","docstring_summary":"Convenient accessor to the top position.","docstring_tokens":["Convenient","accessor","to","the","top","position","."],"function":"def top(self):\n # type: () -> int\n \"\"\" Convenient accessor to the top position. \"\"\"\n return self.pos.top","function_tokens":["def","top","(","self",")",":","# type: () -> int","return","self",".","pos",".","top"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/screenshot.py#L131-L134"}
15
+ {"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/screenshot.py","language":"python","identifier":"ScreenShot.width","parameters":"(self)","argument_list":"","return_statement":"return self.size.width","docstring":"Convenient accessor to the width size.","docstring_summary":"Convenient accessor to the width size.","docstring_tokens":["Convenient","accessor","to","the","width","size","."],"function":"def width(self):\n # type: () -> int\n \"\"\" Convenient accessor to the width size. \"\"\"\n return self.size.width","function_tokens":["def","width","(","self",")",":","# type: () -> int","return","self",".","size",".","width"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/screenshot.py#L137-L140"}
16
+ {"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/screenshot.py","language":"python","identifier":"ScreenShot.pixel","parameters":"(self, coord_x, coord_y)","argument_list":"","return_statement":"","docstring":"Returns the pixel value at a given position.\n\n :param int coord_x: The x coordinate.\n :param int coord_y: The y coordinate.\n :return tuple: The pixel value as (R, G, B).","docstring_summary":"Returns the pixel value at a given position.","docstring_tokens":["Returns","the","pixel","value","at","a","given","position","."],"function":"def pixel(self, coord_x, coord_y):\n # type: (int, int) -> Pixel\n \"\"\"\n Returns the pixel value at a given position.\n\n :param int coord_x: The x coordinate.\n :param int coord_y: The y coordinate.\n :return tuple: The pixel value as (R, G, B).\n \"\"\"\n\n try:\n return self.pixels[coord_y][coord_x] # type: ignore\n except IndexError:\n # pylint: disable=raise-missing-from\n raise ScreenShotError(\n \"Pixel location ({}, {}) is out of range.\".format(coord_x, coord_y)\n )","function_tokens":["def","pixel","(","self",",","coord_x",",","coord_y",")",":","# type: (int, int) -> Pixel","try",":","return","self",".","pixels","[","coord_y","]","[","coord_x","]","# type: ignore","except","IndexError",":","# pylint: disable=raise-missing-from","raise","ScreenShotError","(","\"Pixel location ({}, {}) is out of range.\"",".","format","(","coord_x",",","coord_y",")",")"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/screenshot.py#L142-L158"}
17
+ {"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/factory.py","language":"python","identifier":"mss","parameters":"(**kwargs)","argument_list":"","return_statement":"","docstring":"Factory returning a proper MSS class instance.\n\n It detects the platform we are running on\n and chooses the most adapted mss_class to take\n screenshots.\n\n It then proxies its arguments to the class for\n instantiation.","docstring_summary":"Factory returning a proper MSS class instance.","docstring_tokens":["Factory","returning","a","proper","MSS","class","instance","."],"function":"def mss(**kwargs):\n # type: (Any) -> MSSBase\n \"\"\" Factory returning a proper MSS class instance.\n\n It detects the platform we are running on\n and chooses the most adapted mss_class to take\n screenshots.\n\n It then proxies its arguments to the class for\n instantiation.\n \"\"\"\n # pylint: disable=import-outside-toplevel\n\n os_ = platform.system().lower()\n\n if os_ == \"darwin\":\n from . import darwin\n\n return darwin.MSS(**kwargs)\n\n if os_ == \"linux\":\n from . import linux\n\n return linux.MSS(**kwargs)\n\n if os_ == \"windows\":\n from . import windows\n\n return windows.MSS(**kwargs)\n\n raise ScreenShotError(\"System {!r} not (yet?) implemented.\".format(os_))","function_tokens":["def","mss","(","*","*","kwargs",")",":","# type: (Any) -> MSSBase","# pylint: disable=import-outside-toplevel","os_","=","platform",".","system","(",")",".","lower","(",")","if","os_","==","\"darwin\"",":","from",".","import","darwin","return","darwin",".","MSS","(","*","*","kwargs",")","if","os_","==","\"linux\"",":","from",".","import","linux","return","linux",".","MSS","(","*","*","kwargs",")","if","os_","==","\"windows\"",":","from",".","import","windows","return","windows",".","MSS","(","*","*","kwargs",")","raise","ScreenShotError","(","\"System {!r} not (yet?) implemented.\"",".","format","(","os_",")",")"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/factory.py#L18-L48"}
18
+ {"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/base.py","language":"python","identifier":"MSSBase.__enter__","parameters":"(self)","argument_list":"","return_statement":"return self","docstring":"For the cool call `with MSS() as mss:`.","docstring_summary":"For the cool call `with MSS() as mss:`.","docstring_tokens":["For","the","cool","call","with","MSS","()","as","mss",":","."],"function":"def __enter__(self):\n # type: () -> MSSBase\n \"\"\" For the cool call `with MSS() as mss:`. \"\"\"\n\n return self","function_tokens":["def","__enter__","(","self",")",":","# type: () -> MSSBase","return","self"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/base.py#L35-L39"}
19
+ {"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/base.py","language":"python","identifier":"MSSBase.__exit__","parameters":"(self, *_)","argument_list":"","return_statement":"","docstring":"For the cool call `with MSS() as mss:`.","docstring_summary":"For the cool call `with MSS() as mss:`.","docstring_tokens":["For","the","cool","call","with","MSS","()","as","mss",":","."],"function":"def __exit__(self, *_):\n \"\"\" For the cool call `with MSS() as mss:`. \"\"\"\n\n self.close()","function_tokens":["def","__exit__","(","self",",","*","_",")",":","self",".","close","(",")"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/base.py#L41-L44"}
20
+ {"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/base.py","language":"python","identifier":"MSSBase._grab_impl","parameters":"(self, monitor)","argument_list":"","return_statement":"","docstring":"Retrieve all pixels from a monitor. Pixels have to be RGB.\n That method has to be run using a threading lock.","docstring_summary":"Retrieve all pixels from a monitor. Pixels have to be RGB.\n That method has to be run using a threading lock.","docstring_tokens":["Retrieve","all","pixels","from","a","monitor",".","Pixels","have","to","be","RGB",".","That","method","has","to","be","run","using","a","threading","lock","."],"function":"def _grab_impl(self, monitor):\n # type: (Monitor) -> ScreenShot\n \"\"\"\n Retrieve all pixels from a monitor. Pixels have to be RGB.\n That method has to be run using a threading lock.\n \"\"\"","function_tokens":["def","_grab_impl","(","self",",","monitor",")",":","# type: (Monitor) -> ScreenShot"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/base.py#L47-L52"}
21
+ {"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/base.py","language":"python","identifier":"MSSBase._monitors_impl","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Get positions of monitors (has to be run using a threading lock).\n It must populate self._monitors.","docstring_summary":"Get positions of monitors (has to be run using a threading lock).\n It must populate self._monitors.","docstring_tokens":["Get","positions","of","monitors","(","has","to","be","run","using","a","threading","lock",")",".","It","must","populate","self",".","_monitors","."],"function":"def _monitors_impl(self):\n # type: () -> None\n \"\"\"\n Get positions of monitors (has to be run using a threading lock).\n It must populate self._monitors.\n \"\"\"","function_tokens":["def","_monitors_impl","(","self",")",":","# type: () -> None"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/base.py#L55-L60"}
22
+ {"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/base.py","language":"python","identifier":"MSSBase.close","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Clean-up.","docstring_summary":"Clean-up.","docstring_tokens":["Clean","-","up","."],"function":"def close(self):\n # type: () -> None\n \"\"\" Clean-up. \"\"\"","function_tokens":["def","close","(","self",")",":","# type: () -> None"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/base.py#L62-L64"}
23
+ {"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/base.py","language":"python","identifier":"MSSBase.grab","parameters":"(self, monitor)","argument_list":"","return_statement":"","docstring":"Retrieve screen pixels for a given monitor.\n\n Note: *monitor* can be a tuple like the one PIL.Image.grab() accepts.\n\n :param monitor: The coordinates and size of the box to capture.\n See :meth:`monitors <monitors>` for object details.\n :return :class:`ScreenShot <ScreenShot>`.","docstring_summary":"Retrieve screen pixels for a given monitor.","docstring_tokens":["Retrieve","screen","pixels","for","a","given","monitor","."],"function":"def grab(self, monitor):\n # type: (Monitor) -> ScreenShot\n \"\"\"\n Retrieve screen pixels for a given monitor.\n\n Note: *monitor* can be a tuple like the one PIL.Image.grab() accepts.\n\n :param monitor: The coordinates and size of the box to capture.\n See :meth:`monitors <monitors>` for object details.\n :return :class:`ScreenShot <ScreenShot>`.\n \"\"\"\n\n # Convert PIL bbox style\n if isinstance(monitor, tuple):\n monitor = {\n \"left\": monitor[0],\n \"top\": monitor[1],\n \"width\": monitor[2] - monitor[0],\n \"height\": monitor[3] - monitor[1],\n }\n\n with lock:\n return self._grab_impl(monitor)","function_tokens":["def","grab","(","self",",","monitor",")",":","# type: (Monitor) -> ScreenShot","# Convert PIL bbox style","if","isinstance","(","monitor",",","tuple",")",":","monitor","=","{","\"left\"",":","monitor","[","0","]",",","\"top\"",":","monitor","[","1","]",",","\"width\"",":","monitor","[","2","]","-","monitor","[","0","]",",","\"height\"",":","monitor","[","3","]","-","monitor","[","1","]",",","}","with","lock",":","return","self",".","_grab_impl","(","monitor",")"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/base.py#L66-L88"}
24
+ {"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/base.py","language":"python","identifier":"MSSBase.monitors","parameters":"(self)","argument_list":"","return_statement":"return self._monitors","docstring":"Get positions of all monitors.\n If the monitor has rotation, you have to deal with it\n inside this method.\n\n This method has to fill self._monitors with all information\n and use it as a cache:\n self._monitors[0] is a dict of all monitors together\n self._monitors[N] is a dict of the monitor N (with N > 0)\n\n Each monitor is a dict with:\n {\n 'left': the x-coordinate of the upper-left corner,\n 'top': the y-coordinate of the upper-left corner,\n 'width': the width,\n 'height': the height\n }","docstring_summary":"Get positions of all monitors.\n If the monitor has rotation, you have to deal with it\n inside this method.","docstring_tokens":["Get","positions","of","all","monitors",".","If","the","monitor","has","rotation","you","have","to","deal","with","it","inside","this","method","."],"function":"def monitors(self):\n # type: () -> Monitors\n \"\"\"\n Get positions of all monitors.\n If the monitor has rotation, you have to deal with it\n inside this method.\n\n This method has to fill self._monitors with all information\n and use it as a cache:\n self._monitors[0] is a dict of all monitors together\n self._monitors[N] is a dict of the monitor N (with N > 0)\n\n Each monitor is a dict with:\n {\n 'left': the x-coordinate of the upper-left corner,\n 'top': the y-coordinate of the upper-left corner,\n 'width': the width,\n 'height': the height\n }\n \"\"\"\n\n if not self._monitors:\n with lock:\n self._monitors_impl()\n\n return self._monitors","function_tokens":["def","monitors","(","self",")",":","# type: () -> Monitors","if","not","self",".","_monitors",":","with","lock",":","self",".","_monitors_impl","(",")","return","self",".","_monitors"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/base.py#L91-L116"}
25
+ {"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/base.py","language":"python","identifier":"MSSBase.save","parameters":"(self, mon=0, output=\"monitor-{mon}.png\", callback=None)","argument_list":"","return_statement":"","docstring":"Grab a screen shot and save it to a file.\n\n :param int mon: The monitor to screen shot (default=0).\n -1: grab one screen shot of all monitors\n 0: grab one screen shot by monitor\n N: grab the screen shot of the monitor N\n\n :param str output: The output filename.\n\n It can take several keywords to customize the filename:\n - `{mon}`: the monitor number\n - `{top}`: the screen shot y-coordinate of the upper-left corner\n - `{left}`: the screen shot x-coordinate of the upper-left corner\n - `{width}`: the screen shot's width\n - `{height}`: the screen shot's height\n - `{date}`: the current date using the default formatter\n\n As it is using the `format()` function, you can specify\n formatting options like `{date:%Y-%m-%s}`.\n\n :param callable callback: Callback called before saving the\n screen shot to a file. Take the `output` argument as parameter.\n\n :return generator: Created file(s).","docstring_summary":"Grab a screen shot and save it to a file.","docstring_tokens":["Grab","a","screen","shot","and","save","it","to","a","file","."],"function":"def save(self, mon=0, output=\"monitor-{mon}.png\", callback=None):\n # type: (int, str, Callable[[str], None]) -> Iterator[str]\n \"\"\"\n Grab a screen shot and save it to a file.\n\n :param int mon: The monitor to screen shot (default=0).\n -1: grab one screen shot of all monitors\n 0: grab one screen shot by monitor\n N: grab the screen shot of the monitor N\n\n :param str output: The output filename.\n\n It can take several keywords to customize the filename:\n - `{mon}`: the monitor number\n - `{top}`: the screen shot y-coordinate of the upper-left corner\n - `{left}`: the screen shot x-coordinate of the upper-left corner\n - `{width}`: the screen shot's width\n - `{height}`: the screen shot's height\n - `{date}`: the current date using the default formatter\n\n As it is using the `format()` function, you can specify\n formatting options like `{date:%Y-%m-%s}`.\n\n :param callable callback: Callback called before saving the\n screen shot to a file. Take the `output` argument as parameter.\n\n :return generator: Created file(s).\n \"\"\"\n\n monitors = self.monitors\n if not monitors:\n raise ScreenShotError(\"No monitor found.\")\n\n if mon == 0:\n # One screen shot by monitor\n for idx, monitor in enumerate(monitors[1:], 1):\n fname = output.format(mon=idx, date=datetime.now(), **monitor)\n if callable(callback):\n callback(fname)\n sct = self.grab(monitor)\n to_png(sct.rgb, sct.size, level=self.compression_level, output=fname)\n yield fname\n else:\n # A screen shot of all monitors together or\n # a screen shot of the monitor N.\n mon = 0 if mon == -1 else mon\n try:\n monitor = monitors[mon]\n except IndexError:\n # pylint: disable=raise-missing-from\n raise ScreenShotError(\"Monitor {!r} does not exist.\".format(mon))\n\n output = output.format(mon=mon, date=datetime.now(), **monitor)\n if callable(callback):\n callback(output)\n sct = self.grab(monitor)\n to_png(sct.rgb, sct.size, level=self.compression_level, output=output)\n yield output","function_tokens":["def","save","(","self",",","mon","=","0",",","output","=","\"monitor-{mon}.png\"",",","callback","=","None",")",":","# type: (int, str, Callable[[str], None]) -> Iterator[str]","monitors","=","self",".","monitors","if","not","monitors",":","raise","ScreenShotError","(","\"No monitor found.\"",")","if","mon","==","0",":","# One screen shot by monitor","for","idx",",","monitor","in","enumerate","(","monitors","[","1",":","]",",","1",")",":","fname","=","output",".","format","(","mon","=","idx",",","date","=","datetime",".","now","(",")",",","*","*","monitor",")","if","callable","(","callback",")",":","callback","(","fname",")","sct","=","self",".","grab","(","monitor",")","to_png","(","sct",".","rgb",",","sct",".","size",",","level","=","self",".","compression_level",",","output","=","fname",")","yield","fname","else",":","# A screen shot of all monitors together or","# a screen shot of the monitor N.","mon","=","0","if","mon","==","-","1","else","mon","try",":","monitor","=","monitors","[","mon","]","except","IndexError",":","# pylint: disable=raise-missing-from","raise","ScreenShotError","(","\"Monitor {!r} does not exist.\"",".","format","(","mon",")",")","output","=","output",".","format","(","mon","=","mon",",","date","=","datetime",".","now","(",")",",","*","*","monitor",")","if","callable","(","callback",")",":","callback","(","output",")","sct","=","self",".","grab","(","monitor",")","to_png","(","sct",".","rgb",",","sct",".","size",",","level","=","self",".","compression_level",",","output","=","output",")","yield","output"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/base.py#L118-L175"}
26
+ {"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/base.py","language":"python","identifier":"MSSBase.shot","parameters":"(self, **kwargs)","argument_list":"","return_statement":"return next(self.save(**kwargs))","docstring":"Helper to save the screen shot of the 1st monitor, by default.\n You can pass the same arguments as for ``save``.","docstring_summary":"Helper to save the screen shot of the 1st monitor, by default.\n You can pass the same arguments as for ``save``.","docstring_tokens":["Helper","to","save","the","screen","shot","of","the","1st","monitor","by","default",".","You","can","pass","the","same","arguments","as","for","save","."],"function":"def shot(self, **kwargs):\n # type: (Any) -> str\n \"\"\"\n Helper to save the screen shot of the 1st monitor, by default.\n You can pass the same arguments as for ``save``.\n \"\"\"\n\n kwargs[\"mon\"] = kwargs.get(\"mon\", 1)\n return next(self.save(**kwargs))","function_tokens":["def","shot","(","self",",","*","*","kwargs",")",":","# type: (Any) -> str","kwargs","[","\"mon\"","]","=","kwargs",".","get","(","\"mon\"",",","1",")","return","next","(","self",".","save","(","*","*","kwargs",")",")"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/base.py#L177-L185"}
27
+ {"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/base.py","language":"python","identifier":"MSSBase._cfactory","parameters":"(attr, func, argtypes, restype, errcheck=None)","argument_list":"","return_statement":"","docstring":"Factory to create a ctypes function and automatically manage errors.","docstring_summary":"Factory to create a ctypes function and automatically manage errors.","docstring_tokens":["Factory","to","create","a","ctypes","function","and","automatically","manage","errors","."],"function":"def _cfactory(attr, func, argtypes, restype, errcheck=None):\n # type: (Any, str, List[Any], Any, Optional[Callable]) -> None\n \"\"\" Factory to create a ctypes function and automatically manage errors. \"\"\"\n\n meth = getattr(attr, func)\n meth.argtypes = argtypes\n meth.restype = restype\n if errcheck:\n meth.errcheck = errcheck","function_tokens":["def","_cfactory","(","attr",",","func",",","argtypes",",","restype",",","errcheck","=","None",")",":","# type: (Any, str, List[Any], Any, Optional[Callable]) -> None","meth","=","getattr","(","attr",",","func",")","meth",".","argtypes","=","argtypes","meth",".","restype","=","restype","if","errcheck",":","meth",".","errcheck","=","errcheck"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/base.py#L188-L196"}
28
+ {"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/darwin.py","language":"python","identifier":"cgfloat","parameters":"()","argument_list":"","return_statement":"return c_double if sys.maxsize > 2 ** 32 else c_float","docstring":"Get the appropriate value for a float.","docstring_summary":"Get the appropriate value for a float.","docstring_tokens":["Get","the","appropriate","value","for","a","float","."],"function":"def cgfloat():\n # type: () -> Union[Type[c_double], Type[c_float]]\n \"\"\" Get the appropriate value for a float. \"\"\"\n\n return c_double if sys.maxsize > 2 ** 32 else c_float","function_tokens":["def","cgfloat","(",")",":","# type: () -> Union[Type[c_double], Type[c_float]]","return","c_double","if","sys",".","maxsize",">","2","**","32","else","c_float"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/darwin.py#L36-L40"}
29
+ {"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/darwin.py","language":"python","identifier":"MSS.__init__","parameters":"(self, **_)","argument_list":"","return_statement":"","docstring":"macOS initialisations.","docstring_summary":"macOS initialisations.","docstring_tokens":["macOS","initialisations","."],"function":"def __init__(self, **_):\n \"\"\" macOS initialisations. \"\"\"\n\n super().__init__()\n\n self.max_displays = 32\n\n self._init_library()\n self._set_cfunctions()","function_tokens":["def","__init__","(","self",",","*","*","_",")",":","super","(",")",".","__init__","(",")","self",".","max_displays","=","32","self",".","_init_library","(",")","self",".","_set_cfunctions","(",")"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/darwin.py#L116-L124"}
30
+ {"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/darwin.py","language":"python","identifier":"MSS._init_library","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Load the CoreGraphics library.","docstring_summary":"Load the CoreGraphics library.","docstring_tokens":["Load","the","CoreGraphics","library","."],"function":"def _init_library(self):\n \"\"\" Load the CoreGraphics library. \"\"\"\n version = float(\".\".join(mac_ver()[0].split(\".\")[:2]))\n if version < 10.16:\n coregraphics = ctypes.util.find_library(\"CoreGraphics\")\n else:\n # macOS Big Sur and newer\n # pylint: disable=line-too-long\n coregraphics = \"\/System\/Library\/Frameworks\/CoreGraphics.framework\/Versions\/Current\/CoreGraphics\"\n\n if not coregraphics:\n raise ScreenShotError(\"No CoreGraphics library found.\")\n self.core = ctypes.cdll.LoadLibrary(coregraphics)","function_tokens":["def","_init_library","(","self",")",":","version","=","float","(","\".\"",".","join","(","mac_ver","(",")","[","0","]",".","split","(","\".\"",")","[",":","2","]",")",")","if","version","<","10.16",":","coregraphics","=","ctypes",".","util",".","find_library","(","\"CoreGraphics\"",")","else",":","# macOS Big Sur and newer","# pylint: disable=line-too-long","coregraphics","=","\"\/System\/Library\/Frameworks\/CoreGraphics.framework\/Versions\/Current\/CoreGraphics\"","if","not","coregraphics",":","raise","ScreenShotError","(","\"No CoreGraphics library found.\"",")","self",".","core","=","ctypes",".","cdll",".","LoadLibrary","(","coregraphics",")"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/darwin.py#L126-L138"}
31
+ {"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/darwin.py","language":"python","identifier":"MSS._set_cfunctions","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Set all ctypes functions and attach them to attributes.","docstring_summary":"Set all ctypes functions and attach them to attributes.","docstring_tokens":["Set","all","ctypes","functions","and","attach","them","to","attributes","."],"function":"def _set_cfunctions(self):\n # type: () -> None\n \"\"\" Set all ctypes functions and attach them to attributes. \"\"\"\n\n cfactory = self._cfactory\n attrs = {\"core\": self.core}\n for func, (attr, argtypes, restype) in CFUNCTIONS.items():\n cfactory(\n attr=attrs[attr],\n func=func,\n argtypes=argtypes, # type: ignore\n restype=restype,\n )","function_tokens":["def","_set_cfunctions","(","self",")",":","# type: () -> None","cfactory","=","self",".","_cfactory","attrs","=","{","\"core\"",":","self",".","core","}","for","func",",","(","attr",",","argtypes",",","restype",")","in","CFUNCTIONS",".","items","(",")",":","cfactory","(","attr","=","attrs","[","attr","]",",","func","=","func",",","argtypes","=","argtypes",",","# type: ignore","restype","=","restype",",",")"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/darwin.py#L140-L152"}
32
+ {"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/darwin.py","language":"python","identifier":"MSS._monitors_impl","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Get positions of monitors. It will populate self._monitors.","docstring_summary":"Get positions of monitors. It will populate self._monitors.","docstring_tokens":["Get","positions","of","monitors",".","It","will","populate","self",".","_monitors","."],"function":"def _monitors_impl(self):\n # type: () -> None\n \"\"\" Get positions of monitors. It will populate self._monitors. \"\"\"\n\n int_ = int\n core = self.core\n\n # All monitors\n # We need to update the value with every single monitor found\n # using CGRectUnion. Else we will end with infinite values.\n all_monitors = CGRect()\n self._monitors.append({})\n\n # Each monitor\n display_count = c_uint32(0)\n active_displays = (c_uint32 * self.max_displays)()\n core.CGGetActiveDisplayList(\n self.max_displays, active_displays, ctypes.byref(display_count)\n )\n rotations = {0.0: \"normal\", 90.0: \"right\", -90.0: \"left\"}\n for idx in range(display_count.value):\n display = active_displays[idx]\n rect = core.CGDisplayBounds(display)\n rect = core.CGRectStandardize(rect)\n width, height = rect.size.width, rect.size.height\n rot = core.CGDisplayRotation(display)\n if rotations[rot] in [\"left\", \"right\"]:\n width, height = height, width\n self._monitors.append(\n {\n \"left\": int_(rect.origin.x),\n \"top\": int_(rect.origin.y),\n \"width\": int_(width),\n \"height\": int_(height),\n }\n )\n\n # Update AiO monitor's values\n all_monitors = core.CGRectUnion(all_monitors, rect)\n\n # Set the AiO monitor's values\n self._monitors[0] = {\n \"left\": int_(all_monitors.origin.x),\n \"top\": int_(all_monitors.origin.y),\n \"width\": int_(all_monitors.size.width),\n \"height\": int_(all_monitors.size.height),\n }","function_tokens":["def","_monitors_impl","(","self",")",":","# type: () -> None","int_","=","int","core","=","self",".","core","# All monitors","# We need to update the value with every single monitor found","# using CGRectUnion. Else we will end with infinite values.","all_monitors","=","CGRect","(",")","self",".","_monitors",".","append","(","{","}",")","# Each monitor","display_count","=","c_uint32","(","0",")","active_displays","=","(","c_uint32","*","self",".","max_displays",")","(",")","core",".","CGGetActiveDisplayList","(","self",".","max_displays",",","active_displays",",","ctypes",".","byref","(","display_count",")",")","rotations","=","{","0.0",":","\"normal\"",",","90.0",":","\"right\"",",","-","90.0",":","\"left\"","}","for","idx","in","range","(","display_count",".","value",")",":","display","=","active_displays","[","idx","]","rect","=","core",".","CGDisplayBounds","(","display",")","rect","=","core",".","CGRectStandardize","(","rect",")","width",",","height","=","rect",".","size",".","width",",","rect",".","size",".","height","rot","=","core",".","CGDisplayRotation","(","display",")","if","rotations","[","rot","]","in","[","\"left\"",",","\"right\"","]",":","width",",","height","=","height",",","width","self",".","_monitors",".","append","(","{","\"left\"",":","int_","(","rect",".","origin",".","x",")",",","\"top\"",":","int_","(","rect",".","origin",".","y",")",",","\"width\"",":","int_","(","width",")",",","\"height\"",":","int_","(","height",")",",","}",")","# Update AiO monitor's values","all_monitors","=","core",".","CGRectUnion","(","all_monitors",",","rect",")","# Set the AiO monitor's values","self",".","_monitors","[","0","]","=","{","\"left\"",":","int_","(","all_monitors",".","origin",".","x",")",",","\"top\"",":","int_","(","all_monitors",".","origin",".","y",")",",","\"width\"",":","int_","(","all_monitors",".","size",".","width",")",",","\"height\"",":","int_","(","all_monitors",".","size",".","height",")",",","}"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/darwin.py#L154-L200"}
33
+ {"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/darwin.py","language":"python","identifier":"MSS._grab_impl","parameters":"(self, monitor)","argument_list":"","return_statement":"return self.cls_image(data, monitor, size=Size(width, height))","docstring":"Retrieve all pixels from a monitor. Pixels have to be RGB.","docstring_summary":"Retrieve all pixels from a monitor. Pixels have to be RGB.","docstring_tokens":["Retrieve","all","pixels","from","a","monitor",".","Pixels","have","to","be","RGB","."],"function":"def _grab_impl(self, monitor):\n # type: (Monitor) -> ScreenShot\n \"\"\" Retrieve all pixels from a monitor. Pixels have to be RGB. \"\"\"\n\n # pylint: disable=too-many-locals\n\n core = self.core\n rect = CGRect(\n (monitor[\"left\"], monitor[\"top\"]), (monitor[\"width\"], monitor[\"height\"])\n )\n\n image_ref = core.CGWindowListCreateImage(rect, 1, 0, 0)\n if not image_ref:\n raise ScreenShotError(\"CoreGraphics.CGWindowListCreateImage() failed.\")\n\n width = core.CGImageGetWidth(image_ref)\n height = core.CGImageGetHeight(image_ref)\n prov = copy_data = None\n try:\n prov = core.CGImageGetDataProvider(image_ref)\n copy_data = core.CGDataProviderCopyData(prov)\n data_ref = core.CFDataGetBytePtr(copy_data)\n buf_len = core.CFDataGetLength(copy_data)\n raw = ctypes.cast(data_ref, POINTER(c_ubyte * buf_len))\n data = bytearray(raw.contents)\n\n # Remove padding per row\n bytes_per_row = core.CGImageGetBytesPerRow(image_ref)\n bytes_per_pixel = core.CGImageGetBitsPerPixel(image_ref)\n bytes_per_pixel = (bytes_per_pixel + 7) \/\/ 8\n\n if bytes_per_pixel * width != bytes_per_row:\n cropped = bytearray()\n for row in range(height):\n start = row * bytes_per_row\n end = start + width * bytes_per_pixel\n cropped.extend(data[start:end])\n data = cropped\n finally:\n if prov:\n core.CGDataProviderRelease(prov)\n if copy_data:\n core.CFRelease(copy_data)\n\n return self.cls_image(data, monitor, size=Size(width, height))","function_tokens":["def","_grab_impl","(","self",",","monitor",")",":","# type: (Monitor) -> ScreenShot","# pylint: disable=too-many-locals","core","=","self",".","core","rect","=","CGRect","(","(","monitor","[","\"left\"","]",",","monitor","[","\"top\"","]",")",",","(","monitor","[","\"width\"","]",",","monitor","[","\"height\"","]",")",")","image_ref","=","core",".","CGWindowListCreateImage","(","rect",",","1",",","0",",","0",")","if","not","image_ref",":","raise","ScreenShotError","(","\"CoreGraphics.CGWindowListCreateImage() failed.\"",")","width","=","core",".","CGImageGetWidth","(","image_ref",")","height","=","core",".","CGImageGetHeight","(","image_ref",")","prov","=","copy_data","=","None","try",":","prov","=","core",".","CGImageGetDataProvider","(","image_ref",")","copy_data","=","core",".","CGDataProviderCopyData","(","prov",")","data_ref","=","core",".","CFDataGetBytePtr","(","copy_data",")","buf_len","=","core",".","CFDataGetLength","(","copy_data",")","raw","=","ctypes",".","cast","(","data_ref",",","POINTER","(","c_ubyte","*","buf_len",")",")","data","=","bytearray","(","raw",".","contents",")","# Remove padding per row","bytes_per_row","=","core",".","CGImageGetBytesPerRow","(","image_ref",")","bytes_per_pixel","=","core",".","CGImageGetBitsPerPixel","(","image_ref",")","bytes_per_pixel","=","(","bytes_per_pixel","+","7",")","\/\/","8","if","bytes_per_pixel","*","width","!=","bytes_per_row",":","cropped","=","bytearray","(",")","for","row","in","range","(","height",")",":","start","=","row","*","bytes_per_row","end","=","start","+","width","*","bytes_per_pixel","cropped",".","extend","(","data","[","start",":","end","]",")","data","=","cropped","finally",":","if","prov",":","core",".","CGDataProviderRelease","(","prov",")","if","copy_data",":","core",".","CFRelease","(","copy_data",")","return","self",".","cls_image","(","data",",","monitor",",","size","=","Size","(","width",",","height",")",")"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/darwin.py#L202-L246"}
34
+ {"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/__main__.py","language":"python","identifier":"main","parameters":"(args=None)","argument_list":"","return_statement":"","docstring":"Main logic.","docstring_summary":"Main logic.","docstring_tokens":["Main","logic","."],"function":"def main(args=None):\n # type: (Optional[List[str]]) -> int\n \"\"\" Main logic. \"\"\"\n\n cli_args = ArgumentParser()\n cli_args.add_argument(\n \"-c\",\n \"--coordinates\",\n default=\"\",\n type=str,\n help=\"the part of the screen to capture: top, left, width, height\",\n )\n cli_args.add_argument(\n \"-l\",\n \"--level\",\n default=6,\n type=int,\n choices=list(range(10)),\n help=\"the PNG compression level\",\n )\n cli_args.add_argument(\n \"-m\", \"--monitor\", default=0, type=int, help=\"the monitor to screen shot\"\n )\n cli_args.add_argument(\n \"-o\", \"--output\", default=\"monitor-{mon}.png\", help=\"the output file name\"\n )\n cli_args.add_argument(\n \"-q\",\n \"--quiet\",\n default=False,\n action=\"store_true\",\n help=\"do not print created files\",\n )\n cli_args.add_argument(\"-v\", \"--version\", action=\"version\", version=__version__)\n\n options = cli_args.parse_args(args)\n kwargs = {\"mon\": options.monitor, \"output\": options.output}\n if options.coordinates:\n try:\n top, left, width, height = options.coordinates.split(\",\")\n except ValueError:\n print(\"Coordinates syntax: top, left, width, height\")\n return 2\n\n kwargs[\"mon\"] = {\n \"top\": int(top),\n \"left\": int(left),\n \"width\": int(width),\n \"height\": int(height),\n }\n if options.output == \"monitor-{mon}.png\":\n kwargs[\"output\"] = \"sct-{top}x{left}_{width}x{height}.png\"\n\n try:\n with mss() as sct:\n if options.coordinates:\n output = kwargs[\"output\"].format(**kwargs[\"mon\"])\n sct_img = sct.grab(kwargs[\"mon\"])\n to_png(sct_img.rgb, sct_img.size, level=options.level, output=output)\n if not options.quiet:\n print(os.path.realpath(output))\n else:\n for file_name in sct.save(**kwargs):\n if not options.quiet:\n print(os.path.realpath(file_name))\n return 0\n except ScreenShotError:\n return 1","function_tokens":["def","main","(","args","=","None",")",":","# type: (Optional[List[str]]) -> int","cli_args","=","ArgumentParser","(",")","cli_args",".","add_argument","(","\"-c\"",",","\"--coordinates\"",",","default","=","\"\"",",","type","=","str",",","help","=","\"the part of the screen to capture: top, left, width, height\"",",",")","cli_args",".","add_argument","(","\"-l\"",",","\"--level\"",",","default","=","6",",","type","=","int",",","choices","=","list","(","range","(","10",")",")",",","help","=","\"the PNG compression level\"",",",")","cli_args",".","add_argument","(","\"-m\"",",","\"--monitor\"",",","default","=","0",",","type","=","int",",","help","=","\"the monitor to screen shot\"",")","cli_args",".","add_argument","(","\"-o\"",",","\"--output\"",",","default","=","\"monitor-{mon}.png\"",",","help","=","\"the output file name\"",")","cli_args",".","add_argument","(","\"-q\"",",","\"--quiet\"",",","default","=","False",",","action","=","\"store_true\"",",","help","=","\"do not print created files\"",",",")","cli_args",".","add_argument","(","\"-v\"",",","\"--version\"",",","action","=","\"version\"",",","version","=","__version__",")","options","=","cli_args",".","parse_args","(","args",")","kwargs","=","{","\"mon\"",":","options",".","monitor",",","\"output\"",":","options",".","output","}","if","options",".","coordinates",":","try",":","top",",","left",",","width",",","height","=","options",".","coordinates",".","split","(","\",\"",")","except","ValueError",":","print","(","\"Coordinates syntax: top, left, width, height\"",")","return","2","kwargs","[","\"mon\"","]","=","{","\"top\"",":","int","(","top",")",",","\"left\"",":","int","(","left",")",",","\"width\"",":","int","(","width",")",",","\"height\"",":","int","(","height",")",",","}","if","options",".","output","==","\"monitor-{mon}.png\"",":","kwargs","[","\"output\"","]","=","\"sct-{top}x{left}_{width}x{height}.png\"","try",":","with","mss","(",")","as","sct",":","if","options",".","coordinates",":","output","=","kwargs","[","\"output\"","]",".","format","(","*","*","kwargs","[","\"mon\"","]",")","sct_img","=","sct",".","grab","(","kwargs","[","\"mon\"","]",")","to_png","(","sct_img",".","rgb",",","sct_img",".","size",",","level","=","options",".","level",",","output","=","output",")","if","not","options",".","quiet",":","print","(","os",".","path",".","realpath","(","output",")",")","else",":","for","file_name","in","sct",".","save","(","*","*","kwargs",")",":","if","not","options",".","quiet",":","print","(","os",".","path",".","realpath","(","file_name",")",")","return","0","except","ScreenShotError",":","return","1"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/__main__.py#L20-L87"}
35
+ {"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/linux.py","language":"python","identifier":"error_handler","parameters":"(_, event)","argument_list":"","return_statement":"return 0","docstring":"Specifies the program's supplied error handler.","docstring_summary":"Specifies the program's supplied error handler.","docstring_tokens":["Specifies","the","program","s","supplied","error","handler","."],"function":"def error_handler(_, event):\n # type: (Any, Any) -> int\n \"\"\" Specifies the program's supplied error handler. \"\"\"\n\n evt = event.contents\n ERROR.details = {\n \"type\": evt.type,\n \"serial\": evt.serial,\n \"error_code\": evt.error_code,\n \"request_code\": evt.request_code,\n \"minor_code\": evt.minor_code,\n }\n return 0","function_tokens":["def","error_handler","(","_",",","event",")",":","# type: (Any, Any) -> int","evt","=","event",".","contents","ERROR",".","details","=","{","\"type\"",":","evt",".","type",",","\"serial\"",":","evt",".","serial",",","\"error_code\"",":","evt",".","error_code",",","\"request_code\"",":","evt",".","request_code",",","\"minor_code\"",":","evt",".","minor_code",",","}","return","0"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/linux.py#L167-L179"}
36
+ {"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/linux.py","language":"python","identifier":"validate","parameters":"(retval, func, args)","argument_list":"","return_statement":"","docstring":"Validate the returned value of a Xlib or XRANDR function.","docstring_summary":"Validate the returned value of a Xlib or XRANDR function.","docstring_tokens":["Validate","the","returned","value","of","a","Xlib","or","XRANDR","function","."],"function":"def validate(retval, func, args):\n # type: (int, Any, Tuple[Any, Any]) -> Optional[Tuple[Any, Any]]\n \"\"\" Validate the returned value of a Xlib or XRANDR function. \"\"\"\n\n if retval != 0 and not ERROR.details:\n return args\n\n err = \"{}() failed\".format(func.__name__)\n details = {\"retval\": retval, \"args\": args}\n raise ScreenShotError(err, details=details)","function_tokens":["def","validate","(","retval",",","func",",","args",")",":","# type: (int, Any, Tuple[Any, Any]) -> Optional[Tuple[Any, Any]]","if","retval","!=","0","and","not","ERROR",".","details",":","return","args","err","=","\"{}() failed\"",".","format","(","func",".","__name__",")","details","=","{","\"retval\"",":","retval",",","\"args\"",":","args","}","raise","ScreenShotError","(","err",",","details","=","details",")"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/linux.py#L182-L191"}
37
+ {"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/linux.py","language":"python","identifier":"MSS.__init__","parameters":"(self, display=None)","argument_list":"","return_statement":"","docstring":"GNU\/Linux initialisations.","docstring_summary":"GNU\/Linux initialisations.","docstring_tokens":["GNU","\/","Linux","initialisations","."],"function":"def __init__(self, display=None):\n # type: (Optional[Union[bytes, str]]) -> None\n \"\"\" GNU\/Linux initialisations. \"\"\"\n\n super().__init__()\n\n if not display:\n try:\n display = os.environ[\"DISPLAY\"].encode(\"utf-8\")\n except KeyError:\n # pylint: disable=raise-missing-from\n raise ScreenShotError(\"$DISPLAY not set.\")\n\n if not isinstance(display, bytes):\n display = display.encode(\"utf-8\")\n\n if b\":\" not in display:\n raise ScreenShotError(\"Bad display value: {!r}.\".format(display))\n\n x11 = ctypes.util.find_library(\"X11\")\n if not x11:\n raise ScreenShotError(\"No X11 library found.\")\n self.xlib = ctypes.cdll.LoadLibrary(x11)\n\n # Install the error handler to prevent interpreter crashes:\n # any error will raise a ScreenShotError exception.\n self.xlib.XSetErrorHandler(error_handler)\n\n xrandr = ctypes.util.find_library(\"Xrandr\")\n if not xrandr:\n raise ScreenShotError(\"No Xrandr extension found.\")\n self.xrandr = ctypes.cdll.LoadLibrary(xrandr)\n\n self._set_cfunctions()\n\n self.root = self.xlib.XDefaultRootWindow(self._get_display(display))\n\n if not self.has_extension(\"RANDR\"):\n raise ScreenShotError(\"No Xrandr extension found.\")\n\n # Fix for XRRGetScreenResources and XGetImage:\n # expected LP_Display instance instead of LP_XWindowAttributes\n self.drawable = ctypes.cast(self.root, POINTER(Display))","function_tokens":["def","__init__","(","self",",","display","=","None",")",":","# type: (Optional[Union[bytes, str]]) -> None","super","(",")",".","__init__","(",")","if","not","display",":","try",":","display","=","os",".","environ","[","\"DISPLAY\"","]",".","encode","(","\"utf-8\"",")","except","KeyError",":","# pylint: disable=raise-missing-from","raise","ScreenShotError","(","\"$DISPLAY not set.\"",")","if","not","isinstance","(","display",",","bytes",")",":","display","=","display",".","encode","(","\"utf-8\"",")","if","b\":\"","not","in","display",":","raise","ScreenShotError","(","\"Bad display value: {!r}.\"",".","format","(","display",")",")","x11","=","ctypes",".","util",".","find_library","(","\"X11\"",")","if","not","x11",":","raise","ScreenShotError","(","\"No X11 library found.\"",")","self",".","xlib","=","ctypes",".","cdll",".","LoadLibrary","(","x11",")","# Install the error handler to prevent interpreter crashes:","# any error will raise a ScreenShotError exception.","self",".","xlib",".","XSetErrorHandler","(","error_handler",")","xrandr","=","ctypes",".","util",".","find_library","(","\"Xrandr\"",")","if","not","xrandr",":","raise","ScreenShotError","(","\"No Xrandr extension found.\"",")","self",".","xrandr","=","ctypes",".","cdll",".","LoadLibrary","(","xrandr",")","self",".","_set_cfunctions","(",")","self",".","root","=","self",".","xlib",".","XDefaultRootWindow","(","self",".","_get_display","(","display",")",")","if","not","self",".","has_extension","(","\"RANDR\"",")",":","raise","ScreenShotError","(","\"No Xrandr extension found.\"",")","# Fix for XRRGetScreenResources and XGetImage:","# expected LP_Display instance instead of LP_XWindowAttributes","self",".","drawable","=","ctypes",".","cast","(","self",".","root",",","POINTER","(","Display",")",")"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/linux.py#L270-L312"}
38
+ {"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/linux.py","language":"python","identifier":"MSS.has_extension","parameters":"(self, extension)","argument_list":"","return_statement":"","docstring":"Return True if the given *extension* is part of the extensions list of the server.","docstring_summary":"Return True if the given *extension* is part of the extensions list of the server.","docstring_tokens":["Return","True","if","the","given","*","extension","*","is","part","of","the","extensions","list","of","the","server","."],"function":"def has_extension(self, extension):\n # type: (str) -> bool\n \"\"\"Return True if the given *extension* is part of the extensions list of the server.\"\"\"\n with lock:\n major_opcode_return = c_int()\n first_event_return = c_int()\n first_error_return = c_int()\n\n try:\n self.xlib.XQueryExtension(\n self._get_display(),\n extension.encode(\"latin1\"),\n ctypes.byref(major_opcode_return),\n ctypes.byref(first_event_return),\n ctypes.byref(first_error_return),\n )\n except ScreenShotError:\n return False\n else:\n return True","function_tokens":["def","has_extension","(","self",",","extension",")",":","# type: (str) -> bool","with","lock",":","major_opcode_return","=","c_int","(",")","first_event_return","=","c_int","(",")","first_error_return","=","c_int","(",")","try",":","self",".","xlib",".","XQueryExtension","(","self",".","_get_display","(",")",",","extension",".","encode","(","\"latin1\"",")",",","ctypes",".","byref","(","major_opcode_return",")",",","ctypes",".","byref","(","first_event_return",")",",","ctypes",".","byref","(","first_error_return",")",",",")","except","ScreenShotError",":","return","False","else",":","return","True"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/linux.py#L314-L333"}
39
+ {"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/linux.py","language":"python","identifier":"MSS._get_display","parameters":"(self, disp=None)","argument_list":"","return_statement":"return display","docstring":"Retrieve a thread-safe display from XOpenDisplay().\n In multithreading, if the thread that creates *display* is dead, *display* will\n no longer be valid to grab the screen. The *display* attribute is replaced\n with *_display_dict* to maintain the *display* values in multithreading.\n Since the current thread and main thread are always alive, reuse their\n *display* value first.","docstring_summary":"Retrieve a thread-safe display from XOpenDisplay().\n In multithreading, if the thread that creates *display* is dead, *display* will\n no longer be valid to grab the screen. The *display* attribute is replaced\n with *_display_dict* to maintain the *display* values in multithreading.\n Since the current thread and main thread are always alive, reuse their\n *display* value first.","docstring_tokens":["Retrieve","a","thread","-","safe","display","from","XOpenDisplay","()",".","In","multithreading","if","the","thread","that","creates","*","display","*","is","dead","*","display","*","will","no","longer","be","valid","to","grab","the","screen",".","The","*","display","*","attribute","is","replaced","with","*","_display_dict","*","to","maintain","the","*","display","*","values","in","multithreading",".","Since","the","current","thread","and","main","thread","are","always","alive","reuse","their","*","display","*","value","first","."],"function":"def _get_display(self, disp=None):\n \"\"\"\n Retrieve a thread-safe display from XOpenDisplay().\n In multithreading, if the thread that creates *display* is dead, *display* will\n no longer be valid to grab the screen. The *display* attribute is replaced\n with *_display_dict* to maintain the *display* values in multithreading.\n Since the current thread and main thread are always alive, reuse their\n *display* value first.\n \"\"\"\n cur_thread, main_thread = threading.current_thread(), threading.main_thread()\n display = MSS._display_dict.get(cur_thread) or MSS._display_dict.get(\n main_thread\n )\n if not display:\n display = MSS._display_dict[cur_thread] = self.xlib.XOpenDisplay(disp)\n return display","function_tokens":["def","_get_display","(","self",",","disp","=","None",")",":","cur_thread",",","main_thread","=","threading",".","current_thread","(",")",",","threading",".","main_thread","(",")","display","=","MSS",".","_display_dict",".","get","(","cur_thread",")","or","MSS",".","_display_dict",".","get","(","main_thread",")","if","not","display",":","display","=","MSS",".","_display_dict","[","cur_thread","]","=","self",".","xlib",".","XOpenDisplay","(","disp",")","return","display"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/linux.py#L335-L350"}
40
+ {"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/linux.py","language":"python","identifier":"MSS._set_cfunctions","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Set all ctypes functions and attach them to attributes.","docstring_summary":"Set all ctypes functions and attach them to attributes.","docstring_tokens":["Set","all","ctypes","functions","and","attach","them","to","attributes","."],"function":"def _set_cfunctions(self):\n \"\"\" Set all ctypes functions and attach them to attributes. \"\"\"\n\n cfactory = self._cfactory\n attrs = {\n \"xlib\": self.xlib,\n \"xrandr\": self.xrandr,\n }\n for func, (attr, argtypes, restype) in CFUNCTIONS.items():\n try:\n cfactory(\n attr=attrs[attr],\n errcheck=validate,\n func=func,\n argtypes=argtypes,\n restype=restype,\n ) # type: ignore\n except AttributeError:\n pass","function_tokens":["def","_set_cfunctions","(","self",")",":","cfactory","=","self",".","_cfactory","attrs","=","{","\"xlib\"",":","self",".","xlib",",","\"xrandr\"",":","self",".","xrandr",",","}","for","func",",","(","attr",",","argtypes",",","restype",")","in","CFUNCTIONS",".","items","(",")",":","try",":","cfactory","(","attr","=","attrs","[","attr","]",",","errcheck","=","validate",",","func","=","func",",","argtypes","=","argtypes",",","restype","=","restype",",",")","# type: ignore","except","AttributeError",":","pass"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/linux.py#L352-L370"}
41
+ {"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/linux.py","language":"python","identifier":"MSS.get_error_details","parameters":"(self)","argument_list":"","return_statement":"return details","docstring":"Get more information about the latest X server error.","docstring_summary":"Get more information about the latest X server error.","docstring_tokens":["Get","more","information","about","the","latest","X","server","error","."],"function":"def get_error_details(self):\n # type: () -> Optional[Dict[str, Any]]\n \"\"\" Get more information about the latest X server error. \"\"\"\n\n details = {} # type: Dict[str, Any]\n\n if ERROR.details:\n details = {\"xerror_details\": ERROR.details}\n ERROR.details = None\n xserver_error = ctypes.create_string_buffer(1024)\n self.xlib.XGetErrorText(\n self._get_display(),\n details.get(\"xerror_details\", {}).get(\"error_code\", 0),\n xserver_error,\n len(xserver_error),\n )\n xerror = xserver_error.value.decode(\"utf-8\")\n if xerror != \"0\":\n details[\"xerror\"] = xerror\n\n return details","function_tokens":["def","get_error_details","(","self",")",":","# type: () -> Optional[Dict[str, Any]]","details","=","{","}","# type: Dict[str, Any]","if","ERROR",".","details",":","details","=","{","\"xerror_details\"",":","ERROR",".","details","}","ERROR",".","details","=","None","xserver_error","=","ctypes",".","create_string_buffer","(","1024",")","self",".","xlib",".","XGetErrorText","(","self",".","_get_display","(",")",",","details",".","get","(","\"xerror_details\"",",","{","}",")",".","get","(","\"error_code\"",",","0",")",",","xserver_error",",","len","(","xserver_error",")",",",")","xerror","=","xserver_error",".","value",".","decode","(","\"utf-8\"",")","if","xerror","!=","\"0\"",":","details","[","\"xerror\"","]","=","xerror","return","details"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/linux.py#L372-L392"}
42
+ {"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/linux.py","language":"python","identifier":"MSS._monitors_impl","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Get positions of monitors. It will populate self._monitors.","docstring_summary":"Get positions of monitors. It will populate self._monitors.","docstring_tokens":["Get","positions","of","monitors",".","It","will","populate","self",".","_monitors","."],"function":"def _monitors_impl(self):\n # type: () -> None\n \"\"\" Get positions of monitors. It will populate self._monitors. \"\"\"\n\n display = self._get_display()\n int_ = int\n xrandr = self.xrandr\n\n # All monitors\n gwa = XWindowAttributes()\n self.xlib.XGetWindowAttributes(display, self.root, ctypes.byref(gwa))\n self._monitors.append(\n {\n \"left\": int_(gwa.x),\n \"top\": int_(gwa.y),\n \"width\": int_(gwa.width),\n \"height\": int_(gwa.height),\n }\n )\n\n # Each monitor\n # A simple benchmark calling 10 times those 2 functions:\n # XRRGetScreenResources(): 0.1755971429956844 s\n # XRRGetScreenResourcesCurrent(): 0.0039125580078689 s\n # The second is faster by a factor of 44! So try to use it first.\n try:\n mon = xrandr.XRRGetScreenResourcesCurrent(display, self.drawable).contents\n except AttributeError:\n mon = xrandr.XRRGetScreenResources(display, self.drawable).contents\n\n crtcs = mon.crtcs\n for idx in range(mon.ncrtc):\n crtc = xrandr.XRRGetCrtcInfo(display, mon, crtcs[idx]).contents\n if crtc.noutput == 0:\n xrandr.XRRFreeCrtcInfo(crtc)\n continue\n\n self._monitors.append(\n {\n \"left\": int_(crtc.x),\n \"top\": int_(crtc.y),\n \"width\": int_(crtc.width),\n \"height\": int_(crtc.height),\n }\n )\n xrandr.XRRFreeCrtcInfo(crtc)\n xrandr.XRRFreeScreenResources(mon)","function_tokens":["def","_monitors_impl","(","self",")",":","# type: () -> None","display","=","self",".","_get_display","(",")","int_","=","int","xrandr","=","self",".","xrandr","# All monitors","gwa","=","XWindowAttributes","(",")","self",".","xlib",".","XGetWindowAttributes","(","display",",","self",".","root",",","ctypes",".","byref","(","gwa",")",")","self",".","_monitors",".","append","(","{","\"left\"",":","int_","(","gwa",".","x",")",",","\"top\"",":","int_","(","gwa",".","y",")",",","\"width\"",":","int_","(","gwa",".","width",")",",","\"height\"",":","int_","(","gwa",".","height",")",",","}",")","# Each monitor","# A simple benchmark calling 10 times those 2 functions:","# XRRGetScreenResources(): 0.1755971429956844 s","# XRRGetScreenResourcesCurrent(): 0.0039125580078689 s","# The second is faster by a factor of 44! So try to use it first.","try",":","mon","=","xrandr",".","XRRGetScreenResourcesCurrent","(","display",",","self",".","drawable",")",".","contents","except","AttributeError",":","mon","=","xrandr",".","XRRGetScreenResources","(","display",",","self",".","drawable",")",".","contents","crtcs","=","mon",".","crtcs","for","idx","in","range","(","mon",".","ncrtc",")",":","crtc","=","xrandr",".","XRRGetCrtcInfo","(","display",",","mon",",","crtcs","[","idx","]",")",".","contents","if","crtc",".","noutput","==","0",":","xrandr",".","XRRFreeCrtcInfo","(","crtc",")","continue","self",".","_monitors",".","append","(","{","\"left\"",":","int_","(","crtc",".","x",")",",","\"top\"",":","int_","(","crtc",".","y",")",",","\"width\"",":","int_","(","crtc",".","width",")",",","\"height\"",":","int_","(","crtc",".","height",")",",","}",")","xrandr",".","XRRFreeCrtcInfo","(","crtc",")","xrandr",".","XRRFreeScreenResources","(","mon",")"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/linux.py#L394-L440"}
43
+ {"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/linux.py","language":"python","identifier":"MSS._grab_impl","parameters":"(self, monitor)","argument_list":"","return_statement":"return self.cls_image(data, monitor)","docstring":"Retrieve all pixels from a monitor. Pixels have to be RGB.","docstring_summary":"Retrieve all pixels from a monitor. Pixels have to be RGB.","docstring_tokens":["Retrieve","all","pixels","from","a","monitor",".","Pixels","have","to","be","RGB","."],"function":"def _grab_impl(self, monitor):\n # type: (Monitor) -> ScreenShot\n \"\"\" Retrieve all pixels from a monitor. Pixels have to be RGB. \"\"\"\n\n ximage = self.xlib.XGetImage(\n self._get_display(),\n self.drawable,\n monitor[\"left\"],\n monitor[\"top\"],\n monitor[\"width\"],\n monitor[\"height\"],\n PLAINMASK,\n ZPIXMAP,\n )\n\n try:\n bits_per_pixel = ximage.contents.bits_per_pixel\n if bits_per_pixel != 32:\n raise ScreenShotError(\n \"[XImage] bits per pixel value not (yet?) implemented: {}.\".format(\n bits_per_pixel\n )\n )\n\n raw_data = ctypes.cast(\n ximage.contents.data,\n POINTER(c_ubyte * monitor[\"height\"] * monitor[\"width\"] * 4),\n )\n data = bytearray(raw_data.contents)\n finally:\n # Free\n self.xlib.XDestroyImage(ximage)\n\n return self.cls_image(data, monitor)","function_tokens":["def","_grab_impl","(","self",",","monitor",")",":","# type: (Monitor) -> ScreenShot","ximage","=","self",".","xlib",".","XGetImage","(","self",".","_get_display","(",")",",","self",".","drawable",",","monitor","[","\"left\"","]",",","monitor","[","\"top\"","]",",","monitor","[","\"width\"","]",",","monitor","[","\"height\"","]",",","PLAINMASK",",","ZPIXMAP",",",")","try",":","bits_per_pixel","=","ximage",".","contents",".","bits_per_pixel","if","bits_per_pixel","!=","32",":","raise","ScreenShotError","(","\"[XImage] bits per pixel value not (yet?) implemented: {}.\"",".","format","(","bits_per_pixel",")",")","raw_data","=","ctypes",".","cast","(","ximage",".","contents",".","data",",","POINTER","(","c_ubyte","*","monitor","[","\"height\"","]","*","monitor","[","\"width\"","]","*","4",")",",",")","data","=","bytearray","(","raw_data",".","contents",")","finally",":","# Free","self",".","xlib",".","XDestroyImage","(","ximage",")","return","self",".","cls_image","(","data",",","monitor",")"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/linux.py#L442-L475"}
44
+ {"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"mss\/tools.py","language":"python","identifier":"to_png","parameters":"(data, size, level=6, output=None)","argument_list":"","return_statement":"return None","docstring":"Dump data to a PNG file. If `output` is `None`, create no file but return\n the whole PNG data.\n\n :param bytes data: RGBRGB...RGB data.\n :param tuple size: The (width, height) pair.\n :param int level: PNG compression level.\n :param str output: Output file name.","docstring_summary":"Dump data to a PNG file. If `output` is `None`, create no file but return\n the whole PNG data.","docstring_tokens":["Dump","data","to","a","PNG","file",".","If","output","is","None","create","no","file","but","return","the","whole","PNG","data","."],"function":"def to_png(data, size, level=6, output=None):\n # type: (bytes, Tuple[int, int], int, Optional[str]) -> Optional[bytes]\n \"\"\"\n Dump data to a PNG file. If `output` is `None`, create no file but return\n the whole PNG data.\n\n :param bytes data: RGBRGB...RGB data.\n :param tuple size: The (width, height) pair.\n :param int level: PNG compression level.\n :param str output: Output file name.\n \"\"\"\n # pylint: disable=too-many-locals\n\n pack = struct.pack\n crc32 = zlib.crc32\n\n width, height = size\n line = width * 3\n png_filter = pack(\">B\", 0)\n scanlines = b\"\".join(\n [png_filter + data[y * line : y * line + line] for y in range(height)]\n )\n\n magic = pack(\">8B\", 137, 80, 78, 71, 13, 10, 26, 10)\n\n # Header: size, marker, data, CRC32\n ihdr = [b\"\", b\"IHDR\", b\"\", b\"\"]\n ihdr[2] = pack(\">2I5B\", width, height, 8, 2, 0, 0, 0)\n ihdr[3] = pack(\">I\", crc32(b\"\".join(ihdr[1:3])) & 0xFFFFFFFF)\n ihdr[0] = pack(\">I\", len(ihdr[2]))\n\n # Data: size, marker, data, CRC32\n idat = [b\"\", b\"IDAT\", zlib.compress(scanlines, level), b\"\"]\n idat[3] = pack(\">I\", crc32(b\"\".join(idat[1:3])) & 0xFFFFFFFF)\n idat[0] = pack(\">I\", len(idat[2]))\n\n # Footer: size, marker, None, CRC32\n iend = [b\"\", b\"IEND\", b\"\", b\"\"]\n iend[3] = pack(\">I\", crc32(iend[1]) & 0xFFFFFFFF)\n iend[0] = pack(\">I\", len(iend[2]))\n\n if not output:\n # Returns raw bytes of the whole PNG data\n return magic + b\"\".join(ihdr + idat + iend)\n\n with open(output, \"wb\") as fileh:\n fileh.write(magic)\n fileh.write(b\"\".join(ihdr))\n fileh.write(b\"\".join(idat))\n fileh.write(b\"\".join(iend))\n\n # Force write of file to disk\n fileh.flush()\n os.fsync(fileh.fileno())\n\n return None","function_tokens":["def","to_png","(","data",",","size",",","level","=","6",",","output","=","None",")",":","# type: (bytes, Tuple[int, int], int, Optional[str]) -> Optional[bytes]","# pylint: disable=too-many-locals","pack","=","struct",".","pack","crc32","=","zlib",".","crc32","width",",","height","=","size","line","=","width","*","3","png_filter","=","pack","(","\">B\"",",","0",")","scanlines","=","b\"\"",".","join","(","[","png_filter","+","data","[","y","*","line",":","y","*","line","+","line","]","for","y","in","range","(","height",")","]",")","magic","=","pack","(","\">8B\"",",","137",",","80",",","78",",","71",",","13",",","10",",","26",",","10",")","# Header: size, marker, data, CRC32","ihdr","=","[","b\"\"",",","b\"IHDR\"",",","b\"\"",",","b\"\"","]","ihdr","[","2","]","=","pack","(","\">2I5B\"",",","width",",","height",",","8",",","2",",","0",",","0",",","0",")","ihdr","[","3","]","=","pack","(","\">I\"",",","crc32","(","b\"\"",".","join","(","ihdr","[","1",":","3","]",")",")","&","0xFFFFFFFF",")","ihdr","[","0","]","=","pack","(","\">I\"",",","len","(","ihdr","[","2","]",")",")","# Data: size, marker, data, CRC32","idat","=","[","b\"\"",",","b\"IDAT\"",",","zlib",".","compress","(","scanlines",",","level",")",",","b\"\"","]","idat","[","3","]","=","pack","(","\">I\"",",","crc32","(","b\"\"",".","join","(","idat","[","1",":","3","]",")",")","&","0xFFFFFFFF",")","idat","[","0","]","=","pack","(","\">I\"",",","len","(","idat","[","2","]",")",")","# Footer: size, marker, None, CRC32","iend","=","[","b\"\"",",","b\"IEND\"",",","b\"\"",",","b\"\"","]","iend","[","3","]","=","pack","(","\">I\"",",","crc32","(","iend","[","1","]",")","&","0xFFFFFFFF",")","iend","[","0","]","=","pack","(","\">I\"",",","len","(","iend","[","2","]",")",")","if","not","output",":","# Returns raw bytes of the whole PNG data","return","magic","+","b\"\"",".","join","(","ihdr","+","idat","+","iend",")","with","open","(","output",",","\"wb\"",")","as","fileh",":","fileh",".","write","(","magic",")","fileh",".","write","(","b\"\"",".","join","(","ihdr",")",")","fileh",".","write","(","b\"\"",".","join","(","idat",")",")","fileh",".","write","(","b\"\"",".","join","(","iend",")",")","# Force write of file to disk","fileh",".","flush","(",")","os",".","fsync","(","fileh",".","fileno","(",")",")","return","None"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/mss\/tools.py#L15-L70"}
45
+ {"nwo":"BoboTiG\/python-mss","sha":"78e5a8de625734ae84235a82af03a803d56da58b","path":"docs\/source\/examples\/callback.py","language":"python","identifier":"on_exists","parameters":"(fname)","argument_list":"","return_statement":"","docstring":"Callback example when we try to overwrite an existing screenshot.","docstring_summary":"Callback example when we try to overwrite an existing screenshot.","docstring_tokens":["Callback","example","when","we","try","to","overwrite","an","existing","screenshot","."],"function":"def on_exists(fname):\n # type: (str) -> None\n \"\"\"\n Callback example when we try to overwrite an existing screenshot.\n \"\"\"\n\n if os.path.isfile(fname):\n newfile = fname + \".old\"\n print(\"{} -> {}\".format(fname, newfile))\n os.rename(fname, newfile)","function_tokens":["def","on_exists","(","fname",")",":","# type: (str) -> None","if","os",".","path",".","isfile","(","fname",")",":","newfile","=","fname","+","\".old\"","print","(","\"{} -> {}\"",".","format","(","fname",",","newfile",")",")","os",".","rename","(","fname",",","newfile",")"],"url":"https:\/\/github.com\/BoboTiG\/python-mss\/blob\/78e5a8de625734ae84235a82af03a803d56da58b\/docs\/source\/examples\/callback.py#L14-L23"}
BrieflyX__ctf-pwns.jsonl ADDED
File without changes
CLUEbenchmark__CLUE.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
CQFIO__FastImageProcessing.jsonl ADDED
File without changes
CR-Gjx__LeakGAN.jsonl ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ {"nwo":"CR-Gjx\/LeakGAN","sha":"dc3360e30f2572cc4d7281cf2c8f490558e4a794","path":"No Temperature\/Synthetic Data\/Discriminator.py","language":"python","identifier":"linear","parameters":"(input_, output_size, scope=None)","argument_list":"","return_statement":"return tf.matmul(input_, tf.transpose(matrix)) + bias_term","docstring":"Linear map: output[k] = sum_i(Matrix[k, i] * input_[i] ) + Bias[k]\n Args:\n input_: a tensor or a list of 2D, batch x n, Tensors.\n output_size: int, second dimension of W[i].\n scope: VariableScope for the created subgraph; defaults to \"Linear\".\n Returns:\n A 2D Tensor with shape [batch x output_size] equal to\n sum_i(input_[i] * W[i]), where W[i]s are newly created matrices.\n Raises:\n ValueError: if some of the arguments has unspecified or wrong shape.","docstring_summary":"Linear map: output[k] = sum_i(Matrix[k, i] * input_[i] ) + Bias[k]\n Args:\n input_: a tensor or a list of 2D, batch x n, Tensors.\n output_size: int, second dimension of W[i].\n scope: VariableScope for the created subgraph; defaults to \"Linear\".\n Returns:\n A 2D Tensor with shape [batch x output_size] equal to\n sum_i(input_[i] * W[i]), where W[i]s are newly created matrices.\n Raises:\n ValueError: if some of the arguments has unspecified or wrong shape.","docstring_tokens":["Linear","map",":","output","[","k","]","=","sum_i","(","Matrix","[","k","i","]","*","input_","[","i","]",")","+","Bias","[","k","]","Args",":","input_",":","a","tensor","or","a","list","of","2D","batch","x","n","Tensors",".","output_size",":","int","second","dimension","of","W","[","i","]",".","scope",":","VariableScope","for","the","created","subgraph",";","defaults","to","Linear",".","Returns",":","A","2D","Tensor","with","shape","[","batch","x","output_size","]","equal","to","sum_i","(","input_","[","i","]","*","W","[","i","]",")","where","W","[","i","]","s","are","newly","created","matrices",".","Raises",":","ValueError",":","if","some","of","the","arguments","has","unspecified","or","wrong","shape","."],"function":"def linear(input_, output_size, scope=None):\n '''\n Linear map: output[k] = sum_i(Matrix[k, i] * input_[i] ) + Bias[k]\n Args:\n input_: a tensor or a list of 2D, batch x n, Tensors.\n output_size: int, second dimension of W[i].\n scope: VariableScope for the created subgraph; defaults to \"Linear\".\n Returns:\n A 2D Tensor with shape [batch x output_size] equal to\n sum_i(input_[i] * W[i]), where W[i]s are newly created matrices.\n Raises:\n ValueError: if some of the arguments has unspecified or wrong shape.\n '''\n\n shape = input_.get_shape().as_list()\n if len(shape) != 2:\n raise ValueError(\"Linear is expecting 2D arguments: %s\" % str(shape))\n if not shape[1]:\n raise ValueError(\"Linear expects shape[1] of arguments: %s\" % str(shape))\n input_size = shape[1]\n\n # Now the computation.\n with tf.variable_scope(scope or \"SimpleLinear\"):\n matrix = tf.get_variable(\"Matrix\", [output_size, input_size], dtype=input_.dtype)\n bias_term = tf.get_variable(\"Bias\", [output_size], dtype=input_.dtype)\n\n return tf.matmul(input_, tf.transpose(matrix)) + bias_term","function_tokens":["def","linear","(","input_",",","output_size",",","scope","=","None",")",":","shape","=","input_",".","get_shape","(",")",".","as_list","(",")","if","len","(","shape",")","!=","2",":","raise","ValueError","(","\"Linear is expecting 2D arguments: %s\"","%","str","(","shape",")",")","if","not","shape","[","1","]",":","raise","ValueError","(","\"Linear expects shape[1] of arguments: %s\"","%","str","(","shape",")",")","input_size","=","shape","[","1","]","# Now the computation.","with","tf",".","variable_scope","(","scope","or","\"SimpleLinear\"",")",":","matrix","=","tf",".","get_variable","(","\"Matrix\"",",","[","output_size",",","input_size","]",",","dtype","=","input_",".","dtype",")","bias_term","=","tf",".","get_variable","(","\"Bias\"",",","[","output_size","]",",","dtype","=","input_",".","dtype",")","return","tf",".","matmul","(","input_",",","tf",".","transpose","(","matrix",")",")","+","bias_term"],"url":"https:\/\/github.com\/CR-Gjx\/LeakGAN\/blob\/dc3360e30f2572cc4d7281cf2c8f490558e4a794\/No Temperature\/Synthetic Data\/Discriminator.py#L12-L38"}
2
+ {"nwo":"CR-Gjx\/LeakGAN","sha":"dc3360e30f2572cc4d7281cf2c8f490558e4a794","path":"No Temperature\/Synthetic Data\/Discriminator.py","language":"python","identifier":"highway","parameters":"(input_, size, num_layers=1, bias=-2.0, f=tf.nn.relu, scope='Highway')","argument_list":"","return_statement":"return output","docstring":"Highway Network (cf. http:\/\/arxiv.org\/abs\/1505.00387).\n t = sigmoid(Wy + b)\n z = t * g(Wy + b) + (1 - t) * y\n where g is nonlinearity, t is transform gate, and (1 - t) is carry gate.","docstring_summary":"Highway Network (cf. http:\/\/arxiv.org\/abs\/1505.00387).\n t = sigmoid(Wy + b)\n z = t * g(Wy + b) + (1 - t) * y\n where g is nonlinearity, t is transform gate, and (1 - t) is carry gate.","docstring_tokens":["Highway","Network","(","cf",".","http",":","\/\/","arxiv",".","org","\/","abs","\/","1505",".","00387",")",".","t","=","sigmoid","(","Wy","+","b",")","z","=","t","*","g","(","Wy","+","b",")","+","(","1","-","t",")","*","y","where","g","is","nonlinearity","t","is","transform","gate","and","(","1","-","t",")","is","carry","gate","."],"function":"def highway(input_, size, num_layers=1, bias=-2.0, f=tf.nn.relu, scope='Highway'):\n \"\"\"Highway Network (cf. http:\/\/arxiv.org\/abs\/1505.00387).\n t = sigmoid(Wy + b)\n z = t * g(Wy + b) + (1 - t) * y\n where g is nonlinearity, t is transform gate, and (1 - t) is carry gate.\n \"\"\"\n\n with tf.variable_scope(scope):\n for idx in range(num_layers):\n g = f(linear(input_, size, scope='highway_lin_%d' % idx))\n\n t = tf.sigmoid(linear(input_, size, scope='highway_gate_%d' % idx) + bias)\n\n output = t * g + (1. - t) * input_\n input_ = output\n\n return output","function_tokens":["def","highway","(","input_",",","size",",","num_layers","=","1",",","bias","=","-","2.0",",","f","=","tf",".","nn",".","relu",",","scope","=","'Highway'",")",":","with","tf",".","variable_scope","(","scope",")",":","for","idx","in","range","(","num_layers",")",":","g","=","f","(","linear","(","input_",",","size",",","scope","=","'highway_lin_%d'","%","idx",")",")","t","=","tf",".","sigmoid","(","linear","(","input_",",","size",",","scope","=","'highway_gate_%d'","%","idx",")","+","bias",")","output","=","t","*","g","+","(","1.","-","t",")","*","input_","input_","=","output","return","output"],"url":"https:\/\/github.com\/CR-Gjx\/LeakGAN\/blob\/dc3360e30f2572cc4d7281cf2c8f490558e4a794\/No Temperature\/Synthetic Data\/Discriminator.py#L41-L57"}
3
+ {"nwo":"CR-Gjx\/LeakGAN","sha":"dc3360e30f2572cc4d7281cf2c8f490558e4a794","path":"No Temperature\/Image COCO\/Discriminator.py","language":"python","identifier":"linear","parameters":"(input_, output_size, scope=None)","argument_list":"","return_statement":"return tf.matmul(input_, tf.transpose(matrix)) + bias_term","docstring":"Linear map: output[k] = sum_i(Matrix[k, i] * input_[i] ) + Bias[k]\n Args:\n input_: a tensor or a list of 2D, batch x n, Tensors.\n output_size: int, second dimension of W[i].\n scope: VariableScope for the created subgraph; defaults to \"Linear\".\n Returns:\n A 2D Tensor with shape [batch x output_size] equal to\n sum_i(input_[i] * W[i]), where W[i]s are newly created matrices.\n Raises:\n ValueError: if some of the arguments has unspecified or wrong shape.","docstring_summary":"Linear map: output[k] = sum_i(Matrix[k, i] * input_[i] ) + Bias[k]\n Args:\n input_: a tensor or a list of 2D, batch x n, Tensors.\n output_size: int, second dimension of W[i].\n scope: VariableScope for the created subgraph; defaults to \"Linear\".\n Returns:\n A 2D Tensor with shape [batch x output_size] equal to\n sum_i(input_[i] * W[i]), where W[i]s are newly created matrices.\n Raises:\n ValueError: if some of the arguments has unspecified or wrong shape.","docstring_tokens":["Linear","map",":","output","[","k","]","=","sum_i","(","Matrix","[","k","i","]","*","input_","[","i","]",")","+","Bias","[","k","]","Args",":","input_",":","a","tensor","or","a","list","of","2D","batch","x","n","Tensors",".","output_size",":","int","second","dimension","of","W","[","i","]",".","scope",":","VariableScope","for","the","created","subgraph",";","defaults","to","Linear",".","Returns",":","A","2D","Tensor","with","shape","[","batch","x","output_size","]","equal","to","sum_i","(","input_","[","i","]","*","W","[","i","]",")","where","W","[","i","]","s","are","newly","created","matrices",".","Raises",":","ValueError",":","if","some","of","the","arguments","has","unspecified","or","wrong","shape","."],"function":"def linear(input_, output_size, scope=None):\n '''\n Linear map: output[k] = sum_i(Matrix[k, i] * input_[i] ) + Bias[k]\n Args:\n input_: a tensor or a list of 2D, batch x n, Tensors.\n output_size: int, second dimension of W[i].\n scope: VariableScope for the created subgraph; defaults to \"Linear\".\n Returns:\n A 2D Tensor with shape [batch x output_size] equal to\n sum_i(input_[i] * W[i]), where W[i]s are newly created matrices.\n Raises:\n ValueError: if some of the arguments has unspecified or wrong shape.\n '''\n\n shape = input_.get_shape().as_list()\n if len(shape) != 2:\n raise ValueError(\"Linear is expecting 2D arguments: %s\" % str(shape))\n if not shape[1]:\n raise ValueError(\"Linear expects shape[1] of arguments: %s\" % str(shape))\n input_size = shape[1]\n\n # Now the computation.\n with tf.variable_scope(scope or \"SimpleLinear\"):\n matrix = tf.get_variable(\"Matrix\", [output_size, input_size], dtype=input_.dtype)\n bias_term = tf.get_variable(\"Bias\", [output_size], dtype=input_.dtype)\n\n return tf.matmul(input_, tf.transpose(matrix)) + bias_term","function_tokens":["def","linear","(","input_",",","output_size",",","scope","=","None",")",":","shape","=","input_",".","get_shape","(",")",".","as_list","(",")","if","len","(","shape",")","!=","2",":","raise","ValueError","(","\"Linear is expecting 2D arguments: %s\"","%","str","(","shape",")",")","if","not","shape","[","1","]",":","raise","ValueError","(","\"Linear expects shape[1] of arguments: %s\"","%","str","(","shape",")",")","input_size","=","shape","[","1","]","# Now the computation.","with","tf",".","variable_scope","(","scope","or","\"SimpleLinear\"",")",":","matrix","=","tf",".","get_variable","(","\"Matrix\"",",","[","output_size",",","input_size","]",",","dtype","=","input_",".","dtype",")","bias_term","=","tf",".","get_variable","(","\"Bias\"",",","[","output_size","]",",","dtype","=","input_",".","dtype",")","return","tf",".","matmul","(","input_",",","tf",".","transpose","(","matrix",")",")","+","bias_term"],"url":"https:\/\/github.com\/CR-Gjx\/LeakGAN\/blob\/dc3360e30f2572cc4d7281cf2c8f490558e4a794\/No Temperature\/Image COCO\/Discriminator.py#L12-L38"}
4
+ {"nwo":"CR-Gjx\/LeakGAN","sha":"dc3360e30f2572cc4d7281cf2c8f490558e4a794","path":"No Temperature\/Image COCO\/Discriminator.py","language":"python","identifier":"highway","parameters":"(input_, size, num_layers=1, bias=-2.0, f=tf.nn.relu, scope='Highway')","argument_list":"","return_statement":"return output","docstring":"Highway Network (cf. http:\/\/arxiv.org\/abs\/1505.00387).\n t = sigmoid(Wy + b)\n z = t * g(Wy + b) + (1 - t) * y\n where g is nonlinearity, t is transform gate, and (1 - t) is carry gate.","docstring_summary":"Highway Network (cf. http:\/\/arxiv.org\/abs\/1505.00387).\n t = sigmoid(Wy + b)\n z = t * g(Wy + b) + (1 - t) * y\n where g is nonlinearity, t is transform gate, and (1 - t) is carry gate.","docstring_tokens":["Highway","Network","(","cf",".","http",":","\/\/","arxiv",".","org","\/","abs","\/","1505",".","00387",")",".","t","=","sigmoid","(","Wy","+","b",")","z","=","t","*","g","(","Wy","+","b",")","+","(","1","-","t",")","*","y","where","g","is","nonlinearity","t","is","transform","gate","and","(","1","-","t",")","is","carry","gate","."],"function":"def highway(input_, size, num_layers=1, bias=-2.0, f=tf.nn.relu, scope='Highway'):\n \"\"\"Highway Network (cf. http:\/\/arxiv.org\/abs\/1505.00387).\n t = sigmoid(Wy + b)\n z = t * g(Wy + b) + (1 - t) * y\n where g is nonlinearity, t is transform gate, and (1 - t) is carry gate.\n \"\"\"\n\n with tf.variable_scope(scope):\n for idx in range(num_layers):\n g = f(linear(input_, size, scope='highway_lin_%d' % idx))\n\n t = tf.sigmoid(linear(input_, size, scope='highway_gate_%d' % idx) + bias)\n\n output = t * g + (1. - t) * input_\n input_ = output\n\n return output","function_tokens":["def","highway","(","input_",",","size",",","num_layers","=","1",",","bias","=","-","2.0",",","f","=","tf",".","nn",".","relu",",","scope","=","'Highway'",")",":","with","tf",".","variable_scope","(","scope",")",":","for","idx","in","range","(","num_layers",")",":","g","=","f","(","linear","(","input_",",","size",",","scope","=","'highway_lin_%d'","%","idx",")",")","t","=","tf",".","sigmoid","(","linear","(","input_",",","size",",","scope","=","'highway_gate_%d'","%","idx",")","+","bias",")","output","=","t","*","g","+","(","1.","-","t",")","*","input_","input_","=","output","return","output"],"url":"https:\/\/github.com\/CR-Gjx\/LeakGAN\/blob\/dc3360e30f2572cc4d7281cf2c8f490558e4a794\/No Temperature\/Image COCO\/Discriminator.py#L41-L57"}
5
+ {"nwo":"CR-Gjx\/LeakGAN","sha":"dc3360e30f2572cc4d7281cf2c8f490558e4a794","path":"Synthetic Data\/Discriminator.py","language":"python","identifier":"linear","parameters":"(input_, output_size, scope=None)","argument_list":"","return_statement":"return tf.matmul(input_, tf.transpose(matrix)) + bias_term","docstring":"Linear map: output[k] = sum_i(Matrix[k, i] * input_[i] ) + Bias[k]\n Args:\n input_: a tensor or a list of 2D, batch x n, Tensors.\n output_size: int, second dimension of W[i].\n scope: VariableScope for the created subgraph; defaults to \"Linear\".\n Returns:\n A 2D Tensor with shape [batch x output_size] equal to\n sum_i(input_[i] * W[i]), where W[i]s are newly created matrices.\n Raises:\n ValueError: if some of the arguments has unspecified or wrong shape.","docstring_summary":"Linear map: output[k] = sum_i(Matrix[k, i] * input_[i] ) + Bias[k]\n Args:\n input_: a tensor or a list of 2D, batch x n, Tensors.\n output_size: int, second dimension of W[i].\n scope: VariableScope for the created subgraph; defaults to \"Linear\".\n Returns:\n A 2D Tensor with shape [batch x output_size] equal to\n sum_i(input_[i] * W[i]), where W[i]s are newly created matrices.\n Raises:\n ValueError: if some of the arguments has unspecified or wrong shape.","docstring_tokens":["Linear","map",":","output","[","k","]","=","sum_i","(","Matrix","[","k","i","]","*","input_","[","i","]",")","+","Bias","[","k","]","Args",":","input_",":","a","tensor","or","a","list","of","2D","batch","x","n","Tensors",".","output_size",":","int","second","dimension","of","W","[","i","]",".","scope",":","VariableScope","for","the","created","subgraph",";","defaults","to","Linear",".","Returns",":","A","2D","Tensor","with","shape","[","batch","x","output_size","]","equal","to","sum_i","(","input_","[","i","]","*","W","[","i","]",")","where","W","[","i","]","s","are","newly","created","matrices",".","Raises",":","ValueError",":","if","some","of","the","arguments","has","unspecified","or","wrong","shape","."],"function":"def linear(input_, output_size, scope=None):\n '''\n Linear map: output[k] = sum_i(Matrix[k, i] * input_[i] ) + Bias[k]\n Args:\n input_: a tensor or a list of 2D, batch x n, Tensors.\n output_size: int, second dimension of W[i].\n scope: VariableScope for the created subgraph; defaults to \"Linear\".\n Returns:\n A 2D Tensor with shape [batch x output_size] equal to\n sum_i(input_[i] * W[i]), where W[i]s are newly created matrices.\n Raises:\n ValueError: if some of the arguments has unspecified or wrong shape.\n '''\n\n shape = input_.get_shape().as_list()\n if len(shape) != 2:\n raise ValueError(\"Linear is expecting 2D arguments: %s\" % str(shape))\n if not shape[1]:\n raise ValueError(\"Linear expects shape[1] of arguments: %s\" % str(shape))\n input_size = shape[1]\n\n # Now the computation.\n with tf.variable_scope(scope or \"SimpleLinear\"):\n matrix = tf.get_variable(\"Matrix\", [output_size, input_size], dtype=input_.dtype)\n bias_term = tf.get_variable(\"Bias\", [output_size], dtype=input_.dtype)\n\n return tf.matmul(input_, tf.transpose(matrix)) + bias_term","function_tokens":["def","linear","(","input_",",","output_size",",","scope","=","None",")",":","shape","=","input_",".","get_shape","(",")",".","as_list","(",")","if","len","(","shape",")","!=","2",":","raise","ValueError","(","\"Linear is expecting 2D arguments: %s\"","%","str","(","shape",")",")","if","not","shape","[","1","]",":","raise","ValueError","(","\"Linear expects shape[1] of arguments: %s\"","%","str","(","shape",")",")","input_size","=","shape","[","1","]","# Now the computation.","with","tf",".","variable_scope","(","scope","or","\"SimpleLinear\"",")",":","matrix","=","tf",".","get_variable","(","\"Matrix\"",",","[","output_size",",","input_size","]",",","dtype","=","input_",".","dtype",")","bias_term","=","tf",".","get_variable","(","\"Bias\"",",","[","output_size","]",",","dtype","=","input_",".","dtype",")","return","tf",".","matmul","(","input_",",","tf",".","transpose","(","matrix",")",")","+","bias_term"],"url":"https:\/\/github.com\/CR-Gjx\/LeakGAN\/blob\/dc3360e30f2572cc4d7281cf2c8f490558e4a794\/Synthetic Data\/Discriminator.py#L12-L38"}
6
+ {"nwo":"CR-Gjx\/LeakGAN","sha":"dc3360e30f2572cc4d7281cf2c8f490558e4a794","path":"Synthetic Data\/Discriminator.py","language":"python","identifier":"highway","parameters":"(input_, size, num_layers=1, bias=-2.0, f=tf.nn.relu, scope='Highway')","argument_list":"","return_statement":"return output","docstring":"Highway Network (cf. http:\/\/arxiv.org\/abs\/1505.00387).\n t = sigmoid(Wy + b)\n z = t * g(Wy + b) + (1 - t) * y\n where g is nonlinearity, t is transform gate, and (1 - t) is carry gate.","docstring_summary":"Highway Network (cf. http:\/\/arxiv.org\/abs\/1505.00387).\n t = sigmoid(Wy + b)\n z = t * g(Wy + b) + (1 - t) * y\n where g is nonlinearity, t is transform gate, and (1 - t) is carry gate.","docstring_tokens":["Highway","Network","(","cf",".","http",":","\/\/","arxiv",".","org","\/","abs","\/","1505",".","00387",")",".","t","=","sigmoid","(","Wy","+","b",")","z","=","t","*","g","(","Wy","+","b",")","+","(","1","-","t",")","*","y","where","g","is","nonlinearity","t","is","transform","gate","and","(","1","-","t",")","is","carry","gate","."],"function":"def highway(input_, size, num_layers=1, bias=-2.0, f=tf.nn.relu, scope='Highway'):\n \"\"\"Highway Network (cf. http:\/\/arxiv.org\/abs\/1505.00387).\n t = sigmoid(Wy + b)\n z = t * g(Wy + b) + (1 - t) * y\n where g is nonlinearity, t is transform gate, and (1 - t) is carry gate.\n \"\"\"\n\n with tf.variable_scope(scope):\n for idx in range(num_layers):\n g = f(linear(input_, size, scope='highway_lin_%d' % idx))\n\n t = tf.sigmoid(linear(input_, size, scope='highway_gate_%d' % idx) + bias)\n\n output = t * g + (1. - t) * input_\n input_ = output\n\n return output","function_tokens":["def","highway","(","input_",",","size",",","num_layers","=","1",",","bias","=","-","2.0",",","f","=","tf",".","nn",".","relu",",","scope","=","'Highway'",")",":","with","tf",".","variable_scope","(","scope",")",":","for","idx","in","range","(","num_layers",")",":","g","=","f","(","linear","(","input_",",","size",",","scope","=","'highway_lin_%d'","%","idx",")",")","t","=","tf",".","sigmoid","(","linear","(","input_",",","size",",","scope","=","'highway_gate_%d'","%","idx",")","+","bias",")","output","=","t","*","g","+","(","1.","-","t",")","*","input_","input_","=","output","return","output"],"url":"https:\/\/github.com\/CR-Gjx\/LeakGAN\/blob\/dc3360e30f2572cc4d7281cf2c8f490558e4a794\/Synthetic Data\/Discriminator.py#L41-L57"}
7
+ {"nwo":"CR-Gjx\/LeakGAN","sha":"dc3360e30f2572cc4d7281cf2c8f490558e4a794","path":"Image COCO\/Discriminator.py","language":"python","identifier":"linear","parameters":"(input_, output_size, scope=None)","argument_list":"","return_statement":"return tf.matmul(input_, tf.transpose(matrix)) + bias_term","docstring":"Linear map: output[k] = sum_i(Matrix[k, i] * input_[i] ) + Bias[k]\n Args:\n input_: a tensor or a list of 2D, batch x n, Tensors.\n output_size: int, second dimension of W[i].\n scope: VariableScope for the created subgraph; defaults to \"Linear\".\n Returns:\n A 2D Tensor with shape [batch x output_size] equal to\n sum_i(input_[i] * W[i]), where W[i]s are newly created matrices.\n Raises:\n ValueError: if some of the arguments has unspecified or wrong shape.","docstring_summary":"Linear map: output[k] = sum_i(Matrix[k, i] * input_[i] ) + Bias[k]\n Args:\n input_: a tensor or a list of 2D, batch x n, Tensors.\n output_size: int, second dimension of W[i].\n scope: VariableScope for the created subgraph; defaults to \"Linear\".\n Returns:\n A 2D Tensor with shape [batch x output_size] equal to\n sum_i(input_[i] * W[i]), where W[i]s are newly created matrices.\n Raises:\n ValueError: if some of the arguments has unspecified or wrong shape.","docstring_tokens":["Linear","map",":","output","[","k","]","=","sum_i","(","Matrix","[","k","i","]","*","input_","[","i","]",")","+","Bias","[","k","]","Args",":","input_",":","a","tensor","or","a","list","of","2D","batch","x","n","Tensors",".","output_size",":","int","second","dimension","of","W","[","i","]",".","scope",":","VariableScope","for","the","created","subgraph",";","defaults","to","Linear",".","Returns",":","A","2D","Tensor","with","shape","[","batch","x","output_size","]","equal","to","sum_i","(","input_","[","i","]","*","W","[","i","]",")","where","W","[","i","]","s","are","newly","created","matrices",".","Raises",":","ValueError",":","if","some","of","the","arguments","has","unspecified","or","wrong","shape","."],"function":"def linear(input_, output_size, scope=None):\n '''\n Linear map: output[k] = sum_i(Matrix[k, i] * input_[i] ) + Bias[k]\n Args:\n input_: a tensor or a list of 2D, batch x n, Tensors.\n output_size: int, second dimension of W[i].\n scope: VariableScope for the created subgraph; defaults to \"Linear\".\n Returns:\n A 2D Tensor with shape [batch x output_size] equal to\n sum_i(input_[i] * W[i]), where W[i]s are newly created matrices.\n Raises:\n ValueError: if some of the arguments has unspecified or wrong shape.\n '''\n\n shape = input_.get_shape().as_list()\n if len(shape) != 2:\n raise ValueError(\"Linear is expecting 2D arguments: %s\" % str(shape))\n if not shape[1]:\n raise ValueError(\"Linear expects shape[1] of arguments: %s\" % str(shape))\n input_size = shape[1]\n\n # Now the computation.\n with tf.variable_scope(scope or \"SimpleLinear\"):\n matrix = tf.get_variable(\"Matrix\", [output_size, input_size], dtype=input_.dtype)\n bias_term = tf.get_variable(\"Bias\", [output_size], dtype=input_.dtype)\n\n return tf.matmul(input_, tf.transpose(matrix)) + bias_term","function_tokens":["def","linear","(","input_",",","output_size",",","scope","=","None",")",":","shape","=","input_",".","get_shape","(",")",".","as_list","(",")","if","len","(","shape",")","!=","2",":","raise","ValueError","(","\"Linear is expecting 2D arguments: %s\"","%","str","(","shape",")",")","if","not","shape","[","1","]",":","raise","ValueError","(","\"Linear expects shape[1] of arguments: %s\"","%","str","(","shape",")",")","input_size","=","shape","[","1","]","# Now the computation.","with","tf",".","variable_scope","(","scope","or","\"SimpleLinear\"",")",":","matrix","=","tf",".","get_variable","(","\"Matrix\"",",","[","output_size",",","input_size","]",",","dtype","=","input_",".","dtype",")","bias_term","=","tf",".","get_variable","(","\"Bias\"",",","[","output_size","]",",","dtype","=","input_",".","dtype",")","return","tf",".","matmul","(","input_",",","tf",".","transpose","(","matrix",")",")","+","bias_term"],"url":"https:\/\/github.com\/CR-Gjx\/LeakGAN\/blob\/dc3360e30f2572cc4d7281cf2c8f490558e4a794\/Image COCO\/Discriminator.py#L12-L38"}
8
+ {"nwo":"CR-Gjx\/LeakGAN","sha":"dc3360e30f2572cc4d7281cf2c8f490558e4a794","path":"Image COCO\/Discriminator.py","language":"python","identifier":"highway","parameters":"(input_, size, num_layers=1, bias=-2.0, f=tf.nn.relu, scope='Highway')","argument_list":"","return_statement":"return output","docstring":"Highway Network (cf. http:\/\/arxiv.org\/abs\/1505.00387).\n t = sigmoid(Wy + b)\n z = t * g(Wy + b) + (1 - t) * y\n where g is nonlinearity, t is transform gate, and (1 - t) is carry gate.","docstring_summary":"Highway Network (cf. http:\/\/arxiv.org\/abs\/1505.00387).\n t = sigmoid(Wy + b)\n z = t * g(Wy + b) + (1 - t) * y\n where g is nonlinearity, t is transform gate, and (1 - t) is carry gate.","docstring_tokens":["Highway","Network","(","cf",".","http",":","\/\/","arxiv",".","org","\/","abs","\/","1505",".","00387",")",".","t","=","sigmoid","(","Wy","+","b",")","z","=","t","*","g","(","Wy","+","b",")","+","(","1","-","t",")","*","y","where","g","is","nonlinearity","t","is","transform","gate","and","(","1","-","t",")","is","carry","gate","."],"function":"def highway(input_, size, num_layers=1, bias=-2.0, f=tf.nn.relu, scope='Highway'):\n \"\"\"Highway Network (cf. http:\/\/arxiv.org\/abs\/1505.00387).\n t = sigmoid(Wy + b)\n z = t * g(Wy + b) + (1 - t) * y\n where g is nonlinearity, t is transform gate, and (1 - t) is carry gate.\n \"\"\"\n\n with tf.variable_scope(scope):\n for idx in range(num_layers):\n g = f(linear(input_, size, scope='highway_lin_%d' % idx))\n\n t = tf.sigmoid(linear(input_, size, scope='highway_gate_%d' % idx) + bias)\n\n output = t * g + (1. - t) * input_\n input_ = output\n\n return output","function_tokens":["def","highway","(","input_",",","size",",","num_layers","=","1",",","bias","=","-","2.0",",","f","=","tf",".","nn",".","relu",",","scope","=","'Highway'",")",":","with","tf",".","variable_scope","(","scope",")",":","for","idx","in","range","(","num_layers",")",":","g","=","f","(","linear","(","input_",",","size",",","scope","=","'highway_lin_%d'","%","idx",")",")","t","=","tf",".","sigmoid","(","linear","(","input_",",","size",",","scope","=","'highway_gate_%d'","%","idx",")","+","bias",")","output","=","t","*","g","+","(","1.","-","t",")","*","input_","input_","=","output","return","output"],"url":"https:\/\/github.com\/CR-Gjx\/LeakGAN\/blob\/dc3360e30f2572cc4d7281cf2c8f490558e4a794\/Image COCO\/Discriminator.py#L41-L57"}
Cadene__bootstrap.pytorch.jsonl ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {"nwo":"Cadene\/bootstrap.pytorch","sha":"e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c","path":"bootstrap\/lib\/options.py","language":"python","identifier":"Options.save","parameters":"(self, path_yaml)","argument_list":"","return_statement":"","docstring":"Write options dictionary to a yaml file","docstring_summary":"Write options dictionary to a yaml file","docstring_tokens":["Write","options","dictionary","to","a","yaml","file"],"function":"def save(self, path_yaml):\n \"\"\" Write options dictionary to a yaml file\n \"\"\"\n Options.save_yaml_opts(self.options, path_yaml)","function_tokens":["def","save","(","self",",","path_yaml",")",":","Options",".","save_yaml_opts","(","self",".","options",",","path_yaml",")"],"url":"https:\/\/github.com\/Cadene\/bootstrap.pytorch\/blob\/e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c\/bootstrap\/lib\/options.py#L278-L281"}
2
+ {"nwo":"Cadene\/bootstrap.pytorch","sha":"e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c","path":"bootstrap\/lib\/options.py","language":"python","identifier":"Options.load_yaml_opts","parameters":"(source)","argument_list":"","return_statement":"return result","docstring":"Load options dictionary from a yaml file","docstring_summary":"Load options dictionary from a yaml file","docstring_tokens":["Load","options","dictionary","from","a","yaml","file"],"function":"def load_yaml_opts(source):\n \"\"\" Load options dictionary from a yaml file\n \"\"\"\n result = {}\n if isinstance(source, str):\n with open(source, 'r') as yaml_file:\n options_dict = yaml.safe_load(yaml_file)\n elif isinstance(source, dict):\n options_dict = source\n else:\n raise TypeError('Unsupported source type: {}'.format(type(source)))\n includes = options_dict.get('__include__', False)\n if includes:\n if type(includes) != list:\n includes = [includes]\n for include in includes:\n filename = '{}\/{}'.format(os.path.dirname(source), include)\n if os.path.isfile(filename):\n parent = Options.load_yaml_opts(filename)\n else:\n parent = Options.load_yaml_opts(include)\n merge_dictionaries(result, parent)\n merge_dictionaries(result, options_dict) # to be sure the main options overwrite the parent options\n result.pop('__include__', None)\n result = OptionsDict(result)\n return result","function_tokens":["def","load_yaml_opts","(","source",")",":","result","=","{","}","if","isinstance","(","source",",","str",")",":","with","open","(","source",",","'r'",")","as","yaml_file",":","options_dict","=","yaml",".","safe_load","(","yaml_file",")","elif","isinstance","(","source",",","dict",")",":","options_dict","=","source","else",":","raise","TypeError","(","'Unsupported source type: {}'",".","format","(","type","(","source",")",")",")","includes","=","options_dict",".","get","(","'__include__'",",","False",")","if","includes",":","if","type","(","includes",")","!=","list",":","includes","=","[","includes","]","for","include","in","includes",":","filename","=","'{}\/{}'",".","format","(","os",".","path",".","dirname","(","source",")",",","include",")","if","os",".","path",".","isfile","(","filename",")",":","parent","=","Options",".","load_yaml_opts","(","filename",")","else",":","parent","=","Options",".","load_yaml_opts","(","include",")","merge_dictionaries","(","result",",","parent",")","merge_dictionaries","(","result",",","options_dict",")","# to be sure the main options overwrite the parent options","result",".","pop","(","'__include__'",",","None",")","result","=","OptionsDict","(","result",")","return","result"],"url":"https:\/\/github.com\/Cadene\/bootstrap.pytorch\/blob\/e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c\/bootstrap\/lib\/options.py#L291-L316"}
3
+ {"nwo":"Cadene\/bootstrap.pytorch","sha":"e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c","path":"bootstrap\/lib\/utils.py","language":"python","identifier":"env_info","parameters":"()","argument_list":"","return_statement":"return info","docstring":"Collects information about the environment, for reproducibility","docstring_summary":"Collects information about the environment, for reproducibility","docstring_tokens":["Collects","information","about","the","environment","for","reproducibility"],"function":"def env_info():\n \"\"\" Collects information about the environment, for reproducibility \"\"\"\n info = {}\n info['python_version'] = sys.version\n info['command'] = subprocess.list2cmdline(sys.argv)\n with open(os.devnull, 'w') as devnull:\n info['pip_modules'] = subprocess.check_output(['pip', 'freeze'], stderr=devnull)\n try:\n git_branch_cmd = ['git', 'rev-parse', '--abbrev-ref', 'HEAD']\n info['git_branch'] = subprocess.check_output(git_branch_cmd, stderr=devnull).strip().decode('UTF-8')\n git_local_commit_cmd = ['git', 'rev-parse', 'HEAD']\n git_status_cmd = ['git', 'status']\n git_origin_commit_cmd = ['git', 'rev-parse', 'origin\/{}'.format(info['git_branch'])]\n git_diff_origin_commit_cmd = ['git', 'diff', 'origin\/{}'.format(info['git_branch'])]\n info['git_origin_commit'] = subprocess.check_output(git_origin_commit_cmd, stderr=devnull)\n git_log_since_origin_cmd = ['git', 'log', '--pretty=oneline', '{}..HEAD'.format(info['git_origin_commit'])]\n info['git_local_commit'] = subprocess.check_output(git_local_commit_cmd, stderr=devnull)\n info['git_status'] = subprocess.check_output(git_status_cmd, stderr=devnull)\n info['git_diff_origin_commit'] = subprocess.check_output(git_diff_origin_commit_cmd, stderr=devnull)\n info['git_log_since_origin'] = subprocess.check_output(git_log_since_origin_cmd, stderr=devnull)\n except subprocess.CalledProcessError:\n pass\n info['creation_time'] = time.strftime('%y-%m-%d-%H-%M-%S')\n info['sysname'] = os.uname()[0]\n info['nodename'] = os.uname()[1]\n info['release'] = os.uname()[2]\n info['version'] = os.uname()[3]\n info['architecture'] = os.uname()[4]\n info['user'] = os.environ['USER']\n info['path'] = os.environ['PWD']\n info['conda_environment'] = os.environ.get('CONDA_DEFAULT_ENV', '')\n info['environment_vars'] = dict(os.environ)\n info = {k: info[k].decode(\"UTF-8\") if type(info[k]) == bytes else info[k] for k in info}\n return info","function_tokens":["def","env_info","(",")",":","info","=","{","}","info","[","'python_version'","]","=","sys",".","version","info","[","'command'","]","=","subprocess",".","list2cmdline","(","sys",".","argv",")","with","open","(","os",".","devnull",",","'w'",")","as","devnull",":","info","[","'pip_modules'","]","=","subprocess",".","check_output","(","[","'pip'",",","'freeze'","]",",","stderr","=","devnull",")","try",":","git_branch_cmd","=","[","'git'",",","'rev-parse'",",","'--abbrev-ref'",",","'HEAD'","]","info","[","'git_branch'","]","=","subprocess",".","check_output","(","git_branch_cmd",",","stderr","=","devnull",")",".","strip","(",")",".","decode","(","'UTF-8'",")","git_local_commit_cmd","=","[","'git'",",","'rev-parse'",",","'HEAD'","]","git_status_cmd","=","[","'git'",",","'status'","]","git_origin_commit_cmd","=","[","'git'",",","'rev-parse'",",","'origin\/{}'",".","format","(","info","[","'git_branch'","]",")","]","git_diff_origin_commit_cmd","=","[","'git'",",","'diff'",",","'origin\/{}'",".","format","(","info","[","'git_branch'","]",")","]","info","[","'git_origin_commit'","]","=","subprocess",".","check_output","(","git_origin_commit_cmd",",","stderr","=","devnull",")","git_log_since_origin_cmd","=","[","'git'",",","'log'",",","'--pretty=oneline'",",","'{}..HEAD'",".","format","(","info","[","'git_origin_commit'","]",")","]","info","[","'git_local_commit'","]","=","subprocess",".","check_output","(","git_local_commit_cmd",",","stderr","=","devnull",")","info","[","'git_status'","]","=","subprocess",".","check_output","(","git_status_cmd",",","stderr","=","devnull",")","info","[","'git_diff_origin_commit'","]","=","subprocess",".","check_output","(","git_diff_origin_commit_cmd",",","stderr","=","devnull",")","info","[","'git_log_since_origin'","]","=","subprocess",".","check_output","(","git_log_since_origin_cmd",",","stderr","=","devnull",")","except","subprocess",".","CalledProcessError",":","pass","info","[","'creation_time'","]","=","time",".","strftime","(","'%y-%m-%d-%H-%M-%S'",")","info","[","'sysname'","]","=","os",".","uname","(",")","[","0","]","info","[","'nodename'","]","=","os",".","uname","(",")","[","1","]","info","[","'release'","]","=","os",".","uname","(",")","[","2","]","info","[","'version'","]","=","os",".","uname","(",")","[","3","]","info","[","'architecture'","]","=","os",".","uname","(",")","[","4","]","info","[","'user'","]","=","os",".","environ","[","'USER'","]","info","[","'path'","]","=","os",".","environ","[","'PWD'","]","info","[","'conda_environment'","]","=","os",".","environ",".","get","(","'CONDA_DEFAULT_ENV'",",","''",")","info","[","'environment_vars'","]","=","dict","(","os",".","environ",")","info","=","{","k",":","info","[","k","]",".","decode","(","\"UTF-8\"",")","if","type","(","info","[","k","]",")","==","bytes","else","info","[","k","]","for","k","in","info","}","return","info"],"url":"https:\/\/github.com\/Cadene\/bootstrap.pytorch\/blob\/e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c\/bootstrap\/lib\/utils.py#L47-L80"}
4
+ {"nwo":"Cadene\/bootstrap.pytorch","sha":"e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c","path":"bootstrap\/models\/model.py","language":"python","identifier":"Model.eval","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Activate evaluation mode","docstring_summary":"Activate evaluation mode","docstring_tokens":["Activate","evaluation","mode"],"function":"def eval(self):\n \"\"\" Activate evaluation mode\n \"\"\"\n super(Model, self).train(mode=False)\n self.mode = 'eval'","function_tokens":["def","eval","(","self",")",":","super","(","Model",",","self",")",".","train","(","mode","=","False",")","self",".","mode","=","'eval'"],"url":"https:\/\/github.com\/Cadene\/bootstrap.pytorch\/blob\/e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c\/bootstrap\/models\/model.py#L28-L32"}
5
+ {"nwo":"Cadene\/bootstrap.pytorch","sha":"e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c","path":"bootstrap\/models\/model.py","language":"python","identifier":"Model.train","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Activate training mode","docstring_summary":"Activate training mode","docstring_tokens":["Activate","training","mode"],"function":"def train(self):\n \"\"\" Activate training mode\n \"\"\"\n super(Model, self).train(mode=True)\n self.mode = 'train'","function_tokens":["def","train","(","self",")",":","super","(","Model",",","self",")",".","train","(","mode","=","True",")","self",".","mode","=","'train'"],"url":"https:\/\/github.com\/Cadene\/bootstrap.pytorch\/blob\/e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c\/bootstrap\/models\/model.py#L34-L38"}
6
+ {"nwo":"Cadene\/bootstrap.pytorch","sha":"e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c","path":"bootstrap\/models\/model.py","language":"python","identifier":"Model.cuda","parameters":"(self, device_id=None)","argument_list":"","return_statement":"return self._apply(lambda t: t.cuda(device_id))","docstring":"Moves all model parameters and buffers to the GPU.\n\n Args:\n device_id (int, optional): if specified, all parameters will be\n copied to that device","docstring_summary":"Moves all model parameters and buffers to the GPU.","docstring_tokens":["Moves","all","model","parameters","and","buffers","to","the","GPU","."],"function":"def cuda(self, device_id=None):\n \"\"\" Moves all model parameters and buffers to the GPU.\n\n Args:\n device_id (int, optional): if specified, all parameters will be\n copied to that device\n \"\"\"\n self.is_cuda = True\n return self._apply(lambda t: t.cuda(device_id))","function_tokens":["def","cuda","(","self",",","device_id","=","None",")",":","self",".","is_cuda","=","True","return","self",".","_apply","(","lambda","t",":","t",".","cuda","(","device_id",")",")"],"url":"https:\/\/github.com\/Cadene\/bootstrap.pytorch\/blob\/e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c\/bootstrap\/models\/model.py#L40-L48"}
7
+ {"nwo":"Cadene\/bootstrap.pytorch","sha":"e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c","path":"bootstrap\/models\/model.py","language":"python","identifier":"Model.cpu","parameters":"(self)","argument_list":"","return_statement":"return self._apply(lambda t: t.cpu())","docstring":"Moves all model parameters and buffers to the CPU.","docstring_summary":"Moves all model parameters and buffers to the CPU.","docstring_tokens":["Moves","all","model","parameters","and","buffers","to","the","CPU","."],"function":"def cpu(self):\n \"\"\" Moves all model parameters and buffers to the CPU.\n \"\"\"\n self.is_cuda = False\n return self._apply(lambda t: t.cpu())","function_tokens":["def","cpu","(","self",")",":","self",".","is_cuda","=","False","return","self",".","_apply","(","lambda","t",":","t",".","cpu","(",")",")"],"url":"https:\/\/github.com\/Cadene\/bootstrap.pytorch\/blob\/e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c\/bootstrap\/models\/model.py#L50-L54"}
8
+ {"nwo":"Cadene\/bootstrap.pytorch","sha":"e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c","path":"bootstrap\/models\/model.py","language":"python","identifier":"Model.prepare_batch","parameters":"(self, batch)","argument_list":"","return_statement":"return batch","docstring":"Prepare a batch with two functions: cuda_tf and detach_tf (only in eval mode)","docstring_summary":"Prepare a batch with two functions: cuda_tf and detach_tf (only in eval mode)","docstring_tokens":["Prepare","a","batch","with","two","functions",":","cuda_tf","and","detach_tf","(","only","in","eval","mode",")"],"function":"def prepare_batch(self, batch):\n \"\"\" Prepare a batch with two functions: cuda_tf and detach_tf (only in eval mode)\n \"\"\"\n if self.is_cuda:\n batch = self.cuda_tf()(batch)\n if self.mode == 'eval':\n batch = self.detach_tf()(batch)\n return batch","function_tokens":["def","prepare_batch","(","self",",","batch",")",":","if","self",".","is_cuda",":","batch","=","self",".","cuda_tf","(",")","(","batch",")","if","self",".","mode","==","'eval'",":","batch","=","self",".","detach_tf","(",")","(","batch",")","return","batch"],"url":"https:\/\/github.com\/Cadene\/bootstrap.pytorch\/blob\/e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c\/bootstrap\/models\/model.py#L56-L63"}
9
+ {"nwo":"Cadene\/bootstrap.pytorch","sha":"e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c","path":"bootstrap\/models\/model.py","language":"python","identifier":"Model.forward","parameters":"(self, batch)","argument_list":"","return_statement":"return out","docstring":"Prepare the batch and feed it to the network, criterion and metric.\n\n Returns:\n out (dict): a dictionary of outputs","docstring_summary":"Prepare the batch and feed it to the network, criterion and metric.","docstring_tokens":["Prepare","the","batch","and","feed","it","to","the","network","criterion","and","metric","."],"function":"def forward(self, batch):\n \"\"\" Prepare the batch and feed it to the network, criterion and metric.\n\n Returns:\n out (dict): a dictionary of outputs\n \"\"\"\n batch = self.prepare_batch(batch)\n net_out = self.network(batch)\n\n cri_out = {}\n if self.mode in self.criterions:\n cri_tmp = self.criterions[self.mode](net_out, batch)\n if cri_tmp is not None:\n cri_out = cri_tmp\n\n met_out = {}\n if self.mode in self.metrics:\n met_tmp = self.metrics[self.mode](cri_out, net_out, batch)\n if met_tmp is not None:\n met_out = met_tmp\n\n out = {}\n if type(net_out) is dict:\n for key, value in net_out.items():\n out[key] = value\n if type(cri_out) is dict:\n for key, value in cri_out.items():\n out[key] = value\n if type(met_out) is dict:\n for key, value in met_out.items():\n out[key] = value\n return out","function_tokens":["def","forward","(","self",",","batch",")",":","batch","=","self",".","prepare_batch","(","batch",")","net_out","=","self",".","network","(","batch",")","cri_out","=","{","}","if","self",".","mode","in","self",".","criterions",":","cri_tmp","=","self",".","criterions","[","self",".","mode","]","(","net_out",",","batch",")","if","cri_tmp","is","not","None",":","cri_out","=","cri_tmp","met_out","=","{","}","if","self",".","mode","in","self",".","metrics",":","met_tmp","=","self",".","metrics","[","self",".","mode","]","(","cri_out",",","net_out",",","batch",")","if","met_tmp","is","not","None",":","met_out","=","met_tmp","out","=","{","}","if","type","(","net_out",")","is","dict",":","for","key",",","value","in","net_out",".","items","(",")",":","out","[","key","]","=","value","if","type","(","cri_out",")","is","dict",":","for","key",",","value","in","cri_out",".","items","(",")",":","out","[","key","]","=","value","if","type","(","met_out",")","is","dict",":","for","key",",","value","in","met_out",".","items","(",")",":","out","[","key","]","=","value","return","out"],"url":"https:\/\/github.com\/Cadene\/bootstrap.pytorch\/blob\/e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c\/bootstrap\/models\/model.py#L65-L96"}
10
+ {"nwo":"Cadene\/bootstrap.pytorch","sha":"e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c","path":"bootstrap\/models\/model.py","language":"python","identifier":"DefaultModel._init_network","parameters":"(self, engine=None)","argument_list":"","return_statement":"return net_factory(engine)","docstring":"Create the network using the bootstrap network factory","docstring_summary":"Create the network using the bootstrap network factory","docstring_tokens":["Create","the","network","using","the","bootstrap","network","factory"],"function":"def _init_network(self, engine=None):\n \"\"\" Create the network using the bootstrap network factory\n \"\"\"\n return net_factory(engine)","function_tokens":["def","_init_network","(","self",",","engine","=","None",")",":","return","net_factory","(","engine",")"],"url":"https:\/\/github.com\/Cadene\/bootstrap.pytorch\/blob\/e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c\/bootstrap\/models\/model.py#L141-L144"}
11
+ {"nwo":"Cadene\/bootstrap.pytorch","sha":"e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c","path":"bootstrap\/models\/model.py","language":"python","identifier":"DefaultModel._init_criterions","parameters":"(self, engine=None)","argument_list":"","return_statement":"return criterions","docstring":"Create the two criterions using the bootstrap criterion factory","docstring_summary":"Create the two criterions using the bootstrap criterion factory","docstring_tokens":["Create","the","two","criterions","using","the","bootstrap","criterion","factory"],"function":"def _init_criterions(self, engine=None):\n \"\"\" Create the two criterions using the bootstrap criterion factory\n \"\"\"\n # by default all modes have criterions\n if engine:\n modes = list(engine.dataset.keys()) # [train, val] for mnist\n else:\n modes = ['train', 'eval']\n\n criterions = {}\n for mode in modes:\n tmp_cri = cri_factory(engine, mode)\n if tmp_cri is not None:\n criterions[mode] = tmp_cri\n return criterions","function_tokens":["def","_init_criterions","(","self",",","engine","=","None",")",":","# by default all modes have criterions","if","engine",":","modes","=","list","(","engine",".","dataset",".","keys","(",")",")","# [train, val] for mnist","else",":","modes","=","[","'train'",",","'eval'","]","criterions","=","{","}","for","mode","in","modes",":","tmp_cri","=","cri_factory","(","engine",",","mode",")","if","tmp_cri","is","not","None",":","criterions","[","mode","]","=","tmp_cri","return","criterions"],"url":"https:\/\/github.com\/Cadene\/bootstrap.pytorch\/blob\/e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c\/bootstrap\/models\/model.py#L146-L160"}
12
+ {"nwo":"Cadene\/bootstrap.pytorch","sha":"e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c","path":"bootstrap\/models\/model.py","language":"python","identifier":"DefaultModel._init_metrics","parameters":"(self, engine=None)","argument_list":"","return_statement":"return metrics","docstring":"Create the two metrics using the bootstrap metric factory","docstring_summary":"Create the two metrics using the bootstrap metric factory","docstring_tokens":["Create","the","two","metrics","using","the","bootstrap","metric","factory"],"function":"def _init_metrics(self, engine=None):\n \"\"\" Create the two metrics using the bootstrap metric factory\n \"\"\"\n # by default all modes have metrics\n if engine:\n modes = list(engine.dataset.keys())\n else:\n modes = ['train', 'eval']\n\n metrics = {}\n for mode in modes:\n tmp_met = met_factory(engine, mode)\n if tmp_met is not None:\n metrics[mode] = tmp_met\n return metrics","function_tokens":["def","_init_metrics","(","self",",","engine","=","None",")",":","# by default all modes have metrics","if","engine",":","modes","=","list","(","engine",".","dataset",".","keys","(",")",")","else",":","modes","=","[","'train'",",","'eval'","]","metrics","=","{","}","for","mode","in","modes",":","tmp_met","=","met_factory","(","engine",",","mode",")","if","tmp_met","is","not","None",":","metrics","[","mode","]","=","tmp_met","return","metrics"],"url":"https:\/\/github.com\/Cadene\/bootstrap.pytorch\/blob\/e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c\/bootstrap\/models\/model.py#L162-L176"}
13
+ {"nwo":"Cadene\/bootstrap.pytorch","sha":"e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c","path":"bootstrap\/models\/model.py","language":"python","identifier":"SimpleModel.forward","parameters":"(self, batch)","argument_list":"","return_statement":"return out","docstring":"The forward call to the network uses batch['data'] instead of batch","docstring_summary":"The forward call to the network uses batch['data'] instead of batch","docstring_tokens":["The","forward","call","to","the","network","uses","batch","[","data","]","instead","of","batch"],"function":"def forward(self, batch):\n \"\"\" The forward call to the network uses batch['data'] instead of batch\n \"\"\"\n batch = self.prepare_batch(batch)\n net_out = self.network(batch['data'])\n\n cri_out = {}\n if self.mode in self.criterions:\n cri_tmp = self.criterions[self.mode](net_out, batch)\n if cri_tmp is not None:\n cri_out = cri_tmp\n\n met_out = {}\n if self.mode in self.metrics:\n met_tmp = self.metrics[self.mode](cri_out, net_out, batch)\n if met_tmp is not None:\n met_out = met_tmp\n\n out = {}\n if type(net_out) is dict:\n for key, value in net_out.items():\n out[key] = value\n if type(cri_out) is dict:\n for key, value in cri_out.items():\n out[key] = value\n if type(met_out) is dict:\n for key, value in met_out.items():\n out[key] = value\n return out","function_tokens":["def","forward","(","self",",","batch",")",":","batch","=","self",".","prepare_batch","(","batch",")","net_out","=","self",".","network","(","batch","[","'data'","]",")","cri_out","=","{","}","if","self",".","mode","in","self",".","criterions",":","cri_tmp","=","self",".","criterions","[","self",".","mode","]","(","net_out",",","batch",")","if","cri_tmp","is","not","None",":","cri_out","=","cri_tmp","met_out","=","{","}","if","self",".","mode","in","self",".","metrics",":","met_tmp","=","self",".","metrics","[","self",".","mode","]","(","cri_out",",","net_out",",","batch",")","if","met_tmp","is","not","None",":","met_out","=","met_tmp","out","=","{","}","if","type","(","net_out",")","is","dict",":","for","key",",","value","in","net_out",".","items","(",")",":","out","[","key","]","=","value","if","type","(","cri_out",")","is","dict",":","for","key",",","value","in","cri_out",".","items","(",")",":","out","[","key","]","=","value","if","type","(","met_out",")","is","dict",":","for","key",",","value","in","met_out",".","items","(",")",":","out","[","key","]","=","value","return","out"],"url":"https:\/\/github.com\/Cadene\/bootstrap.pytorch\/blob\/e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c\/bootstrap\/models\/model.py#L191-L219"}
14
+ {"nwo":"Cadene\/bootstrap.pytorch","sha":"e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c","path":"bootstrap\/models\/metrics\/accuracy.py","language":"python","identifier":"accuracy","parameters":"(output, target, topk=None, ignore_index=None)","argument_list":"","return_statement":"return res","docstring":"Computes the precision@k for the specified values of k","docstring_summary":"Computes the precision","docstring_tokens":["Computes","the","precision"],"function":"def accuracy(output, target, topk=None, ignore_index=None):\n \"\"\"Computes the precision@k for the specified values of k\"\"\"\n topk = topk or [1, 5]\n\n if ignore_index is not None:\n target_mask = (target != ignore_index)\n target = target[target_mask]\n output_mask = target_mask.unsqueeze(1)\n output_mask = output_mask.expand_as(output)\n output = output[output_mask]\n output = output.view(-1, output_mask.size(1))\n\n maxk = max(topk)\n batch_size = target.size(0)\n\n _, pred = output.topk(maxk, 1, True, True)\n pred = pred.t()\n correct = pred.eq(target.view(1, -1).expand_as(pred))\n\n res = []\n for k in topk:\n correct_k = correct[:k].view(-1).float().sum(0, keepdim=True)\n res.append(correct_k.mul_(100.0 \/ batch_size)[0])\n return res","function_tokens":["def","accuracy","(","output",",","target",",","topk","=","None",",","ignore_index","=","None",")",":","topk","=","topk","or","[","1",",","5","]","if","ignore_index","is","not","None",":","target_mask","=","(","target","!=","ignore_index",")","target","=","target","[","target_mask","]","output_mask","=","target_mask",".","unsqueeze","(","1",")","output_mask","=","output_mask",".","expand_as","(","output",")","output","=","output","[","output_mask","]","output","=","output",".","view","(","-","1",",","output_mask",".","size","(","1",")",")","maxk","=","max","(","topk",")","batch_size","=","target",".","size","(","0",")","_",",","pred","=","output",".","topk","(","maxk",",","1",",","True",",","True",")","pred","=","pred",".","t","(",")","correct","=","pred",".","eq","(","target",".","view","(","1",",","-","1",")",".","expand_as","(","pred",")",")","res","=","[","]","for","k","in","topk",":","correct_k","=","correct","[",":","k","]",".","view","(","-","1",")",".","float","(",")",".","sum","(","0",",","keepdim","=","True",")","res",".","append","(","correct_k",".","mul_","(","100.0","\/","batch_size",")","[","0","]",")","return","res"],"url":"https:\/\/github.com\/Cadene\/bootstrap.pytorch\/blob\/e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c\/bootstrap\/models\/metrics\/accuracy.py#L19-L42"}
15
+ {"nwo":"Cadene\/bootstrap.pytorch","sha":"e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c","path":"bootstrap\/models\/networks\/data_parallel.py","language":"python","identifier":"gather","parameters":"(outputs, target_device, dim=0)","argument_list":"","return_statement":"","docstring":"r\"\"\"\n Gathers tensors from different GPUs on a specified device\n (-1 means the CPU).","docstring_summary":"r\"\"\"\n Gathers tensors from different GPUs on a specified device\n (-1 means the CPU).","docstring_tokens":["r","Gathers","tensors","from","different","GPUs","on","a","specified","device","(","-","1","means","the","CPU",")","."],"function":"def gather(outputs, target_device, dim=0):\n r\"\"\"\n Gathers tensors from different GPUs on a specified device\n (-1 means the CPU).\n \"\"\"\n def gather_map(outputs):\n out = outputs[0]\n if torch.is_tensor(out):\n return Gather.apply(target_device, dim, *outputs)\n if out is None:\n return None\n if isinstance(out, dict):\n if not all((len(out) == len(d) for d in outputs)):\n raise ValueError('All dicts must have the same number of keys')\n return type(out)(((k, gather_map([d[k] for d in outputs]))\n for k in out))\n return type(out)(map(gather_map, zip(*outputs)))\n\n # Recursive function calls like this create reference cycles.\n # Setting the function to None clears the refcycle.\n try:\n return gather_map(outputs)\n finally:\n gather_map = None","function_tokens":["def","gather","(","outputs",",","target_device",",","dim","=","0",")",":","def","gather_map","(","outputs",")",":","out","=","outputs","[","0","]","if","torch",".","is_tensor","(","out",")",":","return","Gather",".","apply","(","target_device",",","dim",",","*","outputs",")","if","out","is","None",":","return","None","if","isinstance","(","out",",","dict",")",":","if","not","all","(","(","len","(","out",")","==","len","(","d",")","for","d","in","outputs",")",")",":","raise","ValueError","(","'All dicts must have the same number of keys'",")","return","type","(","out",")","(","(","(","k",",","gather_map","(","[","d","[","k","]","for","d","in","outputs","]",")",")","for","k","in","out",")",")","return","type","(","out",")","(","map","(","gather_map",",","zip","(","*","outputs",")",")",")","# Recursive function calls like this create reference cycles.","# Setting the function to None clears the refcycle.","try",":","return","gather_map","(","outputs",")","finally",":","gather_map","=","None"],"url":"https:\/\/github.com\/Cadene\/bootstrap.pytorch\/blob\/e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c\/bootstrap\/models\/networks\/data_parallel.py#L6-L29"}
16
+ {"nwo":"Cadene\/bootstrap.pytorch","sha":"e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c","path":"bootstrap\/engines\/engine.py","language":"python","identifier":"Engine.generate_view","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Generate a view.html via an asynchronous call to `self.view.generate()`","docstring_summary":"Generate a view.html via an asynchronous call to `self.view.generate()`","docstring_tokens":["Generate","a","view",".","html","via","an","asynchronous","call","to","self",".","view",".","generate","()"],"function":"def generate_view(self):\n \"\"\" Generate a view.html via an asynchronous call to `self.view.generate()`\n \"\"\"\n if self.view is not None:\n if hasattr(self.view, 'current_thread') and self.view.current_thread.is_alive():\n Logger()('Skipping view generation: another view is already being generated', log_level=Logger.WARNING)\n Logger()('Consider removing batch entries from views.items in order to speed it up', log_level=Logger.WARNING)\n else:\n # TODO: Redesign this threading system so it wont slow down training\n # Python threads don't really exist, because of the interpreter lock\n # we might need multi-proessing or some other way.\n self.view.current_thread = threading.Thread(target=self.view.generate)\n self.view.current_thread.start()","function_tokens":["def","generate_view","(","self",")",":","if","self",".","view","is","not","None",":","if","hasattr","(","self",".","view",",","'current_thread'",")","and","self",".","view",".","current_thread",".","is_alive","(",")",":","Logger","(",")","(","'Skipping view generation: another view is already being generated'",",","log_level","=","Logger",".","WARNING",")","Logger","(",")","(","'Consider removing batch entries from views.items in order to speed it up'",",","log_level","=","Logger",".","WARNING",")","else",":","# TODO: Redesign this threading system so it wont slow down training","# Python threads don't really exist, because of the interpreter lock","# we might need multi-proessing or some other way.","self",".","view",".","current_thread","=","threading",".","Thread","(","target","=","self",".","view",".","generate",")","self",".","view",".","current_thread",".","start","(",")"],"url":"https:\/\/github.com\/Cadene\/bootstrap.pytorch\/blob\/e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c\/bootstrap\/engines\/engine.py#L31-L43"}
17
+ {"nwo":"Cadene\/bootstrap.pytorch","sha":"e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c","path":"bootstrap\/engines\/engine.py","language":"python","identifier":"Engine.hook","parameters":"(self, name)","argument_list":"","return_statement":"","docstring":"Run all the callback functions that have been registered\n for a hook.\n\n Args:\n name: the name of the hook","docstring_summary":"Run all the callback functions that have been registered\n for a hook.","docstring_tokens":["Run","all","the","callback","functions","that","have","been","registered","for","a","hook","."],"function":"def hook(self, name):\n \"\"\" Run all the callback functions that have been registered\n for a hook.\n\n Args:\n name: the name of the hook\n \"\"\"\n if name in self.hooks:\n for func in self.hooks[name]:\n func()","function_tokens":["def","hook","(","self",",","name",")",":","if","name","in","self",".","hooks",":","for","func","in","self",".","hooks","[","name","]",":","func","(",")"],"url":"https:\/\/github.com\/Cadene\/bootstrap.pytorch\/blob\/e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c\/bootstrap\/engines\/engine.py#L57-L66"}
18
+ {"nwo":"Cadene\/bootstrap.pytorch","sha":"e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c","path":"bootstrap\/engines\/engine.py","language":"python","identifier":"Engine.register_hook","parameters":"(self, name, func)","argument_list":"","return_statement":"","docstring":"Register a callback function to be triggered when the hook\n is called.\n\n Args:\n name: the name of the hook\n func: the callback function (no argument)\n\n Example usage:\n\n .. code-block:: python\n\n def func():\n print('hooked!')\n\n engine.register_hook('train_on_start_batch', func)","docstring_summary":"Register a callback function to be triggered when the hook\n is called.","docstring_tokens":["Register","a","callback","function","to","be","triggered","when","the","hook","is","called","."],"function":"def register_hook(self, name, func):\n \"\"\" Register a callback function to be triggered when the hook\n is called.\n\n Args:\n name: the name of the hook\n func: the callback function (no argument)\n\n Example usage:\n\n .. code-block:: python\n\n def func():\n print('hooked!')\n\n engine.register_hook('train_on_start_batch', func)\n \"\"\"\n if name not in self.hooks:\n self.hooks[name] = []\n self.hooks[name].append(func)","function_tokens":["def","register_hook","(","self",",","name",",","func",")",":","if","name","not","in","self",".","hooks",":","self",".","hooks","[","name","]","=","[","]","self",".","hooks","[","name","]",".","append","(","func",")"],"url":"https:\/\/github.com\/Cadene\/bootstrap.pytorch\/blob\/e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c\/bootstrap\/engines\/engine.py#L68-L87"}
19
+ {"nwo":"Cadene\/bootstrap.pytorch","sha":"e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c","path":"bootstrap\/engines\/engine.py","language":"python","identifier":"Engine.resume","parameters":"(self, map_location=None)","argument_list":"","return_statement":"","docstring":"Resume a checkpoint using the `bootstrap.lib.options.Options`","docstring_summary":"Resume a checkpoint using the `bootstrap.lib.options.Options`","docstring_tokens":["Resume","a","checkpoint","using","the","bootstrap",".","lib",".","options",".","Options"],"function":"def resume(self, map_location=None):\n \"\"\" Resume a checkpoint using the `bootstrap.lib.options.Options`\n \"\"\"\n Logger()('Loading {} checkpoint'.format(Options()['exp']['resume']))\n self.load(Options()['exp']['dir'],\n Options()['exp']['resume'],\n self.model, self.optimizer,\n map_location=map_location)\n self.epoch += 1","function_tokens":["def","resume","(","self",",","map_location","=","None",")",":","Logger","(",")","(","'Loading {} checkpoint'",".","format","(","Options","(",")","[","'exp'","]","[","'resume'","]",")",")","self",".","load","(","Options","(",")","[","'exp'","]","[","'dir'","]",",","Options","(",")","[","'exp'","]","[","'resume'","]",",","self",".","model",",","self",".","optimizer",",","map_location","=","map_location",")","self",".","epoch","+=","1"],"url":"https:\/\/github.com\/Cadene\/bootstrap.pytorch\/blob\/e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c\/bootstrap\/engines\/engine.py#L89-L97"}
20
+ {"nwo":"Cadene\/bootstrap.pytorch","sha":"e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c","path":"bootstrap\/engines\/engine.py","language":"python","identifier":"Engine.eval","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Launch evaluation procedures","docstring_summary":"Launch evaluation procedures","docstring_tokens":["Launch","evaluation","procedures"],"function":"def eval(self):\n \"\"\" Launch evaluation procedures\n \"\"\"\n Logger()('Launching evaluation procedures')\n\n if Options()['dataset']['eval_split']:\n # self.epoch-1 to be equal to the same resumed epoch\n # or to be equal to -1 when not resumed\n self.eval_epoch(self.model, self.dataset['eval'], self.epoch - 1, logs_json=True)\n\n Logger()('Ending evaluation procedures')","function_tokens":["def","eval","(","self",")",":","Logger","(",")","(","'Launching evaluation procedures'",")","if","Options","(",")","[","'dataset'","]","[","'eval_split'","]",":","# self.epoch-1 to be equal to the same resumed epoch","# or to be equal to -1 when not resumed","self",".","eval_epoch","(","self",".","model",",","self",".","dataset","[","'eval'","]",",","self",".","epoch","-","1",",","logs_json","=","True",")","Logger","(",")","(","'Ending evaluation procedures'",")"],"url":"https:\/\/github.com\/Cadene\/bootstrap.pytorch\/blob\/e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c\/bootstrap\/engines\/engine.py#L99-L109"}
21
+ {"nwo":"Cadene\/bootstrap.pytorch","sha":"e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c","path":"bootstrap\/engines\/engine.py","language":"python","identifier":"Engine.train","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Launch training procedures\n\n List of the hooks:\n\n - train_on_start: before the full training procedure","docstring_summary":"Launch training procedures","docstring_tokens":["Launch","training","procedures"],"function":"def train(self):\n \"\"\" Launch training procedures\n\n List of the hooks:\n\n - train_on_start: before the full training procedure\n\n \"\"\"\n Logger()('Launching training procedures')\n\n self.hook('train_on_start')\n while self.epoch < Options()['engine']['nb_epochs']:\n self.train_epoch(self.model, self.dataset['train'], self.optimizer, self.epoch)\n\n if Options()['dataset']['eval_split']:\n out = self.eval_epoch(self.model, self.dataset['eval'], self.epoch)\n\n if 'saving_criteria' in Options()['engine'] and Options()['engine']['saving_criteria'] is not None:\n for saving_criteria in Options()['engine']['saving_criteria']:\n if self.is_best(out, saving_criteria):\n name = saving_criteria.split(':')[0]\n Logger()('Saving best checkpoint for strategy {}'.format(name))\n self.save(Options()['exp']['dir'], 'best_{}'.format(name), self.model, self.optimizer)\n\n Logger()('Saving last checkpoint')\n self.save(Options()['exp']['dir'], 'last', self.model, self.optimizer)\n self.epoch += 1\n\n Logger()('Ending training procedures')","function_tokens":["def","train","(","self",")",":","Logger","(",")","(","'Launching training procedures'",")","self",".","hook","(","'train_on_start'",")","while","self",".","epoch","<","Options","(",")","[","'engine'","]","[","'nb_epochs'","]",":","self",".","train_epoch","(","self",".","model",",","self",".","dataset","[","'train'","]",",","self",".","optimizer",",","self",".","epoch",")","if","Options","(",")","[","'dataset'","]","[","'eval_split'","]",":","out","=","self",".","eval_epoch","(","self",".","model",",","self",".","dataset","[","'eval'","]",",","self",".","epoch",")","if","'saving_criteria'","in","Options","(",")","[","'engine'","]","and","Options","(",")","[","'engine'","]","[","'saving_criteria'","]","is","not","None",":","for","saving_criteria","in","Options","(",")","[","'engine'","]","[","'saving_criteria'","]",":","if","self",".","is_best","(","out",",","saving_criteria",")",":","name","=","saving_criteria",".","split","(","':'",")","[","0","]","Logger","(",")","(","'Saving best checkpoint for strategy {}'",".","format","(","name",")",")","self",".","save","(","Options","(",")","[","'exp'","]","[","'dir'","]",",","'best_{}'",".","format","(","name",")",",","self",".","model",",","self",".","optimizer",")","Logger","(",")","(","'Saving last checkpoint'",")","self",".","save","(","Options","(",")","[","'exp'","]","[","'dir'","]",",","'last'",",","self",".","model",",","self",".","optimizer",")","self",".","epoch","+=","1","Logger","(",")","(","'Ending training procedures'",")"],"url":"https:\/\/github.com\/Cadene\/bootstrap.pytorch\/blob\/e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c\/bootstrap\/engines\/engine.py#L111-L139"}
22
+ {"nwo":"Cadene\/bootstrap.pytorch","sha":"e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c","path":"bootstrap\/engines\/engine.py","language":"python","identifier":"Engine.train_epoch","parameters":"(self, model, dataset, optimizer, epoch, mode='train')","argument_list":"","return_statement":"","docstring":"Launch training procedures for one epoch\n\n List of the hooks:\n\n - train_on_start_epoch: before the training procedure for an epoch\n - train_on_start_batch: before the training precedure for a batch\n - train_on_forward: after the forward of the model\n - train_on_backward: after the backward of the loss\n - train_on_update: after the optimization step\n - train_on_print: after the print to the terminal\n - train_on_end_batch: end of the training procedure for a batch\n - train_on_end_epoch: before saving the logs in logs.json\n - train_on_flush: end of the training procedure for an epoch","docstring_summary":"Launch training procedures for one epoch","docstring_tokens":["Launch","training","procedures","for","one","epoch"],"function":"def train_epoch(self, model, dataset, optimizer, epoch, mode='train'):\n \"\"\" Launch training procedures for one epoch\n\n List of the hooks:\n\n - train_on_start_epoch: before the training procedure for an epoch\n - train_on_start_batch: before the training precedure for a batch\n - train_on_forward: after the forward of the model\n - train_on_backward: after the backward of the loss\n - train_on_update: after the optimization step\n - train_on_print: after the print to the terminal\n - train_on_end_batch: end of the training procedure for a batch\n - train_on_end_epoch: before saving the logs in logs.json\n - train_on_flush: end of the training procedure for an epoch\n \"\"\"\n utils.set_random_seed(Options()['misc']['seed'] + epoch) # to be able to reproduce exps on reload\n Logger()('Training model on {}set for epoch {}'.format(dataset.split, epoch))\n model.train()\n\n timer = {\n 'begin': time.time(),\n 'elapsed': time.time(),\n 'process': None,\n 'load': None,\n 'run_avg': 0\n }\n out_epoch = {}\n batch_loader = dataset.make_batch_loader()\n\n self.hook(f'{mode}_on_start_epoch')\n for i, batch in enumerate(batch_loader):\n timer['load'] = time.time() - timer['elapsed']\n self.hook(f'{mode}_on_start_batch')\n\n optimizer.zero_grad()\n out = model(batch)\n self.hook(f'{mode}_on_forward')\n\n if not torch.isnan(out['loss']):\n out['loss'].backward()\n else:\n Logger()('NaN detected')\n # torch.cuda.synchronize()\n self.hook(f'{mode}_on_backward')\n\n optimizer.step()\n # torch.cuda.synchronize()\n self.hook(f'{mode}_on_update')\n\n timer['process'] = time.time() - timer['elapsed']\n if i == 0:\n timer['run_avg'] = timer['process']\n else:\n timer['run_avg'] = timer['run_avg'] * 0.8 + timer['process'] * 0.2\n\n Logger().log_value(f'{mode}_batch.epoch', epoch, should_print=False)\n Logger().log_value(f'{mode}_batch.batch', i, should_print=False)\n Logger().log_value(f'{mode}_batch.timer.process', timer['process'], should_print=False)\n Logger().log_value(f'{mode}_batch.timer.load', timer['load'], should_print=False)\n\n for key, value in out.items():\n if torch.is_tensor(value):\n if value.numel() <= 1:\n value = value.item() # get number from a torch scalar\n else:\n continue\n if isinstance(value, (list, dict, tuple)):\n continue\n if key not in out_epoch:\n out_epoch[key] = []\n out_epoch[key].append(value)\n Logger().log_value(f'{mode}_batch.' + key, value, should_print=False)\n\n if i % Options()['engine']['print_freq'] == 0 or i == len(batch_loader) - 1:\n Logger()(\"{}: epoch {} | batch {}\/{}\".format(mode, epoch, i, len(batch_loader) - 1))\n Logger()(\"{} elapsed: {} | left: {}\".format(\n ' ' * len(mode),\n datetime.timedelta(seconds=math.floor(time.time() - timer['begin'])),\n datetime.timedelta(seconds=math.floor(timer['run_avg'] * (len(batch_loader) - 1 - i)))))\n Logger()(\"{} process: {:.5f} | load: {:.5f}\".format(' ' * len(mode), timer['process'], timer['load']))\n Logger()(\"{} loss: {:.5f}\".format(' ' * len(mode), out['loss'].data.item()))\n self.hook(f'{mode}_on_print')\n\n timer['elapsed'] = time.time()\n self.hook(f'{mode}_on_end_batch')\n\n Logger().log_value(f'{mode}_epoch.epoch', epoch, should_print=True)\n for key, value in out_epoch.items():\n Logger().log_value(f'{mode}_epoch.' + key, np.asarray(value).mean(), should_print=True)\n\n self.hook(f'{mode}_on_end_epoch')\n Logger().flush()\n self.hook(f'{mode}_on_flush')","function_tokens":["def","train_epoch","(","self",",","model",",","dataset",",","optimizer",",","epoch",",","mode","=","'train'",")",":","utils",".","set_random_seed","(","Options","(",")","[","'misc'","]","[","'seed'","]","+","epoch",")","# to be able to reproduce exps on reload","Logger","(",")","(","'Training model on {}set for epoch {}'",".","format","(","dataset",".","split",",","epoch",")",")","model",".","train","(",")","timer","=","{","'begin'",":","time",".","time","(",")",",","'elapsed'",":","time",".","time","(",")",",","'process'",":","None",",","'load'",":","None",",","'run_avg'",":","0","}","out_epoch","=","{","}","batch_loader","=","dataset",".","make_batch_loader","(",")","self",".","hook","(","f'{mode}_on_start_epoch'",")","for","i",",","batch","in","enumerate","(","batch_loader",")",":","timer","[","'load'","]","=","time",".","time","(",")","-","timer","[","'elapsed'","]","self",".","hook","(","f'{mode}_on_start_batch'",")","optimizer",".","zero_grad","(",")","out","=","model","(","batch",")","self",".","hook","(","f'{mode}_on_forward'",")","if","not","torch",".","isnan","(","out","[","'loss'","]",")",":","out","[","'loss'","]",".","backward","(",")","else",":","Logger","(",")","(","'NaN detected'",")","# torch.cuda.synchronize()","self",".","hook","(","f'{mode}_on_backward'",")","optimizer",".","step","(",")","# torch.cuda.synchronize()","self",".","hook","(","f'{mode}_on_update'",")","timer","[","'process'","]","=","time",".","time","(",")","-","timer","[","'elapsed'","]","if","i","==","0",":","timer","[","'run_avg'","]","=","timer","[","'process'","]","else",":","timer","[","'run_avg'","]","=","timer","[","'run_avg'","]","*","0.8","+","timer","[","'process'","]","*","0.2","Logger","(",")",".","log_value","(","f'{mode}_batch.epoch'",",","epoch",",","should_print","=","False",")","Logger","(",")",".","log_value","(","f'{mode}_batch.batch'",",","i",",","should_print","=","False",")","Logger","(",")",".","log_value","(","f'{mode}_batch.timer.process'",",","timer","[","'process'","]",",","should_print","=","False",")","Logger","(",")",".","log_value","(","f'{mode}_batch.timer.load'",",","timer","[","'load'","]",",","should_print","=","False",")","for","key",",","value","in","out",".","items","(",")",":","if","torch",".","is_tensor","(","value",")",":","if","value",".","numel","(",")","<=","1",":","value","=","value",".","item","(",")","# get number from a torch scalar","else",":","continue","if","isinstance","(","value",",","(","list",",","dict",",","tuple",")",")",":","continue","if","key","not","in","out_epoch",":","out_epoch","[","key","]","=","[","]","out_epoch","[","key","]",".","append","(","value",")","Logger","(",")",".","log_value","(","f'{mode}_batch.'","+","key",",","value",",","should_print","=","False",")","if","i","%","Options","(",")","[","'engine'","]","[","'print_freq'","]","==","0","or","i","==","len","(","batch_loader",")","-","1",":","Logger","(",")","(","\"{}: epoch {} | batch {}\/{}\"",".","format","(","mode",",","epoch",",","i",",","len","(","batch_loader",")","-","1",")",")","Logger","(",")","(","\"{} elapsed: {} | left: {}\"",".","format","(","' '","*","len","(","mode",")",",","datetime",".","timedelta","(","seconds","=","math",".","floor","(","time",".","time","(",")","-","timer","[","'begin'","]",")",")",",","datetime",".","timedelta","(","seconds","=","math",".","floor","(","timer","[","'run_avg'","]","*","(","len","(","batch_loader",")","-","1","-","i",")",")",")",")",")","Logger","(",")","(","\"{} process: {:.5f} | load: {:.5f}\"",".","format","(","' '","*","len","(","mode",")",",","timer","[","'process'","]",",","timer","[","'load'","]",")",")","Logger","(",")","(","\"{} loss: {:.5f}\"",".","format","(","' '","*","len","(","mode",")",",","out","[","'loss'","]",".","data",".","item","(",")",")",")","self",".","hook","(","f'{mode}_on_print'",")","timer","[","'elapsed'","]","=","time",".","time","(",")","self",".","hook","(","f'{mode}_on_end_batch'",")","Logger","(",")",".","log_value","(","f'{mode}_epoch.epoch'",",","epoch",",","should_print","=","True",")","for","key",",","value","in","out_epoch",".","items","(",")",":","Logger","(",")",".","log_value","(","f'{mode}_epoch.'","+","key",",","np",".","asarray","(","value",")",".","mean","(",")",",","should_print","=","True",")","self",".","hook","(","f'{mode}_on_end_epoch'",")","Logger","(",")",".","flush","(",")","self",".","hook","(","f'{mode}_on_flush'",")"],"url":"https:\/\/github.com\/Cadene\/bootstrap.pytorch\/blob\/e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c\/bootstrap\/engines\/engine.py#L141-L233"}
23
+ {"nwo":"Cadene\/bootstrap.pytorch","sha":"e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c","path":"bootstrap\/engines\/engine.py","language":"python","identifier":"Engine.eval_epoch","parameters":"(self, model, dataset, epoch, mode='eval', logs_json=True)","argument_list":"","return_statement":"return out","docstring":"Launch evaluation procedures for one epoch\n\n List of the hooks (``mode='eval'`` by default):\n\n - mode_on_start_epoch: before the evaluation procedure for an epoch\n - mode_on_start_batch: before the evaluation precedure for a batch\n - mode_on_forward: after the forward of the model\n - mode_on_print: after the print to the terminal\n - mode_on_end_batch: end of the evaluation procedure for a batch\n - mode_on_end_epoch: before saving the logs in logs.json\n - mode_on_flush: end of the evaluation procedure for an epoch\n\n Returns:\n out(dict): mean of all the scalar outputs of the model, indexed by output name, for this epoch","docstring_summary":"Launch evaluation procedures for one epoch","docstring_tokens":["Launch","evaluation","procedures","for","one","epoch"],"function":"def eval_epoch(self, model, dataset, epoch, mode='eval', logs_json=True):\n \"\"\" Launch evaluation procedures for one epoch\n\n List of the hooks (``mode='eval'`` by default):\n\n - mode_on_start_epoch: before the evaluation procedure for an epoch\n - mode_on_start_batch: before the evaluation precedure for a batch\n - mode_on_forward: after the forward of the model\n - mode_on_print: after the print to the terminal\n - mode_on_end_batch: end of the evaluation procedure for a batch\n - mode_on_end_epoch: before saving the logs in logs.json\n - mode_on_flush: end of the evaluation procedure for an epoch\n\n Returns:\n out(dict): mean of all the scalar outputs of the model, indexed by output name, for this epoch\n \"\"\"\n utils.set_random_seed(Options()['misc']['seed'] + epoch) # to be able to reproduce exps on reload\n Logger()('Evaluating model on {}set for epoch {}'.format(dataset.split, epoch))\n model.eval()\n\n timer = {\n 'begin': time.time(),\n 'elapsed': time.time(),\n 'process': None,\n 'load': None,\n 'run_avg': 0\n }\n out_epoch = {}\n batch_loader = dataset.make_batch_loader()\n\n self.hook('{}_on_start_epoch'.format(mode))\n for i, batch in enumerate(batch_loader):\n timer['load'] = time.time() - timer['elapsed']\n self.hook('{}_on_start_batch'.format(mode))\n\n with torch.no_grad():\n out = model(batch)\n # torch.cuda.synchronize()\n self.hook('{}_on_forward'.format(mode))\n\n timer['process'] = time.time() - timer['elapsed']\n if i == 0:\n timer['run_avg'] = timer['process']\n else:\n timer['run_avg'] = timer['run_avg'] * 0.8 + timer['process'] * 0.2\n\n Logger().log_value('{}_batch.batch'.format(mode), i, should_print=False)\n Logger().log_value('{}_batch.epoch'.format(mode), epoch, should_print=False)\n Logger().log_value('{}_batch.timer.process'.format(mode), timer['process'], should_print=False)\n Logger().log_value('{}_batch.timer.load'.format(mode), timer['load'], should_print=False)\n\n for key, value in out.items():\n if torch.is_tensor(value):\n if value.dim() <= 1:\n value = value.item() # get number from a torch scalar\n else:\n continue\n if isinstance(value, (list, dict, tuple)):\n continue\n if key not in out_epoch:\n out_epoch[key] = []\n out_epoch[key].append(value)\n Logger().log_value('{}_batch.{}'.format(mode, key), value, should_print=False)\n\n if i % Options()['engine']['print_freq'] == 0:\n Logger()(\"{}: epoch {} | batch {}\/{}\".format(mode, epoch, i, len(batch_loader) - 1))\n Logger()(\"{} elapsed: {} | left: {}\".format(\n ' ' * len(mode),\n datetime.timedelta(seconds=math.floor(time.time() - timer['begin'])),\n datetime.timedelta(seconds=math.floor(timer['run_avg'] * (len(batch_loader) - 1 - i)))))\n Logger()(\"{} process: {:.5f} | load: {:.5f}\".format(' ' * len(mode), timer['process'], timer['load']))\n self.hook('{}_on_print'.format(mode))\n\n timer['elapsed'] = time.time()\n self.hook('{}_on_end_batch'.format(mode))\n\n out = {}\n for key, value in out_epoch.items():\n out[key] = sum(value) \/ len(value)\n\n Logger().log_value('{}_epoch.epoch'.format(mode), epoch, should_print=True)\n for key, value in out.items():\n Logger().log_value('{}_epoch.{}'.format(mode, key), value, should_print=True)\n\n self.hook('{}_on_end_epoch'.format(mode))\n if logs_json:\n Logger().flush()\n\n self.hook('{}_on_flush'.format(mode))\n return out","function_tokens":["def","eval_epoch","(","self",",","model",",","dataset",",","epoch",",","mode","=","'eval'",",","logs_json","=","True",")",":","utils",".","set_random_seed","(","Options","(",")","[","'misc'","]","[","'seed'","]","+","epoch",")","# to be able to reproduce exps on reload","Logger","(",")","(","'Evaluating model on {}set for epoch {}'",".","format","(","dataset",".","split",",","epoch",")",")","model",".","eval","(",")","timer","=","{","'begin'",":","time",".","time","(",")",",","'elapsed'",":","time",".","time","(",")",",","'process'",":","None",",","'load'",":","None",",","'run_avg'",":","0","}","out_epoch","=","{","}","batch_loader","=","dataset",".","make_batch_loader","(",")","self",".","hook","(","'{}_on_start_epoch'",".","format","(","mode",")",")","for","i",",","batch","in","enumerate","(","batch_loader",")",":","timer","[","'load'","]","=","time",".","time","(",")","-","timer","[","'elapsed'","]","self",".","hook","(","'{}_on_start_batch'",".","format","(","mode",")",")","with","torch",".","no_grad","(",")",":","out","=","model","(","batch",")","# torch.cuda.synchronize()","self",".","hook","(","'{}_on_forward'",".","format","(","mode",")",")","timer","[","'process'","]","=","time",".","time","(",")","-","timer","[","'elapsed'","]","if","i","==","0",":","timer","[","'run_avg'","]","=","timer","[","'process'","]","else",":","timer","[","'run_avg'","]","=","timer","[","'run_avg'","]","*","0.8","+","timer","[","'process'","]","*","0.2","Logger","(",")",".","log_value","(","'{}_batch.batch'",".","format","(","mode",")",",","i",",","should_print","=","False",")","Logger","(",")",".","log_value","(","'{}_batch.epoch'",".","format","(","mode",")",",","epoch",",","should_print","=","False",")","Logger","(",")",".","log_value","(","'{}_batch.timer.process'",".","format","(","mode",")",",","timer","[","'process'","]",",","should_print","=","False",")","Logger","(",")",".","log_value","(","'{}_batch.timer.load'",".","format","(","mode",")",",","timer","[","'load'","]",",","should_print","=","False",")","for","key",",","value","in","out",".","items","(",")",":","if","torch",".","is_tensor","(","value",")",":","if","value",".","dim","(",")","<=","1",":","value","=","value",".","item","(",")","# get number from a torch scalar","else",":","continue","if","isinstance","(","value",",","(","list",",","dict",",","tuple",")",")",":","continue","if","key","not","in","out_epoch",":","out_epoch","[","key","]","=","[","]","out_epoch","[","key","]",".","append","(","value",")","Logger","(",")",".","log_value","(","'{}_batch.{}'",".","format","(","mode",",","key",")",",","value",",","should_print","=","False",")","if","i","%","Options","(",")","[","'engine'","]","[","'print_freq'","]","==","0",":","Logger","(",")","(","\"{}: epoch {} | batch {}\/{}\"",".","format","(","mode",",","epoch",",","i",",","len","(","batch_loader",")","-","1",")",")","Logger","(",")","(","\"{} elapsed: {} | left: {}\"",".","format","(","' '","*","len","(","mode",")",",","datetime",".","timedelta","(","seconds","=","math",".","floor","(","time",".","time","(",")","-","timer","[","'begin'","]",")",")",",","datetime",".","timedelta","(","seconds","=","math",".","floor","(","timer","[","'run_avg'","]","*","(","len","(","batch_loader",")","-","1","-","i",")",")",")",")",")","Logger","(",")","(","\"{} process: {:.5f} | load: {:.5f}\"",".","format","(","' '","*","len","(","mode",")",",","timer","[","'process'","]",",","timer","[","'load'","]",")",")","self",".","hook","(","'{}_on_print'",".","format","(","mode",")",")","timer","[","'elapsed'","]","=","time",".","time","(",")","self",".","hook","(","'{}_on_end_batch'",".","format","(","mode",")",")","out","=","{","}","for","key",",","value","in","out_epoch",".","items","(",")",":","out","[","key","]","=","sum","(","value",")","\/","len","(","value",")","Logger","(",")",".","log_value","(","'{}_epoch.epoch'",".","format","(","mode",")",",","epoch",",","should_print","=","True",")","for","key",",","value","in","out",".","items","(",")",":","Logger","(",")",".","log_value","(","'{}_epoch.{}'",".","format","(","mode",",","key",")",",","value",",","should_print","=","True",")","self",".","hook","(","'{}_on_end_epoch'",".","format","(","mode",")",")","if","logs_json",":","Logger","(",")",".","flush","(",")","self",".","hook","(","'{}_on_flush'",".","format","(","mode",")",")","return","out"],"url":"https:\/\/github.com\/Cadene\/bootstrap.pytorch\/blob\/e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c\/bootstrap\/engines\/engine.py#L235-L324"}
24
+ {"nwo":"Cadene\/bootstrap.pytorch","sha":"e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c","path":"bootstrap\/engines\/engine.py","language":"python","identifier":"Engine.is_best","parameters":"(self, out, saving_criteria)","argument_list":"","return_statement":"return False","docstring":"Verify if the last model is the best for a specific saving criteria\n\n Args:\n out(dict): mean of all the scalar outputs of model indexed by output name\n saving_criteria(str):\n\n Returns:\n is_best(bool)\n\n Example usage:\n\n .. code-block:: python\n\n out = {\n 'loss': 0.2,\n 'acctop1': 87.02\n }\n\n engine.is_best(out, 'loss:min')","docstring_summary":"Verify if the last model is the best for a specific saving criteria","docstring_tokens":["Verify","if","the","last","model","is","the","best","for","a","specific","saving","criteria"],"function":"def is_best(self, out, saving_criteria):\n \"\"\" Verify if the last model is the best for a specific saving criteria\n\n Args:\n out(dict): mean of all the scalar outputs of model indexed by output name\n saving_criteria(str):\n\n Returns:\n is_best(bool)\n\n Example usage:\n\n .. code-block:: python\n\n out = {\n 'loss': 0.2,\n 'acctop1': 87.02\n }\n\n engine.is_best(out, 'loss:min')\n \"\"\"\n if ':min' in saving_criteria:\n name = saving_criteria.replace(':min', '')\n order = '<'\n elif ':max' in saving_criteria:\n name = saving_criteria.replace(':max', '')\n order = '>'\n else:\n error_msg = \"\"\"'--engine.saving_criteria' named '{}' does not specify order,\n you need to chose between '{}' or '{}' to specify if the criteria needs to be minimize or maximize\"\"\".format(\n saving_criteria, saving_criteria + ':min', saving_criteria + ':max')\n raise ValueError(error_msg)\n\n if name not in out:\n raise KeyError(\"'--engine.saving_criteria' named '{}' not in outputs '{}'\".format(name, list(out.keys())))\n\n if name not in self.best_out:\n self.best_out[name] = out[name]\n return True\n else:\n if eval('{} {} {}'.format(out[name], order, self.best_out[name])):\n self.best_out[name] = out[name]\n return True\n\n return False","function_tokens":["def","is_best","(","self",",","out",",","saving_criteria",")",":","if","':min'","in","saving_criteria",":","name","=","saving_criteria",".","replace","(","':min'",",","''",")","order","=","'<'","elif","':max'","in","saving_criteria",":","name","=","saving_criteria",".","replace","(","':max'",",","''",")","order","=","'>'","else",":","error_msg","=","\"\"\"'--engine.saving_criteria' named '{}' does not specify order,\n you need to chose between '{}' or '{}' to specify if the criteria needs to be minimize or maximize\"\"\"",".","format","(","saving_criteria",",","saving_criteria","+","':min'",",","saving_criteria","+","':max'",")","raise","ValueError","(","error_msg",")","if","name","not","in","out",":","raise","KeyError","(","\"'--engine.saving_criteria' named '{}' not in outputs '{}'\"",".","format","(","name",",","list","(","out",".","keys","(",")",")",")",")","if","name","not","in","self",".","best_out",":","self",".","best_out","[","name","]","=","out","[","name","]","return","True","else",":","if","eval","(","'{} {} {}'",".","format","(","out","[","name","]",",","order",",","self",".","best_out","[","name","]",")",")",":","self",".","best_out","[","name","]","=","out","[","name","]","return","True","return","False"],"url":"https:\/\/github.com\/Cadene\/bootstrap.pytorch\/blob\/e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c\/bootstrap\/engines\/engine.py#L326-L370"}
25
+ {"nwo":"Cadene\/bootstrap.pytorch","sha":"e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c","path":"bootstrap\/engines\/engine.py","language":"python","identifier":"Engine.load","parameters":"(self, dir_logs, name, model, optimizer, map_location=None)","argument_list":"","return_statement":"","docstring":"Load a checkpoint\n\n Args:\n dir_logs: directory of the checkpoint\n name: name of the checkpoint\n model: model associated to the checkpoint\n optimizer: optimizer associated to the checkpoint","docstring_summary":"Load a checkpoint","docstring_tokens":["Load","a","checkpoint"],"function":"def load(self, dir_logs, name, model, optimizer, map_location=None):\n \"\"\" Load a checkpoint\n\n Args:\n dir_logs: directory of the checkpoint\n name: name of the checkpoint\n model: model associated to the checkpoint\n optimizer: optimizer associated to the checkpoint\n \"\"\"\n path_template = os.path.join(dir_logs, 'ckpt_{}_{}.pth.tar')\n\n Logger()('Loading model...')\n model_state = torch.load(path_template.format(name, 'model'), map_location=map_location)\n model.load_state_dict(model_state)\n\n if Options()['dataset']['train_split'] is not None:\n if os.path.isfile(path_template.format(name, 'optimizer')):\n Logger()('Loading optimizer...')\n optimizer_state = torch.load(path_template.format(name, 'optimizer'), map_location=map_location)\n optimizer.load_state_dict(optimizer_state)\n else:\n Logger()('No optimizer checkpoint', log_level=Logger.WARNING)\n\n if os.path.isfile(path_template.format(name, 'engine')):\n Logger()('Loading engine...')\n engine_state = torch.load(path_template.format(name, 'engine'), map_location=map_location)\n self.load_state_dict(engine_state)\n else:\n Logger()('No engine checkpoint', log_level=Logger.WARNING)","function_tokens":["def","load","(","self",",","dir_logs",",","name",",","model",",","optimizer",",","map_location","=","None",")",":","path_template","=","os",".","path",".","join","(","dir_logs",",","'ckpt_{}_{}.pth.tar'",")","Logger","(",")","(","'Loading model...'",")","model_state","=","torch",".","load","(","path_template",".","format","(","name",",","'model'",")",",","map_location","=","map_location",")","model",".","load_state_dict","(","model_state",")","if","Options","(",")","[","'dataset'","]","[","'train_split'","]","is","not","None",":","if","os",".","path",".","isfile","(","path_template",".","format","(","name",",","'optimizer'",")",")",":","Logger","(",")","(","'Loading optimizer...'",")","optimizer_state","=","torch",".","load","(","path_template",".","format","(","name",",","'optimizer'",")",",","map_location","=","map_location",")","optimizer",".","load_state_dict","(","optimizer_state",")","else",":","Logger","(",")","(","'No optimizer checkpoint'",",","log_level","=","Logger",".","WARNING",")","if","os",".","path",".","isfile","(","path_template",".","format","(","name",",","'engine'",")",")",":","Logger","(",")","(","'Loading engine...'",")","engine_state","=","torch",".","load","(","path_template",".","format","(","name",",","'engine'",")",",","map_location","=","map_location",")","self",".","load_state_dict","(","engine_state",")","else",":","Logger","(",")","(","'No engine checkpoint'",",","log_level","=","Logger",".","WARNING",")"],"url":"https:\/\/github.com\/Cadene\/bootstrap.pytorch\/blob\/e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c\/bootstrap\/engines\/engine.py#L372-L400"}
26
+ {"nwo":"Cadene\/bootstrap.pytorch","sha":"e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c","path":"bootstrap\/engines\/engine.py","language":"python","identifier":"Engine.save","parameters":"(self, dir_logs, name, model, optimizer)","argument_list":"","return_statement":"","docstring":"Save a checkpoint\n\n Args:\n dir_logs: directory of the checkpoint\n name: name of the checkpoint\n model: model associated to the checkpoint\n optimizer: optimizer associated to the checkpoint","docstring_summary":"Save a checkpoint","docstring_tokens":["Save","a","checkpoint"],"function":"def save(self, dir_logs, name, model, optimizer):\n \"\"\" Save a checkpoint\n\n Args:\n dir_logs: directory of the checkpoint\n name: name of the checkpoint\n model: model associated to the checkpoint\n optimizer: optimizer associated to the checkpoint\n \"\"\"\n path_template = os.path.join(dir_logs, 'ckpt_{}_{}.pth.tar')\n\n Logger()('Saving model...')\n model_state = model.state_dict()\n torch.save(model_state, path_template.format(name, 'model'))\n\n Logger()('Saving optimizer...')\n optimizer_state = optimizer.state_dict()\n torch.save(optimizer_state, path_template.format(name, 'optimizer'))\n\n Logger()('Saving engine...')\n engine_state = self.state_dict()\n torch.save(engine_state, path_template.format(name, 'engine'))","function_tokens":["def","save","(","self",",","dir_logs",",","name",",","model",",","optimizer",")",":","path_template","=","os",".","path",".","join","(","dir_logs",",","'ckpt_{}_{}.pth.tar'",")","Logger","(",")","(","'Saving model...'",")","model_state","=","model",".","state_dict","(",")","torch",".","save","(","model_state",",","path_template",".","format","(","name",",","'model'",")",")","Logger","(",")","(","'Saving optimizer...'",")","optimizer_state","=","optimizer",".","state_dict","(",")","torch",".","save","(","optimizer_state",",","path_template",".","format","(","name",",","'optimizer'",")",")","Logger","(",")","(","'Saving engine...'",")","engine_state","=","self",".","state_dict","(",")","torch",".","save","(","engine_state",",","path_template",".","format","(","name",",","'engine'",")",")"],"url":"https:\/\/github.com\/Cadene\/bootstrap.pytorch\/blob\/e7d55b52fe8d819de7ea3da8b1027d4a3dcc9e0c\/bootstrap\/engines\/engine.py#L402-L423"}
Cadene__pretrained-models.pytorch.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
CalciferZh__minimal-hand.jsonl ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {"nwo":"CalciferZh\/minimal-hand","sha":"da91d777a36207ea67d87f06fc881a4806312ef0","path":"prepare_mano.py","language":"python","identifier":"prepare_mano","parameters":"()","argument_list":"","return_statement":"","docstring":"Use this function to convert a mano model (from MANO-Hand Project) to the hand\n model we want to use in the project.","docstring_summary":"Use this function to convert a mano model (from MANO-Hand Project) to the hand\n model we want to use in the project.","docstring_tokens":["Use","this","function","to","convert","a","mano","model","(","from","MANO","-","Hand","Project",")","to","the","hand","model","we","want","to","use","in","the","project","."],"function":"def prepare_mano():\n \"\"\"\n Use this function to convert a mano model (from MANO-Hand Project) to the hand\n model we want to use in the project.\n \"\"\"\n with open(OFFICIAL_MANO_PATH, 'rb') as f:\n data = pickle.load(f, encoding='latin1')\n\n output = {}\n output['verts'] = np.array(data['v_template'])\n output['faces'] = np.array(data['f'])\n output['mesh_basis'] = np.transpose(data['shapedirs'], (2, 0, 1))\n\n j_regressor = np.zeros([21, 778])\n j_regressor[:16] = data['J_regressor'].toarray()\n for k, v in MANOHandJoints.mesh_mapping.items():\n j_regressor[k, v] = 1\n output['j_regressor'] = j_regressor\n output['joints'] = np.matmul(output['j_regressor'], output['verts'])\n\n raw_weights = data['weights']\n weights = [None] * 21\n weights[0] = raw_weights[:, 0]\n for j in 'IMLRT':\n weights[MANOHandJoints.labels.index(j + '0')] = np.zeros(778)\n for k in [1, 2, 3]:\n src_idx = MANOHandJoints.labels.index(j + str(k - 1))\n tar_idx = MANOHandJoints.labels.index(j + str(k))\n weights[tar_idx] = raw_weights[:, src_idx]\n output['weights'] = np.expand_dims(np.stack(weights, -1), -1)\n with open(HAND_MESH_MODEL_PATH, 'wb') as f:\n pickle.dump(output, f)","function_tokens":["def","prepare_mano","(",")",":","with","open","(","OFFICIAL_MANO_PATH",",","'rb'",")","as","f",":","data","=","pickle",".","load","(","f",",","encoding","=","'latin1'",")","output","=","{","}","output","[","'verts'","]","=","np",".","array","(","data","[","'v_template'","]",")","output","[","'faces'","]","=","np",".","array","(","data","[","'f'","]",")","output","[","'mesh_basis'","]","=","np",".","transpose","(","data","[","'shapedirs'","]",",","(","2",",","0",",","1",")",")","j_regressor","=","np",".","zeros","(","[","21",",","778","]",")","j_regressor","[",":","16","]","=","data","[","'J_regressor'","]",".","toarray","(",")","for","k",",","v","in","MANOHandJoints",".","mesh_mapping",".","items","(",")",":","j_regressor","[","k",",","v","]","=","1","output","[","'j_regressor'","]","=","j_regressor","output","[","'joints'","]","=","np",".","matmul","(","output","[","'j_regressor'","]",",","output","[","'verts'","]",")","raw_weights","=","data","[","'weights'","]","weights","=","[","None","]","*","21","weights","[","0","]","=","raw_weights","[",":",",","0","]","for","j","in","'IMLRT'",":","weights","[","MANOHandJoints",".","labels",".","index","(","j","+","'0'",")","]","=","np",".","zeros","(","778",")","for","k","in","[","1",",","2",",","3","]",":","src_idx","=","MANOHandJoints",".","labels",".","index","(","j","+","str","(","k","-","1",")",")","tar_idx","=","MANOHandJoints",".","labels",".","index","(","j","+","str","(","k",")",")","weights","[","tar_idx","]","=","raw_weights","[",":",",","src_idx","]","output","[","'weights'","]","=","np",".","expand_dims","(","np",".","stack","(","weights",",","-","1",")",",","-","1",")","with","open","(","HAND_MESH_MODEL_PATH",",","'wb'",")","as","f",":","pickle",".","dump","(","output",",","f",")"],"url":"https:\/\/github.com\/CalciferZh\/minimal-hand\/blob\/da91d777a36207ea67d87f06fc881a4806312ef0\/prepare_mano.py#L7-L38"}
2
+ {"nwo":"CalciferZh\/minimal-hand","sha":"da91d777a36207ea67d87f06fc881a4806312ef0","path":"wrappers.py","language":"python","identifier":"ModelDet.__init__","parameters":"(self, model_path)","argument_list":"","return_statement":"","docstring":"Parameters\n ----------\n model_path : str\n Path to the trained model.","docstring_summary":"Parameters\n ----------\n model_path : str\n Path to the trained model.","docstring_tokens":["Parameters","----------","model_path",":","str","Path","to","the","trained","model","."],"function":"def __init__(self, model_path):\n \"\"\"\n Parameters\n ----------\n model_path : str\n Path to the trained model.\n \"\"\"\n self.graph = tf.Graph()\n with self.graph.as_default():\n with tf.variable_scope('prior_based_hand'):\n config = tf.ConfigProto()\n config.gpu_options.allow_growth = True\n self.sess = tf.Session(config=config)\n self.input_ph = tf.placeholder(tf.uint8, [128, 128, 3])\n self.feed_img = \\\n tf.cast(tf.expand_dims(self.input_ph, 0), tf.float32) \/ 255\n self.hmaps, self.dmaps, self.lmaps = \\\n detnet(self.feed_img, 1, False)\n\n self.hmap = self.hmaps[-1]\n self.dmap = self.dmaps[-1]\n self.lmap = self.lmaps[-1]\n\n self.uv = tf_hmap_to_uv(self.hmap)\n self.delta = tf.gather_nd(\n tf.transpose(self.dmap, [0, 3, 1, 2, 4]), self.uv, batch_dims=2\n )[0]\n self.xyz = tf.gather_nd(\n tf.transpose(self.lmap, [0, 3, 1, 2, 4]), self.uv, batch_dims=2\n )[0]\n\n self.uv = self.uv[0]\n tf.train.Saver().restore(self.sess, model_path)","function_tokens":["def","__init__","(","self",",","model_path",")",":","self",".","graph","=","tf",".","Graph","(",")","with","self",".","graph",".","as_default","(",")",":","with","tf",".","variable_scope","(","'prior_based_hand'",")",":","config","=","tf",".","ConfigProto","(",")","config",".","gpu_options",".","allow_growth","=","True","self",".","sess","=","tf",".","Session","(","config","=","config",")","self",".","input_ph","=","tf",".","placeholder","(","tf",".","uint8",",","[","128",",","128",",","3","]",")","self",".","feed_img","=","tf",".","cast","(","tf",".","expand_dims","(","self",".","input_ph",",","0",")",",","tf",".","float32",")","\/","255","self",".","hmaps",",","self",".","dmaps",",","self",".","lmaps","=","detnet","(","self",".","feed_img",",","1",",","False",")","self",".","hmap","=","self",".","hmaps","[","-","1","]","self",".","dmap","=","self",".","dmaps","[","-","1","]","self",".","lmap","=","self",".","lmaps","[","-","1","]","self",".","uv","=","tf_hmap_to_uv","(","self",".","hmap",")","self",".","delta","=","tf",".","gather_nd","(","tf",".","transpose","(","self",".","dmap",",","[","0",",","3",",","1",",","2",",","4","]",")",",","self",".","uv",",","batch_dims","=","2",")","[","0","]","self",".","xyz","=","tf",".","gather_nd","(","tf",".","transpose","(","self",".","lmap",",","[","0",",","3",",","1",",","2",",","4","]",")",",","self",".","uv",",","batch_dims","=","2",")","[","0","]","self",".","uv","=","self",".","uv","[","0","]","tf",".","train",".","Saver","(",")",".","restore","(","self",".","sess",",","model_path",")"],"url":"https:\/\/github.com\/CalciferZh\/minimal-hand\/blob\/da91d777a36207ea67d87f06fc881a4806312ef0\/wrappers.py#L16-L48"}
3
+ {"nwo":"CalciferZh\/minimal-hand","sha":"da91d777a36207ea67d87f06fc881a4806312ef0","path":"wrappers.py","language":"python","identifier":"ModelDet.process","parameters":"(self, img)","argument_list":"","return_statement":"return results","docstring":"Process a color image.\n\n Parameters\n ----------\n img : np.ndarray\n A 128x128 RGB image of **left hand** with dtype uint8.\n\n Returns\n -------\n np.ndarray, shape [21, 3]\n Normalized keypoint locations. The coordinates are relative to the M0\n joint and normalized by the length of the bone from wrist to M0. The\n order of keypoints is as `kinematics.MPIIHandJoints`.\n np.ndarray, shape [21, 2]\n The uv coordinates of the keypoints on the heat map, whose resolution is\n 32x32.","docstring_summary":"Process a color image.","docstring_tokens":["Process","a","color","image","."],"function":"def process(self, img):\n \"\"\"\n Process a color image.\n\n Parameters\n ----------\n img : np.ndarray\n A 128x128 RGB image of **left hand** with dtype uint8.\n\n Returns\n -------\n np.ndarray, shape [21, 3]\n Normalized keypoint locations. The coordinates are relative to the M0\n joint and normalized by the length of the bone from wrist to M0. The\n order of keypoints is as `kinematics.MPIIHandJoints`.\n np.ndarray, shape [21, 2]\n The uv coordinates of the keypoints on the heat map, whose resolution is\n 32x32.\n \"\"\"\n results = self.sess.run([self.xyz, self.uv], {self.input_ph: img})\n return results","function_tokens":["def","process","(","self",",","img",")",":","results","=","self",".","sess",".","run","(","[","self",".","xyz",",","self",".","uv","]",",","{","self",".","input_ph",":","img","}",")","return","results"],"url":"https:\/\/github.com\/CalciferZh\/minimal-hand\/blob\/da91d777a36207ea67d87f06fc881a4806312ef0\/wrappers.py#L50-L70"}
4
+ {"nwo":"CalciferZh\/minimal-hand","sha":"da91d777a36207ea67d87f06fc881a4806312ef0","path":"wrappers.py","language":"python","identifier":"ModelIK.__init__","parameters":"(self, input_size, network_fn, model_path, net_depth, net_width)","argument_list":"","return_statement":"","docstring":"Parameters\n ----------\n input_size : int\n Number of joints to be used, e.g. 21, 42.\n network_fn : function\n Network function from `network.py`.\n model_path : str\n Path to the trained model.\n net_depth : int\n Number of layers.\n net_width : int\n Number of neurons in each layer.","docstring_summary":"Parameters\n ----------\n input_size : int\n Number of joints to be used, e.g. 21, 42.\n network_fn : function\n Network function from `network.py`.\n model_path : str\n Path to the trained model.\n net_depth : int\n Number of layers.\n net_width : int\n Number of neurons in each layer.","docstring_tokens":["Parameters","----------","input_size",":","int","Number","of","joints","to","be","used","e",".","g",".","21","42",".","network_fn",":","function","Network","function","from","network",".","py",".","model_path",":","str","Path","to","the","trained","model",".","net_depth",":","int","Number","of","layers",".","net_width",":","int","Number","of","neurons","in","each","layer","."],"function":"def __init__(self, input_size, network_fn, model_path, net_depth, net_width):\n \"\"\"\n Parameters\n ----------\n input_size : int\n Number of joints to be used, e.g. 21, 42.\n network_fn : function\n Network function from `network.py`.\n model_path : str\n Path to the trained model.\n net_depth : int\n Number of layers.\n net_width : int\n Number of neurons in each layer.\n \"\"\"\n self.graph = tf.Graph()\n with self.graph.as_default():\n self.input_ph = tf.placeholder(tf.float32, [1, input_size, 3])\n with tf.name_scope('network'):\n self.theta = \\\n network_fn(self.input_ph, net_depth, net_width, training=False)[0]\n config = tf.ConfigProto()\n config.gpu_options.allow_growth = True\n self.sess = tf.Session(config=config)\n tf.train.Saver().restore(self.sess, model_path)","function_tokens":["def","__init__","(","self",",","input_size",",","network_fn",",","model_path",",","net_depth",",","net_width",")",":","self",".","graph","=","tf",".","Graph","(",")","with","self",".","graph",".","as_default","(",")",":","self",".","input_ph","=","tf",".","placeholder","(","tf",".","float32",",","[","1",",","input_size",",","3","]",")","with","tf",".","name_scope","(","'network'",")",":","self",".","theta","=","network_fn","(","self",".","input_ph",",","net_depth",",","net_width",",","training","=","False",")","[","0","]","config","=","tf",".","ConfigProto","(",")","config",".","gpu_options",".","allow_growth","=","True","self",".","sess","=","tf",".","Session","(","config","=","config",")","tf",".","train",".","Saver","(",")",".","restore","(","self",".","sess",",","model_path",")"],"url":"https:\/\/github.com\/CalciferZh\/minimal-hand\/blob\/da91d777a36207ea67d87f06fc881a4806312ef0\/wrappers.py#L77-L101"}
5
+ {"nwo":"CalciferZh\/minimal-hand","sha":"da91d777a36207ea67d87f06fc881a4806312ef0","path":"wrappers.py","language":"python","identifier":"ModelIK.process","parameters":"(self, joints)","argument_list":"","return_statement":"return theta","docstring":"Estimate joint rotations from locations.\n\n Parameters\n ----------\n joints : np.ndarray, shape [N, 3]\n Input joint locations (and other information e.g. bone orientation).\n\n Returns\n -------\n np.ndarray, shape [21, 4]\n Estimated global joint rotations in quaternions.","docstring_summary":"Estimate joint rotations from locations.","docstring_tokens":["Estimate","joint","rotations","from","locations","."],"function":"def process(self, joints):\n \"\"\"\n Estimate joint rotations from locations.\n\n Parameters\n ----------\n joints : np.ndarray, shape [N, 3]\n Input joint locations (and other information e.g. bone orientation).\n\n Returns\n -------\n np.ndarray, shape [21, 4]\n Estimated global joint rotations in quaternions.\n \"\"\"\n theta = \\\n self.sess.run(self.theta, {self.input_ph: np.expand_dims(joints, 0)})\n if len(theta.shape) == 3:\n theta = theta[0]\n return theta","function_tokens":["def","process","(","self",",","joints",")",":","theta","=","self",".","sess",".","run","(","self",".","theta",",","{","self",".","input_ph",":","np",".","expand_dims","(","joints",",","0",")","}",")","if","len","(","theta",".","shape",")","==","3",":","theta","=","theta","[","0","]","return","theta"],"url":"https:\/\/github.com\/CalciferZh\/minimal-hand\/blob\/da91d777a36207ea67d87f06fc881a4806312ef0\/wrappers.py#L103-L121"}
6
+ {"nwo":"CalciferZh\/minimal-hand","sha":"da91d777a36207ea67d87f06fc881a4806312ef0","path":"wrappers.py","language":"python","identifier":"ModelPipeline.process","parameters":"(self, frame)","argument_list":"","return_statement":"return xyz, theta","docstring":"Process a single frame.\n\n Parameters\n ----------\n frame : np.ndarray, shape [128, 128, 3], dtype np.uint8.\n Frame to be processed.\n\n Returns\n -------\n np.ndarray, shape [21, 3]\n Joint locations.\n np.ndarray, shape [21, 4]\n Joint rotations.","docstring_summary":"Process a single frame.","docstring_tokens":["Process","a","single","frame","."],"function":"def process(self, frame):\n \"\"\"\n Process a single frame.\n\n Parameters\n ----------\n frame : np.ndarray, shape [128, 128, 3], dtype np.uint8.\n Frame to be processed.\n\n Returns\n -------\n np.ndarray, shape [21, 3]\n Joint locations.\n np.ndarray, shape [21, 4]\n Joint rotations.\n \"\"\"\n xyz, _ = self.det_model.process(frame)\n delta, length = xyz_to_delta(xyz, MPIIHandJoints)\n delta *= length\n pack = np.concatenate(\n [xyz, delta, self.mpii_ref_xyz, self.mpii_ref_delta], 0\n )\n theta = self.ik_model.process(pack)\n\n return xyz, theta","function_tokens":["def","process","(","self",",","frame",")",":","xyz",",","_","=","self",".","det_model",".","process","(","frame",")","delta",",","length","=","xyz_to_delta","(","xyz",",","MPIIHandJoints",")","delta","*=","length","pack","=","np",".","concatenate","(","[","xyz",",","delta",",","self",".","mpii_ref_xyz",",","self",".","mpii_ref_delta","]",",","0",")","theta","=","self",".","ik_model",".","process","(","pack",")","return","xyz",",","theta"],"url":"https:\/\/github.com\/CalciferZh\/minimal-hand\/blob\/da91d777a36207ea67d87f06fc881a4806312ef0\/wrappers.py#L148-L172"}
7
+ {"nwo":"CalciferZh\/minimal-hand","sha":"da91d777a36207ea67d87f06fc881a4806312ef0","path":"capture.py","language":"python","identifier":"OpenCVCapture.__init__","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Init.","docstring_summary":"Init.","docstring_tokens":["Init","."],"function":"def __init__(self):\n \"\"\"\n Init.\n \"\"\"\n self.cap = cv2.VideoCapture(0)","function_tokens":["def","__init__","(","self",")",":","self",".","cap","=","cv2",".","VideoCapture","(","0",")"],"url":"https:\/\/github.com\/CalciferZh\/minimal-hand\/blob\/da91d777a36207ea67d87f06fc881a4806312ef0\/capture.py#L9-L13"}
8
+ {"nwo":"CalciferZh\/minimal-hand","sha":"da91d777a36207ea67d87f06fc881a4806312ef0","path":"capture.py","language":"python","identifier":"OpenCVCapture.read","parameters":"(self)","argument_list":"","return_statement":"return np.flip(frame, -1).copy()","docstring":"Read one frame. Note this function might be blocked by the sensor.\n\n Returns\n -------\n np.ndarray\n Read frame. Might be `None` is the webcam fails to get on frame.","docstring_summary":"Read one frame. Note this function might be blocked by the sensor.","docstring_tokens":["Read","one","frame",".","Note","this","function","might","be","blocked","by","the","sensor","."],"function":"def read(self):\n \"\"\"\n Read one frame. Note this function might be blocked by the sensor.\n\n Returns\n -------\n np.ndarray\n Read frame. Might be `None` is the webcam fails to get on frame.\n \"\"\"\n flag, frame = self.cap.read()\n if not flag:\n return None\n return np.flip(frame, -1).copy()","function_tokens":["def","read","(","self",")",":","flag",",","frame","=","self",".","cap",".","read","(",")","if","not","flag",":","return","None","return","np",".","flip","(","frame",",","-","1",")",".","copy","(",")"],"url":"https:\/\/github.com\/CalciferZh\/minimal-hand\/blob\/da91d777a36207ea67d87f06fc881a4806312ef0\/capture.py#L15-L27"}
9
+ {"nwo":"CalciferZh\/minimal-hand","sha":"da91d777a36207ea67d87f06fc881a4806312ef0","path":"app.py","language":"python","identifier":"live_application","parameters":"(capture)","argument_list":"","return_statement":"","docstring":"Launch an application that reads from a webcam and estimates hand pose at\n real-time.\n\n The captured hand must be the right hand, but will be flipped internally\n and rendered.\n\n Parameters\n ----------\n capture : object\n An object from `capture.py` to read capture stream from.","docstring_summary":"Launch an application that reads from a webcam and estimates hand pose at\n real-time.","docstring_tokens":["Launch","an","application","that","reads","from","a","webcam","and","estimates","hand","pose","at","real","-","time","."],"function":"def live_application(capture):\n \"\"\"\n Launch an application that reads from a webcam and estimates hand pose at\n real-time.\n\n The captured hand must be the right hand, but will be flipped internally\n and rendered.\n\n Parameters\n ----------\n capture : object\n An object from `capture.py` to read capture stream from.\n \"\"\"\n ############ output visualization ############\n view_mat = axangle2mat([1, 0, 0], np.pi) # align different coordinate systems\n window_size = 1080\n\n hand_mesh = HandMesh(config.HAND_MESH_MODEL_PATH)\n mesh = o3d.geometry.TriangleMesh()\n mesh.triangles = o3d.utility.Vector3iVector(hand_mesh.faces)\n mesh.vertices = \\\n o3d.utility.Vector3dVector(np.matmul(view_mat, hand_mesh.verts.T).T * 1000)\n mesh.compute_vertex_normals()\n\n viewer = o3d.visualization.Visualizer()\n viewer.create_window(\n width=window_size + 1, height=window_size + 1,\n window_name='Minimal Hand - output'\n )\n viewer.add_geometry(mesh)\n\n view_control = viewer.get_view_control()\n cam_params = view_control.convert_to_pinhole_camera_parameters()\n extrinsic = cam_params.extrinsic.copy()\n extrinsic[0:3, 3] = 0\n cam_params.extrinsic = extrinsic\n cam_params.intrinsic.set_intrinsics(\n window_size + 1, window_size + 1, config.CAM_FX, config.CAM_FY,\n window_size \/\/ 2, window_size \/\/ 2\n )\n view_control.convert_from_pinhole_camera_parameters(cam_params)\n view_control.set_constant_z_far(1000)\n\n render_option = viewer.get_render_option()\n render_option.load_from_json('.\/render_option.json')\n viewer.update_renderer()\n\n ############ input visualization ############\n pygame.init()\n display = pygame.display.set_mode((window_size, window_size))\n pygame.display.set_caption('Minimal Hand - input')\n\n ############ misc ############\n mesh_smoother = OneEuroFilter(4.0, 0.0)\n clock = pygame.time.Clock()\n model = ModelPipeline()\n\n while True:\n frame_large = capture.read()\n if frame_large is None:\n continue\n if frame_large.shape[0] > frame_large.shape[1]:\n margin = int((frame_large.shape[0] - frame_large.shape[1]) \/ 2)\n frame_large = frame_large[margin:-margin]\n else:\n margin = int((frame_large.shape[1] - frame_large.shape[0]) \/ 2)\n frame_large = frame_large[:, margin:-margin]\n\n frame_large = np.flip(frame_large, axis=1).copy()\n frame = imresize(frame_large, (128, 128))\n\n _, theta_mpii = model.process(frame)\n theta_mano = mpii_to_mano(theta_mpii)\n\n v = hand_mesh.set_abs_quat(theta_mano)\n v *= 2 # for better visualization\n v = v * 1000 + np.array([0, 0, 400])\n v = mesh_smoother.process(v)\n mesh.triangles = o3d.utility.Vector3iVector(hand_mesh.faces)\n mesh.vertices = o3d.utility.Vector3dVector(np.matmul(view_mat, v.T).T)\n mesh.paint_uniform_color(config.HAND_COLOR)\n mesh.compute_triangle_normals()\n mesh.compute_vertex_normals()\n viewer.update_geometry(mesh)\n\n viewer.poll_events()\n\n display.blit(\n pygame.surfarray.make_surface(\n np.transpose(\n imresize(frame_large, (window_size, window_size)\n ), (1, 0, 2))\n ),\n (0, 0)\n )\n pygame.display.update()\n\n if keyboard.is_pressed(\"esc\"):\n break\n\n clock.tick(30)","function_tokens":["def","live_application","(","capture",")",":","############ output visualization ############","view_mat","=","axangle2mat","(","[","1",",","0",",","0","]",",","np",".","pi",")","# align different coordinate systems","window_size","=","1080","hand_mesh","=","HandMesh","(","config",".","HAND_MESH_MODEL_PATH",")","mesh","=","o3d",".","geometry",".","TriangleMesh","(",")","mesh",".","triangles","=","o3d",".","utility",".","Vector3iVector","(","hand_mesh",".","faces",")","mesh",".","vertices","=","o3d",".","utility",".","Vector3dVector","(","np",".","matmul","(","view_mat",",","hand_mesh",".","verts",".","T",")",".","T","*","1000",")","mesh",".","compute_vertex_normals","(",")","viewer","=","o3d",".","visualization",".","Visualizer","(",")","viewer",".","create_window","(","width","=","window_size","+","1",",","height","=","window_size","+","1",",","window_name","=","'Minimal Hand - output'",")","viewer",".","add_geometry","(","mesh",")","view_control","=","viewer",".","get_view_control","(",")","cam_params","=","view_control",".","convert_to_pinhole_camera_parameters","(",")","extrinsic","=","cam_params",".","extrinsic",".","copy","(",")","extrinsic","[","0",":","3",",","3","]","=","0","cam_params",".","extrinsic","=","extrinsic","cam_params",".","intrinsic",".","set_intrinsics","(","window_size","+","1",",","window_size","+","1",",","config",".","CAM_FX",",","config",".","CAM_FY",",","window_size","\/\/","2",",","window_size","\/\/","2",")","view_control",".","convert_from_pinhole_camera_parameters","(","cam_params",")","view_control",".","set_constant_z_far","(","1000",")","render_option","=","viewer",".","get_render_option","(",")","render_option",".","load_from_json","(","'.\/render_option.json'",")","viewer",".","update_renderer","(",")","############ input visualization ############","pygame",".","init","(",")","display","=","pygame",".","display",".","set_mode","(","(","window_size",",","window_size",")",")","pygame",".","display",".","set_caption","(","'Minimal Hand - input'",")","############ misc ############","mesh_smoother","=","OneEuroFilter","(","4.0",",","0.0",")","clock","=","pygame",".","time",".","Clock","(",")","model","=","ModelPipeline","(",")","while","True",":","frame_large","=","capture",".","read","(",")","if","frame_large","is","None",":","continue","if","frame_large",".","shape","[","0","]",">","frame_large",".","shape","[","1","]",":","margin","=","int","(","(","frame_large",".","shape","[","0","]","-","frame_large",".","shape","[","1","]",")","\/","2",")","frame_large","=","frame_large","[","margin",":","-","margin","]","else",":","margin","=","int","(","(","frame_large",".","shape","[","1","]","-","frame_large",".","shape","[","0","]",")","\/","2",")","frame_large","=","frame_large","[",":",",","margin",":","-","margin","]","frame_large","=","np",".","flip","(","frame_large",",","axis","=","1",")",".","copy","(",")","frame","=","imresize","(","frame_large",",","(","128",",","128",")",")","_",",","theta_mpii","=","model",".","process","(","frame",")","theta_mano","=","mpii_to_mano","(","theta_mpii",")","v","=","hand_mesh",".","set_abs_quat","(","theta_mano",")","v","*=","2","# for better visualization","v","=","v","*","1000","+","np",".","array","(","[","0",",","0",",","400","]",")","v","=","mesh_smoother",".","process","(","v",")","mesh",".","triangles","=","o3d",".","utility",".","Vector3iVector","(","hand_mesh",".","faces",")","mesh",".","vertices","=","o3d",".","utility",".","Vector3dVector","(","np",".","matmul","(","view_mat",",","v",".","T",")",".","T",")","mesh",".","paint_uniform_color","(","config",".","HAND_COLOR",")","mesh",".","compute_triangle_normals","(",")","mesh",".","compute_vertex_normals","(",")","viewer",".","update_geometry","(","mesh",")","viewer",".","poll_events","(",")","display",".","blit","(","pygame",".","surfarray",".","make_surface","(","np",".","transpose","(","imresize","(","frame_large",",","(","window_size",",","window_size",")",")",",","(","1",",","0",",","2",")",")",")",",","(","0",",","0",")",")","pygame",".","display",".","update","(",")","if","keyboard",".","is_pressed","(","\"esc\"",")",":","break","clock",".","tick","(","30",")"],"url":"https:\/\/github.com\/CalciferZh\/minimal-hand\/blob\/da91d777a36207ea67d87f06fc881a4806312ef0\/app.py#L17-L117"}
10
+ {"nwo":"CalciferZh\/minimal-hand","sha":"da91d777a36207ea67d87f06fc881a4806312ef0","path":"utils.py","language":"python","identifier":"imresize","parameters":"(img, size)","argument_list":"","return_statement":"return cv2.resize(img, size, cv2.INTER_LINEAR)","docstring":"Resize an image with cv2.INTER_LINEAR.\n\n Parameters\n ----------\n size: (width, height)","docstring_summary":"Resize an image with cv2.INTER_LINEAR.","docstring_tokens":["Resize","an","image","with","cv2",".","INTER_LINEAR","."],"function":"def imresize(img, size):\n \"\"\"\n Resize an image with cv2.INTER_LINEAR.\n\n Parameters\n ----------\n size: (width, height)\n\n \"\"\"\n return cv2.resize(img, size, cv2.INTER_LINEAR)","function_tokens":["def","imresize","(","img",",","size",")",":","return","cv2",".","resize","(","img",",","size",",","cv2",".","INTER_LINEAR",")"],"url":"https:\/\/github.com\/CalciferZh\/minimal-hand\/blob\/da91d777a36207ea67d87f06fc881a4806312ef0\/utils.py#L7-L16"}
11
+ {"nwo":"CalciferZh\/minimal-hand","sha":"da91d777a36207ea67d87f06fc881a4806312ef0","path":"utils.py","language":"python","identifier":"load_pkl","parameters":"(path)","argument_list":"","return_statement":"return data","docstring":"Load pickle data.\n\n Parameter\n ---------\n path: Path to pickle file.\n\n Return\n ------\n Data in pickle file.","docstring_summary":"Load pickle data.","docstring_tokens":["Load","pickle","data","."],"function":"def load_pkl(path):\n \"\"\"\n Load pickle data.\n\n Parameter\n ---------\n path: Path to pickle file.\n\n Return\n ------\n Data in pickle file.\n\n \"\"\"\n with open(path, 'rb') as f:\n data = pickle.load(f)\n return data","function_tokens":["def","load_pkl","(","path",")",":","with","open","(","path",",","'rb'",")","as","f",":","data","=","pickle",".","load","(","f",")","return","data"],"url":"https:\/\/github.com\/CalciferZh\/minimal-hand\/blob\/da91d777a36207ea67d87f06fc881a4806312ef0\/utils.py#L19-L34"}
12
+ {"nwo":"CalciferZh\/minimal-hand","sha":"da91d777a36207ea67d87f06fc881a4806312ef0","path":"hand_mesh.py","language":"python","identifier":"HandMesh.__init__","parameters":"(self, model_path)","argument_list":"","return_statement":"","docstring":"Init.\n\n Parameters\n ----------\n model_path : str\n Path to the MANO model file. This model is converted by `prepare_mano.py`\n from official release.","docstring_summary":"Init.","docstring_tokens":["Init","."],"function":"def __init__(self, model_path):\n \"\"\"\n Init.\n\n Parameters\n ----------\n model_path : str\n Path to the MANO model file. This model is converted by `prepare_mano.py`\n from official release.\n \"\"\"\n params = load_pkl(model_path)\n self.verts = params['verts']\n self.faces = params['faces']\n self.weights = params['weights']\n self.joints = params['joints']\n\n self.n_verts = self.verts.shape[0]\n self.n_faces = self.faces.shape[0]\n\n self.ref_pose = []\n self.ref_T = []\n for j in range(MANOHandJoints.n_joints):\n parent = MANOHandJoints.parents[j]\n if parent is None:\n self.ref_T.append(self.verts)\n self.ref_pose.append(self.joints[j])\n else:\n self.ref_T.append(self.verts - self.joints[parent])\n self.ref_pose.append(self.joints[j] - self.joints[parent])\n self.ref_pose = np.expand_dims(np.stack(self.ref_pose, 0), -1)\n self.ref_T = np.expand_dims(np.stack(self.ref_T, 1), -1)","function_tokens":["def","__init__","(","self",",","model_path",")",":","params","=","load_pkl","(","model_path",")","self",".","verts","=","params","[","'verts'","]","self",".","faces","=","params","[","'faces'","]","self",".","weights","=","params","[","'weights'","]","self",".","joints","=","params","[","'joints'","]","self",".","n_verts","=","self",".","verts",".","shape","[","0","]","self",".","n_faces","=","self",".","faces",".","shape","[","0","]","self",".","ref_pose","=","[","]","self",".","ref_T","=","[","]","for","j","in","range","(","MANOHandJoints",".","n_joints",")",":","parent","=","MANOHandJoints",".","parents","[","j","]","if","parent","is","None",":","self",".","ref_T",".","append","(","self",".","verts",")","self",".","ref_pose",".","append","(","self",".","joints","[","j","]",")","else",":","self",".","ref_T",".","append","(","self",".","verts","-","self",".","joints","[","parent","]",")","self",".","ref_pose",".","append","(","self",".","joints","[","j","]","-","self",".","joints","[","parent","]",")","self",".","ref_pose","=","np",".","expand_dims","(","np",".","stack","(","self",".","ref_pose",",","0",")",",","-","1",")","self",".","ref_T","=","np",".","expand_dims","(","np",".","stack","(","self",".","ref_T",",","1",")",",","-","1",")"],"url":"https:\/\/github.com\/CalciferZh\/minimal-hand\/blob\/da91d777a36207ea67d87f06fc881a4806312ef0\/hand_mesh.py#L13-L43"}
13
+ {"nwo":"CalciferZh\/minimal-hand","sha":"da91d777a36207ea67d87f06fc881a4806312ef0","path":"hand_mesh.py","language":"python","identifier":"HandMesh.set_abs_quat","parameters":"(self, quat)","argument_list":"","return_statement":"return self.verts.copy()","docstring":"Set absolute (global) rotation for the hand.\n\n Parameters\n ----------\n quat : np.ndarray, shape [J, 4]\n Absolute rotations for each joint in quaternion.\n\n Returns\n -------\n np.ndarray, shape [V, 3]\n Mesh vertices after posing.","docstring_summary":"Set absolute (global) rotation for the hand.","docstring_tokens":["Set","absolute","(","global",")","rotation","for","the","hand","."],"function":"def set_abs_quat(self, quat):\n \"\"\"\n Set absolute (global) rotation for the hand.\n\n Parameters\n ----------\n quat : np.ndarray, shape [J, 4]\n Absolute rotations for each joint in quaternion.\n\n Returns\n -------\n np.ndarray, shape [V, 3]\n Mesh vertices after posing.\n \"\"\"\n mats = []\n for j in range(MANOHandJoints.n_joints):\n mats.append(quat2mat(quat[j]))\n mats = np.stack(mats, 0)\n\n pose = np.matmul(mats, self.ref_pose)\n joint_xyz = [None] * MANOHandJoints.n_joints\n for j in range(MANOHandJoints.n_joints):\n joint_xyz[j] = pose[j]\n parent = MANOHandJoints.parents[j]\n if parent is not None:\n joint_xyz[j] += joint_xyz[parent]\n joint_xyz = np.stack(joint_xyz, 0)[..., 0]\n\n T = np.matmul(np.expand_dims(mats, 0), self.ref_T)[..., 0]\n self.verts = [None] * MANOHandJoints.n_joints\n for j in range(MANOHandJoints.n_joints):\n self.verts[j] = T[:, j]\n parent = MANOHandJoints.parents[j]\n if parent is not None:\n self.verts[j] += joint_xyz[parent]\n self.verts = np.stack(self.verts, 1)\n self.verts = np.sum(self.verts * self.weights, 1)\n\n return self.verts.copy()","function_tokens":["def","set_abs_quat","(","self",",","quat",")",":","mats","=","[","]","for","j","in","range","(","MANOHandJoints",".","n_joints",")",":","mats",".","append","(","quat2mat","(","quat","[","j","]",")",")","mats","=","np",".","stack","(","mats",",","0",")","pose","=","np",".","matmul","(","mats",",","self",".","ref_pose",")","joint_xyz","=","[","None","]","*","MANOHandJoints",".","n_joints","for","j","in","range","(","MANOHandJoints",".","n_joints",")",":","joint_xyz","[","j","]","=","pose","[","j","]","parent","=","MANOHandJoints",".","parents","[","j","]","if","parent","is","not","None",":","joint_xyz","[","j","]","+=","joint_xyz","[","parent","]","joint_xyz","=","np",".","stack","(","joint_xyz",",","0",")","[","...",",","0","]","T","=","np",".","matmul","(","np",".","expand_dims","(","mats",",","0",")",",","self",".","ref_T",")","[","...",",","0","]","self",".","verts","=","[","None","]","*","MANOHandJoints",".","n_joints","for","j","in","range","(","MANOHandJoints",".","n_joints",")",":","self",".","verts","[","j","]","=","T","[",":",",","j","]","parent","=","MANOHandJoints",".","parents","[","j","]","if","parent","is","not","None",":","self",".","verts","[","j","]","+=","joint_xyz","[","parent","]","self",".","verts","=","np",".","stack","(","self",".","verts",",","1",")","self",".","verts","=","np",".","sum","(","self",".","verts","*","self",".","weights",",","1",")","return","self",".","verts",".","copy","(",")"],"url":"https:\/\/github.com\/CalciferZh\/minimal-hand\/blob\/da91d777a36207ea67d87f06fc881a4806312ef0\/hand_mesh.py#L45-L83"}
14
+ {"nwo":"CalciferZh\/minimal-hand","sha":"da91d777a36207ea67d87f06fc881a4806312ef0","path":"kinematics.py","language":"python","identifier":"mpii_to_mano","parameters":"(mpii)","argument_list":"","return_statement":"return mano","docstring":"Map data from MPIIHandJoints order to MANOHandJoints order.\n\n Parameters\n ----------\n mpii : np.ndarray, [21, ...]\n Data in MPIIHandJoints order. Note that the joints are along axis 0.\n\n Returns\n -------\n np.ndarray\n Data in MANOHandJoints order.","docstring_summary":"Map data from MPIIHandJoints order to MANOHandJoints order.","docstring_tokens":["Map","data","from","MPIIHandJoints","order","to","MANOHandJoints","order","."],"function":"def mpii_to_mano(mpii):\n \"\"\"\n Map data from MPIIHandJoints order to MANOHandJoints order.\n\n Parameters\n ----------\n mpii : np.ndarray, [21, ...]\n Data in MPIIHandJoints order. Note that the joints are along axis 0.\n\n Returns\n -------\n np.ndarray\n Data in MANOHandJoints order.\n \"\"\"\n mano = []\n for j in range(MANOHandJoints.n_joints):\n mano.append(\n mpii[MPIIHandJoints.labels.index(MANOHandJoints.labels[j])]\n )\n mano = np.stack(mano, 0)\n return mano","function_tokens":["def","mpii_to_mano","(","mpii",")",":","mano","=","[","]","for","j","in","range","(","MANOHandJoints",".","n_joints",")",":","mano",".","append","(","mpii","[","MPIIHandJoints",".","labels",".","index","(","MANOHandJoints",".","labels","[","j","]",")","]",")","mano","=","np",".","stack","(","mano",",","0",")","return","mano"],"url":"https:\/\/github.com\/CalciferZh\/minimal-hand\/blob\/da91d777a36207ea67d87f06fc881a4806312ef0\/kinematics.py#L53-L73"}
15
+ {"nwo":"CalciferZh\/minimal-hand","sha":"da91d777a36207ea67d87f06fc881a4806312ef0","path":"kinematics.py","language":"python","identifier":"mano_to_mpii","parameters":"(mano)","argument_list":"","return_statement":"return mpii","docstring":"Map data from MANOHandJoints order to MPIIHandJoints order.\n\n Parameters\n ----------\n mano : np.ndarray, [21, ...]\n Data in MANOHandJoints order. Note that the joints are along axis 0.\n\n Returns\n -------\n np.ndarray\n Data in MPIIHandJoints order.","docstring_summary":"Map data from MANOHandJoints order to MPIIHandJoints order.","docstring_tokens":["Map","data","from","MANOHandJoints","order","to","MPIIHandJoints","order","."],"function":"def mano_to_mpii(mano):\n \"\"\"\n Map data from MANOHandJoints order to MPIIHandJoints order.\n\n Parameters\n ----------\n mano : np.ndarray, [21, ...]\n Data in MANOHandJoints order. Note that the joints are along axis 0.\n\n Returns\n -------\n np.ndarray\n Data in MPIIHandJoints order.\n \"\"\"\n mpii = []\n for j in range(MPIIHandJoints.n_joints):\n mpii.append(\n mano[MANOHandJoints.labels.index(MPIIHandJoints.labels[j])]\n )\n mpii = np.stack(mpii, 0)\n return mpii","function_tokens":["def","mano_to_mpii","(","mano",")",":","mpii","=","[","]","for","j","in","range","(","MPIIHandJoints",".","n_joints",")",":","mpii",".","append","(","mano","[","MANOHandJoints",".","labels",".","index","(","MPIIHandJoints",".","labels","[","j","]",")","]",")","mpii","=","np",".","stack","(","mpii",",","0",")","return","mpii"],"url":"https:\/\/github.com\/CalciferZh\/minimal-hand\/blob\/da91d777a36207ea67d87f06fc881a4806312ef0\/kinematics.py#L76-L96"}
16
+ {"nwo":"CalciferZh\/minimal-hand","sha":"da91d777a36207ea67d87f06fc881a4806312ef0","path":"kinematics.py","language":"python","identifier":"xyz_to_delta","parameters":"(xyz, joints_def)","argument_list":"","return_statement":"return delta, lengths","docstring":"Compute bone orientations from joint coordinates (child joint - parent joint).\n The returned vectors are normalized.\n For the root joint, it will be a zero vector.\n\n Parameters\n ----------\n xyz : np.ndarray, shape [J, 3]\n Joint coordinates.\n joints_def : object\n An object that defines the kinematic skeleton, e.g. MPIIHandJoints.\n\n Returns\n -------\n np.ndarray, shape [J, 3]\n The **unit** vectors from each child joint to its parent joint.\n For the root joint, it's are zero vector.\n np.ndarray, shape [J, 1]\n The length of each bone (from child joint to parent joint).\n For the root joint, it's zero.","docstring_summary":"Compute bone orientations from joint coordinates (child joint - parent joint).\n The returned vectors are normalized.\n For the root joint, it will be a zero vector.","docstring_tokens":["Compute","bone","orientations","from","joint","coordinates","(","child","joint","-","parent","joint",")",".","The","returned","vectors","are","normalized",".","For","the","root","joint","it","will","be","a","zero","vector","."],"function":"def xyz_to_delta(xyz, joints_def):\n \"\"\"\n Compute bone orientations from joint coordinates (child joint - parent joint).\n The returned vectors are normalized.\n For the root joint, it will be a zero vector.\n\n Parameters\n ----------\n xyz : np.ndarray, shape [J, 3]\n Joint coordinates.\n joints_def : object\n An object that defines the kinematic skeleton, e.g. MPIIHandJoints.\n\n Returns\n -------\n np.ndarray, shape [J, 3]\n The **unit** vectors from each child joint to its parent joint.\n For the root joint, it's are zero vector.\n np.ndarray, shape [J, 1]\n The length of each bone (from child joint to parent joint).\n For the root joint, it's zero.\n \"\"\"\n delta = []\n for j in range(joints_def.n_joints):\n p = joints_def.parents[j]\n if p is None:\n delta.append(np.zeros(3))\n else:\n delta.append(xyz[j] - xyz[p])\n delta = np.stack(delta, 0)\n lengths = np.linalg.norm(delta, axis=-1, keepdims=True)\n delta \/= np.maximum(lengths, np.finfo(xyz.dtype).eps)\n return delta, lengths","function_tokens":["def","xyz_to_delta","(","xyz",",","joints_def",")",":","delta","=","[","]","for","j","in","range","(","joints_def",".","n_joints",")",":","p","=","joints_def",".","parents","[","j","]","if","p","is","None",":","delta",".","append","(","np",".","zeros","(","3",")",")","else",":","delta",".","append","(","xyz","[","j","]","-","xyz","[","p","]",")","delta","=","np",".","stack","(","delta",",","0",")","lengths","=","np",".","linalg",".","norm","(","delta",",","axis","=","-","1",",","keepdims","=","True",")","delta","\/=","np",".","maximum","(","lengths",",","np",".","finfo","(","xyz",".","dtype",")",".","eps",")","return","delta",",","lengths"],"url":"https:\/\/github.com\/CalciferZh\/minimal-hand\/blob\/da91d777a36207ea67d87f06fc881a4806312ef0\/kinematics.py#L99-L131"}
CamDavidsonPilon__PyProcess.jsonl ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {"nwo":"CamDavidsonPilon\/PyProcess","sha":"382da02d0f9732d75624538effa11caded161779","path":"pyprocess\/pyprocess.py","language":"python","identifier":"transform_path","parameters":"(path,f)","argument_list":"","return_statement":"return [(p[0],f(p[1])) for p in path]","docstring":"accepts a path, ie [(t,x_t)], and transforms it into [(t,f(x)].","docstring_summary":"accepts a path, ie [(t,x_t)], and transforms it into [(t,f(x)].","docstring_tokens":["accepts","a","path","ie","[","(","t","x_t",")","]","and","transforms","it","into","[","(","t","f","(","x",")","]","."],"function":"def transform_path(path,f):\n \"accepts a path, ie [(t,x_t)], and transforms it into [(t,f(x)].\"\n return [(p[0],f(p[1])) for p in path]","function_tokens":["def","transform_path","(","path",",","f",")",":","return","[","(","p","[","0","]",",","f","(","p","[","1","]",")",")","for","p","in","path","]"],"url":"https:\/\/github.com\/CamDavidsonPilon\/PyProcess\/blob\/382da02d0f9732d75624538effa11caded161779\/pyprocess\/pyprocess.py#L1937-L1939"}
2
+ {"nwo":"CamDavidsonPilon\/PyProcess","sha":"382da02d0f9732d75624538effa11caded161779","path":"pyprocess\/pyprocess.py","language":"python","identifier":"Step_process._mean_number_of_jumps","parameters":"(self,t, n_simulations = 10000)","argument_list":"","return_statement":"return sum\/n_simulations","docstring":"This needs to solve the following:\n E[ min(N) | T_1 + T_2 + .. T_N >= t ]\n <=>\n E[ N | T_1 + T_2 + .. T_{N-1} < t, T_1 + T_2 + .. T_N >= t ]\n where we can sample T only.","docstring_summary":"This needs to solve the following:\n E[ min(N) | T_1 + T_2 + .. T_N >= t ]\n <=>\n E[ N | T_1 + T_2 + .. T_{N-1} < t, T_1 + T_2 + .. T_N >= t ]\n where we can sample T only.","docstring_tokens":["This","needs","to","solve","the","following",":","E","[","min","(","N",")","|","T_1","+","T_2","+","..","T_N",">","=","t","]","<","=",">","E","[","N","|","T_1","+","T_2","+","..","T_","{","N","-","1","}","<","t","T_1","+","T_2","+","..","T_N",">","=","t","]","where","we","can","sample","T","only","."],"function":"def _mean_number_of_jumps(self,t, n_simulations = 10000):\n self._check_time(t)\n \"\"\"\n This needs to solve the following:\n E[ min(N) | T_1 + T_2 + .. T_N >= t ]\n <=>\n E[ N | T_1 + T_2 + .. T_{N-1} < t, T_1 + T_2 + .. T_N >= t ]\n where we can sample T only. \n \n \"\"\"\n warnings.warn(\"Attn: performing MC simulation. %d simulations.\"%n_simulations)\n v = np.zeros( n_simulations )\n continue_ = True\n i = 1\n t = t - self.startTime #should be positive.\n size = v.shape[0]\n sum = 0\n sum_sq = 0\n while continue_:\n v += self.T.rvs( size )\n #count how many are greater than t\n n_greater_than_t = (v>=t).sum()\n sum += n_greater_than_t*i \n \n v = v[v < t]\n i+=1\n size = v.shape[0]\n empty = size == 0\n \n \n if empty:\n continue_ = False\n \n if i > 10000:\n warnings.warn(\"The algorithm did not converge. Be sure 'T' is a non negative random \\\n variable, or set 't' lower.\")\n break\n\n return sum\/n_simulations","function_tokens":["def","_mean_number_of_jumps","(","self",",","t",",","n_simulations","=","10000",")",":","self",".","_check_time","(","t",")","warnings",".","warn","(","\"Attn: performing MC simulation. %d simulations.\"","%","n_simulations",")","v","=","np",".","zeros","(","n_simulations",")","continue_","=","True","i","=","1","t","=","t","-","self",".","startTime","#should be positive.","size","=","v",".","shape","[","0","]","sum","=","0","sum_sq","=","0","while","continue_",":","v","+=","self",".","T",".","rvs","(","size",")","#count how many are greater than t","n_greater_than_t","=","(","v",">=","t",")",".","sum","(",")","sum","+=","n_greater_than_t","*","i","v","=","v","[","v","<","t","]","i","+=","1","size","=","v",".","shape","[","0","]","empty","=","size","==","0","if","empty",":","continue_","=","False","if","i",">","10000",":","warnings",".","warn","(","\"The algorithm did not converge. Be sure 'T' is a non negative random \\\n variable, or set 't' lower.\"",")","break","return","sum","\/","n_simulations"],"url":"https:\/\/github.com\/CamDavidsonPilon\/PyProcess\/blob\/382da02d0f9732d75624538effa11caded161779\/pyprocess\/pyprocess.py#L79-L117"}
3
+ {"nwo":"CamDavidsonPilon\/PyProcess","sha":"382da02d0f9732d75624538effa11caded161779","path":"pyprocess\/pyprocess.py","language":"python","identifier":"Renewal_process.forward_recurrence_time_pdf","parameters":"(self,x)","argument_list":"","return_statement":"return self.renewal_rate*self.T.sf(x)","docstring":"the forward recurrence time RV is the time need to wait till the next event, after arriving to the system at a large future time","docstring_summary":"the forward recurrence time RV is the time need to wait till the next event, after arriving to the system at a large future time","docstring_tokens":["the","forward","recurrence","time","RV","is","the","time","need","to","wait","till","the","next","event","after","arriving","to","the","system","at","a","large","future","time"],"function":"def forward_recurrence_time_pdf(self,x):\n \"the forward recurrence time RV is the time need to wait till the next event, after arriving to the system at a large future time\"\n return self.renewal_rate*self.T.sf(x)","function_tokens":["def","forward_recurrence_time_pdf","(","self",",","x",")",":","return","self",".","renewal_rate","*","self",".","T",".","sf","(","x",")"],"url":"https:\/\/github.com\/CamDavidsonPilon\/PyProcess\/blob\/382da02d0f9732d75624538effa11caded161779\/pyprocess\/pyprocess.py#L178-L180"}
4
+ {"nwo":"CamDavidsonPilon\/PyProcess","sha":"382da02d0f9732d75624538effa11caded161779","path":"pyprocess\/pyprocess.py","language":"python","identifier":"Renewal_process.backwards_recurrence_time_pdf","parameters":"(self,x)","argument_list":"","return_statement":"return self.forward_recurrence_time_pdf(x)","docstring":"the backwards recurrence time is the time since the last event after arriving to the system at a large future time","docstring_summary":"the backwards recurrence time is the time since the last event after arriving to the system at a large future time","docstring_tokens":["the","backwards","recurrence","time","is","the","time","since","the","last","event","after","arriving","to","the","system","at","a","large","future","time"],"function":"def backwards_recurrence_time_pdf(self,x):\n \"the backwards recurrence time is the time since the last event after arriving to the system at a large future time\"\n return self.forward_recurrence_time_pdf(x)","function_tokens":["def","backwards_recurrence_time_pdf","(","self",",","x",")",":","return","self",".","forward_recurrence_time_pdf","(","x",")"],"url":"https:\/\/github.com\/CamDavidsonPilon\/PyProcess\/blob\/382da02d0f9732d75624538effa11caded161779\/pyprocess\/pyprocess.py#L182-L184"}
5
+ {"nwo":"CamDavidsonPilon\/PyProcess","sha":"382da02d0f9732d75624538effa11caded161779","path":"pyprocess\/pyprocess.py","language":"python","identifier":"Renewal_process.forward_recurrence_time_cdf","parameters":"(self,x)","argument_list":"","return_statement":"return int.quad(self.forward_recurrence_time_pdf, 0, x)","docstring":"the forward recurrence time RV is the time need to wait till the next event, after arriving to the system at a large future time","docstring_summary":"the forward recurrence time RV is the time need to wait till the next event, after arriving to the system at a large future time","docstring_tokens":["the","forward","recurrence","time","RV","is","the","time","need","to","wait","till","the","next","event","after","arriving","to","the","system","at","a","large","future","time"],"function":"def forward_recurrence_time_cdf(self,x):\n \"the forward recurrence time RV is the time need to wait till the next event, after arriving to the system at a large future time\"\n return int.quad(self.forward_recurrence_time_pdf, 0, x)","function_tokens":["def","forward_recurrence_time_cdf","(","self",",","x",")",":","return","int",".","quad","(","self",".","forward_recurrence_time_pdf",",","0",",","x",")"],"url":"https:\/\/github.com\/CamDavidsonPilon\/PyProcess\/blob\/382da02d0f9732d75624538effa11caded161779\/pyprocess\/pyprocess.py#L186-L188"}
6
+ {"nwo":"CamDavidsonPilon\/PyProcess","sha":"382da02d0f9732d75624538effa11caded161779","path":"pyprocess\/pyprocess.py","language":"python","identifier":"Renewal_process.backward_recurrence_time_cdf","parameters":"(self,x)","argument_list":"","return_statement":"return int.quad(self.forward_recurrence_time_pdf, 0, x)","docstring":"the backwards recurrence time is the time since the last event after arriving to the system at a large future time","docstring_summary":"the backwards recurrence time is the time since the last event after arriving to the system at a large future time","docstring_tokens":["the","backwards","recurrence","time","is","the","time","since","the","last","event","after","arriving","to","the","system","at","a","large","future","time"],"function":"def backward_recurrence_time_cdf(self,x):\n \"the backwards recurrence time is the time since the last event after arriving to the system at a large future time\"\n return int.quad(self.forward_recurrence_time_pdf, 0, x)","function_tokens":["def","backward_recurrence_time_cdf","(","self",",","x",")",":","return","int",".","quad","(","self",".","forward_recurrence_time_pdf",",","0",",","x",")"],"url":"https:\/\/github.com\/CamDavidsonPilon\/PyProcess\/blob\/382da02d0f9732d75624538effa11caded161779\/pyprocess\/pyprocess.py#L190-L192"}
7
+ {"nwo":"CamDavidsonPilon\/PyProcess","sha":"382da02d0f9732d75624538effa11caded161779","path":"pyprocess\/pyprocess.py","language":"python","identifier":"Renewal_process.spread_pdf","parameters":"(self,x)","argument_list":"","return_statement":"","docstring":"the RV distributed according to the spread_pdf is the (random) length of time between the previous and next event\/jump\n when you arrive at a large future time.","docstring_summary":"the RV distributed according to the spread_pdf is the (random) length of time between the previous and next event\/jump\n when you arrive at a large future time.","docstring_tokens":["the","RV","distributed","according","to","the","spread_pdf","is","the","(","random",")","length","of","time","between","the","previous","and","next","event","\/","jump","when","you","arrive","at","a","large","future","time","."],"function":"def spread_pdf(self,x):\n \"\"\"the RV distributed according to the spread_pdf is the (random) length of time between the previous and next event\/jump\n when you arrive at a large future time.\"\"\"\n try:\n return self.renewal_rate*x*self.T.pdf(x)\n except AttributeError:\n return self.renewal_rate*x*self.T.pmf(x)","function_tokens":["def","spread_pdf","(","self",",","x",")",":","try",":","return","self",".","renewal_rate","*","x","*","self",".","T",".","pdf","(","x",")","except","AttributeError",":","return","self",".","renewal_rate","*","x","*","self",".","T",".","pmf","(","x",")"],"url":"https:\/\/github.com\/CamDavidsonPilon\/PyProcess\/blob\/382da02d0f9732d75624538effa11caded161779\/pyprocess\/pyprocess.py#L194-L200"}
8
+ {"nwo":"CamDavidsonPilon\/PyProcess","sha":"382da02d0f9732d75624538effa11caded161779","path":"pyprocess\/pyprocess.py","language":"python","identifier":"Renewal_process._sample_path","parameters":"(self,time, N =1)","argument_list":"","return_statement":"","docstring":"parameters: \n time: an interable that returns floats OR if a single float, returns (path,jumps) up to time t.\n N: the number of paths to return. negative N returns an iterator of size N.\n returns:\n path: the sample path at the times in times\n jumps: the times when the process jumps\n \n Scales linearly with number of sequences and time.","docstring_summary":"parameters: \n time: an interable that returns floats OR if a single float, returns (path,jumps) up to time t.\n N: the number of paths to return. negative N returns an iterator of size N.\n returns:\n path: the sample path at the times in times\n jumps: the times when the process jumps\n \n Scales linearly with number of sequences and time.","docstring_tokens":["parameters",":","time",":","an","interable","that","returns","floats","OR","if","a","single","float","returns","(","path","jumps",")","up","to","time","t",".","N",":","the","number","of","paths","to","return",".","negative","N","returns","an","iterator","of","size","N",".","returns",":","path",":","the","sample","path","at","the","times","in","times","jumps",":","the","times","when","the","process","jumps","Scales","linearly","with","number","of","sequences","and","time","."],"function":"def _sample_path(self,time, N =1):\n \"\"\"\n parameters: \n time: an interable that returns floats OR if a single float, returns (path,jumps) up to time t.\n N: the number of paths to return. negative N returns an iterator of size N.\n returns:\n path: the sample path at the times in times\n jumps: the times when the process jumps\n \n Scales linearly with number of sequences and time.\n \n \"\"\"\n if N < 0:\n return self._iterator_sample_paths(time, -N)\n \n else:\n return self.__sample_path( time, N )","function_tokens":["def","_sample_path","(","self",",","time",",","N","=","1",")",":","if","N","<","0",":","return","self",".","_iterator_sample_paths","(","time",",","-","N",")","else",":","return","self",".","__sample_path","(","time",",","N",")"],"url":"https:\/\/github.com\/CamDavidsonPilon\/PyProcess\/blob\/382da02d0f9732d75624538effa11caded161779\/pyprocess\/pyprocess.py#L202-L218"}
9
+ {"nwo":"CamDavidsonPilon\/PyProcess","sha":"382da02d0f9732d75624538effa11caded161779","path":"pyprocess\/pyprocess.py","language":"python","identifier":"Renewal_process._sample_jumps","parameters":"(self,t, N=1)","argument_list":"","return_statement":"","docstring":"Generate N simulations of jump times prior to some time t > startTime.\n \n parameters:\n t: the end of the processes. \n N: the number of samples to return, -N to return a generator of size N\n returns:\n An irregular numpy array, with first dimension N, and each element an np.array \n with random length.\n \n example:\n >> print renewal_ps.generate_sample_jumps( 1, N=2)\n np.array( [ [2,2.5,3.0], [1.0,2.0] ], dtype=0bject )","docstring_summary":"Generate N simulations of jump times prior to some time t > startTime.\n \n parameters:\n t: the end of the processes. \n N: the number of samples to return, -N to return a generator of size N\n returns:\n An irregular numpy array, with first dimension N, and each element an np.array \n with random length.\n \n example:\n >> print renewal_ps.generate_sample_jumps( 1, N=2)\n np.array( [ [2,2.5,3.0], [1.0,2.0] ], dtype=0bject )","docstring_tokens":["Generate","N","simulations","of","jump","times","prior","to","some","time","t",">","startTime",".","parameters",":","t",":","the","end","of","the","processes",".","N",":","the","number","of","samples","to","return","-","N","to","return","a","generator","of","size","N","returns",":","An","irregular","numpy","array","with","first","dimension","N","and","each","element","an","np",".","array","with","random","length",".","example",":",">>","print","renewal_ps",".","generate_sample_jumps","(","1","N","=","2",")","np",".","array","(","[","[","2","2",".","5","3",".","0","]","[","1",".","0","2",".","0","]","]","dtype","=","0bject",")"],"function":"def _sample_jumps(self,t, N=1):\n \"\"\" \n Generate N simulations of jump times prior to some time t > startTime.\n \n parameters:\n t: the end of the processes. \n N: the number of samples to return, -N to return a generator of size N\n returns:\n An irregular numpy array, with first dimension N, and each element an np.array \n with random length.\n \n example:\n >> print renewal_ps.generate_sample_jumps( 1, N=2)\n np.array( [ [2,2.5,3.0], [1.0,2.0] ], dtype=0bject )\n \n \"\"\"\n if N<0:\n return ( self.__sample_jumps(t) for i in xrange(-N) )\n else:\n return np.asarray( [ self.__sample_jumps(t) for i in xrange(N) ] )","function_tokens":["def","_sample_jumps","(","self",",","t",",","N","=","1",")",":","if","N","<","0",":","return","(","self",".","__sample_jumps","(","t",")","for","i","in","xrange","(","-","N",")",")","else",":","return","np",".","asarray","(","[","self",".","__sample_jumps","(","t",")","for","i","in","xrange","(","N",")","]",")"],"url":"https:\/\/github.com\/CamDavidsonPilon\/PyProcess\/blob\/382da02d0f9732d75624538effa11caded161779\/pyprocess\/pyprocess.py#L266-L285"}
10
+ {"nwo":"CamDavidsonPilon\/PyProcess","sha":"382da02d0f9732d75624538effa11caded161779","path":"pyprocess\/pyprocess.py","language":"python","identifier":"Renewal_process._sample_position","parameters":"(self,t, N = 1)","argument_list":"","return_statement":"return x","docstring":"Generate the position of the process at time t > startTime\n parameters:\n N: number of samples\n t: position to sample at.\n returns:\n returns a (n,) np.array","docstring_summary":"Generate the position of the process at time t > startTime\n parameters:\n N: number of samples\n t: position to sample at.\n returns:\n returns a (n,) np.array","docstring_tokens":["Generate","the","position","of","the","process","at","time","t",">","startTime","parameters",":","N",":","number","of","samples","t",":","position","to","sample","at",".","returns",":","returns","a","(","n",")","np",".","array"],"function":"def _sample_position(self,t, N = 1):\n \"\"\"\n Generate the position of the process at time t > startTime\n parameters:\n N: number of samples\n t: position to sample at.\n returns:\n returns a (n,) np.array \n \"\"\"\n v = np.zeros( N ) \n iv = np.ones( N, dtype=bool )\n x = self.startPosition*np.ones( N) \n continue_ = True\n i = 1\n t = t - self.startTime #should be positive.\n size = v.shape[0]\n while continue_:\n n_samples = iv.sum()\n v[iv] += self.T.rvs( n_samples )\n \n #if the next time is beyond reach, we do not add a new jump\n iv[ v >= t] = False\n n_samples = iv.sum()\n\n x[iv] += self.J.rvs( n_samples )\n\n size = iv.sum() #any left?\n empty = size == 0\n \n i+=1\n if empty:\n continue_ = False\n \n if i > 10000:\n warnings.warn(\"The algorithm did not converge. Be sure 'T' is a non negative random \\\n variable, or set 't' to a smaller value.\")\n break\n \n return x","function_tokens":["def","_sample_position","(","self",",","t",",","N","=","1",")",":","v","=","np",".","zeros","(","N",")","iv","=","np",".","ones","(","N",",","dtype","=","bool",")","x","=","self",".","startPosition","*","np",".","ones","(","N",")","continue_","=","True","i","=","1","t","=","t","-","self",".","startTime","#should be positive.","size","=","v",".","shape","[","0","]","while","continue_",":","n_samples","=","iv",".","sum","(",")","v","[","iv","]","+=","self",".","T",".","rvs","(","n_samples",")","#if the next time is beyond reach, we do not add a new jump","iv","[","v",">=","t","]","=","False","n_samples","=","iv",".","sum","(",")","x","[","iv","]","+=","self",".","J",".","rvs","(","n_samples",")","size","=","iv",".","sum","(",")","#any left?","empty","=","size","==","0","i","+=","1","if","empty",":","continue_","=","False","if","i",">","10000",":","warnings",".","warn","(","\"The algorithm did not converge. Be sure 'T' is a non negative random \\\n variable, or set 't' to a smaller value.\"",")","break","return","x"],"url":"https:\/\/github.com\/CamDavidsonPilon\/PyProcess\/blob\/382da02d0f9732d75624538effa11caded161779\/pyprocess\/pyprocess.py#L297-L335"}
11
+ {"nwo":"CamDavidsonPilon\/PyProcess","sha":"382da02d0f9732d75624538effa11caded161779","path":"pyprocess\/pyprocess.py","language":"python","identifier":"Poisson_process._mean","parameters":"(self,t)","argument_list":"","return_statement":"","docstring":"recall that a conditional poisson process N_t | N_T=n ~ Bin(n, t\/T)","docstring_summary":"recall that a conditional poisson process N_t | N_T=n ~ Bin(n, t\/T)","docstring_tokens":["recall","that","a","conditional","poisson","process","N_t","|","N_T","=","n","~","Bin","(","n","t","\/","T",")"],"function":"def _mean(self,t):\n \"\"\"\n recall that a conditional poisson process N_t | N_T=n ~ Bin(n, t\/T)\n \"\"\"\n if not self.conditional: \n return self.startPosition + self.rate*(t-self.startTime)\n else:\n return self.endPosition*float(t)\/self.endTime","function_tokens":["def","_mean","(","self",",","t",")",":","if","not","self",".","conditional",":","return","self",".","startPosition","+","self",".","rate","*","(","t","-","self",".","startTime",")","else",":","return","self",".","endPosition","*","float","(","t",")","\/","self",".","endTime"],"url":"https:\/\/github.com\/CamDavidsonPilon\/PyProcess\/blob\/382da02d0f9732d75624538effa11caded161779\/pyprocess\/pyprocess.py#L376-L383"}
12
+ {"nwo":"CamDavidsonPilon\/PyProcess","sha":"382da02d0f9732d75624538effa11caded161779","path":"pyprocess\/pyprocess.py","language":"python","identifier":"Poisson_process._var","parameters":"(self,t)","argument_list":"","return_statement":"","docstring":"parameters:\n t: a time > startTime (and less than endTime if present).\n returns:\n a float.\n \n recall that a conditional poisson process N_t | N_T=n ~ Bin(n, t\/T)","docstring_summary":"parameters:\n t: a time > startTime (and less than endTime if present).\n returns:\n a float.\n \n recall that a conditional poisson process N_t | N_T=n ~ Bin(n, t\/T)","docstring_tokens":["parameters",":","t",":","a","time",">","startTime","(","and","less","than","endTime","if","present",")",".","returns",":","a","float",".","recall","that","a","conditional","poisson","process","N_t","|","N_T","=","n","~","Bin","(","n","t","\/","T",")"],"function":"def _var(self,t):\n \"\"\"\n parameters:\n t: a time > startTime (and less than endTime if present).\n returns:\n a float.\n \n recall that a conditional poisson process N_t | N_T=n ~ Bin(n, t\/T)\n \n \"\"\"\n if self.conditional:\n return self.endPosition*(1-float(t)\/self.endTime)*float(t)\/self.endTime\n else:\n return self.rate*(t-self.startTime)","function_tokens":["def","_var","(","self",",","t",")",":","if","self",".","conditional",":","return","self",".","endPosition","*","(","1","-","float","(","t",")","\/","self",".","endTime",")","*","float","(","t",")","\/","self",".","endTime","else",":","return","self",".","rate","*","(","t","-","self",".","startTime",")"],"url":"https:\/\/github.com\/CamDavidsonPilon\/PyProcess\/blob\/382da02d0f9732d75624538effa11caded161779\/pyprocess\/pyprocess.py#L385-L398"}
13
+ {"nwo":"CamDavidsonPilon\/PyProcess","sha":"382da02d0f9732d75624538effa11caded161779","path":"pyprocess\/pyprocess.py","language":"python","identifier":"Poisson_process._sample_jumps","parameters":"(self, t, N=1)","argument_list":"","return_statement":"","docstring":"Probably to be deleted.\n T: a float\n N: the number of sample paths\n Returns:\n an (N,) np.array of jump times.","docstring_summary":"Probably to be deleted.\n T: a float\n N: the number of sample paths\n Returns:\n an (N,) np.array of jump times.","docstring_tokens":["Probably","to","be","deleted",".","T",":","a","float","N",":","the","number","of","sample","paths","Returns",":","an","(","N",")","np",".","array","of","jump","times","."],"function":"def _sample_jumps(self, t, N=1):\n \"\"\"\n Probably to be deleted.\n T: a float\n N: the number of sample paths\n Returns:\n an (N,) np.array of jump times. \n \"\"\"\n if N<0:\n return ( self.__sample_jumps(t) for i in xrange(-N) )\n else:\n return np.asarray( [self.__sample_jumps(t) for i in xrange(N)] )","function_tokens":["def","_sample_jumps","(","self",",","t",",","N","=","1",")",":","if","N","<","0",":","return","(","self",".","__sample_jumps","(","t",")","for","i","in","xrange","(","-","N",")",")","else",":","return","np",".","asarray","(","[","self",".","__sample_jumps","(","t",")","for","i","in","xrange","(","N",")","]",")"],"url":"https:\/\/github.com\/CamDavidsonPilon\/PyProcess\/blob\/382da02d0f9732d75624538effa11caded161779\/pyprocess\/pyprocess.py#L416-L427"}
14
+ {"nwo":"CamDavidsonPilon\/PyProcess","sha":"382da02d0f9732d75624538effa11caded161779","path":"pyprocess\/pyprocess.py","language":"python","identifier":"Diffusion_process.transition_pdf","parameters":"(self,t,y)","argument_list":"","return_statement":"","docstring":"this method calls self._transition_pdf(x,t,y) in the subclass","docstring_summary":"this method calls self._transition_pdf(x,t,y) in the subclass","docstring_tokens":["this","method","calls","self",".","_transition_pdf","(","x","t","y",")","in","the","subclass"],"function":"def transition_pdf(self,t,y):\n self._check_time(t)\n \"this method calls self._transition_pdf(x,t,y) in the subclass\"\n try:\n if not self.conditional:\n return self._transition_pdf(self.startPosition, t-self.startTime, y)\n else:\n return self._transition_pdf(self.startPosition, t-self.startTime, y)*self._transition_pdf(y, self.endTime-t, self.endPosition)\\\n \/self._transition_pdf(self.startPosition,self.endTime - self.startTime, self.endPosition)\n except AttributeError:\n raise AttributeError(\"Attn: transition density for process is not defined.\")","function_tokens":["def","transition_pdf","(","self",",","t",",","y",")",":","self",".","_check_time","(","t",")","try",":","if","not","self",".","conditional",":","return","self",".","_transition_pdf","(","self",".","startPosition",",","t","-","self",".","startTime",",","y",")","else",":","return","self",".","_transition_pdf","(","self",".","startPosition",",","t","-","self",".","startTime",",","y",")","*","self",".","_transition_pdf","(","y",",","self",".","endTime","-","t",",","self",".","endPosition",")","\/","self",".","_transition_pdf","(","self",".","startPosition",",","self",".","endTime","-","self",".","startTime",",","self",".","endPosition",")","except","AttributeError",":","raise","AttributeError","(","\"Attn: transition density for process is not defined.\"",")"],"url":"https:\/\/github.com\/CamDavidsonPilon\/PyProcess\/blob\/382da02d0f9732d75624538effa11caded161779\/pyprocess\/pyprocess.py#L542-L552"}
15
+ {"nwo":"CamDavidsonPilon\/PyProcess","sha":"382da02d0f9732d75624538effa11caded161779","path":"pyprocess\/pyprocess.py","language":"python","identifier":"Diffusion_process.expected_value","parameters":"(self,t, f= lambda x:x, N=1e6)","argument_list":"","return_statement":"","docstring":"This function calculates the expected value of E[ X_t | F ] where F includes start conditions and possibly end conditions.","docstring_summary":"This function calculates the expected value of E[ X_t | F ] where F includes start conditions and possibly end conditions.","docstring_tokens":["This","function","calculates","the","expected","value","of","E","[","X_t","|","F","]","where","F","includes","start","conditions","and","possibly","end","conditions","."],"function":"def expected_value(self,t, f= lambda x:x, N=1e6):\n \"\"\"\n This function calculates the expected value of E[ X_t | F ] where F includes start conditions and possibly end conditions.\n \n \n \"\"\"\n warnings.warn( \"Performing Monte Carlo with %d simulations.\"%N)\n self._check_time(t)\n if not self.conditional:\n return f( self.sample_position(t, N) ).mean() \n else:\n #This uses a change of measure technique.\n \"\"\"\n sum=0\n self.conditional=False\n for i in range(N):\n X = self.generate_position_at(t)\n sum+=self._transition_pdf(X,self.endTime-t,self.endPosition)*f(X)\n self.conditional=True\n \"\"\"\n x = self.sample_position(t, N)\n mean = (self._transition_pdf(x,self.endTime-t,self.endPosition)*f(x)).mean()\n return mean\/self._transition_pdf(self.startPosition, self.endTime-self.startTime, self.endPosition)","function_tokens":["def","expected_value","(","self",",","t",",","f","=","lambda","x",":","x",",","N","=","1e6",")",":","warnings",".","warn","(","\"Performing Monte Carlo with %d simulations.\"","%","N",")","self",".","_check_time","(","t",")","if","not","self",".","conditional",":","return","f","(","self",".","sample_position","(","t",",","N",")",")",".","mean","(",")","else",":","#This uses a change of measure technique.","\"\"\"\n sum=0\n self.conditional=False\n for i in range(N):\n X = self.generate_position_at(t)\n sum+=self._transition_pdf(X,self.endTime-t,self.endPosition)*f(X)\n self.conditional=True\n \"\"\"","x","=","self",".","sample_position","(","t",",","N",")","mean","=","(","self",".","_transition_pdf","(","x",",","self",".","endTime","-","t",",","self",".","endPosition",")","*","f","(","x",")",")",".","mean","(",")","return","mean","\/","self",".","_transition_pdf","(","self",".","startPosition",",","self",".","endTime","-","self",".","startTime",",","self",".","endPosition",")"],"url":"https:\/\/github.com\/CamDavidsonPilon\/PyProcess\/blob\/382da02d0f9732d75624538effa11caded161779\/pyprocess\/pyprocess.py#L554-L576"}
16
+ {"nwo":"CamDavidsonPilon\/PyProcess","sha":"382da02d0f9732d75624538effa11caded161779","path":"pyprocess\/pyprocess.py","language":"python","identifier":"Diffusion_process.sample_position","parameters":"(self,t, N=1)","argument_list":"","return_statement":"return self._sample_position(t, N)","docstring":"if _get_position_at() is not overwritten in a subclass, this function will use euler scheme","docstring_summary":"if _get_position_at() is not overwritten in a subclass, this function will use euler scheme","docstring_tokens":["if","_get_position_at","()","is","not","overwritten","in","a","subclass","this","function","will","use","euler","scheme"],"function":"def sample_position(self,t, N=1):\n \"\"\" \n if _get_position_at() is not overwritten in a subclass, this function will use euler scheme\n \"\"\"\n\n self._check_time(t)\n return self._sample_position(t, N)","function_tokens":["def","sample_position","(","self",",","t",",","N","=","1",")",":","self",".","_check_time","(","t",")","return","self",".","_sample_position","(","t",",","N",")"],"url":"https:\/\/github.com\/CamDavidsonPilon\/PyProcess\/blob\/382da02d0f9732d75624538effa11caded161779\/pyprocess\/pyprocess.py#L578-L584"}
17
+ {"nwo":"CamDavidsonPilon\/PyProcess","sha":"382da02d0f9732d75624538effa11caded161779","path":"pyprocess\/pyprocess.py","language":"python","identifier":"Diffusion_process._var","parameters":"(self,t, N = 1e6)","argument_list":"","return_statement":"return self.sample_position(t, n).var()","docstring":"var = SampleVarStat()\n for i in range(10000):\n var.push(self.generate_position_at(t))\n return var.get_variance()","docstring_summary":"var = SampleVarStat()\n for i in range(10000):\n var.push(self.generate_position_at(t))\n return var.get_variance()","docstring_tokens":["var","=","SampleVarStat","()","for","i","in","range","(","10000",")",":","var",".","push","(","self",".","generate_position_at","(","t","))","return","var",".","get_variance","()"],"function":"def _var(self,t, N = 1e6):\n \"\"\"\n var = SampleVarStat()\n for i in range(10000):\n var.push(self.generate_position_at(t))\n return var.get_variance()\n \"\"\"\n return self.sample_position(t, n).var()","function_tokens":["def","_var","(","self",",","t",",","N","=","1e6",")",":","return","self",".","sample_position","(","t",",","n",")",".","var","(",")"],"url":"https:\/\/github.com\/CamDavidsonPilon\/PyProcess\/blob\/382da02d0f9732d75624538effa11caded161779\/pyprocess\/pyprocess.py#L607-L614"}
18
+ {"nwo":"CamDavidsonPilon\/PyProcess","sha":"382da02d0f9732d75624538effa11caded161779","path":"pyprocess\/pyprocess.py","language":"python","identifier":"Diffusion_process.Euler_scheme","parameters":"(self, times,delta=0.001)","argument_list":"","return_statement":"return path","docstring":"times is an array of floats.\n The process needs the methods drift() and diffusion() defined.","docstring_summary":"times is an array of floats.\n The process needs the methods drift() and diffusion() defined.","docstring_tokens":["times","is","an","array","of","floats",".","The","process","needs","the","methods","drift","()","and","diffusion","()","defined","."],"function":"def Euler_scheme(self, times,delta=0.001):\n \"\"\"\n times is an array of floats.\n The process needs the methods drift() and diffusion() defined.\n \"\"\"\n warnings.warn(\"Attn: starting an Euler scheme to approxmiate process.\")\n \n Nor = stats.norm()\n finalTime = times[-1]\n steps = int(finalTime\/delta)\n t = self.startTime\n x=self.startPosition\n path=[]\n j=0\n time = times[j]\n for i in xrange(steps):\n if t+delta>time>t:\n delta = time-t\n x += drift(x,t)*delta + np.sqrt(delta)*diffusion(x,t)*Nor.rvs()\n path.append((x,time))\n delta=0.001\n j+=1\n time = times[j]\n else:\n x += drift(x,t)*delta + np.sqrt(delta)*diffusion(x,t)*Nor.rvs()\n t += delta\n \n return path","function_tokens":["def","Euler_scheme","(","self",",","times",",","delta","=","0.001",")",":","warnings",".","warn","(","\"Attn: starting an Euler scheme to approxmiate process.\"",")","Nor","=","stats",".","norm","(",")","finalTime","=","times","[","-","1","]","steps","=","int","(","finalTime","\/","delta",")","t","=","self",".","startTime","x","=","self",".","startPosition","path","=","[","]","j","=","0","time","=","times","[","j","]","for","i","in","xrange","(","steps",")",":","if","t","+","delta",">","time",">","t",":","delta","=","time","-","t","x","+=","drift","(","x",",","t",")","*","delta","+","np",".","sqrt","(","delta",")","*","diffusion","(","x",",","t",")","*","Nor",".","rvs","(",")","path",".","append","(","(","x",",","time",")",")","delta","=","0.001","j","+=","1","time","=","times","[","j","]","else",":","x","+=","drift","(","x",",","t",")","*","delta","+","np",".","sqrt","(","delta",")","*","diffusion","(","x",",","t",")","*","Nor",".","rvs","(",")","t","+=","delta","return","path"],"url":"https:\/\/github.com\/CamDavidsonPilon\/PyProcess\/blob\/382da02d0f9732d75624538effa11caded161779\/pyprocess\/pyprocess.py#L629-L656"}
19
+ {"nwo":"CamDavidsonPilon\/PyProcess","sha":"382da02d0f9732d75624538effa11caded161779","path":"pyprocess\/pyprocess.py","language":"python","identifier":"Wiener_process._sample_position","parameters":"(self,t, n=1)","argument_list":"","return_statement":"return self.mean(t) + np.sqrt(self.var(t))*self.Nor.rvs(n)","docstring":"This incorporates both conditional and unconditional","docstring_summary":"This incorporates both conditional and unconditional","docstring_tokens":["This","incorporates","both","conditional","and","unconditional"],"function":"def _sample_position(self,t, n=1):\n \"\"\"\n This incorporates both conditional and unconditional\n \"\"\"\n return self.mean(t) + np.sqrt(self.var(t))*self.Nor.rvs(n)","function_tokens":["def","_sample_position","(","self",",","t",",","n","=","1",")",":","return","self",".","mean","(","t",")","+","np",".","sqrt","(","self",".","var","(","t",")",")","*","self",".","Nor",".","rvs","(","n",")"],"url":"https:\/\/github.com\/CamDavidsonPilon\/PyProcess\/blob\/382da02d0f9732d75624538effa11caded161779\/pyprocess\/pyprocess.py#L722-L726"}
20
+ {"nwo":"CamDavidsonPilon\/PyProcess","sha":"382da02d0f9732d75624538effa11caded161779","path":"pyprocess\/pyprocess.py","language":"python","identifier":"OU_process.sample_path","parameters":"(self,times, N= 1, return_normals = False)","argument_list":"","return_statement":"","docstring":"the parameter Normals = 0 is used for the Integrated OU Process","docstring_summary":"the parameter Normals = 0 is used for the Integrated OU Process","docstring_tokens":["the","parameter","Normals","=","0","is","used","for","the","Integrated","OU","Process"],"function":"def sample_path(self,times, N= 1, return_normals = False):\n \"the parameter Normals = 0 is used for the Integrated OU Process\"\n if not self.conditional:\n path=np.zeros( (N,len(times)) )\n times = np.insert( times, 0,self.startTime)\n path[ :, 0] = self.startPosition\n \n deltas = np.diff(times )\n normals = np.random.randn( N, len(times)-1 )\n x = self.startPosition*np.ones( N) \n sigma = np.sqrt(self.sigma**2*(1-np.exp(-2*self.theta*deltas))\/(2*self.theta))\n for i, delta in enumerate(deltas):\n mu = self.mu + np.exp(-self.theta*delta)*(x-self.mu)\n path[:, i] = mu + sigma[i]*normals[:,i] \n x = path[:,i]\n \"\"\"\n It would be really cool if there was a numpy func like np.cumf( func, array )\n that applies func(next_x, prev_x) to each element. For example, lambda x,y: y + x\n is the cumsum, and lambda x,y: x*y is the cumprod function.\n \"\"\"\n if return_normals:\n return (path, normals )\n else:\n return path\n \n else:\n #TODO\n path = bridge_creation(self,times)\n return path","function_tokens":["def","sample_path","(","self",",","times",",","N","=","1",",","return_normals","=","False",")",":","if","not","self",".","conditional",":","path","=","np",".","zeros","(","(","N",",","len","(","times",")",")",")","times","=","np",".","insert","(","times",",","0",",","self",".","startTime",")","path","[",":",",","0","]","=","self",".","startPosition","deltas","=","np",".","diff","(","times",")","normals","=","np",".","random",".","randn","(","N",",","len","(","times",")","-","1",")","x","=","self",".","startPosition","*","np",".","ones","(","N",")","sigma","=","np",".","sqrt","(","self",".","sigma","**","2","*","(","1","-","np",".","exp","(","-","2","*","self",".","theta","*","deltas",")",")","\/","(","2","*","self",".","theta",")",")","for","i",",","delta","in","enumerate","(","deltas",")",":","mu","=","self",".","mu","+","np",".","exp","(","-","self",".","theta","*","delta",")","*","(","x","-","self",".","mu",")","path","[",":",",","i","]","=","mu","+","sigma","[","i","]","*","normals","[",":",",","i","]","x","=","path","[",":",",","i","]","\"\"\"\n It would be really cool if there was a numpy func like np.cumf( func, array )\n that applies func(next_x, prev_x) to each element. For example, lambda x,y: y + x\n is the cumsum, and lambda x,y: x*y is the cumprod function.\n \"\"\"","if","return_normals",":","return","(","path",",","normals",")","else",":","return","path","else",":","#TODO","path","=","bridge_creation","(","self",",","times",")","return","path"],"url":"https:\/\/github.com\/CamDavidsonPilon\/PyProcess\/blob\/382da02d0f9732d75624538effa11caded161779\/pyprocess\/pyprocess.py#L832-L860"}
21
+ {"nwo":"CamDavidsonPilon\/PyProcess","sha":"382da02d0f9732d75624538effa11caded161779","path":"pyprocess\/pyprocess.py","language":"python","identifier":"Integrated_OU_process.generate_sample_path","parameters":"(self,times, returnUO = 0)","argument_list":"","return_statement":"","docstring":"set returnUO to 1 to return the underlying UO path as well as the integrated UO path.","docstring_summary":"set returnUO to 1 to return the underlying UO path as well as the integrated UO path.","docstring_tokens":["set","returnUO","to","1","to","return","the","underlying","UO","path","as","well","as","the","integrated","UO","path","."],"function":"def generate_sample_path(self,times, returnUO = 0):\n \"set returnUO to 1 to return the underlying UO path as well as the integrated UO path.\"\n if not self.conditional: \n xPath, listOfNormals = self.OU.generate_sample_path(times, 1)\n path = []\n t = self.startTime\n y = self.startPosition\n for i, position in enumerate(xPath):\n delta = position[0]-t\n x = position[1]\n if delta != 0:\n #there is an error here, I can smell it.\n sigmaX = self.sigma**2*(1-np.exp(-2*self.theta*delta))\/(2*self.theta)\n sigmaY = self.sigma**2*(2*self.theta*delta-3+4*np.exp(-self.theta*delta)\n -np.exp(-2*self.theta*delta))\/(2*self.sigma**3)\n muY = y + (x-self.mu)\/self.theta + self.mu*delta-(x-self.mu)*np.exp(-self.theta*delta)\/self.theta\n covXY = self.sigma**2*(1+np.exp(-2*self.theta*delta)-2*np.exp(-self.theta*delta))\/(2*self.theta**2)\n y = muY + np.sqrt(sigmaY - covXY**2\/sigmaX)*self.Normal.rvs()+ covXY\/np.sqrt(sigmaX)*listOfNormals[i]\n t = position[0]\n path.append((t,y))\n if returnUO==0:\n return path\n else:\n return path, xPath\n else:\n path = bridge_creation(self,times)\n if returnUO==0:\n return path\n else:\n return path, xPath","function_tokens":["def","generate_sample_path","(","self",",","times",",","returnUO","=","0",")",":","if","not","self",".","conditional",":","xPath",",","listOfNormals","=","self",".","OU",".","generate_sample_path","(","times",",","1",")","path","=","[","]","t","=","self",".","startTime","y","=","self",".","startPosition","for","i",",","position","in","enumerate","(","xPath",")",":","delta","=","position","[","0","]","-","t","x","=","position","[","1","]","if","delta","!=","0",":","#there is an error here, I can smell it.","sigmaX","=","self",".","sigma","**","2","*","(","1","-","np",".","exp","(","-","2","*","self",".","theta","*","delta",")",")","\/","(","2","*","self",".","theta",")","sigmaY","=","self",".","sigma","**","2","*","(","2","*","self",".","theta","*","delta","-","3","+","4","*","np",".","exp","(","-","self",".","theta","*","delta",")","-","np",".","exp","(","-","2","*","self",".","theta","*","delta",")",")","\/","(","2","*","self",".","sigma","**","3",")","muY","=","y","+","(","x","-","self",".","mu",")","\/","self",".","theta","+","self",".","mu","*","delta","-","(","x","-","self",".","mu",")","*","np",".","exp","(","-","self",".","theta","*","delta",")","\/","self",".","theta","covXY","=","self",".","sigma","**","2","*","(","1","+","np",".","exp","(","-","2","*","self",".","theta","*","delta",")","-","2","*","np",".","exp","(","-","self",".","theta","*","delta",")",")","\/","(","2","*","self",".","theta","**","2",")","y","=","muY","+","np",".","sqrt","(","sigmaY","-","covXY","**","2","\/","sigmaX",")","*","self",".","Normal",".","rvs","(",")","+","covXY","\/","np",".","sqrt","(","sigmaX",")","*","listOfNormals","[","i","]","t","=","position","[","0","]","path",".","append","(","(","t",",","y",")",")","if","returnUO","==","0",":","return","path","else",":","return","path",",","xPath","else",":","path","=","bridge_creation","(","self",",","times",")","if","returnUO","==","0",":","return","path","else",":","return","path",",","xPath"],"url":"https:\/\/github.com\/CamDavidsonPilon\/PyProcess\/blob\/382da02d0f9732d75624538effa11caded161779\/pyprocess\/pyprocess.py#L915-L944"}
22
+ {"nwo":"CamDavidsonPilon\/PyProcess","sha":"382da02d0f9732d75624538effa11caded161779","path":"pyprocess\/pyprocess.py","language":"python","identifier":"SqBessel_process.generate_sample_path","parameters":"(self,times,absb=0)","argument_list":"","return_statement":"","docstring":"absb is a boolean, true if absorbtion at 0, false else. See class' __doc__ for when \n absorbtion is valid.","docstring_summary":"absb is a boolean, true if absorbtion at 0, false else. See class' __doc__ for when \n absorbtion is valid.","docstring_tokens":["absb","is","a","boolean","true","if","absorbtion","at","0","false","else",".","See","class","__doc__","for","when","absorbtion","is","valid","."],"function":"def generate_sample_path(self,times,absb=0):\n \"\"\"\n absb is a boolean, true if absorbtion at 0, false else. See class' __doc__ for when \n absorbtion is valid.\n \"\"\"\n if absb:\n return self._generate_sample_path_with_absorption(times)\n else:\n return self._generate_sample_path_no_absorption(times)","function_tokens":["def","generate_sample_path","(","self",",","times",",","absb","=","0",")",":","if","absb",":","return","self",".","_generate_sample_path_with_absorption","(","times",")","else",":","return","self",".","_generate_sample_path_no_absorption","(","times",")"],"url":"https:\/\/github.com\/CamDavidsonPilon\/PyProcess\/blob\/382da02d0f9732d75624538effa11caded161779\/pyprocess\/pyprocess.py#L987-L995"}
23
+ {"nwo":"CamDavidsonPilon\/PyProcess","sha":"382da02d0f9732d75624538effa11caded161779","path":"pyprocess\/pyprocess.py","language":"python","identifier":"SqBessel_process._generate_sample_path_no_absorption","parameters":"(self, times)","argument_list":"","return_statement":"","docstring":"mu must be greater than -1. The parameter times is a list of times to sample at.","docstring_summary":"mu must be greater than -1. The parameter times is a list of times to sample at.","docstring_tokens":["mu","must","be","greater","than","-","1",".","The","parameter","times","is","a","list","of","times","to","sample","at","."],"function":"def _generate_sample_path_no_absorption(self, times):\n \"mu must be greater than -1. The parameter times is a list of times to sample at.\"\n if self.mu<=-1:\n print \"Attn: mu must be greater than -1. It is currently %f.\"%self.mu\n return\n else:\n if not self.conditional:\n x=self.startPosition\n t=self.startTime\n path=[]\n for time in times:\n delta=float(time-t)\n try:\n y=self.Poi.rvs(0.5*x\/delta)\n x=self.Gamma.rvs(y+self.mu+1)*2*delta\n except:\n pass\n path.append((time,x))\n t=time\n else:\n path = bridge_creation(self, times, 0)\n return path\n return [(p[0],self.rescalePath(p[1])) for p in path]","function_tokens":["def","_generate_sample_path_no_absorption","(","self",",","times",")",":","if","self",".","mu","<=","-","1",":","print","\"Attn: mu must be greater than -1. It is currently %f.\"","%","self",".","mu","return","else",":","if","not","self",".","conditional",":","x","=","self",".","startPosition","t","=","self",".","startTime","path","=","[","]","for","time","in","times",":","delta","=","float","(","time","-","t",")","try",":","y","=","self",".","Poi",".","rvs","(","0.5","*","x","\/","delta",")","x","=","self",".","Gamma",".","rvs","(","y","+","self",".","mu","+","1",")","*","2","*","delta","except",":","pass","path",".","append","(","(","time",",","x",")",")","t","=","time","else",":","path","=","bridge_creation","(","self",",","times",",","0",")","return","path","return","[","(","p","[","0","]",",","self",".","rescalePath","(","p","[","1","]",")",")","for","p","in","path","]"],"url":"https:\/\/github.com\/CamDavidsonPilon\/PyProcess\/blob\/382da02d0f9732d75624538effa11caded161779\/pyprocess\/pyprocess.py#L1004-L1026"}
24
+ {"nwo":"CamDavidsonPilon\/PyProcess","sha":"382da02d0f9732d75624538effa11caded161779","path":"pyprocess\/pyprocess.py","language":"python","identifier":"SqBessel_process._generate_sample_path_with_absorption","parameters":"(self,times)","argument_list":"","return_statement":"","docstring":"mu must be less than 0.","docstring_summary":"mu must be less than 0.","docstring_tokens":["mu","must","be","less","than","0","."],"function":"def _generate_sample_path_with_absorption(self,times):\n \"mu must be less than 0.\"\n if self.mu>=0:\n print \"Attn: mu must be less than 0. It is currently %f.\"%self.mu\n else:\n if not self.conditional:\n path=[]\n X=self.startPosition\n t=self.startTime\n tauEst=times[-1]+1\n for time in times:\n delta = float(time - t)\n if tauEst>times[-1]:\n p_a = gammaincc(abs(self.mu),0.5*X\/(delta))\n if np.random.rand() < p_a:\n tauEst = time\n if time<tauEst:\n Y = self.InGamma.rvs(abs(self.mu),0.5*X\/(delta))\n X = self.Gamma.rvs(Y+1)*2*delta\n else:\n X=0\n t=time\n path.append((t,X))\n else:\n path = bridge_creation(self, times, 1)\n return [(p[0],self.rescalePath(p[1])) for p in path]","function_tokens":["def","_generate_sample_path_with_absorption","(","self",",","times",")",":","if","self",".","mu",">=","0",":","print","\"Attn: mu must be less than 0. It is currently %f.\"","%","self",".","mu","else",":","if","not","self",".","conditional",":","path","=","[","]","X","=","self",".","startPosition","t","=","self",".","startTime","tauEst","=","times","[","-","1","]","+","1","for","time","in","times",":","delta","=","float","(","time","-","t",")","if","tauEst",">","times","[","-","1","]",":","p_a","=","gammaincc","(","abs","(","self",".","mu",")",",","0.5","*","X","\/","(","delta",")",")","if","np",".","random",".","rand","(",")","<","p_a",":","tauEst","=","time","if","time","<","tauEst",":","Y","=","self",".","InGamma",".","rvs","(","abs","(","self",".","mu",")",",","0.5","*","X","\/","(","delta",")",")","X","=","self",".","Gamma",".","rvs","(","Y","+","1",")","*","2","*","delta","else",":","X","=","0","t","=","time","path",".","append","(","(","t",",","X",")",")","else",":","path","=","bridge_creation","(","self",",","times",",","1",")","return","[","(","p","[","0","]",",","self",".","rescalePath","(","p","[","1","]",")",")","for","p","in","path","]"],"url":"https:\/\/github.com\/CamDavidsonPilon\/PyProcess\/blob\/382da02d0f9732d75624538effa11caded161779\/pyprocess\/pyprocess.py#L1030-L1055"}
25
+ {"nwo":"CamDavidsonPilon\/PyProcess","sha":"382da02d0f9732d75624538effa11caded161779","path":"pyprocess\/pyprocess.py","language":"python","identifier":"SqBessel_process.generate_sample_FHT_bridge","parameters":"(self,times)","argument_list":"","return_statement":"","docstring":"mu must be less than 0. This process has absorption at L=0. It simulates the absorption at 0 at some random time, tao, and creates a bridge process.","docstring_summary":"mu must be less than 0. This process has absorption at L=0. It simulates the absorption at 0 at some random time, tao, and creates a bridge process.","docstring_tokens":["mu","must","be","less","than","0",".","This","process","has","absorption","at","L","=","0",".","It","simulates","the","absorption","at","0","at","some","random","time","tao","and","creates","a","bridge","process","."],"function":"def generate_sample_FHT_bridge(self,times):\n \"mu must be less than 0. This process has absorption at L=0. It simulates the absorption at 0 at some random time, tao, and creates a bridge process.\"\n if self.mu>0:\n print \"mu must be less than 0. It is currently %f.\"%self.mu\n else:\n X=self.startPosition\n t=self.t_0\n path=[]\n FHT=self.startPosition\/(2*self.Gamma.rvs(abs(self.mu)))\n for time in times:\n if time<FHT:\n d=(FHT-t)*(time-t)\n Y=self.Poi.rvs(X*(FHT-time)\/(2*d))\n X=self.Gamma.rvs(Y-self.mu+1)*d\/(FHT-t)\n else:\n X=0\n t=time\n path.append((t,X))\n return [(p[0],self.rescalePath(p[1])) for p in path]","function_tokens":["def","generate_sample_FHT_bridge","(","self",",","times",")",":","if","self",".","mu",">","0",":","print","\"mu must be less than 0. It is currently %f.\"","%","self",".","mu","else",":","X","=","self",".","startPosition","t","=","self",".","t_0","path","=","[","]","FHT","=","self",".","startPosition","\/","(","2","*","self",".","Gamma",".","rvs","(","abs","(","self",".","mu",")",")",")","for","time","in","times",":","if","time","<","FHT",":","d","=","(","FHT","-","t",")","*","(","time","-","t",")","Y","=","self",".","Poi",".","rvs","(","X","*","(","FHT","-","time",")","\/","(","2","*","d",")",")","X","=","self",".","Gamma",".","rvs","(","Y","-","self",".","mu","+","1",")","*","d","\/","(","FHT","-","t",")","else",":","X","=","0","t","=","time","path",".","append","(","(","t",",","X",")",")","return","[","(","p","[","0","]",",","self",".","rescalePath","(","p","[","1","]",")",")","for","p","in","path","]"],"url":"https:\/\/github.com\/CamDavidsonPilon\/PyProcess\/blob\/382da02d0f9732d75624538effa11caded161779\/pyprocess\/pyprocess.py#L1063-L1081"}
26
+ {"nwo":"CamDavidsonPilon\/PyProcess","sha":"382da02d0f9732d75624538effa11caded161779","path":"pyprocess\/pyprocess.py","language":"python","identifier":"CIR_process.generate_sample_path","parameters":"(self, times, abs=0)","argument_list":"","return_statement":"return path","docstring":"abs is a boolean: true if desire nonzero probability of absorption at 0, false else.","docstring_summary":"abs is a boolean: true if desire nonzero probability of absorption at 0, false else.","docstring_tokens":["abs","is","a","boolean",":","true","if","desire","nonzero","probability","of","absorption","at","0","false","else","."],"function":"def generate_sample_path(self, times, abs=0):\n \"abs is a boolean: true if desire nonzero probability of absorption at 0, false else.\"\n #first, transform times:\n transformedTimes = [self._time_transformation(t) for t in times]\n path = self.SqB.generate_sample_path(transformedTimes,abs)\n tpath = [self._space_transformation(times[i],p[1]) for i,p in enumerate(path) ]\n path=[]\n for i in xrange(len(tpath)):\n path.append((times[i],tpath[i]))\n return path","function_tokens":["def","generate_sample_path","(","self",",","times",",","abs","=","0",")",":","#first, transform times:","transformedTimes","=","[","self",".","_time_transformation","(","t",")","for","t","in","times","]","path","=","self",".","SqB",".","generate_sample_path","(","transformedTimes",",","abs",")","tpath","=","[","self",".","_space_transformation","(","times","[","i","]",",","p","[","1","]",")","for","i",",","p","in","enumerate","(","path",")","]","path","=","[","]","for","i","in","xrange","(","len","(","tpath",")",")",":","path",".","append","(","(","times","[","i","]",",","tpath","[","i","]",")",")","return","path"],"url":"https:\/\/github.com\/CamDavidsonPilon\/PyProcess\/blob\/382da02d0f9732d75624538effa11caded161779\/pyprocess\/pyprocess.py#L1129-L1138"}
27
+ {"nwo":"CamDavidsonPilon\/PyProcess","sha":"382da02d0f9732d75624538effa11caded161779","path":"pyprocess\/pyprocess.py","language":"python","identifier":"Periodic_drift_process.__init__","parameters":"(self, parameters, space_time_constraints)","argument_list":"","return_statement":"","docstring":"Note that space-time constraints cannot be given","docstring_summary":"Note that space-time constraints cannot be given","docstring_tokens":["Note","that","space","-","time","constraints","cannot","be","given"],"function":"def __init__(self, parameters, space_time_constraints):\n \"\"\"Note that space-time constraints cannot be given\"\"\"\n space_time_constraints = {\"startTime\":0, \"startPosition\":0}\n super(Periodic_drift_process,self).__init__(space_time_constraints)\n self.psi = parameters[\"psi\"]\n self.theta = parameters[\"theta\"]\n self._findBounds() \n self.BB = Wiener_process({\"mu\":0, \"sigma\":1}, space_time_constraints)\n self.Poi = Marked_poisson_process({\"rate\":1, \"U\":self.max, \"L\":self.min, \"startTime\":0}) #need to create marked poisson process class\n self.Nor = stats.norm\n self.Uni = stats.uniform()","function_tokens":["def","__init__","(","self",",","parameters",",","space_time_constraints",")",":","space_time_constraints","=","{","\"startTime\"",":","0",",","\"startPosition\"",":","0","}","super","(","Periodic_drift_process",",","self",")",".","__init__","(","space_time_constraints",")","self",".","psi","=","parameters","[","\"psi\"","]","self",".","theta","=","parameters","[","\"theta\"","]","self",".","_findBounds","(",")","self",".","BB","=","Wiener_process","(","{","\"mu\"",":","0",",","\"sigma\"",":","1","}",",","space_time_constraints",")","self",".","Poi","=","Marked_poisson_process","(","{","\"rate\"",":","1",",","\"U\"",":","self",".","max",",","\"L\"",":","self",".","min",",","\"startTime\"",":","0","}",")","#need to create marked poisson process class","self",".","Nor","=","stats",".","norm","self",".","Uni","=","stats",".","uniform","(",")"],"url":"https:\/\/github.com\/CamDavidsonPilon\/PyProcess\/blob\/382da02d0f9732d75624538effa11caded161779\/pyprocess\/pyprocess.py#L1239-L1249"}
28
+ {"nwo":"CamDavidsonPilon\/PyProcess","sha":"382da02d0f9732d75624538effa11caded161779","path":"pyprocess\/pyprocess.py","language":"python","identifier":"Periodic_drift_process.generate_sample_path","parameters":"(self,times)","argument_list":"","return_statement":"return self._construct_path_from_skeleton([(0,self.startPosition)]+skeleton, times)","docstring":"currently will only return a random path before time T. Can be connected by brownian bridges","docstring_summary":"currently will only return a random path before time T. Can be connected by brownian bridges","docstring_tokens":["currently","will","only","return","a","random","path","before","time","T",".","Can","be","connected","by","brownian","bridges"],"function":"def generate_sample_path(self,times):\n \"currently will only return a random path before time T. Can be connected by brownian bridges\"\n #this algorithm uses the EA1 algorithm by Beskos and \n # Roberts on exact simulation of diffusions. It's an AR algorithm.\n # For some parameters, the probability of acceptance can be very low.\n time = 0\n endPoint = 0\n skeleton=[]\n T = times[-1]\n while time<T:\n if time+2<T:\n delta=2\n else:\n delta = T-time\n endPoint, tempSkeleton = self.__generate_sample_path(delta,endPoint)\n tk = [(time + x[0],x[1]) for x in tempSkeleton] \n skeleton+=tk\n \n time+=2\n \n \n \n return self._construct_path_from_skeleton([(0,self.startPosition)]+skeleton, times)","function_tokens":["def","generate_sample_path","(","self",",","times",")",":","#this algorithm uses the EA1 algorithm by Beskos and ","# Roberts on exact simulation of diffusions. It's an AR algorithm.","# For some parameters, the probability of acceptance can be very low.","time","=","0","endPoint","=","0","skeleton","=","[","]","T","=","times","[","-","1","]","while","time","<","T",":","if","time","+","2","<","T",":","delta","=","2","else",":","delta","=","T","-","time","endPoint",",","tempSkeleton","=","self",".","__generate_sample_path","(","delta",",","endPoint",")","tk","=","[","(","time","+","x","[","0","]",",","x","[","1","]",")","for","x","in","tempSkeleton","]","skeleton","+=","tk","time","+=","2","return","self",".","_construct_path_from_skeleton","(","[","(","0",",","self",".","startPosition",")","]","+","skeleton",",","times",")"],"url":"https:\/\/github.com\/CamDavidsonPilon\/PyProcess\/blob\/382da02d0f9732d75624538effa11caded161779\/pyprocess\/pyprocess.py#L1293-L1315"}
29
+ {"nwo":"CamDavidsonPilon\/PyProcess","sha":"382da02d0f9732d75624538effa11caded161779","path":"pyprocess\/pyprocess.py","language":"python","identifier":"Jump_Diffusion_process.transition_pdf","parameters":"(self,t,y)","argument_list":"","return_statement":"","docstring":"this method calls self._transition_pdf(x) in the subclass","docstring_summary":"this method calls self._transition_pdf(x) in the subclass","docstring_tokens":["this","method","calls","self",".","_transition_pdf","(","x",")","in","the","subclass"],"function":"def transition_pdf(self,t,y):\n \"this method calls self._transition_pdf(x) in the subclass\"\n self._check_time(t)\n if not self.conditional:\n return self._transition_pdf(self.startPosition, t-self.startTime, y)\n else:\n return self._transition_pdf(self.startPosition, t-self.startTime, y)*self._transition_pdf(y, self.endTime-t, self.endPosition)\\\n \/self._transition_pdf(self.startPosition,self.endTime - self.startTime, self.endPosition)","function_tokens":["def","transition_pdf","(","self",",","t",",","y",")",":","self",".","_check_time","(","t",")","if","not","self",".","conditional",":","return","self",".","_transition_pdf","(","self",".","startPosition",",","t","-","self",".","startTime",",","y",")","else",":","return","self",".","_transition_pdf","(","self",".","startPosition",",","t","-","self",".","startTime",",","y",")","*","self",".","_transition_pdf","(","y",",","self",".","endTime","-","t",",","self",".","endPosition",")","\/","self",".","_transition_pdf","(","self",".","startPosition",",","self",".","endTime","-","self",".","startTime",",","self",".","endPosition",")"],"url":"https:\/\/github.com\/CamDavidsonPilon\/PyProcess\/blob\/382da02d0f9732d75624538effa11caded161779\/pyprocess\/pyprocess.py#L1451-L1458"}
30
+ {"nwo":"CamDavidsonPilon\/PyProcess","sha":"382da02d0f9732d75624538effa11caded161779","path":"pyprocess\/pyprocess.py","language":"python","identifier":"Jump_Diffusion_process.expected_value","parameters":"(self,f,t,N)","argument_list":"","return_statement":"","docstring":"uses a monte carlo approach to evaluate the expected value of the process f(X_t). N is the number of iterations. The parameter f\\\n is a univariate python function.","docstring_summary":"uses a monte carlo approach to evaluate the expected value of the process f(X_t). N is the number of iterations. The parameter f\\\n is a univariate python function.","docstring_tokens":["uses","a","monte","carlo","approach","to","evaluate","the","expected","value","of","the","process","f","(","X_t",")",".","N","is","the","number","of","iterations",".","The","parameter","f","\\","is","a","univariate","python","function","."],"function":"def expected_value(self,f,t,N):\n \"uses a monte carlo approach to evaluate the expected value of the process f(X_t). N is the number of iterations. The parameter f\\\n is a univariate python function.\"\n print \"Attn: performing a Monte Carlo simulation...\"\n self._check_time(t)\n if not self.conditional:\n sum=0\n for i in xrange(N):\n sum+=f(self.generate_position_at(t))\n return sum\/N\n else:\n #This uses a change of measure technique.\n sum=0\n self.conditional=False\n for i in xrange(N):\n X = self.generate_position_at(t)\n sum+=self._transition_pdf(X,self.endTime-t,self.endPosition)*f(X)\n self.conditional=True\n return sum\/(N*self._transition_pdf(self.startPosition, self.endTime-self.startTime, self.endPosition))","function_tokens":["def","expected_value","(","self",",","f",",","t",",","N",")",":","print","\"Attn: performing a Monte Carlo simulation...\"","self",".","_check_time","(","t",")","if","not","self",".","conditional",":","sum","=","0","for","i","in","xrange","(","N",")",":","sum","+=","f","(","self",".","generate_position_at","(","t",")",")","return","sum","\/","N","else",":","#This uses a change of measure technique.","sum","=","0","self",".","conditional","=","False","for","i","in","xrange","(","N",")",":","X","=","self",".","generate_position_at","(","t",")","sum","+=","self",".","_transition_pdf","(","X",",","self",".","endTime","-","t",",","self",".","endPosition",")","*","f","(","X",")","self",".","conditional","=","True","return","sum","\/","(","N","*","self",".","_transition_pdf","(","self",".","startPosition",",","self",".","endTime","-","self",".","startTime",",","self",".","endPosition",")",")"],"url":"https:\/\/github.com\/CamDavidsonPilon\/PyProcess\/blob\/382da02d0f9732d75624538effa11caded161779\/pyprocess\/pyprocess.py#L1461-L1479"}
31
+ {"nwo":"CamDavidsonPilon\/PyProcess","sha":"382da02d0f9732d75624538effa11caded161779","path":"pyprocess\/pyprocess.py","language":"python","identifier":"Jump_Diffusion_process.generate_position_at","parameters":"(self,t)","argument_list":"","return_statement":"","docstring":"if _get_position_at() is not overwritten in a subclass, this function will use euler scheme","docstring_summary":"if _get_position_at() is not overwritten in a subclass, this function will use euler scheme","docstring_tokens":["if","_get_position_at","()","is","not","overwritten","in","a","subclass","this","function","will","use","euler","scheme"],"function":"def generate_position_at(self,t):\n \"if _get_position_at() is not overwritten in a subclass, this function will use euler scheme\"\n self._check_time(t) \n if self.startTime<t:\n return self._generate_position_at(t)","function_tokens":["def","generate_position_at","(","self",",","t",")",":","self",".","_check_time","(","t",")","if","self",".","startTime","<","t",":","return","self",".","_generate_position_at","(","t",")"],"url":"https:\/\/github.com\/CamDavidsonPilon\/PyProcess\/blob\/382da02d0f9732d75624538effa11caded161779\/pyprocess\/pyprocess.py#L1481-L1485"}
32
+ {"nwo":"CamDavidsonPilon\/PyProcess","sha":"382da02d0f9732d75624538effa11caded161779","path":"pyprocess\/pyprocess.py","language":"python","identifier":"Jump_Diffusion_process.generate_sample_path","parameters":"(self,times)","argument_list":"","return_statement":"return self._generate_sample_path(times)","docstring":"\"times\" is a list of times, with the first time greater than initial time.\"","docstring_summary":"\"times\" is a list of times, with the first time greater than initial time.\"","docstring_tokens":["times","is","a","list","of","times","with","the","first","time","greater","than","initial","time","."],"function":"def generate_sample_path(self,times):\n '\"times\" is a list of times, with the first time greater than initial time.\"'\n self._check_time(times[0])\n return self._generate_sample_path(times)","function_tokens":["def","generate_sample_path","(","self",",","times",")",":","self",".","_check_time","(","times","[","0","]",")","return","self",".","_generate_sample_path","(","times",")"],"url":"https:\/\/github.com\/CamDavidsonPilon\/PyProcess\/blob\/382da02d0f9732d75624538effa11caded161779\/pyprocess\/pyprocess.py#L1497-L1500"}
33
+ {"nwo":"CamDavidsonPilon\/PyProcess","sha":"382da02d0f9732d75624538effa11caded161779","path":"pyprocess\/pyprocess.py","language":"python","identifier":"Jump_Diffusion_process._generate_sample_path","parameters":"(self,times)","argument_list":"","return_statement":"","docstring":"I need some way to use a euler scheme AND evaluate the approximation at t in times","docstring_summary":"I need some way to use a euler scheme AND evaluate the approximation at t in times","docstring_tokens":["I","need","some","way","to","use","a","euler","scheme","AND","evaluate","the","approximation","at","t","in","times"],"function":"def _generate_sample_path(self,times):\n \"I need some way to use a euler scheme AND evaluate the approximation at t in times\"\n pass","function_tokens":["def","_generate_sample_path","(","self",",","times",")",":","pass"],"url":"https:\/\/github.com\/CamDavidsonPilon\/PyProcess\/blob\/382da02d0f9732d75624538effa11caded161779\/pyprocess\/pyprocess.py#L1503-L1505"}
34
+ {"nwo":"CamDavidsonPilon\/PyProcess","sha":"382da02d0f9732d75624538effa11caded161779","path":"pyprocess\/pyprocess.py","language":"python","identifier":"Jump_Diffusion_process._get_mean_at","parameters":"(self,t)","argument_list":"","return_statement":"return self.expected_value(id, t, 100000)","docstring":"if _get_mean_at() is not overwritten, then we use MC methods; 100000 iterations","docstring_summary":"if _get_mean_at() is not overwritten, then we use MC methods; 100000 iterations","docstring_tokens":["if","_get_mean_at","()","is","not","overwritten","then","we","use","MC","methods",";","100000","iterations"],"function":"def _get_mean_at(self,t):\n \"if _get_mean_at() is not overwritten, then we use MC methods; 100000 iterations\"\n def id(x):\n return x\n return self.expected_value(id, t, 100000)","function_tokens":["def","_get_mean_at","(","self",",","t",")",":","def","id","(","x",")",":","return","x","return","self",".","expected_value","(","id",",","t",",","100000",")"],"url":"https:\/\/github.com\/CamDavidsonPilon\/PyProcess\/blob\/382da02d0f9732d75624538effa11caded161779\/pyprocess\/pyprocess.py#L1515-L1519"}
35
+ {"nwo":"CamDavidsonPilon\/PyProcess","sha":"382da02d0f9732d75624538effa11caded161779","path":"pyprocess\/pyprocess.py","language":"python","identifier":"Gamma_process._get_mean_at","parameters":"(self,t)","argument_list":"","return_statement":"","docstring":"notice the conditional is independent of self.mean.","docstring_summary":"notice the conditional is independent of self.mean.","docstring_tokens":["notice","the","conditional","is","independent","of","self",".","mean","."],"function":"def _get_mean_at(self,t):\n \"notice the conditional is independent of self.mean.\"\n if self.conditional:\n return self.startPosition + (self.endPosition-self.startPosition)*(t- self.startTime)\/(self.endTime - self.startTime)\n else:\n return self.startPosition + self.mean*(t-self.startTime)","function_tokens":["def","_get_mean_at","(","self",",","t",")",":","if","self",".","conditional",":","return","self",".","startPosition","+","(","self",".","endPosition","-","self",".","startPosition",")","*","(","t","-","self",".","startTime",")","\/","(","self",".","endTime","-","self",".","startTime",")","else",":","return","self",".","startPosition","+","self",".","mean","*","(","t","-","self",".","startTime",")"],"url":"https:\/\/github.com\/CamDavidsonPilon\/PyProcess\/blob\/382da02d0f9732d75624538effa11caded161779\/pyprocess\/pyprocess.py#L1567-L1572"}
36
+ {"nwo":"CamDavidsonPilon\/PyProcess","sha":"382da02d0f9732d75624538effa11caded161779","path":"pyprocess\/pyprocess.py","language":"python","identifier":"Geometric_gamma_process._transition_pdf","parameters":"(self,z,t,x)","argument_list":"","return_statement":"return (np.log((z-x)\/self.startPosition))**(alpha-1)*((z-x)\/self.startPosition)**(-1\/beta)\/((z-x)*beta**alpha*gamma(alpha))","docstring":"as this is a strictly increasing process, the condition x<z must hold","docstring_summary":"as this is a strictly increasing process, the condition x<z must hold","docstring_tokens":["as","this","is","a","strictly","increasing","process","the","condition","x<z","must","hold"],"function":"def _transition_pdf(self,z,t,x):\n \"as this is a strictly increasing process, the condition x<z must hold\"\n alpha = self.mu**2*t\/self.sigma\n beta = self.sigma\/self.mu\n return (np.log((z-x)\/self.startPosition))**(alpha-1)*((z-x)\/self.startPosition)**(-1\/beta)\/((z-x)*beta**alpha*gamma(alpha))","function_tokens":["def","_transition_pdf","(","self",",","z",",","t",",","x",")",":","alpha","=","self",".","mu","**","2","*","t","\/","self",".","sigma","beta","=","self",".","sigma","\/","self",".","mu","return","(","np",".","log","(","(","z","-","x",")","\/","self",".","startPosition",")",")","**","(","alpha","-","1",")","*","(","(","z","-","x",")","\/","self",".","startPosition",")","**","(","-","1","\/","beta",")","\/","(","(","z","-","x",")","*","beta","**","alpha","*","gamma","(","alpha",")",")"],"url":"https:\/\/github.com\/CamDavidsonPilon\/PyProcess\/blob\/382da02d0f9732d75624538effa11caded161779\/pyprocess\/pyprocess.py#L1703-L1707"}
37
+ {"nwo":"CamDavidsonPilon\/PyProcess","sha":"382da02d0f9732d75624538effa11caded161779","path":"pyprocess\/pyprocess.py","language":"python","identifier":"Custom_process.generate_sample_path","parameters":"(self,times, *args)","argument_list":"","return_statement":"return path","docstring":"returns an array of a path, not an immutable list!","docstring_summary":"returns an array of a path, not an immutable list!","docstring_tokens":["returns","an","array","of","a","path","not","an","immutable","list!"],"function":"def generate_sample_path(self,times, *args):\n \"returns an array of a path, not an immutable list!\"\n path = [[t,0] for t in times]\n for i in xrange(len(self.processes)):\n try:\n tempPath = self.processes[i].generate_sample_path(times, args[i] )\n except:\n tempPath = self.processes[i].generate_sample_path(times)\n for k in xrange(len(tempPath)):\n path[k][1]+=tempPath[k][1]\n return path","function_tokens":["def","generate_sample_path","(","self",",","times",",","*","args",")",":","path","=","[","[","t",",","0","]","for","t","in","times","]","for","i","in","xrange","(","len","(","self",".","processes",")",")",":","try",":","tempPath","=","self",".","processes","[","i","]",".","generate_sample_path","(","times",",","args","[","i","]",")","except",":","tempPath","=","self",".","processes","[","i","]",".","generate_sample_path","(","times",")","for","k","in","xrange","(","len","(","tempPath",")",")",":","path","[","k","]","[","1","]","+=","tempPath","[","k","]","[","1","]","return","path"],"url":"https:\/\/github.com\/CamDavidsonPilon\/PyProcess\/blob\/382da02d0f9732d75624538effa11caded161779\/pyprocess\/pyprocess.py#L1845-L1855"}
38
+ {"nwo":"CamDavidsonPilon\/PyProcess","sha":"382da02d0f9732d75624538effa11caded161779","path":"pyprocess\/pyprocess.py","language":"python","identifier":"IncompleteGamma.rvs","parameters":"(self,shape,scale)","argument_list":"","return_statement":"return float(pos)","docstring":"uses a inversion method: the chop-down-search starting \\\n at the mode","docstring_summary":"uses a inversion method: the chop-down-search starting \\\n at the mode","docstring_tokens":["uses","a","inversion","method",":","the","chop","-","down","-","search","starting","\\","at","the","mode"],"function":"def rvs(self,shape,scale):\n \"uses a inversion method: the chop-down-search starting \\\n at the mode\"\n pos = mode = float(max(0,int(shape-scale)))\n U = self.Uni.rvs()\n sum = self.pdf(mode,shape,scale)\n ub = mode+1\n lb = mode-1\n Pub = sum*scale\/(mode+1+shape)\n Plb = sum*(mode+shape)\/scale\n while sum<U:\n if Plb>Pub and lb>=0:\n sum+=Plb\n pos = lb\n Plb = (lb+shape)\/scale*Plb\n lb-=1\n else:\n sum+=Pub\n pos= ub\n Pub = scale\/(ub+1+shape)*Pub\n ub+=1\n return float(pos)","function_tokens":["def","rvs","(","self",",","shape",",","scale",")",":","pos","=","mode","=","float","(","max","(","0",",","int","(","shape","-","scale",")",")",")","U","=","self",".","Uni",".","rvs","(",")","sum","=","self",".","pdf","(","mode",",","shape",",","scale",")","ub","=","mode","+","1","lb","=","mode","-","1","Pub","=","sum","*","scale","\/","(","mode","+","1","+","shape",")","Plb","=","sum","*","(","mode","+","shape",")","\/","scale","while","sum","<","U",":","if","Plb",">","Pub","and","lb",">=","0",":","sum","+=","Plb","pos","=","lb","Plb","=","(","lb","+","shape",")","\/","scale","*","Plb","lb","-=","1","else",":","sum","+=","Pub","pos","=","ub","Pub","=","scale","\/","(","ub","+","1","+","shape",")","*","Pub","ub","+=","1","return","float","(","pos",")"],"url":"https:\/\/github.com\/CamDavidsonPilon\/PyProcess\/blob\/382da02d0f9732d75624538effa11caded161779\/pyprocess\/pyprocess.py#L1982-L2003"}
Chung-I__Variational-Recurrent-Autoencoder-Tensorflow.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
ClementPinard__DepthNet.jsonl ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ {"nwo":"ClementPinard\/DepthNet","sha":"3c753fc21b06c9be307d73c8e7a0c61f2ea56cc3","path":"terminal_logger.py","language":"python","identifier":"Writer.__init__","parameters":"(self, t, location)","argument_list":"","return_statement":"","docstring":"Input: location - tuple of ints (x, y), the position\n of the bar in the terminal","docstring_summary":"Input: location - tuple of ints (x, y), the position\n of the bar in the terminal","docstring_tokens":["Input",":","location","-","tuple","of","ints","(","x","y",")","the","position","of","the","bar","in","the","terminal"],"function":"def __init__(self, t, location):\n \"\"\"\n Input: location - tuple of ints (x, y), the position\n of the bar in the terminal\n \"\"\"\n self.location = location\n self.t = t","function_tokens":["def","__init__","(","self",",","t",",","location",")",":","self",".","location","=","location","self",".","t","=","t"],"url":"https:\/\/github.com\/ClementPinard\/DepthNet\/blob\/3c753fc21b06c9be307d73c8e7a0c61f2ea56cc3\/terminal_logger.py#L45-L51"}
2
+ {"nwo":"ClementPinard\/DepthNet","sha":"3c753fc21b06c9be307d73c8e7a0c61f2ea56cc3","path":"datasets\/stillbox.py","language":"python","identifier":"make_dataset","parameters":"(root_dir, split=0, shift=3, seed=None)","argument_list":"","return_statement":"return (train_scenes, test_images)","docstring":"Will search for subfolder and will read metadata json files.","docstring_summary":"Will search for subfolder and will read metadata json files.","docstring_tokens":["Will","search","for","subfolder","and","will","read","metadata","json","files","."],"function":"def make_dataset(root_dir, split=0, shift=3, seed=None):\n \"\"\"Will search for subfolder and will read metadata json files.\"\"\"\n global args\n random.seed(seed)\n scenes = []\n for sub_dir in root_dir.dirs():\n metadata_path = sub_dir\/'metadata.json'\n with open(metadata_path, 'r') as f:\n metadata = json.load(f)\n for scene in metadata['scenes']:\n scene['subdir'] = sub_dir.basename()\n scenes.extend(metadata['scenes'])\n\n assert(len(scenes) > 0)\n random.shuffle(scenes)\n split_index = math.floor(len(scenes)*split\/100)\n assert(split_index >= 0 and split_index <= len(scenes))\n train_scenes = scenes[:split_index]\n test_images = []\n if split_index < len(scenes):\n for scene in scenes[split_index+1:]:\n imgs = scene['imgs']\n for i in range(len(imgs)-shift):\n img_pair = [str(scene['subdir']\/imgs[i]), str(scene['subdir']\/imgs[i+shift])]\n depth = str(scene['subdir']\/scene['depth'][i + shift])\n displacement = np.array(scene['speed']).astype(np.float32)*shift*scene['time_step']\n test_images.append(\n [img_pair,\n depth,\n displacement]\n )\n return (train_scenes, test_images)","function_tokens":["def","make_dataset","(","root_dir",",","split","=","0",",","shift","=","3",",","seed","=","None",")",":","global","args","random",".","seed","(","seed",")","scenes","=","[","]","for","sub_dir","in","root_dir",".","dirs","(",")",":","metadata_path","=","sub_dir","\/","'metadata.json'","with","open","(","metadata_path",",","'r'",")","as","f",":","metadata","=","json",".","load","(","f",")","for","scene","in","metadata","[","'scenes'","]",":","scene","[","'subdir'","]","=","sub_dir",".","basename","(",")","scenes",".","extend","(","metadata","[","'scenes'","]",")","assert","(","len","(","scenes",")",">","0",")","random",".","shuffle","(","scenes",")","split_index","=","math",".","floor","(","len","(","scenes",")","*","split","\/","100",")","assert","(","split_index",">=","0","and","split_index","<=","len","(","scenes",")",")","train_scenes","=","scenes","[",":","split_index","]","test_images","=","[","]","if","split_index","<","len","(","scenes",")",":","for","scene","in","scenes","[","split_index","+","1",":","]",":","imgs","=","scene","[","'imgs'","]","for","i","in","range","(","len","(","imgs",")","-","shift",")",":","img_pair","=","[","str","(","scene","[","'subdir'","]","\/","imgs","[","i","]",")",",","str","(","scene","[","'subdir'","]","\/","imgs","[","i","+","shift","]",")","]","depth","=","str","(","scene","[","'subdir'","]","\/","scene","[","'depth'","]","[","i","+","shift","]",")","displacement","=","np",".","array","(","scene","[","'speed'","]",")",".","astype","(","np",".","float32",")","*","shift","*","scene","[","'time_step'","]","test_images",".","append","(","[","img_pair",",","depth",",","displacement","]",")","return","(","train_scenes",",","test_images",")"],"url":"https:\/\/github.com\/ClementPinard\/DepthNet\/blob\/3c753fc21b06c9be307d73c8e7a0c61f2ea56cc3\/datasets\/stillbox.py#L10-L41"}
ClementPinard__Pytorch-Correlation-extension.jsonl ADDED
@@ -0,0 +1 @@
 
 
1
+ {"nwo":"ClementPinard\/Pytorch-Correlation-extension","sha":"3e8ce16124844cd7892ec965cf0ad18fdd8e6a02","path":"Correlation_Module\/spatial_correlation_sampler\/spatial_correlation_sampler.py","language":"python","identifier":"spatial_correlation_sample","parameters":"(input1,\n input2,\n kernel_size=1,\n patch_size=1,\n stride=1,\n padding=0,\n dilation=1,\n dilation_patch=1)","argument_list":"","return_statement":"return SpatialCorrelationSamplerFunction.apply(input1, input2,\n kernel_size, patch_size,\n stride, padding, dilation, dilation_patch)","docstring":"Apply spatial correlation sampling on from input1 to input2,\n\n Every parameter except input1 and input2 can be either single int\n or a pair of int. For more information about Spatial Correlation\n Sampling, see this page.\n https:\/\/lmb.informatik.uni-freiburg.de\/Publications\/2015\/DFIB15\/\n\n Args:\n input1 : The first parameter.\n input2 : The second parameter.\n kernel_size : total size of your correlation kernel, in pixels\n patch_size : total size of your patch, determining how many\n different shifts will be applied\n stride : stride of the spatial sampler, will modify output\n height and width\n padding : padding applied to input1 and input2 before applying\n the correlation sampling, will modify output height and width\n dilation_patch : step for every shift in patch\n\n Returns:\n Tensor: Result of correlation sampling","docstring_summary":"Apply spatial correlation sampling on from input1 to input2,","docstring_tokens":["Apply","spatial","correlation","sampling","on","from","input1","to","input2"],"function":"def spatial_correlation_sample(input1,\n input2,\n kernel_size=1,\n patch_size=1,\n stride=1,\n padding=0,\n dilation=1,\n dilation_patch=1):\n \"\"\"Apply spatial correlation sampling on from input1 to input2,\n\n Every parameter except input1 and input2 can be either single int\n or a pair of int. For more information about Spatial Correlation\n Sampling, see this page.\n https:\/\/lmb.informatik.uni-freiburg.de\/Publications\/2015\/DFIB15\/\n\n Args:\n input1 : The first parameter.\n input2 : The second parameter.\n kernel_size : total size of your correlation kernel, in pixels\n patch_size : total size of your patch, determining how many\n different shifts will be applied\n stride : stride of the spatial sampler, will modify output\n height and width\n padding : padding applied to input1 and input2 before applying\n the correlation sampling, will modify output height and width\n dilation_patch : step for every shift in patch\n\n Returns:\n Tensor: Result of correlation sampling\n\n \"\"\"\n return SpatialCorrelationSamplerFunction.apply(input1, input2,\n kernel_size, patch_size,\n stride, padding, dilation, dilation_patch)","function_tokens":["def","spatial_correlation_sample","(","input1",",","input2",",","kernel_size","=","1",",","patch_size","=","1",",","stride","=","1",",","padding","=","0",",","dilation","=","1",",","dilation_patch","=","1",")",":","return","SpatialCorrelationSamplerFunction",".","apply","(","input1",",","input2",",","kernel_size",",","patch_size",",","stride",",","padding",",","dilation",",","dilation_patch",")"],"url":"https:\/\/github.com\/ClementPinard\/Pytorch-Correlation-extension\/blob\/3e8ce16124844cd7892ec965cf0ad18fdd8e6a02\/Correlation_Module\/spatial_correlation_sampler\/spatial_correlation_sampler.py#L9-L42"}
ClusterHQ__powerstrip.jsonl ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {"nwo":"ClusterHQ\/powerstrip","sha":"b18dc7261b001720149849b8ed8f2a31880d76c1","path":"powerstrip\/powerstrip.py","language":"python","identifier":"DockerProxyClient.setStreamingMode","parameters":"(self, streamingMode)","argument_list":"","return_statement":"","docstring":"Allow anyone with a reference to us to toggle on\/off streaming mode.\n Useful when we have no post-hooks (and no indication from Docker that\n it's sending packets of JSON e.g. with build) and we want to avoid\n buffering slow responses in memory.","docstring_summary":"Allow anyone with a reference to us to toggle on\/off streaming mode.\n Useful when we have no post-hooks (and no indication from Docker that\n it's sending packets of JSON e.g. with build) and we want to avoid\n buffering slow responses in memory.","docstring_tokens":["Allow","anyone","with","a","reference","to","us","to","toggle","on","\/","off","streaming","mode",".","Useful","when","we","have","no","post","-","hooks","(","and","no","indication","from","Docker","that","it","s","sending","packets","of","JSON","e",".","g",".","with","build",")","and","we","want","to","avoid","buffering","slow","responses","in","memory","."],"function":"def setStreamingMode(self, streamingMode):\n \"\"\"\n Allow anyone with a reference to us to toggle on\/off streaming mode.\n Useful when we have no post-hooks (and no indication from Docker that\n it's sending packets of JSON e.g. with build) and we want to avoid\n buffering slow responses in memory.\n \"\"\"\n self._streaming = streamingMode\n if streamingMode:\n self._fireListener(Failure(NoPostHooks()))","function_tokens":["def","setStreamingMode","(","self",",","streamingMode",")",":","self",".","_streaming","=","streamingMode","if","streamingMode",":","self",".","_fireListener","(","Failure","(","NoPostHooks","(",")",")",")"],"url":"https:\/\/github.com\/ClusterHQ\/powerstrip\/blob\/b18dc7261b001720149849b8ed8f2a31880d76c1\/powerstrip\/powerstrip.py#L46-L55"}
2
+ {"nwo":"ClusterHQ\/powerstrip","sha":"b18dc7261b001720149849b8ed8f2a31880d76c1","path":"powerstrip\/powerstrip.py","language":"python","identifier":"DockerProxyClient.registerListener","parameters":"(self, d)","argument_list":"","return_statement":"","docstring":"Register a one shot listener, which can fire either with:\n * Failure(NoPostHooks()) if the proxy is handling comms back to\n the client (streaming\/chunked modes), or\n * A tuple containing the (response, code, content-type).","docstring_summary":"Register a one shot listener, which can fire either with:\n * Failure(NoPostHooks()) if the proxy is handling comms back to\n the client (streaming\/chunked modes), or\n * A tuple containing the (response, code, content-type).","docstring_tokens":["Register","a","one","shot","listener","which","can","fire","either","with",":","*","Failure","(","NoPostHooks","()",")","if","the","proxy","is","handling","comms","back","to","the","client","(","streaming","\/","chunked","modes",")","or","*","A","tuple","containing","the","(","response","code","content","-","type",")","."],"function":"def registerListener(self, d):\n \"\"\"\n Register a one shot listener, which can fire either with:\n * Failure(NoPostHooks()) if the proxy is handling comms back to\n the client (streaming\/chunked modes), or\n * A tuple containing the (response, code, content-type).\n \"\"\"\n self._listener = d","function_tokens":["def","registerListener","(","self",",","d",")",":","self",".","_listener","=","d"],"url":"https:\/\/github.com\/ClusterHQ\/powerstrip\/blob\/b18dc7261b001720149849b8ed8f2a31880d76c1\/powerstrip\/powerstrip.py#L57-L64"}
3
+ {"nwo":"ClusterHQ\/powerstrip","sha":"b18dc7261b001720149849b8ed8f2a31880d76c1","path":"powerstrip\/powerstrip.py","language":"python","identifier":"DockerProxyClient._handleRawStream","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Switch the current connection to be a \"hijacked\" aka raw stream: one\n where bytes just get naively proxied back and forth.","docstring_summary":"Switch the current connection to be a \"hijacked\" aka raw stream: one\n where bytes just get naively proxied back and forth.","docstring_tokens":["Switch","the","current","connection","to","be","a","hijacked","aka","raw","stream",":","one","where","bytes","just","get","naively","proxied","back","and","forth","."],"function":"def _handleRawStream(self):\n \"\"\"\n Switch the current connection to be a \"hijacked\" aka raw stream: one\n where bytes just get naively proxied back and forth.\n \"\"\"\n def loseWriteConnectionReason(reason):\n # discard the reason, for compatibility with readConnectionLost\n self.transport.loseWriteConnection()\n self.father.transport.readConnectionLost = loseWriteConnectionReason\n directlyProvides(self.father.transport, IHalfCloseableProtocol)\n self.http = False\n self.father.transport.write(\n \"HTTP\/1.1 200 OK\\r\\n\"\n \"Content-Type: application\/vnd.docker.raw-stream\\r\\n\"\n \"\\r\\n\")\n def stdinHandler(data):\n self.transport.write(data)\n self.father.transport.protocol.dataReceived = stdinHandler\n self.setStreamingMode(True)","function_tokens":["def","_handleRawStream","(","self",")",":","def","loseWriteConnectionReason","(","reason",")",":","# discard the reason, for compatibility with readConnectionLost","self",".","transport",".","loseWriteConnection","(",")","self",".","father",".","transport",".","readConnectionLost","=","loseWriteConnectionReason","directlyProvides","(","self",".","father",".","transport",",","IHalfCloseableProtocol",")","self",".","http","=","False","self",".","father",".","transport",".","write","(","\"HTTP\/1.1 200 OK\\r\\n\"","\"Content-Type: application\/vnd.docker.raw-stream\\r\\n\"","\"\\r\\n\"",")","def","stdinHandler","(","data",")",":","self",".","transport",".","write","(","data",")","self",".","father",".","transport",".","protocol",".","dataReceived","=","stdinHandler","self",".","setStreamingMode","(","True",")"],"url":"https:\/\/github.com\/ClusterHQ\/powerstrip\/blob\/b18dc7261b001720149849b8ed8f2a31880d76c1\/powerstrip\/powerstrip.py#L66-L84"}
4
+ {"nwo":"ClusterHQ\/powerstrip","sha":"b18dc7261b001720149849b8ed8f2a31880d76c1","path":"powerstrip\/powerstrip.py","language":"python","identifier":"DockerProxyClient.handleResponsePart","parameters":"(self, buffer)","argument_list":"","return_statement":"","docstring":"If we're not in streaming mode, buffer the response part(s).","docstring_summary":"If we're not in streaming mode, buffer the response part(s).","docstring_tokens":["If","we","re","not","in","streaming","mode","buffer","the","response","part","(","s",")","."],"function":"def handleResponsePart(self, buffer):\n \"\"\"\n If we're not in streaming mode, buffer the response part(s).\n \"\"\"\n if self._streaming:\n proxy.ProxyClient.handleResponsePart(self, buffer)\n else:\n self._responsePartBuffer += buffer","function_tokens":["def","handleResponsePart","(","self",",","buffer",")",":","if","self",".","_streaming",":","proxy",".","ProxyClient",".","handleResponsePart","(","self",",","buffer",")","else",":","self",".","_responsePartBuffer","+=","buffer"],"url":"https:\/\/github.com\/ClusterHQ\/powerstrip\/blob\/b18dc7261b001720149849b8ed8f2a31880d76c1\/powerstrip\/powerstrip.py#L93-L100"}
5
+ {"nwo":"ClusterHQ\/powerstrip","sha":"b18dc7261b001720149849b8ed8f2a31880d76c1","path":"powerstrip\/powerstrip.py","language":"python","identifier":"DockerProxyClient.handleResponseEnd","parameters":"(self)","argument_list":"","return_statement":"","docstring":"If we're completing a chunked response, up-call to handle it like a\n regular reverse proxy.\n\n If we're completing a non-chunked response, fire the post-hooks.\n\n If we're completing a hijacked response, pass through the connection\n close.","docstring_summary":"If we're completing a chunked response, up-call to handle it like a\n regular reverse proxy.","docstring_tokens":["If","we","re","completing","a","chunked","response","up","-","call","to","handle","it","like","a","regular","reverse","proxy","."],"function":"def handleResponseEnd(self):\n \"\"\"\n If we're completing a chunked response, up-call to handle it like a\n regular reverse proxy.\n\n If we're completing a non-chunked response, fire the post-hooks.\n\n If we're completing a hijacked response, pass through the connection\n close.\n \"\"\"\n if self.http:\n if self._streaming:\n return proxy.ProxyClient.handleResponseEnd(self)\n else:\n contentType = self.father.responseHeaders.getRawHeaders(\"content-type\")\n if contentType:\n contentType = contentType[0]\n else:\n contentType = None\n body = self._responsePartBuffer\n self._fireListener(\n {\"PowerstripProtocolVersion\": 1,\n \"ModifiedServerResponse\":\n {\"Body\": body,\n \"Code\": self.father.code,\n \"ContentType\": contentType}})\n else:\n self.father.transport.loseConnection()","function_tokens":["def","handleResponseEnd","(","self",")",":","if","self",".","http",":","if","self",".","_streaming",":","return","proxy",".","ProxyClient",".","handleResponseEnd","(","self",")","else",":","contentType","=","self",".","father",".","responseHeaders",".","getRawHeaders","(","\"content-type\"",")","if","contentType",":","contentType","=","contentType","[","0","]","else",":","contentType","=","None","body","=","self",".","_responsePartBuffer","self",".","_fireListener","(","{","\"PowerstripProtocolVersion\"",":","1",",","\"ModifiedServerResponse\"",":","{","\"Body\"",":","body",",","\"Code\"",":","self",".","father",".","code",",","\"ContentType\"",":","contentType","}","}",")","else",":","self",".","father",".","transport",".","loseConnection","(",")"],"url":"https:\/\/github.com\/ClusterHQ\/powerstrip\/blob\/b18dc7261b001720149849b8ed8f2a31880d76c1\/powerstrip\/powerstrip.py#L103-L130"}
6
+ {"nwo":"ClusterHQ\/powerstrip","sha":"b18dc7261b001720149849b8ed8f2a31880d76c1","path":"powerstrip\/powerstrip.py","language":"python","identifier":"DockerProxy.__init__","parameters":"(self, dockerAddr=None, dockerPort=None, dockerSocket=None,\n path='', reactor=reactor, config=None)","argument_list":"","return_statement":"","docstring":"A docker proxy resource which knows how to connect to real Docker\n daemon either via socket (dockerSocket specified) or address + port for\n TCP connection (dockerAddr + dockerPort specified).","docstring_summary":"A docker proxy resource which knows how to connect to real Docker\n daemon either via socket (dockerSocket specified) or address + port for\n TCP connection (dockerAddr + dockerPort specified).","docstring_tokens":["A","docker","proxy","resource","which","knows","how","to","connect","to","real","Docker","daemon","either","via","socket","(","dockerSocket","specified",")","or","address","+","port","for","TCP","connection","(","dockerAddr","+","dockerPort","specified",")","."],"function":"def __init__(self, dockerAddr=None, dockerPort=None, dockerSocket=None,\n path='', reactor=reactor, config=None):\n \"\"\"\n A docker proxy resource which knows how to connect to real Docker\n daemon either via socket (dockerSocket specified) or address + port for\n TCP connection (dockerAddr + dockerPort specified).\n \"\"\"\n if config is None:\n # Try to get the configuration from the default place on the\n # filesystem.\n self.config = PluginConfiguration()\n else:\n self.config = config\n self.config.read_and_parse()\n self.parser = EndpointParser(self.config)\n Resource.__init__(self)\n self.host = dockerAddr\n self.port = dockerPort\n self.socket = dockerSocket\n self.path = path\n self.reactor = reactor\n proxy.ReverseProxyResource.__init__(self, dockerAddr, dockerPort, path, reactor) # NB dockerAddr is not actually used\n self.agent = Agent(reactor) # no connectionpool\n self.client = HTTPClient(self.agent)","function_tokens":["def","__init__","(","self",",","dockerAddr","=","None",",","dockerPort","=","None",",","dockerSocket","=","None",",","path","=","''",",","reactor","=","reactor",",","config","=","None",")",":","if","config","is","None",":","# Try to get the configuration from the default place on the","# filesystem.","self",".","config","=","PluginConfiguration","(",")","else",":","self",".","config","=","config","self",".","config",".","read_and_parse","(",")","self",".","parser","=","EndpointParser","(","self",".","config",")","Resource",".","__init__","(","self",")","self",".","host","=","dockerAddr","self",".","port","=","dockerPort","self",".","socket","=","dockerSocket","self",".","path","=","path","self",".","reactor","=","reactor","proxy",".","ReverseProxyResource",".","__init__","(","self",",","dockerAddr",",","dockerPort",",","path",",","reactor",")","# NB dockerAddr is not actually used","self",".","agent","=","Agent","(","reactor",")","# no connectionpool","self",".","client","=","HTTPClient","(","self",".","agent",")"],"url":"https:\/\/github.com\/ClusterHQ\/powerstrip\/blob\/b18dc7261b001720149849b8ed8f2a31880d76c1\/powerstrip\/powerstrip.py#L166-L189"}
7
+ {"nwo":"ClusterHQ\/powerstrip","sha":"b18dc7261b001720149849b8ed8f2a31880d76c1","path":"powerstrip\/_parser.py","language":"python","identifier":"EndpointParser.__init__","parameters":"(self, config)","argument_list":"","return_statement":"","docstring":":param config: A ``PluginConfiguration`` object which has already read\n the current configuration.","docstring_summary":":param config: A ``PluginConfiguration`` object which has already read\n the current configuration.","docstring_tokens":[":","param","config",":","A","PluginConfiguration","object","which","has","already","read","the","current","configuration","."],"function":"def __init__(self, config):\n \"\"\"\n :param config: A ``PluginConfiguration`` object which has already read\n the current configuration.\n \"\"\"\n self.config = config","function_tokens":["def","__init__","(","self",",","config",")",":","self",".","config","=","config"],"url":"https:\/\/github.com\/ClusterHQ\/powerstrip\/blob\/b18dc7261b001720149849b8ed8f2a31880d76c1\/powerstrip\/_parser.py#L17-L22"}
8
+ {"nwo":"ClusterHQ\/powerstrip","sha":"b18dc7261b001720149849b8ed8f2a31880d76c1","path":"powerstrip\/_parser.py","language":"python","identifier":"EndpointParser.match_endpoint","parameters":"(self, method, request)","argument_list":"","return_statement":"return matched_endpoints","docstring":"Return a ``set`` of endpoint expressions which match the provided\n ``method`` and ``request``. The items in this set can be provided\n to ``PluginConfiguration.endpoint`` to get the adapter\n configuration.\n\n :param method: An HTTP method string, e.g. \"GET\" or \"POST\".\n\n :param request: An HTTP request path string, e.g. \"\/v1\/containers\/create\".\n\n :return: The set of endpoint expressions to be provided to\n ``PluginConfiguration.endpoint``.\n\n :raises: If the request containers a query part, an ``InvalidRequest`` is raised.","docstring_summary":"Return a ``set`` of endpoint expressions which match the provided\n ``method`` and ``request``. The items in this set can be provided\n to ``PluginConfiguration.endpoint`` to get the adapter\n configuration.","docstring_tokens":["Return","a","set","of","endpoint","expressions","which","match","the","provided","method","and","request",".","The","items","in","this","set","can","be","provided","to","PluginConfiguration",".","endpoint","to","get","the","adapter","configuration","."],"function":"def match_endpoint(self, method, request):\n \"\"\"\n Return a ``set`` of endpoint expressions which match the provided\n ``method`` and ``request``. The items in this set can be provided\n to ``PluginConfiguration.endpoint`` to get the adapter\n configuration.\n\n :param method: An HTTP method string, e.g. \"GET\" or \"POST\".\n\n :param request: An HTTP request path string, e.g. \"\/v1\/containers\/create\".\n\n :return: The set of endpoint expressions to be provided to\n ``PluginConfiguration.endpoint``.\n\n :raises: If the request containers a query part, an ``InvalidRequest`` is raised.\n \"\"\"\n if \"?\" in request:\n raise InvalidRequest()\n all_endpoints = self.config.endpoints()\n match_str = \"%s %s\" % (method, request)\n matched_endpoints = set()\n # Note: fnmatch.filter seemed to be broken when trying to do exaclty this.\n for endpoint in all_endpoints:\n if fnmatch.fnmatch(match_str, endpoint):\n matched_endpoints.add(endpoint)\n return matched_endpoints","function_tokens":["def","match_endpoint","(","self",",","method",",","request",")",":","if","\"?\"","in","request",":","raise","InvalidRequest","(",")","all_endpoints","=","self",".","config",".","endpoints","(",")","match_str","=","\"%s %s\"","%","(","method",",","request",")","matched_endpoints","=","set","(",")","# Note: fnmatch.filter seemed to be broken when trying to do exaclty this.","for","endpoint","in","all_endpoints",":","if","fnmatch",".","fnmatch","(","match_str",",","endpoint",")",":","matched_endpoints",".","add","(","endpoint",")","return","matched_endpoints"],"url":"https:\/\/github.com\/ClusterHQ\/powerstrip\/blob\/b18dc7261b001720149849b8ed8f2a31880d76c1\/powerstrip\/_parser.py#L24-L49"}
9
+ {"nwo":"ClusterHQ\/powerstrip","sha":"b18dc7261b001720149849b8ed8f2a31880d76c1","path":"powerstrip\/_config.py","language":"python","identifier":"PluginConfiguration.__init__","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Initializes ``PluginConfiguration`` attributes.\n\n self._endpoints: A dict of Docker API endpoint expressions mapping to\n dicts ``pre`` and ``post`` adapter lists. Each adapter in the adapters\n references the ``_adapters`` attribute.\n\n self._adapters: A dict mapping adapter names to URIs.","docstring_summary":"Initializes ``PluginConfiguration`` attributes.","docstring_tokens":["Initializes","PluginConfiguration","attributes","."],"function":"def __init__(self):\n \"\"\"\n Initializes ``PluginConfiguration`` attributes.\n\n self._endpoints: A dict of Docker API endpoint expressions mapping to\n dicts ``pre`` and ``post`` adapter lists. Each adapter in the adapters\n references the ``_adapters`` attribute.\n\n self._adapters: A dict mapping adapter names to URIs.\n \"\"\"\n self._endpoints = {}\n self._adapters = {}","function_tokens":["def","__init__","(","self",")",":","self",".","_endpoints","=","{","}","self",".","_adapters","=","{","}"],"url":"https:\/\/github.com\/ClusterHQ\/powerstrip\/blob\/b18dc7261b001720149849b8ed8f2a31880d76c1\/powerstrip\/_config.py#L34-L45"}
10
+ {"nwo":"ClusterHQ\/powerstrip","sha":"b18dc7261b001720149849b8ed8f2a31880d76c1","path":"powerstrip\/_config.py","language":"python","identifier":"PluginConfiguration.read_and_parse","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Read and parse the adapter configuration.\n\n :raises: ``NoConfiguration`` if the configuration file was not found.\n\n :raises: ``InvalidConfiguration`` if the file was not valid configuration.","docstring_summary":"Read and parse the adapter configuration.","docstring_tokens":["Read","and","parse","the","adapter","configuration","."],"function":"def read_and_parse(self):\n \"\"\"\n Read and parse the adapter configuration.\n\n :raises: ``NoConfiguration`` if the configuration file was not found.\n\n :raises: ``InvalidConfiguration`` if the file was not valid configuration.\n \"\"\"\n self.__init__() # reset all attributes\n config_struct = self._read_from_yaml_file(None)\n self._parse_adapters(config_struct)","function_tokens":["def","read_and_parse","(","self",")",":","self",".","__init__","(",")","# reset all attributes","config_struct","=","self",".","_read_from_yaml_file","(","None",")","self",".","_parse_adapters","(","config_struct",")"],"url":"https:\/\/github.com\/ClusterHQ\/powerstrip\/blob\/b18dc7261b001720149849b8ed8f2a31880d76c1\/powerstrip\/_config.py#L47-L57"}
11
+ {"nwo":"ClusterHQ\/powerstrip","sha":"b18dc7261b001720149849b8ed8f2a31880d76c1","path":"powerstrip\/_config.py","language":"python","identifier":"PluginConfiguration._read_from_yaml_file","parameters":"(self, path)","argument_list":"","return_statement":"","docstring":"Read the adapter config YAML file and return the YAML datastructure.\n\n :param path: A ``FilePath`` representing the path to the YAML file, or\n self._default_file if None.\n\n :raises: ``NoConfiguration`` if the adapter file was not found.\n\n :raises: ``InvalidConfiguration`` if if the file was not valid YAML.","docstring_summary":"Read the adapter config YAML file and return the YAML datastructure.","docstring_tokens":["Read","the","adapter","config","YAML","file","and","return","the","YAML","datastructure","."],"function":"def _read_from_yaml_file(self, path):\n \"\"\"\n Read the adapter config YAML file and return the YAML datastructure.\n\n :param path: A ``FilePath`` representing the path to the YAML file, or\n self._default_file if None.\n\n :raises: ``NoConfiguration`` if the adapter file was not found.\n\n :raises: ``InvalidConfiguration`` if if the file was not valid YAML.\n \"\"\"\n if path is None:\n path = FilePath(self._default_file)\n try:\n content = path.getContent()\n except IOError:\n raise NoConfiguration(path.path)\n\n try:\n yaml = safe_load(content)\n return yaml\n except YAMLError:\n raise InvalidConfiguration()","function_tokens":["def","_read_from_yaml_file","(","self",",","path",")",":","if","path","is","None",":","path","=","FilePath","(","self",".","_default_file",")","try",":","content","=","path",".","getContent","(",")","except","IOError",":","raise","NoConfiguration","(","path",".","path",")","try",":","yaml","=","safe_load","(","content",")","return","yaml","except","YAMLError",":","raise","InvalidConfiguration","(",")"],"url":"https:\/\/github.com\/ClusterHQ\/powerstrip\/blob\/b18dc7261b001720149849b8ed8f2a31880d76c1\/powerstrip\/_config.py#L59-L81"}
12
+ {"nwo":"ClusterHQ\/powerstrip","sha":"b18dc7261b001720149849b8ed8f2a31880d76c1","path":"powerstrip\/_config.py","language":"python","identifier":"PluginConfiguration._parse_adapters","parameters":"(self, datastructure)","argument_list":"","return_statement":"","docstring":"Take the decoded YAML configuration and store it as usable\n datastructures. See ``self.__init__``.\n\n :raises: ``InvalidConfiguration`` if the configuration is invalid.","docstring_summary":"Take the decoded YAML configuration and store it as usable\n datastructures. See ``self.__init__``.","docstring_tokens":["Take","the","decoded","YAML","configuration","and","store","it","as","usable","datastructures",".","See","self",".","__init__","."],"function":"def _parse_adapters(self, datastructure):\n \"\"\"\n Take the decoded YAML configuration and store it as usable\n datastructures. See ``self.__init__``.\n\n :raises: ``InvalidConfiguration`` if the configuration is invalid.\n \"\"\"\n try:\n self._endpoints = datastructure[\"endpoints\"]\n except KeyError:\n raise InvalidConfiguration(\"Required key 'endpoints' is missing.\")\n except TypeError:\n raise InvalidConfiguration(\"Could not parse adapters file.\")\n try:\n self._adapters = datastructure[\"adapters\"]\n except KeyError:\n raise InvalidConfiguration(\"Required key 'adapters' is missing.\")\n\n # Sanity check that all referenced adapters exist and that optional pre\n # and post keys are added, with no unknown keys\n known_adapters = self.adapters()\n referenced_adapters = set()\n for endpoint, config in self._endpoints.iteritems():\n config_keys = set(config.keys())\n if not config_keys:\n raise InvalidConfiguration(\n \"No configuration found for endpoint '%s'\" % (endpoint,))\n\n unknown_keys = config_keys - set([\"pre\", \"post\"])\n if unknown_keys:\n raise InvalidConfiguration(\n \"Unkonwn keys found in endpoint configuration: %s\" %\n (\", \".join(unknown_keys)))\n\n if \"pre\" not in config:\n config['pre'] = []\n if \"post\" not in config:\n config['post'] = []\n\n referenced_adapters.update(config['pre'])\n referenced_adapters.update(config['post'])\n\n unkown_adapters = referenced_adapters - known_adapters\n if unkown_adapters:\n raise InvalidConfiguration(\n \"Plugins were referenced in endpoint configuration but not \"\n \"defined: %s\" % (\", \".join(unkown_adapters)))","function_tokens":["def","_parse_adapters","(","self",",","datastructure",")",":","try",":","self",".","_endpoints","=","datastructure","[","\"endpoints\"","]","except","KeyError",":","raise","InvalidConfiguration","(","\"Required key 'endpoints' is missing.\"",")","except","TypeError",":","raise","InvalidConfiguration","(","\"Could not parse adapters file.\"",")","try",":","self",".","_adapters","=","datastructure","[","\"adapters\"","]","except","KeyError",":","raise","InvalidConfiguration","(","\"Required key 'adapters' is missing.\"",")","# Sanity check that all referenced adapters exist and that optional pre","# and post keys are added, with no unknown keys","known_adapters","=","self",".","adapters","(",")","referenced_adapters","=","set","(",")","for","endpoint",",","config","in","self",".","_endpoints",".","iteritems","(",")",":","config_keys","=","set","(","config",".","keys","(",")",")","if","not","config_keys",":","raise","InvalidConfiguration","(","\"No configuration found for endpoint '%s'\"","%","(","endpoint",",",")",")","unknown_keys","=","config_keys","-","set","(","[","\"pre\"",",","\"post\"","]",")","if","unknown_keys",":","raise","InvalidConfiguration","(","\"Unkonwn keys found in endpoint configuration: %s\"","%","(","\", \"",".","join","(","unknown_keys",")",")",")","if","\"pre\"","not","in","config",":","config","[","'pre'","]","=","[","]","if","\"post\"","not","in","config",":","config","[","'post'","]","=","[","]","referenced_adapters",".","update","(","config","[","'pre'","]",")","referenced_adapters",".","update","(","config","[","'post'","]",")","unkown_adapters","=","referenced_adapters","-","known_adapters","if","unkown_adapters",":","raise","InvalidConfiguration","(","\"Plugins were referenced in endpoint configuration but not \"","\"defined: %s\"","%","(","\", \"",".","join","(","unkown_adapters",")",")",")"],"url":"https:\/\/github.com\/ClusterHQ\/powerstrip\/blob\/b18dc7261b001720149849b8ed8f2a31880d76c1\/powerstrip\/_config.py#L83-L129"}
13
+ {"nwo":"ClusterHQ\/powerstrip","sha":"b18dc7261b001720149849b8ed8f2a31880d76c1","path":"powerstrip\/_config.py","language":"python","identifier":"PluginConfiguration.endpoints","parameters":"(self)","argument_list":"","return_statement":"return set(self._endpoints.keys())","docstring":"Return a ``set`` of endpoint expressions.","docstring_summary":"Return a ``set`` of endpoint expressions.","docstring_tokens":["Return","a","set","of","endpoint","expressions","."],"function":"def endpoints(self):\n \"\"\"\n Return a ``set`` of endpoint expressions.\n \"\"\"\n return set(self._endpoints.keys())","function_tokens":["def","endpoints","(","self",")",":","return","set","(","self",".","_endpoints",".","keys","(",")",")"],"url":"https:\/\/github.com\/ClusterHQ\/powerstrip\/blob\/b18dc7261b001720149849b8ed8f2a31880d76c1\/powerstrip\/_config.py#L131-L135"}
14
+ {"nwo":"ClusterHQ\/powerstrip","sha":"b18dc7261b001720149849b8ed8f2a31880d76c1","path":"powerstrip\/_config.py","language":"python","identifier":"PluginConfiguration.endpoint","parameters":"(self, endpoint)","argument_list":"","return_statement":"return EndpointConfiguration(**self._endpoints[endpoint])","docstring":"Return the adapter configuration for the endpoint expression returned by\n ``self.endpoints``. This is an ``EndpointConfiguration` object with attrbutes\n ``pre`` and ``post``. These attributes are lists of adapter names.\n\n :raises: `KeyError` if the endpoint expression was not found.","docstring_summary":"Return the adapter configuration for the endpoint expression returned by\n ``self.endpoints``. This is an ``EndpointConfiguration` object with attrbutes\n ``pre`` and ``post``. These attributes are lists of adapter names.","docstring_tokens":["Return","the","adapter","configuration","for","the","endpoint","expression","returned","by","self",".","endpoints",".","This","is","an","EndpointConfiguration","object","with","attrbutes","pre","and","post",".","These","attributes","are","lists","of","adapter","names","."],"function":"def endpoint(self, endpoint):\n \"\"\"\n Return the adapter configuration for the endpoint expression returned by\n ``self.endpoints``. This is an ``EndpointConfiguration` object with attrbutes\n ``pre`` and ``post``. These attributes are lists of adapter names.\n\n :raises: `KeyError` if the endpoint expression was not found.\n \"\"\"\n return EndpointConfiguration(**self._endpoints[endpoint])","function_tokens":["def","endpoint","(","self",",","endpoint",")",":","return","EndpointConfiguration","(","*","*","self",".","_endpoints","[","endpoint","]",")"],"url":"https:\/\/github.com\/ClusterHQ\/powerstrip\/blob\/b18dc7261b001720149849b8ed8f2a31880d76c1\/powerstrip\/_config.py#L137-L145"}
15
+ {"nwo":"ClusterHQ\/powerstrip","sha":"b18dc7261b001720149849b8ed8f2a31880d76c1","path":"powerstrip\/_config.py","language":"python","identifier":"PluginConfiguration.adapters","parameters":"(self)","argument_list":"","return_statement":"return set(self._adapters.keys())","docstring":"Return a ``set`` of known adapters.","docstring_summary":"Return a ``set`` of known adapters.","docstring_tokens":["Return","a","set","of","known","adapters","."],"function":"def adapters(self):\n \"\"\"\n Return a ``set`` of known adapters.\n \"\"\"\n return set(self._adapters.keys())","function_tokens":["def","adapters","(","self",")",":","return","set","(","self",".","_adapters",".","keys","(",")",")"],"url":"https:\/\/github.com\/ClusterHQ\/powerstrip\/blob\/b18dc7261b001720149849b8ed8f2a31880d76c1\/powerstrip\/_config.py#L147-L151"}
16
+ {"nwo":"ClusterHQ\/powerstrip","sha":"b18dc7261b001720149849b8ed8f2a31880d76c1","path":"powerstrip\/_config.py","language":"python","identifier":"PluginConfiguration.adapter_uri","parameters":"(self, adapter)","argument_list":"","return_statement":"return self._adapters[adapter]","docstring":"Return the URI for a adapter.\n\n :param ``adapter``: The the desired adapter.\n\n :raises: `KeyError` if the adapter was not found.","docstring_summary":"Return the URI for a adapter.","docstring_tokens":["Return","the","URI","for","a","adapter","."],"function":"def adapter_uri(self, adapter):\n \"\"\"\n Return the URI for a adapter.\n\n :param ``adapter``: The the desired adapter.\n\n :raises: `KeyError` if the adapter was not found.\n \"\"\"\n return self._adapters[adapter]","function_tokens":["def","adapter_uri","(","self",",","adapter",")",":","return","self",".","_adapters","[","adapter","]"],"url":"https:\/\/github.com\/ClusterHQ\/powerstrip\/blob\/b18dc7261b001720149849b8ed8f2a31880d76c1\/powerstrip\/_config.py#L153-L161"}
CoinCheung__BiSeNet.jsonl ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ {"nwo":"CoinCheung\/BiSeNet","sha":"f9231b7c971413e6ebdfcd961fbea53417b18851","path":"lib\/models\/resnet.py","language":"python","identifier":"conv3x3","parameters":"(in_planes, out_planes, stride=1)","argument_list":"","return_statement":"return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,\n padding=1, bias=False)","docstring":"3x3 convolution with padding","docstring_summary":"3x3 convolution with padding","docstring_tokens":["3x3","convolution","with","padding"],"function":"def conv3x3(in_planes, out_planes, stride=1):\n \"\"\"3x3 convolution with padding\"\"\"\n return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,\n padding=1, bias=False)","function_tokens":["def","conv3x3","(","in_planes",",","out_planes",",","stride","=","1",")",":","return","nn",".","Conv2d","(","in_planes",",","out_planes",",","kernel_size","=","3",",","stride","=","stride",",","padding","=","1",",","bias","=","False",")"],"url":"https:\/\/github.com\/CoinCheung\/BiSeNet\/blob\/f9231b7c971413e6ebdfcd961fbea53417b18851\/lib\/models\/resnet.py#L14-L17"}
2
+ {"nwo":"CoinCheung\/BiSeNet","sha":"f9231b7c971413e6ebdfcd961fbea53417b18851","path":"old\/resnet.py","language":"python","identifier":"conv3x3","parameters":"(in_planes, out_planes, stride=1)","argument_list":"","return_statement":"return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,\n padding=1, bias=False)","docstring":"3x3 convolution with padding","docstring_summary":"3x3 convolution with padding","docstring_tokens":["3x3","convolution","with","padding"],"function":"def conv3x3(in_planes, out_planes, stride=1):\n \"\"\"3x3 convolution with padding\"\"\"\n return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,\n padding=1, bias=False)","function_tokens":["def","conv3x3","(","in_planes",",","out_planes",",","stride","=","1",")",":","return","nn",".","Conv2d","(","in_planes",",","out_planes",",","kernel_size","=","3",",","stride","=","stride",",","padding","=","1",",","bias","=","False",")"],"url":"https:\/\/github.com\/CoinCheung\/BiSeNet\/blob\/f9231b7c971413e6ebdfcd961fbea53417b18851\/old\/resnet.py#L14-L17"}
3
+ {"nwo":"CoinCheung\/BiSeNet","sha":"f9231b7c971413e6ebdfcd961fbea53417b18851","path":"old\/modules\/bn.py","language":"python","identifier":"ABN.__init__","parameters":"(self, num_features, eps=1e-5, momentum=0.1, affine=True, activation=\"leaky_relu\", slope=0.01)","argument_list":"","return_statement":"","docstring":"Creates an Activated Batch Normalization module\n\n Parameters\n ----------\n num_features : int\n Number of feature channels in the input and output.\n eps : float\n Small constant to prevent numerical issues.\n momentum : float\n Momentum factor applied to compute running statistics as.\n affine : bool\n If `True` apply learned scale and shift transformation after normalization.\n activation : str\n Name of the activation functions, one of: `leaky_relu`, `elu` or `none`.\n slope : float\n Negative slope for the `leaky_relu` activation.","docstring_summary":"Creates an Activated Batch Normalization module","docstring_tokens":["Creates","an","Activated","Batch","Normalization","module"],"function":"def __init__(self, num_features, eps=1e-5, momentum=0.1, affine=True, activation=\"leaky_relu\", slope=0.01):\n \"\"\"Creates an Activated Batch Normalization module\n\n Parameters\n ----------\n num_features : int\n Number of feature channels in the input and output.\n eps : float\n Small constant to prevent numerical issues.\n momentum : float\n Momentum factor applied to compute running statistics as.\n affine : bool\n If `True` apply learned scale and shift transformation after normalization.\n activation : str\n Name of the activation functions, one of: `leaky_relu`, `elu` or `none`.\n slope : float\n Negative slope for the `leaky_relu` activation.\n \"\"\"\n super(ABN, self).__init__()\n self.num_features = num_features\n self.affine = affine\n self.eps = eps\n self.momentum = momentum\n self.activation = activation\n self.slope = slope\n if self.affine:\n self.weight = nn.Parameter(torch.ones(num_features))\n self.bias = nn.Parameter(torch.zeros(num_features))\n else:\n self.register_parameter('weight', None)\n self.register_parameter('bias', None)\n self.register_buffer('running_mean', torch.zeros(num_features))\n self.register_buffer('running_var', torch.ones(num_features))\n self.reset_parameters()","function_tokens":["def","__init__","(","self",",","num_features",",","eps","=","1e-5",",","momentum","=","0.1",",","affine","=","True",",","activation","=","\"leaky_relu\"",",","slope","=","0.01",")",":","super","(","ABN",",","self",")",".","__init__","(",")","self",".","num_features","=","num_features","self",".","affine","=","affine","self",".","eps","=","eps","self",".","momentum","=","momentum","self",".","activation","=","activation","self",".","slope","=","slope","if","self",".","affine",":","self",".","weight","=","nn",".","Parameter","(","torch",".","ones","(","num_features",")",")","self",".","bias","=","nn",".","Parameter","(","torch",".","zeros","(","num_features",")",")","else",":","self",".","register_parameter","(","'weight'",",","None",")","self",".","register_parameter","(","'bias'",",","None",")","self",".","register_buffer","(","'running_mean'",",","torch",".","zeros","(","num_features",")",")","self",".","register_buffer","(","'running_var'",",","torch",".","ones","(","num_features",")",")","self",".","reset_parameters","(",")"],"url":"https:\/\/github.com\/CoinCheung\/BiSeNet\/blob\/f9231b7c971413e6ebdfcd961fbea53417b18851\/old\/modules\/bn.py#L19-L52"}
4
+ {"nwo":"CoinCheung\/BiSeNet","sha":"f9231b7c971413e6ebdfcd961fbea53417b18851","path":"old\/modules\/bn.py","language":"python","identifier":"InPlaceABN.__init__","parameters":"(self, num_features, eps=1e-5, momentum=0.1, affine=True, activation=\"leaky_relu\", slope=0.01)","argument_list":"","return_statement":"","docstring":"Creates an InPlace Activated Batch Normalization module\n\n Parameters\n ----------\n num_features : int\n Number of feature channels in the input and output.\n eps : float\n Small constant to prevent numerical issues.\n momentum : float\n Momentum factor applied to compute running statistics as.\n affine : bool\n If `True` apply learned scale and shift transformation after normalization.\n activation : str\n Name of the activation functions, one of: `leaky_relu`, `elu` or `none`.\n slope : float\n Negative slope for the `leaky_relu` activation.","docstring_summary":"Creates an InPlace Activated Batch Normalization module","docstring_tokens":["Creates","an","InPlace","Activated","Batch","Normalization","module"],"function":"def __init__(self, num_features, eps=1e-5, momentum=0.1, affine=True, activation=\"leaky_relu\", slope=0.01):\n \"\"\"Creates an InPlace Activated Batch Normalization module\n\n Parameters\n ----------\n num_features : int\n Number of feature channels in the input and output.\n eps : float\n Small constant to prevent numerical issues.\n momentum : float\n Momentum factor applied to compute running statistics as.\n affine : bool\n If `True` apply learned scale and shift transformation after normalization.\n activation : str\n Name of the activation functions, one of: `leaky_relu`, `elu` or `none`.\n slope : float\n Negative slope for the `leaky_relu` activation.\n \"\"\"\n super(InPlaceABN, self).__init__(num_features, eps, momentum, affine, activation, slope)","function_tokens":["def","__init__","(","self",",","num_features",",","eps","=","1e-5",",","momentum","=","0.1",",","affine","=","True",",","activation","=","\"leaky_relu\"",",","slope","=","0.01",")",":","super","(","InPlaceABN",",","self",")",".","__init__","(","num_features",",","eps",",","momentum",",","affine",",","activation",",","slope",")"],"url":"https:\/\/github.com\/CoinCheung\/BiSeNet\/blob\/f9231b7c971413e6ebdfcd961fbea53417b18851\/old\/modules\/bn.py#L87-L105"}
5
+ {"nwo":"CoinCheung\/BiSeNet","sha":"f9231b7c971413e6ebdfcd961fbea53417b18851","path":"old\/modules\/residual.py","language":"python","identifier":"IdentityResidualBlock.__init__","parameters":"(self,\n in_channels,\n channels,\n stride=1,\n dilation=1,\n groups=1,\n norm_act=ABN,\n dropout=None)","argument_list":"","return_statement":"","docstring":"Configurable identity-mapping residual block\n\n Parameters\n ----------\n in_channels : int\n Number of input channels.\n channels : list of int\n Number of channels in the internal feature maps. Can either have two or three elements: if three construct\n a residual block with two `3 x 3` convolutions, otherwise construct a bottleneck block with `1 x 1`, then\n `3 x 3` then `1 x 1` convolutions.\n stride : int\n Stride of the first `3 x 3` convolution\n dilation : int\n Dilation to apply to the `3 x 3` convolutions.\n groups : int\n Number of convolution groups. This is used to create ResNeXt-style blocks and is only compatible with\n bottleneck blocks.\n norm_act : callable\n Function to create normalization \/ activation Module.\n dropout: callable\n Function to create Dropout Module.","docstring_summary":"Configurable identity-mapping residual block","docstring_tokens":["Configurable","identity","-","mapping","residual","block"],"function":"def __init__(self,\n in_channels,\n channels,\n stride=1,\n dilation=1,\n groups=1,\n norm_act=ABN,\n dropout=None):\n \"\"\"Configurable identity-mapping residual block\n\n Parameters\n ----------\n in_channels : int\n Number of input channels.\n channels : list of int\n Number of channels in the internal feature maps. Can either have two or three elements: if three construct\n a residual block with two `3 x 3` convolutions, otherwise construct a bottleneck block with `1 x 1`, then\n `3 x 3` then `1 x 1` convolutions.\n stride : int\n Stride of the first `3 x 3` convolution\n dilation : int\n Dilation to apply to the `3 x 3` convolutions.\n groups : int\n Number of convolution groups. This is used to create ResNeXt-style blocks and is only compatible with\n bottleneck blocks.\n norm_act : callable\n Function to create normalization \/ activation Module.\n dropout: callable\n Function to create Dropout Module.\n \"\"\"\n super(IdentityResidualBlock, self).__init__()\n\n # Check parameters for inconsistencies\n if len(channels) != 2 and len(channels) != 3:\n raise ValueError(\"channels must contain either two or three values\")\n if len(channels) == 2 and groups != 1:\n raise ValueError(\"groups > 1 are only valid if len(channels) == 3\")\n\n is_bottleneck = len(channels) == 3\n need_proj_conv = stride != 1 or in_channels != channels[-1]\n\n self.bn1 = norm_act(in_channels)\n if not is_bottleneck:\n layers = [\n (\"conv1\", nn.Conv2d(in_channels, channels[0], 3, stride=stride, padding=dilation, bias=False,\n dilation=dilation)),\n (\"bn2\", norm_act(channels[0])),\n (\"conv2\", nn.Conv2d(channels[0], channels[1], 3, stride=1, padding=dilation, bias=False,\n dilation=dilation))\n ]\n if dropout is not None:\n layers = layers[0:2] + [(\"dropout\", dropout())] + layers[2:]\n else:\n layers = [\n (\"conv1\", nn.Conv2d(in_channels, channels[0], 1, stride=stride, padding=0, bias=False)),\n (\"bn2\", norm_act(channels[0])),\n (\"conv2\", nn.Conv2d(channels[0], channels[1], 3, stride=1, padding=dilation, bias=False,\n groups=groups, dilation=dilation)),\n (\"bn3\", norm_act(channels[1])),\n (\"conv3\", nn.Conv2d(channels[1], channels[2], 1, stride=1, padding=0, bias=False))\n ]\n if dropout is not None:\n layers = layers[0:4] + [(\"dropout\", dropout())] + layers[4:]\n self.convs = nn.Sequential(OrderedDict(layers))\n\n if need_proj_conv:\n self.proj_conv = nn.Conv2d(in_channels, channels[-1], 1, stride=stride, padding=0, bias=False)","function_tokens":["def","__init__","(","self",",","in_channels",",","channels",",","stride","=","1",",","dilation","=","1",",","groups","=","1",",","norm_act","=","ABN",",","dropout","=","None",")",":","super","(","IdentityResidualBlock",",","self",")",".","__init__","(",")","# Check parameters for inconsistencies","if","len","(","channels",")","!=","2","and","len","(","channels",")","!=","3",":","raise","ValueError","(","\"channels must contain either two or three values\"",")","if","len","(","channels",")","==","2","and","groups","!=","1",":","raise","ValueError","(","\"groups > 1 are only valid if len(channels) == 3\"",")","is_bottleneck","=","len","(","channels",")","==","3","need_proj_conv","=","stride","!=","1","or","in_channels","!=","channels","[","-","1","]","self",".","bn1","=","norm_act","(","in_channels",")","if","not","is_bottleneck",":","layers","=","[","(","\"conv1\"",",","nn",".","Conv2d","(","in_channels",",","channels","[","0","]",",","3",",","stride","=","stride",",","padding","=","dilation",",","bias","=","False",",","dilation","=","dilation",")",")",",","(","\"bn2\"",",","norm_act","(","channels","[","0","]",")",")",",","(","\"conv2\"",",","nn",".","Conv2d","(","channels","[","0","]",",","channels","[","1","]",",","3",",","stride","=","1",",","padding","=","dilation",",","bias","=","False",",","dilation","=","dilation",")",")","]","if","dropout","is","not","None",":","layers","=","layers","[","0",":","2","]","+","[","(","\"dropout\"",",","dropout","(",")",")","]","+","layers","[","2",":","]","else",":","layers","=","[","(","\"conv1\"",",","nn",".","Conv2d","(","in_channels",",","channels","[","0","]",",","1",",","stride","=","stride",",","padding","=","0",",","bias","=","False",")",")",",","(","\"bn2\"",",","norm_act","(","channels","[","0","]",")",")",",","(","\"conv2\"",",","nn",".","Conv2d","(","channels","[","0","]",",","channels","[","1","]",",","3",",","stride","=","1",",","padding","=","dilation",",","bias","=","False",",","groups","=","groups",",","dilation","=","dilation",")",")",",","(","\"bn3\"",",","norm_act","(","channels","[","1","]",")",")",",","(","\"conv3\"",",","nn",".","Conv2d","(","channels","[","1","]",",","channels","[","2","]",",","1",",","stride","=","1",",","padding","=","0",",","bias","=","False",")",")","]","if","dropout","is","not","None",":","layers","=","layers","[","0",":","4","]","+","[","(","\"dropout\"",",","dropout","(",")",")","]","+","layers","[","4",":","]","self",".","convs","=","nn",".","Sequential","(","OrderedDict","(","layers",")",")","if","need_proj_conv",":","self",".","proj_conv","=","nn",".","Conv2d","(","in_channels",",","channels","[","-","1","]",",","1",",","stride","=","stride",",","padding","=","0",",","bias","=","False",")"],"url":"https:\/\/github.com\/CoinCheung\/BiSeNet\/blob\/f9231b7c971413e6ebdfcd961fbea53417b18851\/old\/modules\/residual.py#L9-L75"}
6
+ {"nwo":"CoinCheung\/BiSeNet","sha":"f9231b7c971413e6ebdfcd961fbea53417b18851","path":"old\/modules\/misc.py","language":"python","identifier":"GlobalAvgPool2d.__init__","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Global average pooling over the input's spatial dimensions","docstring_summary":"Global average pooling over the input's spatial dimensions","docstring_tokens":["Global","average","pooling","over","the","input","s","spatial","dimensions"],"function":"def __init__(self):\n \"\"\"Global average pooling over the input's spatial dimensions\"\"\"\n super(GlobalAvgPool2d, self).__init__()","function_tokens":["def","__init__","(","self",")",":","super","(","GlobalAvgPool2d",",","self",")",".","__init__","(",")"],"url":"https:\/\/github.com\/CoinCheung\/BiSeNet\/blob\/f9231b7c971413e6ebdfcd961fbea53417b18851\/old\/modules\/misc.py#L6-L8"}
7
+ {"nwo":"CoinCheung\/BiSeNet","sha":"f9231b7c971413e6ebdfcd961fbea53417b18851","path":"old\/fp16\/resnet.py","language":"python","identifier":"conv3x3","parameters":"(in_planes, out_planes, stride=1)","argument_list":"","return_statement":"return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,\n padding=1, bias=False)","docstring":"3x3 convolution with padding","docstring_summary":"3x3 convolution with padding","docstring_tokens":["3x3","convolution","with","padding"],"function":"def conv3x3(in_planes, out_planes, stride=1):\n \"\"\"3x3 convolution with padding\"\"\"\n return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,\n padding=1, bias=False)","function_tokens":["def","conv3x3","(","in_planes",",","out_planes",",","stride","=","1",")",":","return","nn",".","Conv2d","(","in_planes",",","out_planes",",","kernel_size","=","3",",","stride","=","stride",",","padding","=","1",",","bias","=","False",")"],"url":"https:\/\/github.com\/CoinCheung\/BiSeNet\/blob\/f9231b7c971413e6ebdfcd961fbea53417b18851\/old\/fp16\/resnet.py#L16-L19"}
8
+ {"nwo":"CoinCheung\/BiSeNet","sha":"f9231b7c971413e6ebdfcd961fbea53417b18851","path":"tools\/gen_coco_annos.py","language":"python","identifier":"gen_coco","parameters":"()","argument_list":"","return_statement":"","docstring":"root_path:\n |- images\n |- train2017\n |- val2017\n |- labels\n |- train2017\n |- val2017","docstring_summary":"root_path:\n |- images\n |- train2017\n |- val2017\n |- labels\n |- train2017\n |- val2017","docstring_tokens":["root_path",":","|","-","images","|","-","train2017","|","-","val2017","|","-","labels","|","-","train2017","|","-","val2017"],"function":"def gen_coco():\n '''\n root_path:\n |- images\n |- train2017\n |- val2017\n |- labels\n |- train2017\n |- val2017\n '''\n root_path = '.\/datasets\/coco'\n save_path = '.\/datasets\/coco\/'\n for mode in ('train', 'val'):\n im_root = osp.join(root_path, f'images\/{mode}2017')\n lb_root = osp.join(root_path, f'labels\/{mode}2017')\n\n ims = os.listdir(im_root)\n lbs = os.listdir(lb_root)\n\n print(len(ims))\n print(len(lbs))\n\n im_names = [el.replace('.jpg', '') for el in ims]\n lb_names = [el.replace('.png', '') for el in lbs]\n common_names = list(set(im_names) & set(lb_names))\n\n lines = [\n f'images\/{mode}2017\/{name}.jpg,labels\/{mode}2017\/{name}.png'\n for name in common_names\n ]\n\n with open(f'{save_path}\/{mode}.txt', 'w') as fw:\n fw.write('\\n'.join(lines))","function_tokens":["def","gen_coco","(",")",":","root_path","=","'.\/datasets\/coco'","save_path","=","'.\/datasets\/coco\/'","for","mode","in","(","'train'",",","'val'",")",":","im_root","=","osp",".","join","(","root_path",",","f'images\/{mode}2017'",")","lb_root","=","osp",".","join","(","root_path",",","f'labels\/{mode}2017'",")","ims","=","os",".","listdir","(","im_root",")","lbs","=","os",".","listdir","(","lb_root",")","print","(","len","(","ims",")",")","print","(","len","(","lbs",")",")","im_names","=","[","el",".","replace","(","'.jpg'",",","''",")","for","el","in","ims","]","lb_names","=","[","el",".","replace","(","'.png'",",","''",")","for","el","in","lbs","]","common_names","=","list","(","set","(","im_names",")","&","set","(","lb_names",")",")","lines","=","[","f'images\/{mode}2017\/{name}.jpg,labels\/{mode}2017\/{name}.png'","for","name","in","common_names","]","with","open","(","f'{save_path}\/{mode}.txt'",",","'w'",")","as","fw",":","fw",".","write","(","'\\n'",".","join","(","lines",")",")"],"url":"https:\/\/github.com\/CoinCheung\/BiSeNet\/blob\/f9231b7c971413e6ebdfcd961fbea53417b18851\/tools\/gen_coco_annos.py#L6-L38"}
Critical-Start__pastebin_scraper.jsonl ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {"nwo":"Critical-Start\/pastebin_scraper","sha":"196270249b0706bbeaf27fc2df379e4a2bb9fb5e","path":"pastebin_scraper.py","language":"python","identifier":"monitor","parameters":"()","argument_list":"","return_statement":"","docstring":"monitor() - Main function... creates and starts threads","docstring_summary":"monitor() - Main function... creates and starts threads","docstring_tokens":["monitor","()","-","Main","function","...","creates","and","starts","threads"],"function":"def monitor():\n '''\n monitor() - Main function... creates and starts threads\n\n '''\n import argparse\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-v\", \"--verbose\", help=\"more verbose\", action=\"store_true\")\n args = parser.parse_args()\n level = logging.INFO\n if args.verbose:\n level = logging.DEBUG\n #logging to both stdout and file\n file_handler = logging.FileHandler(log_file)\n handlers = [file_handler]\n if PRINT_LOG:\n stdout_handler = logging.StreamHandler(sys.stdout)\n handlers.append(stdout_handler)\n logging.basicConfig(\n level=level,\n format='%(asctime)s [%(levelname)s] %(message)s',\n handlers=handlers\n )\n logging.info('Monitoring...')\n paste_lock = threading.Lock()\n\n pastebin_thread = threading.Thread(target=Pastebin().monitor, args=[paste_lock])\n\n # changed threading to not be in a for loop\n # we're only monitoring one site now - Moe\n pastebin_thread.daemon = True\n pastebin_thread.start()\n\n # Let threads run\n try:\n while(1):\n sleep(5)\n except KeyboardInterrupt:\n logging.warning('Stopped.')","function_tokens":["def","monitor","(",")",":","import","argparse","parser","=","argparse",".","ArgumentParser","(",")","parser",".","add_argument","(","\"-v\"",",","\"--verbose\"",",","help","=","\"more verbose\"",",","action","=","\"store_true\"",")","args","=","parser",".","parse_args","(",")","level","=","logging",".","INFO","if","args",".","verbose",":","level","=","logging",".","DEBUG","#logging to both stdout and file","file_handler","=","logging",".","FileHandler","(","log_file",")","handlers","=","[","file_handler","]","if","PRINT_LOG",":","stdout_handler","=","logging",".","StreamHandler","(","sys",".","stdout",")","handlers",".","append","(","stdout_handler",")","logging",".","basicConfig","(","level","=","level",",","format","=","'%(asctime)s [%(levelname)s] %(message)s'",",","handlers","=","handlers",")","logging",".","info","(","'Monitoring...'",")","paste_lock","=","threading",".","Lock","(",")","pastebin_thread","=","threading",".","Thread","(","target","=","Pastebin","(",")",".","monitor",",","args","=","[","paste_lock","]",")","# changed threading to not be in a for loop","# we're only monitoring one site now - Moe","pastebin_thread",".","daemon","=","True","pastebin_thread",".","start","(",")","# Let threads run","try",":","while","(","1",")",":","sleep","(","5",")","except","KeyboardInterrupt",":","logging",".","warning","(","'Stopped.'",")"],"url":"https:\/\/github.com\/Critical-Start\/pastebin_scraper\/blob\/196270249b0706bbeaf27fc2df379e4a2bb9fb5e\/pastebin_scraper.py#L17-L55"}
2
+ {"nwo":"Critical-Start\/pastebin_scraper","sha":"196270249b0706bbeaf27fc2df379e4a2bb9fb5e","path":"lib\/Paste.py","language":"python","identifier":"Paste.__init__","parameters":"(self)","argument_list":"","return_statement":"","docstring":"class Paste: Generic \"Paste\" object to contain attributes of a standard paste","docstring_summary":"class Paste: Generic \"Paste\" object to contain attributes of a standard paste","docstring_tokens":["class","Paste",":","Generic","Paste","object","to","contain","attributes","of","a","standard","paste"],"function":"def __init__(self):\n '''\n class Paste: Generic \"Paste\" object to contain attributes of a standard paste\n\n '''\n self.emails = 0\n self.hashes = 0\n self.num_emails = 0\n self.num_hashes = 0\n self.text = None\n self.type = None\n self.sites = None\n self.db_keywords = 0.0\n self.author = None","function_tokens":["def","__init__","(","self",")",":","self",".","emails","=","0","self",".","hashes","=","0","self",".","num_emails","=","0","self",".","num_hashes","=","0","self",".","text","=","None","self",".","type","=","None","self",".","sites","=","None","self",".","db_keywords","=","0.0","self",".","author","=","None"],"url":"https:\/\/github.com\/Critical-Start\/pastebin_scraper\/blob\/196270249b0706bbeaf27fc2df379e4a2bb9fb5e\/lib\/Paste.py#L7-L20"}
3
+ {"nwo":"Critical-Start\/pastebin_scraper","sha":"196270249b0706bbeaf27fc2df379e4a2bb9fb5e","path":"lib\/Paste.py","language":"python","identifier":"Paste.match","parameters":"(self)","argument_list":"","return_statement":"return self.type","docstring":"Matches the paste against a series of regular expressions to determine if the paste is 'interesting'\n\n Sets the following attributes:\n self.emails\n self.hashes\n self.num_emails\n self.num_hashes\n self.db_keywords\n self.type","docstring_summary":"Matches the paste against a series of regular expressions to determine if the paste is 'interesting'","docstring_tokens":["Matches","the","paste","against","a","series","of","regular","expressions","to","determine","if","the","paste","is","interesting"],"function":"def match(self):\n '''\n Matches the paste against a series of regular expressions to determine if the paste is 'interesting'\n\n Sets the following attributes:\n self.emails\n self.hashes\n self.num_emails\n self.num_hashes\n self.db_keywords\n self.type\n\n '''\n # Get the amount of emails\n self.emails = list(set(regexes['email'].findall(self.text)))\n self.hashes = regexes['hash32'].findall(self.text) #might identify multiple types of hashes\n self.num_emails = len(self.emails)\n self.num_hashes = len(self.hashes)\n if self.num_emails > 0:\n self.sites = list(set([re.search('@(.*)$', email).group(1).lower() for email in self.emails]))\n for regex in regexes['db_keywords']:\n if regex.search(self.text):\n logging.debug('\\t[+] ' + regex.search(self.text).group(1))\n self.db_keywords += round(1\/float(len(regexes['db_keywords'])), 2)\n for regex in regexes['blacklist']:\n if regex.search(self.text):\n logging.debug('\\t[-] ' + regex.search(self.text).group(1))\n self.db_keywords -= round(1.25 * (1\/float(len(regexes['db_keywords']))), 2)\n if (self.num_emails >= settings.EMAIL_THRESHOLD) or (self.num_hashes >= settings.HASH_THRESHOLD) or (self.db_keywords >= settings.DB_KEYWORDS_THRESHOLD):\n self.type = 'db_dump'\n if regexes['cisco_hash'].search(self.text) or regexes['cisco_pass'].search(self.text):\n self.type = 'cisco'\n if regexes['honeypot'].search(self.text):\n self.type = 'honeypot'\n if regexes['google_api'].search(self.text):\n self.type = 'google_api'\n if regexes['pgp_private'].search(self.text):\n self.type = 'pgp_private'\n if regexes['ssh_private'].search(self.text):\n self.type = 'ssh_private'\n for regex in regexes['banlist']:\n if regex.search(self.text):\n self.type = None\n break\n return self.type","function_tokens":["def","match","(","self",")",":","# Get the amount of emails","self",".","emails","=","list","(","set","(","regexes","[","'email'","]",".","findall","(","self",".","text",")",")",")","self",".","hashes","=","regexes","[","'hash32'","]",".","findall","(","self",".","text",")","#might identify multiple types of hashes","self",".","num_emails","=","len","(","self",".","emails",")","self",".","num_hashes","=","len","(","self",".","hashes",")","if","self",".","num_emails",">","0",":","self",".","sites","=","list","(","set","(","[","re",".","search","(","'@(.*)$'",",","email",")",".","group","(","1",")",".","lower","(",")","for","email","in","self",".","emails","]",")",")","for","regex","in","regexes","[","'db_keywords'","]",":","if","regex",".","search","(","self",".","text",")",":","logging",".","debug","(","'\\t[+] '","+","regex",".","search","(","self",".","text",")",".","group","(","1",")",")","self",".","db_keywords","+=","round","(","1","\/","float","(","len","(","regexes","[","'db_keywords'","]",")",")",",","2",")","for","regex","in","regexes","[","'blacklist'","]",":","if","regex",".","search","(","self",".","text",")",":","logging",".","debug","(","'\\t[-] '","+","regex",".","search","(","self",".","text",")",".","group","(","1",")",")","self",".","db_keywords","-=","round","(","1.25","*","(","1","\/","float","(","len","(","regexes","[","'db_keywords'","]",")",")",")",",","2",")","if","(","self",".","num_emails",">=","settings",".","EMAIL_THRESHOLD",")","or","(","self",".","num_hashes",">=","settings",".","HASH_THRESHOLD",")","or","(","self",".","db_keywords",">=","settings",".","DB_KEYWORDS_THRESHOLD",")",":","self",".","type","=","'db_dump'","if","regexes","[","'cisco_hash'","]",".","search","(","self",".","text",")","or","regexes","[","'cisco_pass'","]",".","search","(","self",".","text",")",":","self",".","type","=","'cisco'","if","regexes","[","'honeypot'","]",".","search","(","self",".","text",")",":","self",".","type","=","'honeypot'","if","regexes","[","'google_api'","]",".","search","(","self",".","text",")",":","self",".","type","=","'google_api'","if","regexes","[","'pgp_private'","]",".","search","(","self",".","text",")",":","self",".","type","=","'pgp_private'","if","regexes","[","'ssh_private'","]",".","search","(","self",".","text",")",":","self",".","type","=","'ssh_private'","for","regex","in","regexes","[","'banlist'","]",":","if","regex",".","search","(","self",".","text",")",":","self",".","type","=","None","break","return","self",".","type"],"url":"https:\/\/github.com\/Critical-Start\/pastebin_scraper\/blob\/196270249b0706bbeaf27fc2df379e4a2bb9fb5e\/lib\/Paste.py#L22-L66"}
4
+ {"nwo":"Critical-Start\/pastebin_scraper","sha":"196270249b0706bbeaf27fc2df379e4a2bb9fb5e","path":"lib\/Pastebin.py","language":"python","identifier":"Pastebin.update","parameters":"(self)","argument_list":"","return_statement":"","docstring":"update(self) - Fill Queue with new Pastebin IDs","docstring_summary":"update(self) - Fill Queue with new Pastebin IDs","docstring_tokens":["update","(","self",")","-","Fill","Queue","with","new","Pastebin","IDs"],"function":"def update(self):\n '''update(self) - Fill Queue with new Pastebin IDs'''\n logging.info('Retrieving Pastebin ID\\'s')\n new_pastes = []\n raw = None\n while not raw:\n try:\n raw = urllib.request.urlopen(\"https:\/\/scrape.pastebin.com\/api_scraping.php?limit=\" + str(SCRAPE_LIMIT))\n except:\n logging.info('Error with pastebin')\n raw = None\n sleep(5)\n # import API result as JSON\n decoded = raw.read().decode('utf-8')\n raw_json = json.loads(decoded)\n #parse json to get keys\n results = []\n #populate results list with paste_ids\n for paste_bulk in raw_json:\n results.append(paste_bulk['key'])\n if not self.ref_id:\n #up to 100 new pastes\n results = results[:100]\n for entry in results:\n paste = PastebinPaste(entry)\n # Check to see if we found our last checked paste_id\n if paste.id == self.ref_id:\n #if paste_id matches last checked id, no more new stuff\n break\n new_pastes.append(paste)\n for entry in new_pastes[::-1]:\n logging.info('Adding URL: ' + entry.url)\n self.put(entry)","function_tokens":["def","update","(","self",")",":","logging",".","info","(","'Retrieving Pastebin ID\\'s'",")","new_pastes","=","[","]","raw","=","None","while","not","raw",":","try",":","raw","=","urllib",".","request",".","urlopen","(","\"https:\/\/scrape.pastebin.com\/api_scraping.php?limit=\"","+","str","(","SCRAPE_LIMIT",")",")","except",":","logging",".","info","(","'Error with pastebin'",")","raw","=","None","sleep","(","5",")","# import API result as JSON","decoded","=","raw",".","read","(",")",".","decode","(","'utf-8'",")","raw_json","=","json",".","loads","(","decoded",")","#parse json to get keys","results","=","[","]","#populate results list with paste_ids","for","paste_bulk","in","raw_json",":","results",".","append","(","paste_bulk","[","'key'","]",")","if","not","self",".","ref_id",":","#up to 100 new pastes","results","=","results","[",":","100","]","for","entry","in","results",":","paste","=","PastebinPaste","(","entry",")","# Check to see if we found our last checked paste_id","if","paste",".","id","==","self",".","ref_id",":","#if paste_id matches last checked id, no more new stuff","break","new_pastes",".","append","(","paste",")","for","entry","in","new_pastes","[",":",":","-","1","]",":","logging",".","info","(","'Adding URL: '","+","entry",".","url",")","self",".","put","(","entry",")"],"url":"https:\/\/github.com\/Critical-Start\/pastebin_scraper\/blob\/196270249b0706bbeaf27fc2df379e4a2bb9fb5e\/lib\/Pastebin.py#L32-L64"}
CroweCybersecurity__ad-ldap-enum.jsonl ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {"nwo":"CroweCybersecurity\/ad-ldap-enum","sha":"ae2eb47d3ed0561bf9c6977f8afd86ec601e4b49","path":"ad-ldap-enum.py","language":"python","identifier":"ldap_queries","parameters":"(ldap_client, base_dn, explode_nested_groups)","argument_list":"","return_statement":"","docstring":"Main worker function for the script.","docstring_summary":"Main worker function for the script.","docstring_tokens":["Main","worker","function","for","the","script","."],"function":"def ldap_queries(ldap_client, base_dn, explode_nested_groups):\n \"\"\"Main worker function for the script.\"\"\"\n users_dictionary = {}\n groups_dictionary = {}\n computers_dictionary = {}\n group_id_to_dn_dictionary = {}\n\n # LDAP filters\n user_filter = '(objectcategory=user)'\n user_attributes = ['distinguishedName', 'sAMAccountName', 'userAccountControl', 'primaryGroupID', 'comment', 'description', 'homeDirectory', 'displayName', 'mail', 'pwdLastSet', 'lastLogon', 'profilePath', 'lockoutTime', 'scriptPath', 'userPassword']\n\n group_filter = '(objectcategory=group)'\n group_attributes = ['distinguishedName', 'sAMAccountName', 'member', 'primaryGroupToken']\n\n computer_filters = '(objectcategory=computer)'\n computer_attributes = ['distinguishedName', 'sAMAccountName', 'primaryGroupID', 'operatingSystem', 'operatingSystemHotfix', 'operatingSystemServicePack', 'operatingSystemVersion', 'servicePrincipalName']\n\n # LDAP queries\n logging.info('Querying users')\n users = query_ldap_with_paging(ldap_client, base_dn, user_filter, user_attributes, ADUser)\n logging.info('Querying groups')\n groups = query_ldap_with_paging(ldap_client, base_dn, group_filter, group_attributes, ADGroup)\n logging.info('Querying computers')\n computers = query_ldap_with_paging(ldap_client, base_dn, computer_filters, computer_attributes, ADComputer)\n\n # LDAP dictionaries\n logging.info('Building users dictionary')\n for element in users:\n users_dictionary[element.distinguished_name] = element\n\n logging.info('Building groups dictionary')\n for element in groups:\n group_id_to_dn_dictionary[element.primary_group_token] = element.distinguished_name\n groups_dictionary[element.distinguished_name] = element\n\n logging.info('Building computers dictionary')\n for element in computers:\n computers_dictionary[element.distinguished_name] = element\n\n # Loop through each group. If the membership is a range then query AD to get the full group membership\n logging.info('Exploding large groups')\n for group_key, group_object in groups_dictionary.items():\n if group_object.is_large_group:\n logging.debug('Getting full membership for [%s]', group_key)\n groups_dictionary[group_key].members = get_membership_with_ranges(ldap_client, base_dn, group_key)\n\n # Build group membership\n logging.info('Building group membership')\n logging.info('There is a total of [%i] groups', len(list(groups_dictionary.keys())))\n\n current_group_number = 0\n _output_dictionary = []\n for grp in list(groups_dictionary.keys()):\n current_group_number += 1\n _output_dictionary += process_group(users_dictionary, groups_dictionary, computers_dictionary, grp, explode_nested_groups, None, [])\n\n if current_group_number % 1000 == 0:\n logging.info('Processing group [%i]', current_group_number)\n\n # TODO: This could create output duplicates. It should be fixed at some point.\n # Add users if they have the group set as their primary ID as the group.\n # Additionally, add extended domain user information to a text file.\n user_information_filename = '{0} Extended Domain User Information.tsv'.format(args.filename_prepend).strip()\n with open(user_information_filename, 'w') as user_information_file:\n logging.info('Writing domain user information to [%s]', user_information_file.name)\n user_information_file.write('SAM Account Name\\tStatus\\tLocked Out\\tUser Password\\tDisplay Name\\tEmail\\tHome Directory\\tProfile Path\\tLogon Script Path\\tPassword Last Set\\tLast Logon\\tUser Comment\\tDescription\\n')\n\n for user_object in list(users_dictionary.values()):\n if user_object.primary_group_id and user_object.primary_group_id in group_id_to_dn_dictionary:\n grp_dn = group_id_to_dn_dictionary[user_object.primary_group_id]\n\n temp_list_a = []\n temp_list_b = []\n\n temp_list_a.append(groups_dictionary[grp_dn].sam_account_name)\n temp_list_b.append(groups_dictionary[grp_dn].sam_account_name)\n temp_list_a.append(user_object.sam_account_name)\n temp_list_b.append(user_object.sam_account_name)\n temp_list_a.append(user_object.get_account_flags())\n temp_list_b.append(user_object.get_account_flags())\n temp_list_a.append(user_object.locked_out)\n temp_list_a.append(user_object.user_password)\n temp_list_a.append(user_object.display_name)\n temp_list_a.append(user_object.mail)\n temp_list_a.append(user_object.home_directory)\n temp_list_a.append(user_object.profile_path)\n temp_list_a.append(user_object.logon_script)\n temp_list_a.append(user_object.get_password_last_set_date())\n temp_list_a.append(user_object.get_last_logon_date())\n temp_list_a.append(user_object.comment)\n temp_list_a.append(user_object.description)\n _output_dictionary.append(temp_list_b)\n\n tmp_element = \"\"\n for x, binary_string in enumerate(temp_list_a[1:]):\n binary_string = str(binary_string)\n if binary_string[:2] == \"b'\":\n binary_string = binary_string[2:]\n if binary_string[-1:] == \"'\":\n binary_string = binary_string[:-1]\n if x == len(temp_list_a[1:])-1 :\n tmp_element += binary_string + \"\\n\"\n else:\n tmp_element += binary_string + \"\\t\"\n \n user_information_file.write(tmp_element) #\"\\t\".join(str(temp_list_a[1:])) + \"\\n\")\n\n # Write Domain Computer Information\n computer_information_filename = '{0} Extended Domain Computer Information.tsv'.format(args.filename_prepend).strip()\n with open(computer_information_filename, 'w') as computer_information_file:\n logging.info('Writing domain computer information to [%s]', computer_information_file.name)\n computer_information_file.write('SAM Account Name\\tOS\\tOS Hotfix\\tOS Service Pack\\tOS VersiontSQL SPNs\\tRA SPNS\\tShare SPNs\\tMail SPNs\\tAuth SPNs\\tBackup SPNs\\tManagement SPNs\\tOther SPNs\\n')\n\n # TODO: This could create output duplicates. It should be fixed at some point.\n # Add computers if they have the group set as their primary ID as the group\n for computer_object in list(computers_dictionary.values()):\n if computer_object.primary_group_id:\n grp_dn = group_id_to_dn_dictionary[computer_object.primary_group_id]\n\n temp_list_a = []\n temp_list_b = []\n\n temp_list_a.append(groups_dictionary[grp_dn].sam_account_name)\n temp_list_a.append(computer_object.sam_account_name)\n\n temp_list_b.append(computer_object.sam_account_name)\n temp_list_b.append(computer_object.operating_system)\n temp_list_b.append(computer_object.operating_system_hotfix)\n temp_list_b.append(computer_object.operating_system_service_pack)\n temp_list_b.append(computer_object.operating_system_version)\n [temp_list_b.append(','.join(map(str, item))) for item in parse_spns(computer_object.service_principal_names)]\n\n tmp_element = \"\"\n for x, binary_string in enumerate(temp_list_b):\n binary_string = str(binary_string)\n if binary_string[:2] == \"b'\":\n binary_string = binary_string[2:]\n if binary_string[-1:] == \"'\":\n binary_string = binary_string[:-1]\n if x == len(temp_list_b)-1 :\n tmp_element += binary_string + \"\\n\"\n else:\n tmp_element += binary_string + \"\\t\"\n computer_information_file.write(tmp_element)\n _output_dictionary.append(temp_list_a)\n\n # Write Group Memberships\n group_membership_filename = '{0} Domain Group Membership.tsv'.format(args.filename_prepend).strip()\n with open(group_membership_filename, 'w') as group_membership_file:\n logging.info('Writing membership information to [%s]', group_membership_file.name)\n group_membership_file.write('Group Name\\tSAM Account Name\\tStatus\\n')\n\n for element in _output_dictionary:\n tmp_element = \"\"\n for x, binary_string in enumerate(element):\n binary_string = str(binary_string)\n if binary_string[:2] == \"b'\":\n binary_string = binary_string[2:]\n if binary_string[-1:] == \"'\":\n binary_string = binary_string[:-1]\n if x == len(element)-1 :\n tmp_element += binary_string + \"\\n\"\n else:\n tmp_element += binary_string + \"\\t\"\n \n group_membership_file.write(tmp_element)","function_tokens":["def","ldap_queries","(","ldap_client",",","base_dn",",","explode_nested_groups",")",":","users_dictionary","=","{","}","groups_dictionary","=","{","}","computers_dictionary","=","{","}","group_id_to_dn_dictionary","=","{","}","# LDAP filters","user_filter","=","'(objectcategory=user)'","user_attributes","=","[","'distinguishedName'",",","'sAMAccountName'",",","'userAccountControl'",",","'primaryGroupID'",",","'comment'",",","'description'",",","'homeDirectory'",",","'displayName'",",","'mail'",",","'pwdLastSet'",",","'lastLogon'",",","'profilePath'",",","'lockoutTime'",",","'scriptPath'",",","'userPassword'","]","group_filter","=","'(objectcategory=group)'","group_attributes","=","[","'distinguishedName'",",","'sAMAccountName'",",","'member'",",","'primaryGroupToken'","]","computer_filters","=","'(objectcategory=computer)'","computer_attributes","=","[","'distinguishedName'",",","'sAMAccountName'",",","'primaryGroupID'",",","'operatingSystem'",",","'operatingSystemHotfix'",",","'operatingSystemServicePack'",",","'operatingSystemVersion'",",","'servicePrincipalName'","]","# LDAP queries","logging",".","info","(","'Querying users'",")","users","=","query_ldap_with_paging","(","ldap_client",",","base_dn",",","user_filter",",","user_attributes",",","ADUser",")","logging",".","info","(","'Querying groups'",")","groups","=","query_ldap_with_paging","(","ldap_client",",","base_dn",",","group_filter",",","group_attributes",",","ADGroup",")","logging",".","info","(","'Querying computers'",")","computers","=","query_ldap_with_paging","(","ldap_client",",","base_dn",",","computer_filters",",","computer_attributes",",","ADComputer",")","# LDAP dictionaries","logging",".","info","(","'Building users dictionary'",")","for","element","in","users",":","users_dictionary","[","element",".","distinguished_name","]","=","element","logging",".","info","(","'Building groups dictionary'",")","for","element","in","groups",":","group_id_to_dn_dictionary","[","element",".","primary_group_token","]","=","element",".","distinguished_name","groups_dictionary","[","element",".","distinguished_name","]","=","element","logging",".","info","(","'Building computers dictionary'",")","for","element","in","computers",":","computers_dictionary","[","element",".","distinguished_name","]","=","element","# Loop through each group. If the membership is a range then query AD to get the full group membership","logging",".","info","(","'Exploding large groups'",")","for","group_key",",","group_object","in","groups_dictionary",".","items","(",")",":","if","group_object",".","is_large_group",":","logging",".","debug","(","'Getting full membership for [%s]'",",","group_key",")","groups_dictionary","[","group_key","]",".","members","=","get_membership_with_ranges","(","ldap_client",",","base_dn",",","group_key",")","# Build group membership","logging",".","info","(","'Building group membership'",")","logging",".","info","(","'There is a total of [%i] groups'",",","len","(","list","(","groups_dictionary",".","keys","(",")",")",")",")","current_group_number","=","0","_output_dictionary","=","[","]","for","grp","in","list","(","groups_dictionary",".","keys","(",")",")",":","current_group_number","+=","1","_output_dictionary","+=","process_group","(","users_dictionary",",","groups_dictionary",",","computers_dictionary",",","grp",",","explode_nested_groups",",","None",",","[","]",")","if","current_group_number","%","1000","==","0",":","logging",".","info","(","'Processing group [%i]'",",","current_group_number",")","# TODO: This could create output duplicates. It should be fixed at some point.","# Add users if they have the group set as their primary ID as the group.","# Additionally, add extended domain user information to a text file.","user_information_filename","=","'{0} Extended Domain User Information.tsv'",".","format","(","args",".","filename_prepend",")",".","strip","(",")","with","open","(","user_information_filename",",","'w'",")","as","user_information_file",":","logging",".","info","(","'Writing domain user information to [%s]'",",","user_information_file",".","name",")","user_information_file",".","write","(","'SAM Account Name\\tStatus\\tLocked Out\\tUser Password\\tDisplay Name\\tEmail\\tHome Directory\\tProfile Path\\tLogon Script Path\\tPassword Last Set\\tLast Logon\\tUser Comment\\tDescription\\n'",")","for","user_object","in","list","(","users_dictionary",".","values","(",")",")",":","if","user_object",".","primary_group_id","and","user_object",".","primary_group_id","in","group_id_to_dn_dictionary",":","grp_dn","=","group_id_to_dn_dictionary","[","user_object",".","primary_group_id","]","temp_list_a","=","[","]","temp_list_b","=","[","]","temp_list_a",".","append","(","groups_dictionary","[","grp_dn","]",".","sam_account_name",")","temp_list_b",".","append","(","groups_dictionary","[","grp_dn","]",".","sam_account_name",")","temp_list_a",".","append","(","user_object",".","sam_account_name",")","temp_list_b",".","append","(","user_object",".","sam_account_name",")","temp_list_a",".","append","(","user_object",".","get_account_flags","(",")",")","temp_list_b",".","append","(","user_object",".","get_account_flags","(",")",")","temp_list_a",".","append","(","user_object",".","locked_out",")","temp_list_a",".","append","(","user_object",".","user_password",")","temp_list_a",".","append","(","user_object",".","display_name",")","temp_list_a",".","append","(","user_object",".","mail",")","temp_list_a",".","append","(","user_object",".","home_directory",")","temp_list_a",".","append","(","user_object",".","profile_path",")","temp_list_a",".","append","(","user_object",".","logon_script",")","temp_list_a",".","append","(","user_object",".","get_password_last_set_date","(",")",")","temp_list_a",".","append","(","user_object",".","get_last_logon_date","(",")",")","temp_list_a",".","append","(","user_object",".","comment",")","temp_list_a",".","append","(","user_object",".","description",")","_output_dictionary",".","append","(","temp_list_b",")","tmp_element","=","\"\"","for","x",",","binary_string","in","enumerate","(","temp_list_a","[","1",":","]",")",":","binary_string","=","str","(","binary_string",")","if","binary_string","[",":","2","]","==","\"b'\"",":","binary_string","=","binary_string","[","2",":","]","if","binary_string","[","-","1",":","]","==","\"'\"",":","binary_string","=","binary_string","[",":","-","1","]","if","x","==","len","(","temp_list_a","[","1",":","]",")","-","1",":","tmp_element","+=","binary_string","+","\"\\n\"","else",":","tmp_element","+=","binary_string","+","\"\\t\"","user_information_file",".","write","(","tmp_element",")","#\"\\t\".join(str(temp_list_a[1:])) + \"\\n\")","# Write Domain Computer Information","computer_information_filename","=","'{0} Extended Domain Computer Information.tsv'",".","format","(","args",".","filename_prepend",")",".","strip","(",")","with","open","(","computer_information_filename",",","'w'",")","as","computer_information_file",":","logging",".","info","(","'Writing domain computer information to [%s]'",",","computer_information_file",".","name",")","computer_information_file",".","write","(","'SAM Account Name\\tOS\\tOS Hotfix\\tOS Service Pack\\tOS VersiontSQL SPNs\\tRA SPNS\\tShare SPNs\\tMail SPNs\\tAuth SPNs\\tBackup SPNs\\tManagement SPNs\\tOther SPNs\\n'",")","# TODO: This could create output duplicates. It should be fixed at some point.","# Add computers if they have the group set as their primary ID as the group","for","computer_object","in","list","(","computers_dictionary",".","values","(",")",")",":","if","computer_object",".","primary_group_id",":","grp_dn","=","group_id_to_dn_dictionary","[","computer_object",".","primary_group_id","]","temp_list_a","=","[","]","temp_list_b","=","[","]","temp_list_a",".","append","(","groups_dictionary","[","grp_dn","]",".","sam_account_name",")","temp_list_a",".","append","(","computer_object",".","sam_account_name",")","temp_list_b",".","append","(","computer_object",".","sam_account_name",")","temp_list_b",".","append","(","computer_object",".","operating_system",")","temp_list_b",".","append","(","computer_object",".","operating_system_hotfix",")","temp_list_b",".","append","(","computer_object",".","operating_system_service_pack",")","temp_list_b",".","append","(","computer_object",".","operating_system_version",")","[","temp_list_b",".","append","(","','",".","join","(","map","(","str",",","item",")",")",")","for","item","in","parse_spns","(","computer_object",".","service_principal_names",")","]","tmp_element","=","\"\"","for","x",",","binary_string","in","enumerate","(","temp_list_b",")",":","binary_string","=","str","(","binary_string",")","if","binary_string","[",":","2","]","==","\"b'\"",":","binary_string","=","binary_string","[","2",":","]","if","binary_string","[","-","1",":","]","==","\"'\"",":","binary_string","=","binary_string","[",":","-","1","]","if","x","==","len","(","temp_list_b",")","-","1",":","tmp_element","+=","binary_string","+","\"\\n\"","else",":","tmp_element","+=","binary_string","+","\"\\t\"","computer_information_file",".","write","(","tmp_element",")","_output_dictionary",".","append","(","temp_list_a",")","# Write Group Memberships","group_membership_filename","=","'{0} Domain Group Membership.tsv'",".","format","(","args",".","filename_prepend",")",".","strip","(",")","with","open","(","group_membership_filename",",","'w'",")","as","group_membership_file",":","logging",".","info","(","'Writing membership information to [%s]'",",","group_membership_file",".","name",")","group_membership_file",".","write","(","'Group Name\\tSAM Account Name\\tStatus\\n'",")","for","element","in","_output_dictionary",":","tmp_element","=","\"\"","for","x",",","binary_string","in","enumerate","(","element",")",":","binary_string","=","str","(","binary_string",")","if","binary_string","[",":","2","]","==","\"b'\"",":","binary_string","=","binary_string","[","2",":","]","if","binary_string","[","-","1",":","]","==","\"'\"",":","binary_string","=","binary_string","[",":","-","1","]","if","x","==","len","(","element",")","-","1",":","tmp_element","+=","binary_string","+","\"\\n\"","else",":","tmp_element","+=","binary_string","+","\"\\t\"","group_membership_file",".","write","(","tmp_element",")"],"url":"https:\/\/github.com\/CroweCybersecurity\/ad-ldap-enum\/blob\/ae2eb47d3ed0561bf9c6977f8afd86ec601e4b49\/ad-ldap-enum.py#L176-L341"}
2
+ {"nwo":"CroweCybersecurity\/ad-ldap-enum","sha":"ae2eb47d3ed0561bf9c6977f8afd86ec601e4b49","path":"ad-ldap-enum.py","language":"python","identifier":"process_group","parameters":"(users_dictionary, groups_dictionary, computers_dictionary, group_distinguished_name, explode_nested, base_group_name, groups_seen)","argument_list":"","return_statement":"return group_dictionary","docstring":"Builds group membership for a specified group.","docstring_summary":"Builds group membership for a specified group.","docstring_tokens":["Builds","group","membership","for","a","specified","group","."],"function":"def process_group(users_dictionary, groups_dictionary, computers_dictionary, group_distinguished_name, explode_nested, base_group_name, groups_seen):\n \"\"\"Builds group membership for a specified group.\"\"\"\n # Store assorted group information.\n group_dictionary = []\n\n # Query SAM name or used redefined SAM name if processing a nested group.\n if base_group_name is None:\n group_sam_name = groups_dictionary[group_distinguished_name].sam_account_name\n elif base_group_name is not None:\n group_sam_name = base_group_name\n\n # Add empty groups to the Domain Group Membership list for full visibility.\n if not groups_dictionary[group_distinguished_name].members:\n temp_list = [group_sam_name, '']\n group_dictionary.append(temp_list)\n\n # Add users\/groups\/computer if they are a 'memberOf' the group\n for member in groups_dictionary[group_distinguished_name].members:\n # Process users.\n if member in users_dictionary:\n user_member = users_dictionary[member]\n\n temp_list = [group_sam_name, user_member.sam_account_name, user_member.get_account_flags()]\n group_dictionary.append(temp_list)\n\n # Process computers.\n elif member in computers_dictionary:\n temp_list = [group_sam_name, computers_dictionary[member].sam_account_name]\n group_dictionary.append(temp_list)\n\n # Process groups.\n elif member in groups_dictionary:\n if not explode_nested or (explode_nested and base_group_name is None):\n temp_list = [group_sam_name, groups_dictionary[member].sam_account_name]\n group_dictionary.append(temp_list)\n\n if explode_nested:\n # Stop processing the chain if a circular reference is detected.\n if member in groups_seen:\n pass\n # Process a nested group.\n else:\n groups_seen.append(member)\n group_dictionary += process_group(users_dictionary, groups_dictionary, computers_dictionary, member, True, group_sam_name, groups_seen)\n\n return group_dictionary","function_tokens":["def","process_group","(","users_dictionary",",","groups_dictionary",",","computers_dictionary",",","group_distinguished_name",",","explode_nested",",","base_group_name",",","groups_seen",")",":","# Store assorted group information.","group_dictionary","=","[","]","# Query SAM name or used redefined SAM name if processing a nested group.","if","base_group_name","is","None",":","group_sam_name","=","groups_dictionary","[","group_distinguished_name","]",".","sam_account_name","elif","base_group_name","is","not","None",":","group_sam_name","=","base_group_name","# Add empty groups to the Domain Group Membership list for full visibility.","if","not","groups_dictionary","[","group_distinguished_name","]",".","members",":","temp_list","=","[","group_sam_name",",","''","]","group_dictionary",".","append","(","temp_list",")","# Add users\/groups\/computer if they are a 'memberOf' the group","for","member","in","groups_dictionary","[","group_distinguished_name","]",".","members",":","# Process users.","if","member","in","users_dictionary",":","user_member","=","users_dictionary","[","member","]","temp_list","=","[","group_sam_name",",","user_member",".","sam_account_name",",","user_member",".","get_account_flags","(",")","]","group_dictionary",".","append","(","temp_list",")","# Process computers.","elif","member","in","computers_dictionary",":","temp_list","=","[","group_sam_name",",","computers_dictionary","[","member","]",".","sam_account_name","]","group_dictionary",".","append","(","temp_list",")","# Process groups.","elif","member","in","groups_dictionary",":","if","not","explode_nested","or","(","explode_nested","and","base_group_name","is","None",")",":","temp_list","=","[","group_sam_name",",","groups_dictionary","[","member","]",".","sam_account_name","]","group_dictionary",".","append","(","temp_list",")","if","explode_nested",":","# Stop processing the chain if a circular reference is detected.","if","member","in","groups_seen",":","pass","# Process a nested group.","else",":","groups_seen",".","append","(","member",")","group_dictionary","+=","process_group","(","users_dictionary",",","groups_dictionary",",","computers_dictionary",",","member",",","True",",","group_sam_name",",","groups_seen",")","return","group_dictionary"],"url":"https:\/\/github.com\/CroweCybersecurity\/ad-ldap-enum\/blob\/ae2eb47d3ed0561bf9c6977f8afd86ec601e4b49\/ad-ldap-enum.py#L343-L388"}
3
+ {"nwo":"CroweCybersecurity\/ad-ldap-enum","sha":"ae2eb47d3ed0561bf9c6977f8afd86ec601e4b49","path":"ad-ldap-enum.py","language":"python","identifier":"query_ldap_with_paging","parameters":"(ldap_client, base_dn, search_filter, attributes, output_object=None, page_size=1000)","argument_list":"","return_statement":"return output_array","docstring":"Get all the Active Directory results from LDAP using a paging approach.\n By default Active Directory will return 1,000 results per query before it errors out.","docstring_summary":"Get all the Active Directory results from LDAP using a paging approach.\n By default Active Directory will return 1,000 results per query before it errors out.","docstring_tokens":["Get","all","the","Active","Directory","results","from","LDAP","using","a","paging","approach",".","By","default","Active","Directory","will","return","1","000","results","per","query","before","it","errors","out","."],"function":"def query_ldap_with_paging(ldap_client, base_dn, search_filter, attributes, output_object=None, page_size=1000):\n \"\"\"Get all the Active Directory results from LDAP using a paging approach.\n By default Active Directory will return 1,000 results per query before it errors out.\"\"\"\n\n # Method Variables\n cookie=''\n more_pages = True\n output_array = deque()\n\n # Paging for AD LDAP Queries\n ldap_control = ldap.controls.SimplePagedResultsControl(True, size=page_size, cookie='')\n\n while more_pages:\n # Query the LDAP Server\n msgid = ldap_client.search_ext(base_dn, ldap.SCOPE_SUBTREE, search_filter, attributes, serverctrls=[ldap_control])\n result_type, result_data, message_id, server_controls = ldap_client.result3(msgid)\n\n # Append Page to Results\n for element in result_data:\n if (output_object is None) and (element[0] is not None):\n output_array.append(element[1])\n elif (output_object is not None) and (element[0] is not None):\n output_array.append(output_object(element[1]))\n\n # Get the page control and get the cookie from the control.\n page_controls = [c for c in server_controls if c.controlType == ldap.controls.SimplePagedResultsControl.controlType]\n\n if page_controls:\n cookie = page_controls[0].cookie\n\n # If there is no cookie then all the pages have been retrieved.\n if not cookie:\n more_pages = False\n else:\n ldap_control.cookie = cookie\n\n return output_array","function_tokens":["def","query_ldap_with_paging","(","ldap_client",",","base_dn",",","search_filter",",","attributes",",","output_object","=","None",",","page_size","=","1000",")",":","# Method Variables","cookie","=","''","more_pages","=","True","output_array","=","deque","(",")","# Paging for AD LDAP Queries","ldap_control","=","ldap",".","controls",".","SimplePagedResultsControl","(","True",",","size","=","page_size",",","cookie","=","''",")","while","more_pages",":","# Query the LDAP Server","msgid","=","ldap_client",".","search_ext","(","base_dn",",","ldap",".","SCOPE_SUBTREE",",","search_filter",",","attributes",",","serverctrls","=","[","ldap_control","]",")","result_type",",","result_data",",","message_id",",","server_controls","=","ldap_client",".","result3","(","msgid",")","# Append Page to Results","for","element","in","result_data",":","if","(","output_object","is","None",")","and","(","element","[","0","]","is","not","None",")",":","output_array",".","append","(","element","[","1","]",")","elif","(","output_object","is","not","None",")","and","(","element","[","0","]","is","not","None",")",":","output_array",".","append","(","output_object","(","element","[","1","]",")",")","# Get the page control and get the cookie from the control.","page_controls","=","[","c","for","c","in","server_controls","if","c",".","controlType","==","ldap",".","controls",".","SimplePagedResultsControl",".","controlType","]","if","page_controls",":","cookie","=","page_controls","[","0","]",".","cookie","# If there is no cookie then all the pages have been retrieved.","if","not","cookie",":","more_pages","=","False","else",":","ldap_control",".","cookie","=","cookie","return","output_array"],"url":"https:\/\/github.com\/CroweCybersecurity\/ad-ldap-enum\/blob\/ae2eb47d3ed0561bf9c6977f8afd86ec601e4b49\/ad-ldap-enum.py#L390-L426"}
4
+ {"nwo":"CroweCybersecurity\/ad-ldap-enum","sha":"ae2eb47d3ed0561bf9c6977f8afd86ec601e4b49","path":"ad-ldap-enum.py","language":"python","identifier":"get_membership_with_ranges","parameters":"(ldap_client, base_dn, group_dn)","argument_list":"","return_statement":"return output_array","docstring":"Queries the membership of an Active Directory group. For large groups Active Directory will\n Not return the full membership by default but will instead return partial results. Additional\n processing is needed to get the full membership.","docstring_summary":"Queries the membership of an Active Directory group. For large groups Active Directory will\n Not return the full membership by default but will instead return partial results. Additional\n processing is needed to get the full membership.","docstring_tokens":["Queries","the","membership","of","an","Active","Directory","group",".","For","large","groups","Active","Directory","will","Not","return","the","full","membership","by","default","but","will","instead","return","partial","results",".","Additional","processing","is","needed","to","get","the","full","membership","."],"function":"def get_membership_with_ranges(ldap_client, base_dn, group_dn):\n \"\"\"Queries the membership of an Active Directory group. For large groups Active Directory will\n Not return the full membership by default but will instead return partial results. Additional\n processing is needed to get the full membership.\"\"\"\n output_array = []\n\n # RFC 4515 sanitation.\n sanatized_group_dn = str(group_dn).replace('(', '\\\\28').replace(')', '\\\\29').replace('*', '\\\\2a').replace('\\\\', '\\\\5c')\n\n membership_filter = '(&(|(objectcategory=user)(objectcategory=group)(objectcategory=computer))(memberof={0}))'.format(sanatized_group_dn)\n membership_results = query_ldap_with_paging(ldap_client, base_dn, membership_filter, ['distinguishedName'])\n\n for element in membership_results:\n output_array.append(element['distinguishedName'][0])\n\n return output_array","function_tokens":["def","get_membership_with_ranges","(","ldap_client",",","base_dn",",","group_dn",")",":","output_array","=","[","]","# RFC 4515 sanitation.","sanatized_group_dn","=","str","(","group_dn",")",".","replace","(","'('",",","'\\\\28'",")",".","replace","(","')'",",","'\\\\29'",")",".","replace","(","'*'",",","'\\\\2a'",")",".","replace","(","'\\\\'",",","'\\\\5c'",")","membership_filter","=","'(&(|(objectcategory=user)(objectcategory=group)(objectcategory=computer))(memberof={0}))'",".","format","(","sanatized_group_dn",")","membership_results","=","query_ldap_with_paging","(","ldap_client",",","base_dn",",","membership_filter",",","[","'distinguishedName'","]",")","for","element","in","membership_results",":","output_array",".","append","(","element","[","'distinguishedName'","]","[","0","]",")","return","output_array"],"url":"https:\/\/github.com\/CroweCybersecurity\/ad-ldap-enum\/blob\/ae2eb47d3ed0561bf9c6977f8afd86ec601e4b49\/ad-ldap-enum.py#L466-L481"}
DataBiosphere__dsub.jsonl ADDED
The diff for this file is too large to render. See raw diff