title
stringlengths
2
169
diff
stringlengths
235
19.5k
body
stringlengths
0
30.5k
url
stringlengths
48
84
created_at
stringlengths
20
20
closed_at
stringlengths
20
20
merged_at
stringlengths
20
20
updated_at
stringlengths
20
20
diff_len
float64
101
3.99k
repo_name
stringclasses
83 values
__index_level_0__
int64
15
52.7k
Add "Clozemaster" support
diff --git a/data.json b/data.json index 68d8822c1..20394b8ca 100644 --- a/data.json +++ b/data.json @@ -354,6 +354,14 @@ "username_claimed": "blue", "username_unclaimed": "noonewouldeverusethis" }, + "Clozemaster": { + "errorType": "status_code", + "rank": 105275 , + "url": "https://www.clozemaster.com/players/{}", + "urlMain": "https://www.clozemaster.com", + "username_claimed": "green", + "username_unclaimed": "noonewouldeverusethis7" + }, "Codecademy": { "errorType": "status_code", "rank": 2882,
https://api.github.com/repos/sherlock-project/sherlock/pulls/514
2020-01-11T15:50:13Z
2020-01-12T14:19:50Z
2020-01-12T14:19:50Z
2020-01-12T14:19:50Z
193
sherlock-project/sherlock
36,673
gh-94673: Fix _PyTypes_InitTypes() and get_type_attr_as_size()
diff --git a/Objects/object.c b/Objects/object.c index cd610297aacba0..4ce10cf1192d3f 100644 --- a/Objects/object.c +++ b/Objects/object.c @@ -2102,10 +2102,6 @@ static PyTypeObject* static_types[] = { PyStatus _PyTypes_InitTypes(PyInterpreterState *interp) { - if (!_Py_IsMainInterpreter(interp)) { - return _PyStatus_OK(); - } - // All other static types (unless initialized elsewhere) for (size_t i=0; i < Py_ARRAY_LENGTH(static_types); i++) { PyTypeObject *type = static_types[i]; diff --git a/Objects/structseq.c b/Objects/structseq.c index 727d72865e3bb3..88a71bc52958f5 100644 --- a/Objects/structseq.c +++ b/Objects/structseq.c @@ -31,6 +31,7 @@ get_type_attr_as_size(PyTypeObject *tp, PyObject *name) PyErr_Format(PyExc_TypeError, "Missed attribute '%U' of type %s", name, tp->tp_name); + return -1; } return PyLong_AsSsize_t(v); }
This change has two small parts: 1. a follow-up to gh-103940 with one case I missed 2. adding a missing return that I noticed while working on related code <!-- gh-issue-number: gh-94673 --> * Issue: gh-94673 <!-- /gh-issue-number -->
https://api.github.com/repos/python/cpython/pulls/103961
2023-04-27T23:56:14Z
2023-04-28T00:28:51Z
2023-04-28T00:28:51Z
2023-04-28T00:28:55Z
284
python/cpython
4,709
Fixed Load Image preview not displaying some files (issue #1158)
diff --git a/web/scripts/widgets.js b/web/scripts/widgets.js index 45ac9b8962..9755776312 100644 --- a/web/scripts/widgets.js +++ b/web/scripts/widgets.js @@ -335,7 +335,7 @@ export const ComfyWidgets = { subfolder = name.substring(0, folder_separator); name = name.substring(folder_separator + 1); } - img.src = api.apiURL(`/view?filename=${name}&type=input&subfolder=${subfolder}${app.getPreviewFormatParam()}`); + img.src = api.apiURL(`/view?filename=${encodeURIComponent(name)}&type=input&subfolder=${subfolder}${app.getPreviewFormatParam()}`); node.setSizeForImage?.(); }
Fixed issue #1158.
https://api.github.com/repos/comfyanonymous/ComfyUI/pulls/1455
2023-09-08T09:00:23Z
2023-09-08T15:50:04Z
2023-09-08T15:50:04Z
2023-09-08T16:06:34Z
164
comfyanonymous/ComfyUI
17,991
rename class autoShape -> AutoShape
diff --git a/models/common.py b/models/common.py index 9764d4c3a6c..689aa0f3ed7 100644 --- a/models/common.py +++ b/models/common.py @@ -223,18 +223,18 @@ def forward(self, x): return non_max_suppression(x[0], conf_thres=self.conf, iou_thres=self.iou, classes=self.classes) -class autoShape(nn.Module): +class AutoShape(nn.Module): # input-robust model wrapper for passing cv2/np/PIL/torch inputs. Includes preprocessing, inference and NMS conf = 0.25 # NMS confidence threshold iou = 0.45 # NMS IoU threshold classes = None # (optional list) filter by class def __init__(self, model): - super(autoShape, self).__init__() + super(AutoShape, self).__init__() self.model = model.eval() def autoshape(self): - print('autoShape already enabled, skipping... ') # model already converted to model.autoshape() + print('AutoShape already enabled, skipping... ') # model already converted to model.autoshape() return self @torch.no_grad() diff --git a/models/yolo.py b/models/yolo.py index 314fd806f5e..06b80032d3d 100644 --- a/models/yolo.py +++ b/models/yolo.py @@ -215,9 +215,9 @@ def nms(self, mode=True): # add or remove NMS module self.model = self.model[:-1] # remove return self - def autoshape(self): # add autoShape module - logger.info('Adding autoShape... ') - m = autoShape(self) # wrap model + def autoshape(self): # add AutoShape module + logger.info('Adding AutoShape... ') + m = AutoShape(self) # wrap model copy_attr(m, self, include=('yaml', 'nc', 'hyp', 'names', 'stride'), exclude=()) # copy attributes return m
follow other classes' naming convention ## 🛠️ PR Summary <sub>Made with ❤️ by [Ultralytics Actions](https://github.com/ultralytics/actions)<sub> ### 🌟 Summary Improved naming convention in YOLOv5 codebase. ### 📊 Key Changes - Renamed `autoShape` class to `AutoShape` for consistency in class naming. - Updated constructor and relevant print statements from `autoShape` to `AutoShape`. ### 🎯 Purpose & Impact - 💅 **Code Readability:** Harmonizes class naming conventions for better clarity, adhering to Python's CapWords convention. - 🛠️ **Refactoring:** Reflects best practices in software development, but no changes in functionality. - 🔍 **User Transparency:** Clearer logging messages to inform users when AutoShape is enabled.
https://api.github.com/repos/ultralytics/yolov5/pulls/3173
2021-05-15T13:13:08Z
2021-05-16T13:46:46Z
2021-05-16T13:46:46Z
2024-01-19T18:19:33Z
482
ultralytics/yolov5
25,463
Fix Multi-GPU not working on exllama_hf
diff --git a/modules/exllama_hf.py b/modules/exllama_hf.py index 27cac374ad..64de7a5ff4 100644 --- a/modules/exllama_hf.py +++ b/modules/exllama_hf.py @@ -38,7 +38,6 @@ def prepare_inputs_for_generation(self, input_ids, **kwargs): @property def device(self) -> torch.device: - # TODO: May cause problem on multi-gpu inference? return torch.device(0) def __call__(self, *args, **kwargs): @@ -50,7 +49,7 @@ def __call__(self, *args, **kwargs): if cache is None: cache = ExLlamaCache(self.ex_model) self.ex_model.forward(torch.tensor([seq[:-1]], dtype=torch.long), cache, preprocess_only=True) - logits = self.ex_model.forward(torch.tensor([seq[-1:]], dtype=torch.long), cache).to(self.device) + logits = self.ex_model.forward(torch.tensor([seq[-1:]], dtype=torch.long), cache).to(kwargs['input_ids'].device) return CausalLMOutputWithPast(logits=logits, past_key_values=cache if use_cache else None) @classmethod @@ -72,11 +71,14 @@ def from_pretrained(cls, pretrained_model_name_or_path: Optional[Union[str, os.P assert weight_path is not None, f'could not find weight in "{pretrained_model_name_or_path}"' config.model_path = str(weight_path) + + if shared.args.gpu_split: + config.set_auto_map(shared.args.gpu_split) + config.gpu_peer_fix = True # This slowes down a bit but align better with autogptq generation. # TODO: Should give user choice to tune the exllama config - config.act_order = True - config.fused_attn = False - config.fused_mlp_thd = 0 + # config.fused_attn = False + # config.fused_mlp_thd = 0 - return ExllamaHF(config) \ No newline at end of file + return ExllamaHF(config)
After https://github.com/oobabooga/text-generation-webui/pull/2777, new exllama_hf doesn't support gpu_split, since it wasn't added in the code. It would try to load all on the GPU0, and then get: ``` Traceback (most recent call last): File "F:\ChatIAs\oobabooga\text-generation-webui\server.py", line 62, in load_model_wrapper shared.model, shared.tokenizer = load_model(shared.model_name, loader) File "F:\ChatIAs\oobabooga\text-generation-webui\modules\models.py", line 66, in load_model output = load_func_map[loader](model_name) File "F:\ChatIAs\oobabooga\text-generation-webui\modules\models.py", line 285, in ExLlama_HF_loader return ExllamaHF.from_pretrained(model_name) File "F:\ChatIAs\oobabooga\text-generation-webui\modules\exllama_hf.py", line 82, in from_pretrained return ExllamaHF(config) File "F:\ChatIAs\oobabooga\text-generation-webui\modules\exllama_hf.py", line 27, in __init__ self.ex_model = ExLlama(self.ex_config) File "F:\ChatIAs\oobabooga\text-generation-webui\repositories\exllama\model.py", line 711, in __init__ tensor = tensor.to(device, non_blocking = True) torch.cuda.OutOfMemoryError: CUDA out of memory. Tried to allocate 86.00 MiB. GPU 0 has a total capacty of 23.99 GiB of which 0 bytes is free. Of the allocated memory 22.92 GiB is allocated by PyTorch, and 39.80 MiB is reserved by PyTorch but unallocated. If reserved but unallocated memory is large try setting max_split_size_mb to avoid fragmentation. See documentation for Memory Management and PYTORCH_CUDA_ALLOC_CONF ``` This adds the configuration to let it load in more than 1 GPU. Now it loads without issues on 2x4090. Also, since last PR, fixes the next issue. ``` Traceback (most recent call last): File "F:\ChatIAs\oobabooga\text-generation-webui\modules\callbacks.py", line 74, in gentask ret = self.mfunc(callback=_callback, *args, **self.kwargs) File "F:\ChatIAs\oobabooga\text-generation-webui\modules\text_generation.py", line 262, in generate_with_callback shared.model.generate(**kwargs) File "F:\ChatIAs\oobabooga\venv\lib\site-packages\torch\utils\_contextlib.py", line 115, in decorate_context return func(*args, **kwargs) File "F:\ChatIAs\oobabooga\venv\lib\site-packages\transformers\generation\utils.py", line 1572, in generate return self.sample( File "F:\ChatIAs\oobabooga\venv\lib\site-packages\transformers\generation\utils.py", line 2632, in sample next_token_scores = logits_processor(input_ids, next_token_logits) File "F:\ChatIAs\oobabooga\venv\lib\site-packages\transformers\generation\logits_process.py", line 92, in __call__ scores = processor(input_ids, scores) File "F:\ChatIAs\oobabooga\venv\lib\site-packages\transformers\generation\logits_process.py", line 203, in __call__ score = torch.gather(scores, 1, input_ids) RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cuda:1! (when checking argument for argument index in method wrapper_CUDA_gather) ``` ~~Speeds are reduced a bit (15 tokens/s to 12-13 tokens/s at max context on 65B).~~ Fixed after latest exllama commits. Closes https://github.com/oobabooga/text-generation-webui/issues/2809
https://api.github.com/repos/oobabooga/text-generation-webui/pulls/2803
2023-06-21T20:30:27Z
2023-06-22T19:05:25Z
2023-06-22T19:05:25Z
2023-06-23T14:57:46Z
486
oobabooga/text-generation-webui
26,203
simplify prompt
diff --git a/rich/console.py b/rich/console.py index d9564abed..1fa66e4ee 100644 --- a/rich/console.py +++ b/rich/console.py @@ -1995,23 +1995,15 @@ def input( Returns: str: Text read from stdin. """ - prompt_str = "" if prompt: - with self.capture() as capture: - self.print(prompt, markup=markup, emoji=emoji, end="") - prompt_str = capture.get() - if self.legacy_windows: - # Legacy windows doesn't like ANSI codes in getpass or input (colorama bug)? - self.file.write(prompt_str) - prompt_str = "" + self.print(prompt, markup=markup, emoji=emoji, end="") if password: - result = getpass(prompt_str, stream=stream) + result = getpass("", stream=stream) else: if stream: - self.file.write(prompt_str) result = stream.readline() else: - result = input(prompt_str) + result = input() return result def export_text(self, *, clear: bool = True, styles: bool = False) -> str:
Fixes broken prompt on Windows. Removes a workaround for colorama.
https://api.github.com/repos/Textualize/rich/pulls/2044
2022-03-10T10:39:12Z
2022-03-10T10:39:40Z
2022-03-10T10:39:40Z
2022-03-10T10:39:41Z
267
Textualize/rich
48,529
DOC: remove reference to get_value (removed) in DataFrame.lookup docstring
diff --git a/doc/source/user_guide/indexing.rst b/doc/source/user_guide/indexing.rst index cf55ce0c9a6d4..0229331127441 100644 --- a/doc/source/user_guide/indexing.rst +++ b/doc/source/user_guide/indexing.rst @@ -374,7 +374,7 @@ For getting values with a boolean array: df1.loc['a'] > 0 df1.loc[:, df1.loc['a'] > 0] -For getting a value explicitly (equivalent to deprecated ``df.get_value('a','A')``): +For getting a value explicitly: .. ipython:: python diff --git a/pandas/core/frame.py b/pandas/core/frame.py index d436385ba61ce..d2e396284c5a7 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -3544,13 +3544,6 @@ def lookup(self, row_labels, col_labels): ------- numpy.ndarray - Notes - ----- - Akin to:: - - result = [df.get_value(row, col) - for row, col in zip(row_labels, col_labels)] - Examples -------- values : ndarray
DataFrame.get_value was removed. (now we should maybe also consider deprecating `lookup`, but that is another issue)
https://api.github.com/repos/pandas-dev/pandas/pulls/29925
2019-11-29T09:20:58Z
2019-11-29T17:31:42Z
2019-11-29T17:31:42Z
2019-12-01T18:53:07Z
279
pandas-dev/pandas
45,762
Added einops
diff --git a/README.md b/README.md index 41db0144..714d98ad 100644 --- a/README.md +++ b/README.md @@ -1093,6 +1093,7 @@ be * [Couler](https://github.com/couler-proj/couler) - Unified interface for constructing and managing machine learning workflows on different workflow engines, such as Argo Workflows, Tekton Pipelines, and Apache Airflow. * [auto_ml](https://github.com/ClimbsRocks/auto_ml) - Automated machine learning for production and analytics. Lets you focus on the fun parts of ML, while outputting production-ready code, and detailed analytics of your dataset and results. Includes support for NLP, XGBoost, CatBoost, LightGBM, and soon, deep learning. * [dtaidistance](https://github.com/wannesm/dtaidistance) - High performance library for time series distances (DTW) and time series clustering. +* [einops](https://github.com/arogozhnikov/einops) - Deep learning operations reinvented (for pytorch, tensorflow, jax and others). * [machine learning](https://github.com/jeff1evesque/machine-learning) - automated build consisting of a [web-interface](https://github.com/jeff1evesque/machine-learning#web-interface), and set of [programmatic-interface](https://github.com/jeff1evesque/machine-learning#programmatic-interface) API, for support vector machines. Corresponding dataset(s) are stored into a SQL database, then generated model(s) used for prediction(s), are stored into a NoSQL datastore. * [XGBoost](https://github.com/dmlc/xgboost) - Python bindings for eXtreme Gradient Boosting (Tree) Library. * [ChefBoost](https://github.com/serengil/chefboost) - a lightweight decision tree framework for Python with categorical feature support covering regular decision tree algorithms such as ID3, C4.5, CART, CHAID and regression tree; also some advanved bagging and boosting techniques such as gradient boosting, random forest and adaboost.
https://api.github.com/repos/josephmisiti/awesome-machine-learning/pulls/887
2022-10-04T18:55:16Z
2022-10-06T14:07:18Z
2022-10-06T14:07:18Z
2022-10-06T14:07:18Z
473
josephmisiti/awesome-machine-learning
52,305
Add system design template link
diff --git a/README.md b/README.md index f9563097aa..387902594a 100644 --- a/README.md +++ b/README.md @@ -280,6 +280,7 @@ Check out the following links to get a better idea of what to expect: * [How to ace a systems design interview](https://www.palantir.com/2011/10/how-to-rock-a-systems-design-interview/) * [The system design interview](http://www.hiredintech.com/system-design) * [Intro to Architecture and Systems Design Interviews](https://www.youtube.com/watch?v=ZgdS0EUmn70) +* [System design template](https://leetcode.com/discuss/career/229177/My-System-Design-Template) ## System design interview questions with solutions
https://api.github.com/repos/donnemartin/system-design-primer/pulls/433
2020-06-30T19:55:56Z
2020-07-05T14:53:29Z
2020-07-05T14:53:29Z
2020-07-05T17:48:45Z
179
donnemartin/system-design-primer
36,800
FIX raise an error in CountVectorizer with a custom token pattern that captures several group
diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst index 9db5535415af5..15fc5ddfa5331 100644 --- a/doc/whats_new/v0.24.rst +++ b/doc/whats_new/v0.24.rst @@ -252,6 +252,11 @@ Changelog values for one categorical feature. :pr:`17367` by :user:`Peng Yu <yupbank>` and :user:`Chiara Marmo <cmarmo>`. +- |Fix| :class:`feature_extraction.CountVectorizer` raises an issue if a + custom token pattern which capture more than one group is provided. + :pr:`15427` by :user:`Gangesh Gudmalwar <ggangesh>` and + :user:`Erin R Hoffman <hoffm386>`. + :mod:`sklearn.feature_selection` ................................ diff --git a/sklearn/feature_extraction/tests/test_text.py b/sklearn/feature_extraction/tests/test_text.py index 733785476a66c..6f22e70f1827a 100644 --- a/sklearn/feature_extraction/tests/test_text.py +++ b/sklearn/feature_extraction/tests/test_text.py @@ -341,6 +341,43 @@ def test_fit_countvectorizer_twice(): assert X1.shape[1] != X2.shape[1] +def test_countvectorizer_custom_token_pattern(): + """Check `get_feature_names()` when a custom token pattern is passed. + Non-regression test for: + https://github.com/scikit-learn/scikit-learn/issues/12971 + """ + corpus = [ + 'This is the 1st document in my corpus.', + 'This document is the 2nd sample.', + 'And this is the 3rd one.', + 'Is this the 4th document?', + ] + token_pattern = r"[0-9]{1,3}(?:st|nd|rd|th)\s\b(\w{2,})\b" + vectorizer = CountVectorizer(token_pattern=token_pattern) + vectorizer.fit_transform(corpus) + expected = ['document', 'one', 'sample'] + assert vectorizer.get_feature_names() == expected + + +def test_countvectorizer_custom_token_pattern_with_several_group(): + """Check that we raise an error if token pattern capture several groups. + Non-regression test for: + https://github.com/scikit-learn/scikit-learn/issues/12971 + """ + corpus = [ + 'This is the 1st document in my corpus.', + 'This document is the 2nd sample.', + 'And this is the 3rd one.', + 'Is this the 4th document?', + ] + + token_pattern = r"([0-9]{1,3}(?:st|nd|rd|th))\s\b(\w{2,})\b" + err_msg = "More than 1 capturing group in token pattern" + vectorizer = CountVectorizer(token_pattern=token_pattern) + with pytest.raises(ValueError, match=err_msg): + vectorizer.fit(corpus) + + def test_tf_idf_smoothing(): X = [[1, 1, 1], [1, 1, 0], diff --git a/sklearn/feature_extraction/text.py b/sklearn/feature_extraction/text.py index 4189125705d51..c982f86b3dd3a 100644 --- a/sklearn/feature_extraction/text.py +++ b/sklearn/feature_extraction/text.py @@ -340,6 +340,13 @@ def build_tokenizer(self): if self.tokenizer is not None: return self.tokenizer token_pattern = re.compile(self.token_pattern) + + if token_pattern.groups > 1: + raise ValueError( + "More than 1 capturing group in token pattern. Only a single " + "group should be captured." + ) + return token_pattern.findall def get_stop_words(self): @@ -605,6 +612,10 @@ class HashingVectorizer(TransformerMixin, _VectorizerMixin, BaseEstimator): or more alphanumeric characters (punctuation is completely ignored and always treated as a token separator). + If there is a capturing group in token_pattern then the + captured group content, not the entire match, becomes the token. + At most one capturing group is permitted. + ngram_range : tuple (min_n, max_n), default=(1, 1) The lower and upper boundary of the range of n-values for different n-grams to be extracted. All values of n such that min_n <= n <= max_n @@ -872,6 +883,10 @@ class CountVectorizer(_VectorizerMixin, BaseEstimator): or more alphanumeric characters (punctuation is completely ignored and always treated as a token separator). + If there is a capturing group in token_pattern then the + captured group content, not the entire match, becomes the token. + At most one capturing group is permitted. + ngram_range : tuple (min_n, max_n), default=(1, 1) The lower and upper boundary of the range of n-values for different word n-grams or char n-grams to be extracted. All values of n such @@ -1596,6 +1611,10 @@ class TfidfVectorizer(CountVectorizer): or more alphanumeric characters (punctuation is completely ignored and always treated as a token separator). + If there is a capturing group in token_pattern then the + captured group content, not the entire match, becomes the token. + At most one capturing group is permitted. + ngram_range : tuple (min_n, max_n), default=(1, 1) The lower and upper boundary of the range of n-values for different n-grams to be extracted. All values of n such that min_n <= n <= max_n
<!-- Thanks for contributing a pull request! Please ensure you have taken a look at the contribution guidelines: https://github.com/scikit-learn/scikit-learn/blob/master/CONTRIBUTING.md#pull-request-checklist --> #### Reference Issues/PRs <!-- Example: Fixes #1234. See also #3456. Please use keywords (e.g., Fixes) to create link to the issues or pull requests you resolved, so that they will automatically be closed when your pull request is merged. See https://github.com/blog/1506-closing-issues-via-pull-requests --> Fixes #12971 #### What does this implement/fix? Explain your changes. 1. Merges in changes from #13229, which raises a ValueError if the token pattern regex has more than one capturing group and documents the general behavior of capturing groups in the token pattern regex 2. Improves the doc for token_pattern per requested changes on #13229 3. Changes the test spec from testing 0 capturing groups to testing 1 capturing group per requested changes on #13229 4. Modifies the test corpus and regexes for `test_countvectorizer_custom_token_pattern` so they represent a more "realistic" type of custom token pattern than used in #13229. The previous test used an example from #12971 where the custom token pattern behaved the same as the default token pattern on that particular corpus. My new test is an adapted version of those examples that uses some of the same selectors but also (a) behaves differently than the default and (b) gives an example of what you might actually use a capturing group for. I have modified both regexes so they meet these requirements and are almost identical, but the first has 1 capturing group and the second has 2 capturing groups. #### Any other comments? Same as #13229, this does not address deprecation or backward compatibility <!-- Please be aware that we are a loose team of volunteers so patience is necessary; assistance handling other issues is very welcome. We value all user contributions, no matter how minor they are. If we are slow to review, either the pull request needs some benchmarking, tinkering, convincing, etc. or more likely the reviewers are simply busy. In either case, we ask for your understanding during the review process. For more information, see our FAQ on this topic: http://scikit-learn.org/dev/faq.html#why-is-my-pull-request-not-getting-any-attention. Thanks for contributing! -->
https://api.github.com/repos/scikit-learn/scikit-learn/pulls/15427
2019-11-01T02:35:22Z
2020-10-21T10:43:46Z
2020-10-21T10:43:46Z
2020-10-21T10:43:46Z
1,348
scikit-learn/scikit-learn
46,258
improve: allows connect primitive node to reroute if primitive node has type
diff --git a/web/extensions/core/widgetInputs.js b/web/extensions/core/widgetInputs.js index 4fe0a60135..8955fca878 100644 --- a/web/extensions/core/widgetInputs.js +++ b/web/extensions/core/widgetInputs.js @@ -240,6 +240,7 @@ app.registerExtension({ // No widget, we cant connect if (!input.widget) { + if (this.outputs[0]?.type != '*' && target_node.type == "Reroute") return true; if (!(input.type in ComfyWidgets)) return false; }
https://api.github.com/repos/comfyanonymous/ComfyUI/pulls/751
2023-06-08T08:10:10Z
2023-06-09T06:21:31Z
2023-06-09T06:21:31Z
2023-06-25T00:27:59Z
129
comfyanonymous/ComfyUI
17,877
Remove hard coded max_items in history API
diff --git a/web/scripts/api.js b/web/scripts/api.js index de56b23108..9aa7528af0 100644 --- a/web/scripts/api.js +++ b/web/scripts/api.js @@ -254,9 +254,9 @@ class ComfyApi extends EventTarget { * Gets the prompt execution history * @returns Prompt history including node outputs */ - async getHistory() { + async getHistory(max_items=200) { try { - const res = await this.fetchApi("/history?max_items=200"); + const res = await this.fetchApi(`/history?max_items=${max_items}`); return { History: Object.values(await res.json()) }; } catch (error) { console.error(error);
https://api.github.com/repos/comfyanonymous/ComfyUI/pulls/2063
2023-11-26T13:23:31Z
2023-11-27T17:09:19Z
2023-11-27T17:09:19Z
2023-11-27T17:09:19Z
163
comfyanonymous/ComfyUI
18,044
Don't bubble when metadata_button is clicked
diff --git a/javascript/extraNetworks.js b/javascript/extraNetworks.js index 40818bb4970..742a3c2dbd7 100644 --- a/javascript/extraNetworks.js +++ b/javascript/extraNetworks.js @@ -132,12 +132,14 @@ function popup(contents){ globalPopup.style.display = "flex"; } -function extraNetworksShowMetadata(text){ +function extraNetworksShowMetadata(event, text){ elem = document.createElement('pre') elem.classList.add('popup-metadata'); elem.textContent = text; popup(elem); + + event.stopPropagation() } function requestGet(url, data, handler, errorHandler){ diff --git a/modules/ui_extra_networks.py b/modules/ui_extra_networks.py index 3cf8fcb6955..8418147b6de 100644 --- a/modules/ui_extra_networks.py +++ b/modules/ui_extra_networks.py @@ -150,7 +150,7 @@ def create_html_for_item(self, item, tabname): metadata_button = "" metadata = item.get("metadata") if metadata: - metadata_button = f"<div class='metadata-button' title='Show metadata' onclick='extraNetworksRequestMetadata({json.dumps(self.name)}, {json.dumps(item['name'])})'></div>" + metadata_button = f"<div class='metadata-button' title='Show metadata' onclick='extraNetworksRequestMetadata(event, {json.dumps(self.name)}, {json.dumps(item['name'])})'></div>" args = { "preview_html": "style='background-image: url(\"" + html.escape(preview) + "\")'" if preview else '',
Currently, clicking an extra network's metadata button also triggers the card's own onclick handler. This prevents that. **Environment this was tested in** - OS: Windows 10 - Browser: Edge 111.0.1661.44
https://api.github.com/repos/AUTOMATIC1111/stable-diffusion-webui/pulls/8749
2023-03-20T01:38:20Z
2023-03-25T09:09:05Z
2023-03-25T09:09:05Z
2023-03-25T20:31:05Z
362
AUTOMATIC1111/stable-diffusion-webui
40,452
Optionally sign initial SOA query
diff --git a/AUTHORS.md b/AUTHORS.md index 21bfaa3eb50..bef1f452983 100644 --- a/AUTHORS.md +++ b/AUTHORS.md @@ -227,6 +227,7 @@ Authors * [Rémy HUBSCHER](https://github.com/Natim) * [Rémy Léone](https://github.com/sieben) * [Richard Barnes](https://github.com/r-barnes) +* [Richard Harman](https://github.com/warewolf) * [Richard Panek](https://github.com/kernelpanek) * [Robert Buchholz](https://github.com/rbu) * [Robert Dailey](https://github.com/pahrohfit) diff --git a/certbot-dns-rfc2136/certbot_dns_rfc2136/__init__.py b/certbot-dns-rfc2136/certbot_dns_rfc2136/__init__.py index 3df0b8172ff..ae42fad1e7f 100644 --- a/certbot-dns-rfc2136/certbot_dns_rfc2136/__init__.py +++ b/certbot-dns-rfc2136/certbot_dns_rfc2136/__init__.py @@ -26,8 +26,8 @@ Use of this plugin requires a configuration file containing the target DNS server and optional port that supports RFC 2136 Dynamic Updates, the name -of the TSIG key, the TSIG key secret itself and the algorithm used if it's -different to HMAC-MD5. +of the TSIG key, the TSIG key secret itself, the algorithm used if it's +different to HMAC-MD5, and optionally whether to sign the initial SOA query. .. code-block:: ini :name: credentials.ini @@ -44,6 +44,9 @@ AmKd7ak51vWKgSl12ib86oQRPkpDjg== # TSIG key algorithm dns_rfc2136_algorithm = HMAC-SHA512 + # TSIG sign SOA query (optional, default: false) + dns_rfc2136_sign_query = false + The path to this file can be provided interactively or using the ``--dns-rfc2136-credentials`` command-line argument. Certbot records the @@ -194,4 +197,34 @@ }; }; +Another solution is to add `dns_rfc2136_sign_query = true` to the configuration file and then +add the key to the `match-clients` list within the external zone view. All queries signed with +this key should then be directed to this view, regardless of source IP. + +.. code-block:: none + :caption: Split-view BIND configuration with key-based ACLs + + key "keyname." { + algorithm hmac-sha512; + secret "4q4wM/2I180UXoMyN4INVhJNi8V9BCV+jMw2mXgZw/CSuxUT8C7NKKFs \ +AmKd7ak51vWKgSl12ib86oQRPkpDjg=="; + }; + + // adjust internal-addresses to suit your needs + acl internal-address { 127.0.0.0/8; 10.0.0.0/8; 192.168.0.0/16; 172.16.0.0/12; }; + + acl certbot-keys { key keyname.; } + + view "external" { + match-clients { acl certbot-keys; !internal-addresses; any; }; + + zone "example.com." IN { + type master; + file "named.example.com"; + update-policy { + grant keyname. name _acme-challenge.example.com. txt; + }; + }; + }; + """ diff --git a/certbot-dns-rfc2136/certbot_dns_rfc2136/_internal/dns_rfc2136.py b/certbot-dns-rfc2136/certbot_dns_rfc2136/_internal/dns_rfc2136.py index 36079ddd002..da59cae627f 100644 --- a/certbot-dns-rfc2136/certbot_dns_rfc2136/_internal/dns_rfc2136.py +++ b/certbot-dns-rfc2136/certbot_dns_rfc2136/_internal/dns_rfc2136.py @@ -90,12 +90,14 @@ def _cleanup(self, _domain: str, validation_name: str, validation: str) -> None: def _get_rfc2136_client(self) -> "_RFC2136Client": if not self.credentials: # pragma: no cover raise errors.Error("Plugin has not been prepared.") + return _RFC2136Client(cast(str, self.credentials.conf('server')), int(cast(str, self.credentials.conf('port')) or self.PORT), cast(str, self.credentials.conf('name')), cast(str, self.credentials.conf('secret')), self.ALGORITHMS.get(self.credentials.conf('algorithm') or '', - dns.tsig.HMAC_MD5)) + dns.tsig.HMAC_MD5), + (self.credentials.conf('sign_query') or '').upper() == "TRUE") class _RFC2136Client: @@ -103,13 +105,15 @@ class _RFC2136Client: Encapsulates all communication with the target DNS server. """ def __init__(self, server: str, port: int, key_name: str, key_secret: str, - key_algorithm: dns.name.Name, timeout: int = DEFAULT_NETWORK_TIMEOUT) -> None: + key_algorithm: dns.name.Name, sign_query: bool, + timeout: int = DEFAULT_NETWORK_TIMEOUT) -> None: self.server = server self.port = port self.keyring = dns.tsigkeyring.from_text({ key_name: key_secret }) self.algorithm = key_algorithm + self.sign_query = sign_query self._default_timeout = timeout def add_txt_record(self, record_name: str, record_content: str, record_ttl: int) -> None: @@ -217,8 +221,9 @@ def _query_soa(self, domain_name: str) -> bool: request = dns.message.make_query(domain, dns.rdatatype.SOA, dns.rdataclass.IN) # Turn off Recursion Desired bit in query request.flags ^= dns.flags.RD - # Use our TSIG keyring - request.use_tsig(self.keyring, algorithm=self.algorithm) + # Use our TSIG keyring if configured + if self.sign_query: + request.use_tsig(self.keyring, algorithm=self.algorithm) try: try: diff --git a/certbot/CHANGELOG.md b/certbot/CHANGELOG.md index 11462de2eb6..ee0c3a374f5 100644 --- a/certbot/CHANGELOG.md +++ b/certbot/CHANGELOG.md @@ -13,6 +13,16 @@ Certbot adheres to [Semantic Versioning](https://semver.org/). ### Changed +* Optionally sign the SOA query for dns-rfc2136, to help resolve problems with split-view + DNS setups and hidden primary setups. + * Certbot versions prior to v1.32.0 did not sign queries with the specified TSIG key + resulting in difficulty with split-horizon implementations. + * Certbot v1.32.0 through v2.5.0 signed queries by default, potentially causing + incompatibility with hidden primary setups with `allow-update-forwarding` enabled + if the secondary did not also have the TSIG key within its config. + * Certbot v2.6.0 and later no longer signs queries by default, but allows + the user to optionally sign these queries by explicit configuration using the + `dns_rfc2136_sign_query` option in the credentials .ini file. * Lineage name validity is performed for new lineages. `--cert-name` may no longer contain filepath separators (i.e. `/` or `\`, depending on the platform). * `certbot-dns-google` now loads credentials using the standard [Application Default
Initially implemented (but non-configurable) in #9408 , raised as a regression by @benweeks2 in #9671 . This adds an optional configuration parameter to enable signing of the initial SOA query when determining the authoritative nameserver for the zone. Default is disabled. Documentation has also been updated. Added @warewolf to `AUTHORS.md` as a lot of this has come from his original PR on #9106 Fixes #9671. ## Pull Request Checklist - [x] The Certbot team has recently expressed interest in reviewing a PR for this. If not, this PR may be closed due our limited resources and need to prioritize how we spend them. - [x] If the change being made is to a [distributed component](https://certbot.eff.org/docs/contributing.html#code-components-and-layout), edit the `master` section of `certbot/CHANGELOG.md` to include a description of the change being made. - [x] Add or update any documentation as needed to support the changes in this PR. - [x] Include your name in `AUTHORS.md` if you like.
https://api.github.com/repos/certbot/certbot/pulls/9672
2023-04-15T15:57:17Z
2023-04-25T01:25:58Z
2023-04-25T01:25:58Z
2023-04-26T11:40:40Z
1,843
certbot/certbot
813
Fixed #33515 -- Prevented recreation of migration for ManyToManyField to lowercased swappable setting.
diff --git a/django/db/models/fields/related.py b/django/db/models/fields/related.py index 18c6c4e607413..ca4f4368b6d1d 100644 --- a/django/db/models/fields/related.py +++ b/django/db/models/fields/related.py @@ -1728,11 +1728,15 @@ def deconstruct(self): kwargs["db_table"] = self.db_table if self.remote_field.db_constraint is not True: kwargs["db_constraint"] = self.remote_field.db_constraint - # Rel needs more work. + # Lowercase model names as they should be treated as case-insensitive. if isinstance(self.remote_field.model, str): - kwargs["to"] = self.remote_field.model + if "." in self.remote_field.model: + app_label, model_name = self.remote_field.model.split(".") + kwargs["to"] = "%s.%s" % (app_label, model_name.lower()) + else: + kwargs["to"] = self.remote_field.model.lower() else: - kwargs["to"] = self.remote_field.model._meta.label + kwargs["to"] = self.remote_field.model._meta.label_lower if getattr(self.remote_field, "through", None) is not None: if isinstance(self.remote_field.through, str): kwargs["through"] = self.remote_field.through diff --git a/docs/releases/4.0.3.txt b/docs/releases/4.0.3.txt index 2ef642fe5eb24..17e9f65074af2 100644 --- a/docs/releases/4.0.3.txt +++ b/docs/releases/4.0.3.txt @@ -12,4 +12,6 @@ reformatted with `black`_. Bugfixes ======== -* ... +* Prevented, following a regression in Django 4.0.1, :djadmin:`makemigrations` + from generating infinite migrations for a model with ``ManyToManyField`` to + a lowercased swappable model such as ``'auth.user'`` (:ticket:`33515`). diff --git a/tests/field_deconstruction/tests.py b/tests/field_deconstruction/tests.py index 64b90953f19e2..c78ed62876a0d 100644 --- a/tests/field_deconstruction/tests.py +++ b/tests/field_deconstruction/tests.py @@ -475,34 +475,34 @@ def test_many_to_many_field(self): name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.ManyToManyField") self.assertEqual(args, []) - self.assertEqual(kwargs, {"to": "auth.Permission"}) + self.assertEqual(kwargs, {"to": "auth.permission"}) self.assertFalse(hasattr(kwargs["to"], "setting_name")) # Test swappable field = models.ManyToManyField("auth.User") name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.ManyToManyField") self.assertEqual(args, []) - self.assertEqual(kwargs, {"to": "auth.User"}) + self.assertEqual(kwargs, {"to": "auth.user"}) self.assertEqual(kwargs["to"].setting_name, "AUTH_USER_MODEL") # Test through field = models.ManyToManyField("auth.Permission", through="auth.Group") name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.ManyToManyField") self.assertEqual(args, []) - self.assertEqual(kwargs, {"to": "auth.Permission", "through": "auth.Group"}) + self.assertEqual(kwargs, {"to": "auth.permission", "through": "auth.Group"}) # Test custom db_table field = models.ManyToManyField("auth.Permission", db_table="custom_table") name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.ManyToManyField") self.assertEqual(args, []) - self.assertEqual(kwargs, {"to": "auth.Permission", "db_table": "custom_table"}) + self.assertEqual(kwargs, {"to": "auth.permission", "db_table": "custom_table"}) # Test related_name field = models.ManyToManyField("auth.Permission", related_name="custom_table") name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.ManyToManyField") self.assertEqual(args, []) self.assertEqual( - kwargs, {"to": "auth.Permission", "related_name": "custom_table"} + kwargs, {"to": "auth.permission", "related_name": "custom_table"} ) # Test related_query_name field = models.ManyToManyField("auth.Permission", related_query_name="foobar") @@ -510,7 +510,7 @@ def test_many_to_many_field(self): self.assertEqual(path, "django.db.models.ManyToManyField") self.assertEqual(args, []) self.assertEqual( - kwargs, {"to": "auth.Permission", "related_query_name": "foobar"} + kwargs, {"to": "auth.permission", "related_query_name": "foobar"} ) # Test limit_choices_to field = models.ManyToManyField( @@ -520,7 +520,7 @@ def test_many_to_many_field(self): self.assertEqual(path, "django.db.models.ManyToManyField") self.assertEqual(args, []) self.assertEqual( - kwargs, {"to": "auth.Permission", "limit_choices_to": {"foo": "bar"}} + kwargs, {"to": "auth.permission", "limit_choices_to": {"foo": "bar"}} ) @override_settings(AUTH_USER_MODEL="auth.Permission") @@ -533,7 +533,7 @@ def test_many_to_many_field_swapped(self): self.assertEqual(path, "django.db.models.ManyToManyField") self.assertEqual(args, []) - self.assertEqual(kwargs, {"to": "auth.Permission"}) + self.assertEqual(kwargs, {"to": "auth.permission"}) self.assertEqual(kwargs["to"].setting_name, "AUTH_USER_MODEL") def test_many_to_many_field_related_name(self): @@ -551,7 +551,7 @@ class MyModel(models.Model): self.assertEqual(args, []) # deconstruct() should not include attributes which were not passed to # the field during initialization. - self.assertEqual(kwargs, {"to": "field_deconstruction.MyModel"}) + self.assertEqual(kwargs, {"to": "field_deconstruction.mymodel"}) # Passed attributes. name, path, args, kwargs = MyModel.m2m_related_name.field.deconstruct() self.assertEqual(path, "django.db.models.ManyToManyField") @@ -559,7 +559,7 @@ class MyModel(models.Model): self.assertEqual( kwargs, { - "to": "field_deconstruction.MyModel", + "to": "field_deconstruction.mymodel", "related_query_name": "custom_query_name", "limit_choices_to": {"flag": True}, }, diff --git a/tests/migrations/test_autodetector.py b/tests/migrations/test_autodetector.py index 36c6ffb872d71..8ddb3390029f1 100644 --- a/tests/migrations/test_autodetector.py +++ b/tests/migrations/test_autodetector.py @@ -3279,6 +3279,31 @@ def test_swappable_lowercase(self): [("__setting__", "AUTH_USER_MODEL")], ) + @override_settings(AUTH_USER_MODEL="thirdapp.CustomUser") + def test_swappable_many_to_many_model_case(self): + document_lowercase = ModelState( + "testapp", + "Document", + [ + ("id", models.AutoField(primary_key=True)), + ("owners", models.ManyToManyField(settings.AUTH_USER_MODEL.lower())), + ], + ) + document = ModelState( + "testapp", + "Document", + [ + ("id", models.AutoField(primary_key=True)), + ("owners", models.ManyToManyField(settings.AUTH_USER_MODEL)), + ], + ) + with isolate_lru_cache(apps.get_swappable_settings_name): + changes = self.get_changes( + [self.custom_user, document_lowercase], + [self.custom_user, document], + ) + self.assertEqual(len(changes), 0) + def test_swappable_changed(self): with isolate_lru_cache(apps.get_swappable_settings_name): before = self.make_project_state([self.custom_user, self.author_with_user])
ticket-33515 Thanks Chris Lee for the report. Regression in 43289707809c814a70f0db38ca4f82f35f43dbfd. Refs ticket-23916.
https://api.github.com/repos/django/django/pulls/15433
2022-02-16T08:41:00Z
2022-02-16T20:09:24Z
2022-02-16T20:09:24Z
2022-02-16T20:09:45Z
1,801
django/django
50,710
Bump ipywidgets from 7.5.1 to 7.6.2
diff --git a/poetry.lock b/poetry.lock index ce44f85f9..e0c6969c9 100644 --- a/poetry.lock +++ b/poetry.lock @@ -232,7 +232,7 @@ python-versions = "*" [[package]] name = "ipywidgets" -version = "7.5.1" +version = "7.6.2" description = "IPython HTML widgets for Jupyter" category = "main" optional = true @@ -241,6 +241,7 @@ python-versions = "*" [package.dependencies] ipykernel = ">=4.5.1" ipython = {version = ">=4.0.0", markers = "python_version >= \"3.3\""} +jupyterlab-widgets = {version = ">=1.0.0", markers = "python_version >= \"3.5\""} nbformat = ">=4.2.0" traitlets = ">=4.3.1" widgetsnbextension = ">=3.5.0,<3.6.0" @@ -325,6 +326,14 @@ python-versions = "!=3.0,!=3.1,!=3.2,!=3.3,!=3.4,>=2.7" pywin32 = {version = ">=1.0", markers = "sys_platform == \"win32\""} traitlets = "*" +[[package]] +name = "jupyterlab-widgets" +version = "1.0.0" +description = "A JupyterLab extension." +category = "main" +optional = true +python-versions = ">=3.6" + [[package]] name = "markupsafe" version = "1.1.1" @@ -901,8 +910,8 @@ ipython-genutils = [ {file = "ipython_genutils-0.2.0.tar.gz", hash = "sha256:eb2e116e75ecef9d4d228fdc66af54269afa26ab4463042e33785b887c628ba8"}, ] ipywidgets = [ - {file = "ipywidgets-7.5.1-py2.py3-none-any.whl", hash = "sha256:13ffeca438e0c0f91ae583dc22f50379b9d6b28390ac7be8b757140e9a771516"}, - {file = "ipywidgets-7.5.1.tar.gz", hash = "sha256:e945f6e02854a74994c596d9db83444a1850c01648f1574adf144fbbabe05c97"}, + {file = "ipywidgets-7.6.2-py2.py3-none-any.whl", hash = "sha256:eab960f737f380075cabca41f92e5e81dfb6eba3ce6392094469ef2418ca4d35"}, + {file = "ipywidgets-7.6.2.tar.gz", hash = "sha256:bbb881ce18fb0cff4ac718f40c04709c7ac86a77abee149f1b447965ede86e36"}, ] jedi = [ {file = "jedi-0.17.1-py2.py3-none-any.whl", hash = "sha256:1ddb0ec78059e8e27ec9eb5098360b4ea0a3dd840bedf21415ea820c21b40a22"}, @@ -924,6 +933,10 @@ jupyter-core = [ {file = "jupyter_core-4.6.3-py2.py3-none-any.whl", hash = "sha256:a4ee613c060fe5697d913416fc9d553599c05e4492d58fac1192c9a6844abb21"}, {file = "jupyter_core-4.6.3.tar.gz", hash = "sha256:394fd5dd787e7c8861741880bdf8a00ce39f95de5d18e579c74b882522219e7e"}, ] +jupyterlab-widgets = [ + {file = "jupyterlab_widgets-1.0.0-py3-none-any.whl", hash = "sha256:caeaf3e6103180e654e7d8d2b81b7d645e59e432487c1d35a41d6d3ee56b3fef"}, + {file = "jupyterlab_widgets-1.0.0.tar.gz", hash = "sha256:5c1a29a84d3069208cb506b10609175b249b6486d6b1cbae8fcde2a11584fb78"}, +] markupsafe = [ {file = "MarkupSafe-1.1.1-cp27-cp27m-macosx_10_6_intel.whl", hash = "sha256:09027a7803a62ca78792ad89403b1b7a73a01c8cb65909cd876f7fcebd79b161"}, {file = "MarkupSafe-1.1.1-cp27-cp27m-manylinux1_i686.whl", hash = "sha256:e249096428b3ae81b08327a63a485ad0878de3fb939049038579ac0ef61e17e7"},
Bumps [ipywidgets](http://ipython.org) from 7.5.1 to 7.6.2. [![Dependabot compatibility score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=ipywidgets&package-manager=pip&previous-version=7.5.1&new-version=7.6.2)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores) Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`. [//]: # (dependabot-automerge-start) [//]: # (dependabot-automerge-end) --- <details> <summary>Dependabot commands and options</summary> <br /> You can trigger Dependabot actions by commenting on this PR: - `@dependabot rebase` will rebase this PR - `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it - `@dependabot merge` will merge this PR after your CI passes on it - `@dependabot squash and merge` will squash and merge this PR after your CI passes on it - `@dependabot cancel merge` will cancel a previously requested merge and block automerging - `@dependabot reopen` will reopen this PR if it is closed - `@dependabot close` will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually - `@dependabot ignore this major version` will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself) - `@dependabot ignore this minor version` will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself) - `@dependabot ignore this dependency` will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself) </details>
https://api.github.com/repos/Textualize/rich/pulls/857
2020-12-28T06:45:57Z
2020-12-28T16:42:35Z
2020-12-28T16:42:35Z
2020-12-28T16:42:38Z
1,216
Textualize/rich
48,634
Fix the path of mtsamples.csv
diff --git a/openassistant/datasets/mt_note_generation/prepare.py b/openassistant/datasets/mt_note_generation/prepare.py index 7f0a914661..ff5fcdc5a1 100644 --- a/openassistant/datasets/mt_note_generation/prepare.py +++ b/openassistant/datasets/mt_note_generation/prepare.py @@ -63,7 +63,7 @@ def main(output_dir: str = "data"): """Download and prepare the dataset for use.""" os.makedirs(output_dir, exist_ok=True) kaggle.api.dataset_download_files("tboyle10/medicaltranscriptions", "data", unzip=True) - mt_samples = preprocess(pd.read_csv("mtsamples.csv")) + mt_samples = preprocess(pd.read_csv("data/mtsamples.csv")) conversations = get_conversations(mt_samples) random.shuffle(conversations) train_limit = math.ceil(len(conversations) * 0.6)
minor fix of path
https://api.github.com/repos/LAION-AI/Open-Assistant/pulls/1691
2023-02-17T22:12:31Z
2023-02-23T09:03:54Z
2023-02-23T09:03:54Z
2023-02-23T09:03:55Z
202
LAION-AI/Open-Assistant
37,244
st.echo: improved readability
diff --git a/lib/streamlit/__init__.py b/lib/streamlit/__init__.py index cd925b6762bf..2b8452d53579 100644 --- a/lib/streamlit/__init__.py +++ b/lib/streamlit/__init__.py @@ -52,7 +52,6 @@ # Give the package a version. import pkg_resources as _pkg_resources -from typing import List from typing import NoReturn # This used to be pkg_resources.require('streamlit') but it would cause @@ -60,11 +59,8 @@ __version__ = _pkg_resources.get_distribution("streamlit").version import contextlib as _contextlib -import re as _re import sys as _sys -import textwrap as _textwrap import threading as _threading -import traceback as _traceback import urllib.parse as _parse import click as _click @@ -84,6 +80,8 @@ # Modules that the user should have access to. These are imported with "as" # syntax pass mypy checking with implicit_reexport disabled. + +from streamlit.echo import echo as echo from streamlit.legacy_caching import cache as cache from streamlit.caching import singleton as experimental_singleton from streamlit.caching import memo as experimental_memo @@ -435,61 +433,6 @@ def set_message(): message.empty() -_SPACES_RE = _re.compile("\\s*") - - -@_contextlib.contextmanager -def echo(code_location="above"): - """Use in a `with` block to draw some code on the app, then execute it. - - Parameters - ---------- - code_location : "above" or "below" - Whether to show the echoed code before or after the results of the - executed code block. - - Example - ------- - - >>> with st.echo(): - >>> st.write('This code will be printed') - - """ - if code_location == "below": - show_code = code - show_warning = warning - else: - placeholder = empty() - show_code = placeholder.code - show_warning = placeholder.warning - - try: - frame = _traceback.extract_stack()[-3] - filename, start_line = frame.filename, frame.lineno - yield - frame = _traceback.extract_stack()[-3] - end_line = frame.lineno - lines_to_display = [] # type: List[str] - with _source_util.open_python_file(filename) as source_file: - source_lines = source_file.readlines() - lines_to_display.extend(source_lines[start_line:end_line]) - match = _SPACES_RE.match(lines_to_display[0]) - initial_spaces = match.end() if match else 0 - for line in source_lines[end_line:]: - match = _SPACES_RE.match(line) - indentation = match.end() if match else 0 - # The != 1 is because we want to allow '\n' between sections. - if indentation != 1 and indentation < initial_spaces: - break - lines_to_display.append(line) - line_to_display = _textwrap.dedent("".join(lines_to_display)) - - show_code(line_to_display, "python") - - except FileNotFoundError as err: - show_warning("Unable to display code. %s" % err) - - def _transparent_write(*args): """This is just st.write, but returns the arguments you passed to it.""" write(*args) diff --git a/lib/streamlit/echo.py b/lib/streamlit/echo.py new file mode 100644 index 000000000000..ac48625e30f0 --- /dev/null +++ b/lib/streamlit/echo.py @@ -0,0 +1,95 @@ +# Copyright 2018-2021 Streamlit Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import contextlib +import re +import textwrap +import traceback +from typing import List + +_SPACES_RE = re.compile("\\s*") + + +@contextlib.contextmanager +def echo(code_location="above"): + """Use in a `with` block to draw some code on the app, then execute it. + + Parameters + ---------- + code_location : "above" or "below" + Whether to show the echoed code before or after the results of the + executed code block. + + Example + ------- + + >>> with st.echo(): + >>> st.write('This code will be printed') + + """ + + from streamlit import code, warning, empty, source_util + + if code_location == "below": + show_code = code + show_warning = warning + else: + placeholder = empty() + show_code = placeholder.code + show_warning = placeholder.warning + + try: + # Get stack frame *before* running the echoed code. The frame's + # line number will point to the `st.echo` statement we're running. + frame = traceback.extract_stack()[-3] + filename, start_line = frame.filename, frame.lineno + + # Run the echoed code. + yield + + # Get stack frame *after* running code. This frame's line number will + # point to the last line in the echoed code. + frame = traceback.extract_stack()[-3] + end_line = frame.lineno + + # Open the file containing the source code of the echoed statement, + # and extract the lines inside the `with st.echo` block. + lines_to_display: List[str] = [] + with source_util.open_python_file(filename) as source_file: + source_lines = source_file.readlines() + lines_to_display.extend(source_lines[start_line:end_line]) + + # Our "end_line" is not necessarily the last line in the echo + # block. Iterate over the remaining lines in the source file + # until we find one that's indented less than the rest of the + # block. Note that this is *not* a perfect strategy, because + # de-denting is not guaranteed to signal "end of block". (A + # triple-quoted string might be dedented but still in the + # echo block, for example.) + if len(lines_to_display) > 0: + match = _SPACES_RE.match(lines_to_display[0]) + initial_spaces = match.end() if match else 0 + for line in source_lines[end_line:]: + match = _SPACES_RE.match(line) + indentation = match.end() if match else 0 + # The != 1 is because we want to allow '\n' between sections. + if indentation != 1 and indentation < initial_spaces: + break + lines_to_display.append(line) + + line_to_display = textwrap.dedent("".join(lines_to_display)) + show_code(line_to_display, "python") + + except FileNotFoundError as err: + show_warning("Unable to display code. %s" % err) diff --git a/lib/streamlit/elements/doc_string.py b/lib/streamlit/elements/doc_string.py index 9383162d6979..820f83857a55 100644 --- a/lib/streamlit/elements/doc_string.py +++ b/lib/streamlit/elements/doc_string.py @@ -26,6 +26,7 @@ CONFUSING_STREAMLIT_MODULES = ( + "streamlit.echo", "streamlit.delta_generator", "streamlit.legacy_caching.caching", ) diff --git a/lib/tests/streamlit/echo_test.py b/lib/tests/streamlit/echo_test.py index d4cbf78a1c5a..eff98df0aa84 100644 --- a/lib/tests/streamlit/echo_test.py +++ b/lib/tests/streamlit/echo_test.py @@ -12,37 +12,40 @@ # See the License for the specific language governing permissions and # limitations under the License. +from parameterized import parameterized + from tests import testutil import streamlit as st class EchoTest(testutil.DeltaGeneratorTestCase): - def test_echo(self): - for echo, echo_index, output_index in [ - (lambda: st.echo(), 0, 1), - (lambda: st.echo("above"), 0, 1), - (lambda: st.echo("below"), 1, 0), - ]: - - # The empty lines below are part of the test. Do not remove them. - with echo(): - st.write("Hello") + @parameterized.expand( + [ + ("code_location default", lambda: st.echo(), 0, 1), + ("code_location above", lambda: st.echo("above"), 0, 1), + ("code_location below", lambda: st.echo("below"), 1, 0), + ] + ) + def test_echo(self, _, echo, echo_index, output_index): + # The empty lines below are part of the test. Do not remove them. + with echo(): + st.write("Hello") - "hi" + "hi" - def foo(x): - y = x + 10 + def foo(x): + y = x + 10 - print(y) + print(y) - class MyClass(object): - def do_x(self): - pass + class MyClass(object): + def do_x(self): + pass - def do_y(self): - pass + def do_y(self): + pass - echo_str = """```python + echo_str = """```python st.write("Hello") "hi" @@ -62,13 +65,13 @@ def do_y(self): ```""" - element = self.get_delta_from_queue(echo_index).new_element - self.assertEqual(echo_str, element.markdown.body) + element = self.get_delta_from_queue(echo_index).new_element + self.assertEqual(echo_str, element.markdown.body) - element = self.get_delta_from_queue(output_index).new_element - self.assertEqual("Hello", element.markdown.body) + element = self.get_delta_from_queue(output_index).new_element + self.assertEqual("Hello", element.markdown.body) - self.clear_queue() + self.clear_queue() def test_root_level_echo(self): import tests.streamlit.echo_test_data.root_level_echo
Some drive-by cleanup on st.echo as I was investigating a related issue - Pulls `st.echo` out of `__init__.py` and into `echo.py` - `st.echo()` gets more inline comments explaining what the code is doing - `EchoTest.test_echo` is parameterized
https://api.github.com/repos/streamlit/streamlit/pulls/4169
2021-12-13T21:29:24Z
2021-12-13T21:50:41Z
2021-12-13T21:50:41Z
2021-12-13T21:50:45Z
2,448
streamlit/streamlit
21,912
update cpu related doc
diff --git a/docs/source/en/perf_train_cpu.mdx b/docs/source/en/perf_train_cpu.mdx index 7a12ab160522a..c35a62fcdcefd 100644 --- a/docs/source/en/perf_train_cpu.mdx +++ b/docs/source/en/perf_train_cpu.mdx @@ -25,22 +25,15 @@ Check more detailed information for [Auto Mixed Precision](https://intel.github. IPEX release is following PyTorch, to install via pip: -For PyTorch-1.10: +| PyTorch Version | IPEX version | +| :---------------: | :----------: | +| 1.13 | 1.13.0+cpu | +| 1.12 | 1.12.300+cpu | +| 1.11 | 1.11.200+cpu | +| 1.10 | 1.10.100+cpu | ``` -pip install intel_extension_for_pytorch==1.10.100+cpu -f https://software.intel.com/ipex-whl-stable -``` - -For PyTorch-1.11: - -``` -pip install intel_extension_for_pytorch==1.11.200+cpu -f https://software.intel.com/ipex-whl-stable -``` - -For PyTorch-1.12: - -``` -pip install intel_extension_for_pytorch==1.12.300+cpu -f https://software.intel.com/ipex-whl-stable +pip install intel_extension_for_pytorch==<version_name> -f https://developer.intel.com/ipex-whl-stable-cpu ``` Check more approaches for [IPEX installation](https://intel.github.io/intel-extension-for-pytorch/cpu/latest/tutorials/installation.html). diff --git a/docs/source/en/perf_train_cpu_many.mdx b/docs/source/en/perf_train_cpu_many.mdx index 0f1a1eddfd4e1..1310e40d30e14 100644 --- a/docs/source/en/perf_train_cpu_many.mdx +++ b/docs/source/en/perf_train_cpu_many.mdx @@ -27,15 +27,16 @@ Wheel files are available for the following Python versions: | Extension Version | Python 3.6 | Python 3.7 | Python 3.8 | Python 3.9 | Python 3.10 | | :---------------: | :--------: | :--------: | :--------: | :--------: | :---------: | +| 1.13.0 | | √ | √ | √ | √ | | 1.12.100 | | √ | √ | √ | √ | | 1.12.0 | | √ | √ | √ | √ | | 1.11.0 | | √ | √ | √ | √ | | 1.10.0 | √ | √ | √ | √ | | ``` -pip install oneccl_bind_pt=={pytorch_version} -f https://software.intel.com/ipex-whl-stable +pip install oneccl_bind_pt=={pytorch_version} -f https://developer.intel.com/ipex-whl-stable-cpu ``` -where `{pytorch_version}` should be your PyTorch version, for instance 1.12.0. +where `{pytorch_version}` should be your PyTorch version, for instance 1.13.0. Check more approaches for [oneccl_bind_pt installation](https://github.com/intel/torch-ccl). Versions of oneCCL and PyTorch must match. @@ -63,6 +64,10 @@ torch_ccl_path=$(python -c "import torch; import torch_ccl; import os; print(os source $torch_ccl_path/env/setvars.sh ``` +#### IPEX installation: + +IPEX provides performance optimizations for CPU training with both Float32 and BFloat16, you could refer [single CPU section](./perf_train_cpu). + The following "Usage in Trainer" takes mpirun in Intel® MPI library as an example. @@ -90,7 +95,8 @@ The following command enables training with 2 processes on one Xeon node, with o --doc_stride 128 \ --output_dir /tmp/debug_squad/ \ --no_cuda \ - --xpu_backend ccl + --xpu_backend ccl \ + --use_ipex ``` The following command enables training with a total of four processes on two Xeons (node0 and node1, taking node0 as the main process), ppn (processes per node) is set to 2, with one process running per one socket. The variables OMP_NUM_THREADS/CCL_WORKER_COUNT can be tuned for optimal performance. @@ -100,7 +106,7 @@ In node0, you need to create a configuration file which contains the IP addresse xxx.xxx.xxx.xxx #node0 ip xxx.xxx.xxx.xxx #node1 ip ``` -Now, run the following command in node0 and **4DDP** will be enabled in node0 and node1: +Now, run the following command in node0 and **4DDP** will be enabled in node0 and node1 with BF16 auto mixed precision: ```shell script export CCL_WORKER_COUNT=1 export MASTER_ADDR=xxx.xxx.xxx.xxx #node0 ip @@ -118,5 +124,7 @@ Now, run the following command in node0 and **4DDP** will be enabled in node0 an --doc_stride 128 \ --output_dir /tmp/debug_squad/ \ --no_cuda \ - --xpu_backend ccl -``` \ No newline at end of file + --xpu_backend ccl \ + --use_ipex \ + --bf16 +```
https://api.github.com/repos/huggingface/transformers/pulls/20444
2022-11-25T05:30:06Z
2022-11-28T13:54:36Z
2022-11-28T13:54:36Z
2022-11-28T13:57:31Z
1,326
huggingface/transformers
12,227
Move dg_stack into delta_generator.py and ensure it's never empty
diff --git a/lib/streamlit/__init__.py b/lib/streamlit/__init__.py index 49791c066473..4c53855f54fe 100644 --- a/lib/streamlit/__init__.py +++ b/lib/streamlit/__init__.py @@ -66,8 +66,12 @@ # Give the package a version. __version__ = _STREAMLIT_VERSION_STRING -from streamlit.delta_generator import DeltaGenerator as _DeltaGenerator -from streamlit.proto.RootContainer_pb2 import RootContainer as _RootContainer +from streamlit.delta_generator import ( + main_dg as _main_dg, + sidebar_dg as _sidebar_dg, + event_dg as _event_dg, + bottom_dg as _bottom_dg, +) from streamlit.runtime.caching import ( cache_resource as _cache_resource, cache_data as _cache_data, @@ -121,15 +125,15 @@ def _update_logger() -> None: _config.on_config_parsed(_update_logger, True) -_main = _DeltaGenerator(root_container=_RootContainer.MAIN) -sidebar = _DeltaGenerator(root_container=_RootContainer.SIDEBAR, parent=_main) -_event = _DeltaGenerator(root_container=_RootContainer.EVENT, parent=_main) -_bottom = _DeltaGenerator(root_container=_RootContainer.BOTTOM, parent=_main) - secrets = _secrets_singleton # DeltaGenerator methods: +_main = _main_dg +sidebar = _sidebar_dg +_event = _event_dg +_bottom = _bottom_dg + altair_chart = _main.altair_chart area_chart = _main.area_chart audio = _main.audio diff --git a/lib/streamlit/delta_generator.py b/lib/streamlit/delta_generator.py index 4b64bb57a442..eec5371d41fd 100644 --- a/lib/streamlit/delta_generator.py +++ b/lib/streamlit/delta_generator.py @@ -17,6 +17,7 @@ from __future__ import annotations import sys +from contextvars import ContextVar from copy import deepcopy from typing import ( TYPE_CHECKING, @@ -93,7 +94,6 @@ from streamlit.proto.RootContainer_pb2 import RootContainer from streamlit.runtime import caching, legacy_caching from streamlit.runtime.scriptrunner import get_script_run_ctx -from streamlit.runtime.scriptrunner.script_run_context import dg_stack from streamlit.runtime.state import NoValue if TYPE_CHECKING: @@ -313,7 +313,7 @@ def _active_dg(self) -> DeltaGenerator: # We're being invoked via an `st.foo` pattern - use the current # `with` dg (aka the top of the stack). current_stack = dg_stack.get() - if len(current_stack) > 0: + if len(current_stack) > 1: return current_stack[-1] # We're being invoked via an `st.sidebar.foo` pattern - ignore the @@ -781,6 +781,19 @@ def _arrow_add_rows( return self +main_dg = DeltaGenerator(root_container=RootContainer.MAIN) +sidebar_dg = DeltaGenerator(root_container=RootContainer.SIDEBAR, parent=main_dg) +event_dg = DeltaGenerator(root_container=RootContainer.EVENT, parent=main_dg) +bottom_dg = DeltaGenerator(root_container=RootContainer.BOTTOM, parent=main_dg) + +# The dg_stack tracks the currently active DeltaGenerator, and is pushed to when +# a DeltaGenerator is entered via a `with` block. This is implemented as a ContextVar +# so that different threads or async tasks can have their own stacks. +dg_stack: ContextVar[tuple[DeltaGenerator, ...]] = ContextVar( + "dg_stack", default=(main_dg,) +) + + def _prep_data_for_add_rows( data: Data, delta_type: str, diff --git a/lib/streamlit/elements/form.py b/lib/streamlit/elements/form.py index f13818c04e5c..b6e10ef7e175 100644 --- a/lib/streamlit/elements/form.py +++ b/lib/streamlit/elements/form.py @@ -21,7 +21,6 @@ from streamlit.proto import Block_pb2 from streamlit.runtime.metrics_util import gather_metrics from streamlit.runtime.scriptrunner import ScriptRunContext, get_script_run_ctx -from streamlit.runtime.scriptrunner.script_run_context import dg_stack from streamlit.runtime.state import WidgetArgs, WidgetCallback, WidgetKwargs if TYPE_CHECKING: @@ -42,6 +41,9 @@ def _current_form(this_dg: DeltaGenerator) -> FormData | None: To find the current form, we walk up the dg_stack until we find a DeltaGenerator that has FormData. """ + # Avoid circular imports. + from streamlit.delta_generator import dg_stack + if not runtime.exists(): return None diff --git a/lib/streamlit/runtime/scriptrunner/script_run_context.py b/lib/streamlit/runtime/scriptrunner/script_run_context.py index 030ca861d7b3..d723203dba5b 100644 --- a/lib/streamlit/runtime/scriptrunner/script_run_context.py +++ b/lib/streamlit/runtime/scriptrunner/script_run_context.py @@ -15,7 +15,6 @@ from __future__ import annotations import collections -import contextvars import threading from dataclasses import dataclass, field from typing import Callable, Counter, Dict, Final, Union @@ -37,14 +36,6 @@ UserInfo: TypeAlias = Dict[str, Union[str, None]] -# The dg_stack tracks the currently active DeltaGenerator, and is pushed to when -# a DeltaGenerator is entered via a `with` block. This is implemented as a ContextVar -# so that different threads or async tasks can have their own stacks. -dg_stack: contextvars.ContextVar[ - tuple["streamlit.delta_generator.DeltaGenerator", ...] -] = contextvars.ContextVar("dg_stack", default=tuple()) - - @dataclass class ScriptRunContext: """A context object that contains data for a "script run" - that is,
This work started out as an attempt to fix some bugs that currently exist in `feature/st.experimental_fragment`, but we may want to merge it directly into `develop` as it potentially improves how understandable some of our `DeltaGenerator`-related code is. Currently, `dg_stack` is a bit weird in that the way that it works is that the main `DeltaGenerator` is special and is never contained in it. In other words, `dg_stack` is the empty tuple when the `main` `DeltaGenerator` is active. When inside of one or more `with` blocks corresponding to containers (which by construction must be descendants of the `main` container), `dg_stack` is then populated. This PR changes the way this works so that `dg_stack` is initialized to a singleton tuple containing only the `main` container, and at that point everything works as before. The benefit of this is that there's never any discrepancy between the state of `dg_stack` and the currently active `DeltaGenerator`, which should make things easier to reason about.
https://api.github.com/repos/streamlit/streamlit/pulls/8241
2024-03-06T00:34:57Z
2024-03-06T22:03:43Z
2024-03-06T22:03:43Z
2024-03-06T22:03:48Z
1,355
streamlit/streamlit
22,251
Bump exllama module version
diff --git a/requirements.txt b/requirements.txt index e5530242b7..229ba16946 100644 --- a/requirements.txt +++ b/requirements.txt @@ -24,5 +24,5 @@ llama-cpp-python==0.1.69; platform_system != "Windows" https://github.com/abetlen/llama-cpp-python/releases/download/v0.1.69/llama_cpp_python-0.1.69-cp310-cp310-win_amd64.whl; platform_system == "Windows" https://github.com/PanQiWei/AutoGPTQ/releases/download/v0.2.2/auto_gptq-0.2.2+cu117-cp310-cp310-win_amd64.whl; platform_system == "Windows" https://github.com/PanQiWei/AutoGPTQ/releases/download/v0.2.2/auto_gptq-0.2.2+cu117-cp310-cp310-linux_x86_64.whl; platform_system == "Linux" and platform_machine == "x86_64" -https://github.com/jllllll/exllama/releases/download/0.0.5/exllama-0.0.5+cu117-cp310-cp310-win_amd64.whl; platform_system == "Windows" -https://github.com/jllllll/exllama/releases/download/0.0.5/exllama-0.0.5+cu117-cp310-cp310-linux_x86_64.whl; platform_system == "Linux" and platform_machine == "x86_64" +https://github.com/jllllll/exllama/releases/download/0.0.6/exllama-0.0.6+cu117-cp310-cp310-win_amd64.whl; platform_system == "Windows" +https://github.com/jllllll/exllama/releases/download/0.0.6/exllama-0.0.6+cu117-cp310-cp310-linux_x86_64.whl; platform_system == "Linux" and platform_machine == "x86_64"
https://github.com/turboderp/exllama/compare/d769533b6fe938d5533ffd3673e4751e5afa5a09...e61d4d31d44bd4dd3380fc773509c870ba74cb9f
https://api.github.com/repos/oobabooga/text-generation-webui/pulls/3087
2023-07-10T20:00:11Z
2023-07-10T22:35:59Z
2023-07-10T22:35:59Z
2023-07-20T20:56:48Z
458
oobabooga/text-generation-webui
26,559
Autoformat for json-rpc calls
diff --git a/mitmproxy/contentviews/json.py b/mitmproxy/contentviews/json.py index e045bbb07f..15c624add0 100644 --- a/mitmproxy/contentviews/json.py +++ b/mitmproxy/contentviews/json.py @@ -17,6 +17,7 @@ class ViewJSON(base.View): name = "JSON" content_types = [ "application/json", + "application/json-rpc", "application/vnd.api+json" ]
For json-rpc responses the program won't recognise the response as JSON. I have added the missing line to make it happen. > https://www.jsonrpc.org/historical/json-rpc-over-http.html#http-header > Content-Type SHOULD be 'application/json-rpc'
https://api.github.com/repos/mitmproxy/mitmproxy/pulls/3293
2018-08-13T11:23:51Z
2018-08-13T11:24:50Z
2018-08-13T11:24:50Z
2018-08-13T11:24:51Z
108
mitmproxy/mitmproxy
27,939
Fix off-by-one error.
diff --git a/requests/sessions.py b/requests/sessions.py index b970e0de95..3a517f0800 100644 --- a/requests/sessions.py +++ b/requests/sessions.py @@ -76,7 +76,7 @@ def resolve_redirects(self, resp, req, stream=False, timeout=None, verify=True, resp.content # Consume socket so it can be released - if i > self.max_redirects: + if i >= self.max_redirects: raise TooManyRedirects('Exceeded %s redirects.' % self.max_redirects) # Release the connection back into the pool.
Silly, small change, but may as well fix it. The logic as it stands would do max_redirects + 1 redirects. Which is odd.
https://api.github.com/repos/psf/requests/pulls/1020
2012-12-17T18:43:59Z
2012-12-17T18:46:09Z
2012-12-17T18:46:09Z
2021-09-08T18:01:09Z
145
psf/requests
32,545
NcursesDisplay.menu: treat ESC as cancel
diff --git a/certbot/display/util.py b/certbot/display/util.py index b4004997f60..39486b2bde9 100644 --- a/certbot/display/util.py +++ b/certbot/display/util.py @@ -1,4 +1,5 @@ """Certbot display.""" +import logging import os import textwrap @@ -9,6 +10,9 @@ from certbot import errors from certbot.display import completer + +logger = logging.getLogger(__name__) + WIDTH = 72 HEIGHT = 20 @@ -29,6 +33,9 @@ HELP = "help" """Display exit code when for when the user requests more help.""" +ESC = "esc" +"""Display exit code when the user hits Escape""" + def _wrap_lines(msg): """Format lines nicely to 80 chars. @@ -51,6 +58,24 @@ def _wrap_lines(msg): return os.linesep.join(fixed_l) + +def _clean(dialog_result): + """Treat sundy python-dialog return codes as CANCEL + + :param tuple dialog_result: (code, result) + :returns: the argument but with unknown codes set to -1 (Error) + :rtype: tuple + """ + code, result = dialog_result + if code in (OK, HELP): + return dialog_result + elif code in (CANCEL, ESC): + return (CANCEL, result) + else: + logger.debug("Surprising dialog return code %s", code) + return (CANCEL, result) + + @zope.interface.implementer(interfaces.IDisplay) class NcursesDisplay(object): """Ncurses-based display.""" @@ -58,6 +83,7 @@ class NcursesDisplay(object): def __init__(self, width=WIDTH, height=HEIGHT): super(NcursesDisplay, self).__init__() self.dialog = dialog.Dialog() + assert OK == self.dialog.DIALOG_OK, "What kind of absurdity is this?" self.width = width self.height = height @@ -92,7 +118,7 @@ def menu(self, message, choices, ok_label="OK", cancel_label="Cancel", :param dict unused_kwargs: absorbs default / cli_args :returns: tuple of the form (`code`, `index`) where - `code` - int display exit code + `code` - display exit code `int` - index of the selected item :rtype: tuple @@ -111,7 +137,7 @@ def menu(self, message, choices, ok_label="OK", cancel_label="Cancel", # Can accept either tuples or just the actual choices if choices and isinstance(choices[0], tuple): # pylint: disable=star-args - code, selection = self.dialog.menu(message, **menu_options) + code, selection = _clean(self.dialog.menu(message, **menu_options)) # Return the selection index for i, choice in enumerate(choices): @@ -126,9 +152,9 @@ def menu(self, message, choices, ok_label="OK", cancel_label="Cancel", (str(i), choice) for i, choice in enumerate(choices, 1) ] # pylint: disable=star-args - code, index = self.dialog.menu(message, **menu_options) + code, index = _clean(self.dialog.menu(message, **menu_options)) - if code == CANCEL: + if code == CANCEL or index == "": return code, -1 return code, int(index) - 1 @@ -140,7 +166,7 @@ def input(self, message, **unused_kwargs): :param dict _kwargs: absorbs default / cli_args :returns: tuple of the form (`code`, `string`) where - `code` - int display exit code + `code` - display exit code `string` - input entered by the user """ @@ -148,7 +174,7 @@ def input(self, message, **unused_kwargs): # each section takes at least one line, plus extras if it's longer than self.width wordlines = [1 + (len(section) / self.width) for section in sections] height = 6 + sum(wordlines) + len(sections) - return self.dialog.inputbox(message, width=self.width, height=height) + return _clean(self.dialog.inputbox(message, width=self.width, height=height)) def yesno(self, message, yes_label="Yes", no_label="No", **unused_kwargs): """Display a Yes/No dialog box. @@ -179,13 +205,13 @@ def checklist(self, message, tags, default_status=True, **unused_kwargs): :returns: tuple of the form (`code`, `list_tags`) where - `code` - int display exit code + `code` - display exit code `list_tags` - list of str tags selected by the user """ choices = [(tag, "", default_status) for tag in tags] - return self.dialog.checklist( - message, width=self.width, height=self.height, choices=choices) + return _clean(self.dialog.checklist( + message, width=self.width, height=self.height, choices=choices)) def directory_select(self, message, **unused_kwargs): """Display a directory selection screen. @@ -193,14 +219,14 @@ def directory_select(self, message, **unused_kwargs): :param str message: prompt to give the user :returns: tuple of the form (`code`, `string`) where - `code` - int display exit code + `code` - display exit code `string` - input entered by the user """ root_directory = os.path.abspath(os.sep) - return self.dialog.dselect( + return _clean(self.dialog.dselect( filepath=root_directory, width=self.width, - height=self.height, help_button=True, title=message) + height=self.height, help_button=True, title=message)) @zope.interface.implementer(interfaces.IDisplay) @@ -355,7 +381,7 @@ def directory_select(self, message, **unused_kwargs): :param str message: prompt to give the user :returns: tuple of the form (`code`, `string`) where - `code` - int display exit code + `code` - display exit code `string` - input entered by the user """ diff --git a/certbot/tests/display/util_test.py b/certbot/tests/display/util_test.py index 4a38803d198..a6ced90ab2e 100644 --- a/certbot/tests/display/util_test.py +++ b/certbot/tests/display/util_test.py @@ -96,6 +96,7 @@ def test_menu_desc_only_cancel(self, mock_menu): @mock.patch("certbot.display.util." "dialog.Dialog.inputbox") def test_input(self, mock_input): + mock_input.return_value = (mock.MagicMock(), mock.MagicMock()) self.displayer.input("message") self.assertEqual(mock_input.call_count, 1) @@ -112,6 +113,7 @@ def test_yesno(self, mock_yesno): @mock.patch("certbot.display.util." "dialog.Dialog.checklist") def test_checklist(self, mock_checklist): + mock_checklist.return_value = (mock.MagicMock(), mock.MagicMock()) self.displayer.checklist("message", TAGS) choices = [ @@ -125,6 +127,7 @@ def test_checklist(self, mock_checklist): @mock.patch("certbot.display.util.dialog.Dialog.dselect") def test_directory_select(self, mock_dselect): + mock_dselect.return_value = (mock.MagicMock(), mock.MagicMock()) self.displayer.directory_select("message") self.assertEqual(mock_dselect.call_count, 1)
Currently it will fire a weird traceback like: ``` File "/home/ubuntu/letsencrypt/letsencrypt/plugins/selection.py", line 113, in choose_plugin code, index = disp.menu(question, opts, help_label="More Info") File "/home/ubuntu/letsencrypt/letsencrypt/display/util.py", line 129, in menu return code, int(index) - 1 ValueError: invalid literal for int() with base 10: '' ```
https://api.github.com/repos/certbot/certbot/pulls/2767
2016-04-05T18:37:09Z
2016-07-06T22:12:37Z
2016-07-06T22:12:37Z
2016-10-06T01:21:35Z
1,748
certbot/certbot
3,203
Improve comments in test_idle.py.
diff --git a/Lib/test/test_idle.py b/Lib/test/test_idle.py index 31fffd94a08f2b..8bc01deaa33841 100644 --- a/Lib/test/test_idle.py +++ b/Lib/test/test_idle.py @@ -1,18 +1,20 @@ import unittest from test.support import import_module -# Skip test if _tkinter wasn't built, if idlelib is missing, -# or if tcl/tk is not the 8.5+ needed for ttk widgets. -tk = import_module('tkinter') # imports _tkinter +# Skip test_idle if _tkinter wasn't built, if tkinter is missing, +# if tcl/tk is not the 8.5+ needed for ttk widgets, +# or if idlelib is missing (not installed). +tk = import_module('tkinter') # Also imports _tkinter. if tk.TkVersion < 8.5: raise unittest.SkipTest("IDLE requires tk 8.5 or later.") idlelib = import_module('idlelib') -# Before test imports, tell IDLE to avoid changing the environment. +# Before importing and executing more of idlelib, +# tell IDLE to avoid changing the environment. idlelib.testing = True -# unittest.main and test.libregrtest.runtest.runtest_inner -# call load_tests, when present, to discover tests to run. +# Unittest.main and test.libregrtest.runtest.runtest_inner +# call load_tests, when present here, to discover tests to run. from idlelib.idle_test import load_tests if __name__ == '__main__':
https://api.github.com/repos/python/cpython/pulls/7057
2018-05-22T17:03:49Z
2018-05-22T17:24:05Z
2018-05-22T17:24:05Z
2018-05-22T17:40:12Z
358
python/cpython
4,485
Add same transcription job name case
diff --git a/localstack/services/transcribe/provider.py b/localstack/services/transcribe/provider.py index 0ebbc3b817f01..3d679b50104f0 100644 --- a/localstack/services/transcribe/provider.py +++ b/localstack/services/transcribe/provider.py @@ -12,6 +12,7 @@ from localstack.aws.api import RequestContext, handler from localstack.aws.api.transcribe import ( BadRequestException, + ConflictException, GetTranscriptionJobResponse, ListTranscriptionJobsResponse, MaxResults, @@ -123,6 +124,11 @@ def start_transcription_job( store = transcribe_stores[context.account_id][context.region] + if job_name in store.transcription_jobs: + raise ConflictException( + "The requested job name already exists. Use a different job name." + ) + s3_path = request["Media"]["MediaFileUri"] output_bucket = request.get("OutputBucketName", get_bucket_and_key_from_s3_uri(s3_path)[0]) output_key = request.get("OutputKey") diff --git a/tests/integration/test_transcribe.py b/tests/integration/test_transcribe.py index 24aa8f729467d..a7792b77dea78 100644 --- a/tests/integration/test_transcribe.py +++ b/tests/integration/test_transcribe.py @@ -5,7 +5,7 @@ import pytest from botocore.exceptions import ClientError -from localstack.aws.api.transcribe import BadRequestException, NotFoundException +from localstack.aws.api.transcribe import BadRequestException, ConflictException, NotFoundException from localstack.aws.connect import ServiceLevelClientFactory from localstack.utils.files import new_tmp_file from localstack.utils.platform import get_arch @@ -277,3 +277,38 @@ def _cleanup(): TranscriptionJobName=transcribe_job_name ) snapshot.match("delete-transcription-job", res_delete_transcription_job) + + @pytest.mark.aws_validated + @pytest.mark.skip_snapshot_verify(paths=["$..TranscriptionJob..Transcript"]) + def test_transcribe_start_job_same_name( + self, + s3_bucket, + snapshot, + aws_client, + ): + file_path = os.path.join(BASEDIR, "files/en-gb.wav") + test_key = "test-clip.wav" + transcribe_job_name = f"test-transcribe-job-{short_uid()}" + params = { + "TranscriptionJobName": transcribe_job_name, + "LanguageCode": "en-GB", + "Media": {"MediaFileUri": f"s3://{s3_bucket}/{test_key}"}, + } + + with open(file_path, "rb") as f: + aws_client.s3.upload_fileobj(f, s3_bucket, test_key) + + response_start_job = aws_client.transcribe.start_transcription_job(**params) + snapshot.match("response-start-job", response_start_job) + + self._wait_transcription_job(aws_client.transcribe, params["TranscriptionJobName"]) + + with pytest.raises((ClientError, ConflictException)) as e: + aws_client.transcribe.start_transcription_job(**params) + + snapshot.match("same-transcription-job-name", e.value.response) + + res_delete_transcription_job = aws_client.transcribe.delete_transcription_job( + TranscriptionJobName=transcribe_job_name + ) + snapshot.match("delete-transcription-job", res_delete_transcription_job) diff --git a/tests/integration/test_transcribe.snapshot.json b/tests/integration/test_transcribe.snapshot.json index 053b36b78a3b1..11cf06ed37abe 100644 --- a/tests/integration/test_transcribe.snapshot.json +++ b/tests/integration/test_transcribe.snapshot.json @@ -458,5 +458,43 @@ } } } + }, + "tests/integration/test_transcribe.py::TestTranscribe::test_transcribe_start_job_same_name": { + "recorded-date": "09-05-2023, 22:50:14", + "recorded-content": { + "response-start-job": { + "TranscriptionJob": { + "CreationTime": "datetime", + "LanguageCode": "en-GB", + "Media": { + "MediaFileUri": "s3:/<test-bucket>/test-clip.wav" + }, + "StartTime": "datetime", + "TranscriptionJobName": "<transcription-job:1>", + "TranscriptionJobStatus": "IN_PROGRESS" + }, + "ResponseMetadata": { + "HTTPHeaders": {}, + "HTTPStatusCode": 200 + } + }, + "same-transcription-job-name": { + "Error": { + "Code": "ConflictException", + "Message": "The requested job name already exists. Use a different job name." + }, + "Message": "The requested job name already exists. Use a different job name.", + "ResponseMetadata": { + "HTTPHeaders": {}, + "HTTPStatusCode": 400 + } + }, + "delete-transcription-job": { + "ResponseMetadata": { + "HTTPHeaders": {}, + "HTTPStatusCode": 200 + } + } + } } }
Added fix and test case if transcription job name is same in `StartTranscriptionJob`
https://api.github.com/repos/localstack/localstack/pulls/8288
2023-05-09T18:07:33Z
2023-05-10T06:54:20Z
2023-05-10T06:54:20Z
2023-08-28T13:06:46Z
1,176
localstack/localstack
28,674
Fixed #23014 -- Infinite migration regression with unique/index_together
diff --git a/django/db/migrations/autodetector.py b/django/db/migrations/autodetector.py index 37824e169cf35..36f0f020b27ee 100644 --- a/django/db/migrations/autodetector.py +++ b/django/db/migrations/autodetector.py @@ -795,13 +795,13 @@ def _generate_altered_foo_together(self, operation): if old_model_state.options.get(option_name) is None: old_value = None else: - old_value = [ - [ + old_value = set([ + tuple( self.renamed_fields.get((app_label, model_name, n), n) for n in unique - ] + ) for unique in old_model_state.options[option_name] - ] + ]) if old_value != new_model_state.options.get(option_name): self.add_operation( app_label, diff --git a/tests/migrations/test_autodetector.py b/tests/migrations/test_autodetector.py index 2e097d9247e87..4f7a682d2fcb6 100644 --- a/tests/migrations/test_autodetector.py +++ b/tests/migrations/test_autodetector.py @@ -66,9 +66,9 @@ class AutodetectorTests(TestCase): book_with_field_and_author_renamed = ModelState("otherapp", "Book", [("id", models.AutoField(primary_key=True)), ("writer", models.ForeignKey("testapp.Writer")), ("title", models.CharField(max_length=200))]) book_with_multiple_authors = ModelState("otherapp", "Book", [("id", models.AutoField(primary_key=True)), ("authors", models.ManyToManyField("testapp.Author")), ("title", models.CharField(max_length=200))]) book_with_multiple_authors_through_attribution = ModelState("otherapp", "Book", [("id", models.AutoField(primary_key=True)), ("authors", models.ManyToManyField("testapp.Author", through="otherapp.Attribution")), ("title", models.CharField(max_length=200))]) - book_unique = ModelState("otherapp", "Book", [("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Author")), ("title", models.CharField(max_length=200))], {"unique_together": [("author", "title")]}) - book_unique_2 = ModelState("otherapp", "Book", [("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Author")), ("title", models.CharField(max_length=200))], {"unique_together": [("title", "author")]}) - book_unique_3 = ModelState("otherapp", "Book", [("id", models.AutoField(primary_key=True)), ("newfield", models.IntegerField()), ("author", models.ForeignKey("testapp.Author")), ("title", models.CharField(max_length=200))], {"unique_together": [("title", "newfield")]}) + book_unique = ModelState("otherapp", "Book", [("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Author")), ("title", models.CharField(max_length=200))], {"unique_together": set([("author", "title")])}) + book_unique_2 = ModelState("otherapp", "Book", [("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Author")), ("title", models.CharField(max_length=200))], {"unique_together": set([("title", "author")])}) + book_unique_3 = ModelState("otherapp", "Book", [("id", models.AutoField(primary_key=True)), ("newfield", models.IntegerField()), ("author", models.ForeignKey("testapp.Author")), ("title", models.CharField(max_length=200))], {"unique_together": set([("title", "newfield")])}) attribution = ModelState("otherapp", "Attribution", [("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Author")), ("book", models.ForeignKey("otherapp.Book"))]) edition = ModelState("thirdapp", "Edition", [("id", models.AutoField(primary_key=True)), ("book", models.ForeignKey("otherapp.Book"))]) custom_user = ModelState("thirdapp", "CustomUser", [("id", models.AutoField(primary_key=True)), ("username", models.CharField(max_length=255))], bases=(AbstractBaseUser, )) @@ -77,7 +77,7 @@ class AutodetectorTests(TestCase): aardvark_based_on_author = ModelState("testapp", "Aardvark", [], bases=("testapp.Author", )) aardvark_pk_fk_author = ModelState("testapp", "Aardvark", [("id", models.OneToOneField("testapp.Author", primary_key=True))]) knight = ModelState("eggs", "Knight", [("id", models.AutoField(primary_key=True))]) - rabbit = ModelState("eggs", "Rabbit", [("id", models.AutoField(primary_key=True)), ("knight", models.ForeignKey("eggs.Knight")), ("parent", models.ForeignKey("eggs.Rabbit"))], {"unique_together": [("parent", "knight")]}) + rabbit = ModelState("eggs", "Rabbit", [("id", models.AutoField(primary_key=True)), ("knight", models.ForeignKey("eggs.Knight")), ("parent", models.ForeignKey("eggs.Rabbit"))], {"unique_together": set([("parent", "knight")])}) def repr_changes(self, changes): output = "" @@ -535,6 +535,16 @@ def test_unique_together(self): self.assertEqual(action.name, "book") self.assertEqual(action.unique_together, set([("author", "title")])) + def test_unique_together_no_changes(self): + "Tests that unique_togther doesn't generate a migration if no changes have been made" + # Make state + before = self.make_project_state([self.author_empty, self.book_unique]) + after = self.make_project_state([self.author_empty, self.book_unique]) + autodetector = MigrationAutodetector(before, after) + changes = autodetector._detect_changes() + # Right number of migrations? + self.assertEqual(len(changes), 0) + def test_unique_together_ordering(self): "Tests that unique_together also triggers on ordering changes" # Make state @@ -574,7 +584,7 @@ def test_add_field_and_unique_together(self): def test_remove_index_together(self): author_index_together = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)) - ], {"index_together": [("id", "name")]}) + ], {"index_together": set([("id", "name")])}) before = self.make_project_state([author_index_together]) after = self.make_project_state([self.author_name]) @@ -593,7 +603,7 @@ def test_remove_index_together(self): def test_remove_unique_together(self): author_unique_together = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)) - ], {"unique_together": [("id", "name")]}) + ], {"unique_together": set([("id", "name")])}) before = self.make_project_state([author_unique_together]) after = self.make_project_state([self.author_name])
https://api.github.com/repos/django/django/pulls/2950
2014-07-24T17:44:37Z
2014-07-24T18:30:38Z
2014-07-24T18:30:38Z
2014-07-24T18:42:32Z
1,598
django/django
51,314
enable CI after PR sync
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index a521551c4293..b0270c10cec8 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -1,7 +1,7 @@ name: Build on: pull_request: - types: [review_requested] + types: [review_requested, synchronize] branches: - "*" @@ -13,7 +13,7 @@ jobs: image: nvcr.io/nvidia/pytorch:21.07-py3 options: --gpus all --rm --ipc=host -v /data/cifar-10:/data/cifar-10 timeout-minutes: 1200 - if: github.event.pull_request.draft == false && github.base_ref == 'main' && github.event.pull_request.base.repo.full_name == 'hpcaitech/ColossalAI' + if: github.event.pull_request.draft == false && github.base_ref == 'main' && github.event.pull_request.base.repo.full_name == 'hpcaitech/ColossalAI' && toJson(github.event.pull_request.requested_reviewers) != '[]' steps: - name: Setup Environment run: |
The previous CI is only triggered when reviewer is requested. Now it will be triggered when reviewer is requested and synchronization occurs.
https://api.github.com/repos/hpcaitech/ColossalAI/pulls/97
2021-12-30T08:09:52Z
2022-01-04T12:31:15Z
2022-01-04T12:31:15Z
2022-01-04T12:31:15Z
277
hpcaitech/ColossalAI
11,850
Fix/SportDeutschland extractor
diff --git a/yt_dlp/extractor/sportdeutschland.py b/yt_dlp/extractor/sportdeutschland.py index 75074b31007..6fc3ce9eb12 100644 --- a/yt_dlp/extractor/sportdeutschland.py +++ b/yt_dlp/extractor/sportdeutschland.py @@ -1,95 +1,110 @@ from .common import InfoExtractor + from ..utils import ( - clean_html, - float_or_none, - int_or_none, - parse_iso8601, - parse_qs, - strip_or_none, - try_get, + format_field, + traverse_obj, + unified_timestamp, + strip_or_none ) class SportDeutschlandIE(InfoExtractor): _VALID_URL = r'https?://sportdeutschland\.tv/(?P<id>(?:[^/]+/)?[^?#/&]+)' _TESTS = [{ - 'url': 'https://sportdeutschland.tv/badminton/re-live-deutsche-meisterschaften-2020-halbfinals?playlistId=0', + 'url': 'https://sportdeutschland.tv/blauweissbuchholztanzsport/buchholzer-formationswochenende-2023-samstag-1-bundesliga-landesliga', 'info_dict': { - 'id': '5318cac0275701382770543d7edaf0a0', + 'id': '983758e9-5829-454d-a3cf-eb27bccc3c94', 'ext': 'mp4', - 'title': 'Re-live: Deutsche Meisterschaften 2020 - Halbfinals - Teil 1', - 'duration': 16106.36, - }, - 'params': { - 'noplaylist': True, - # m3u8 download - 'skip_download': True, - }, + 'title': 'Buchholzer Formationswochenende 2023 - Samstag - 1. Bundesliga / Landesliga', + 'description': 'md5:a288c794a5ee69e200d8f12982f81a87', + 'live_status': 'was_live', + 'channel': 'Blau-Weiss Buchholz Tanzsport', + 'channel_url': 'https://sportdeutschland.tv/blauweissbuchholztanzsport', + 'channel_id': '93ec33c9-48be-43b6-b404-e016b64fdfa3', + 'display_id': '9839a5c7-0dbb-48a8-ab63-3b408adc7b54', + 'duration': 32447, + 'upload_date': '20230114', + 'timestamp': 1673730018.0, + } }, { - 'url': 'https://sportdeutschland.tv/badminton/re-live-deutsche-meisterschaften-2020-halbfinals?playlistId=0', + 'url': 'https://sportdeutschland.tv/deutscherbadmintonverband/bwf-tour-1-runde-feld-1-yonex-gainward-german-open-2022-0', 'info_dict': { - 'id': 'c6e2fdd01f63013854c47054d2ab776f', - 'title': 'Re-live: Deutsche Meisterschaften 2020 - Halbfinals', - 'description': 'md5:5263ff4c31c04bb780c9f91130b48530', - 'duration': 31397, - }, - 'playlist_count': 2, - }, { - 'url': 'https://sportdeutschland.tv/freeride-world-tour-2021-fieberbrunn-oesterreich', - 'only_matching': True, + 'id': '95b97d9a-04f6-4880-9039-182985c33943', + 'ext': 'mp4', + 'title': 'BWF Tour: 1. Runde Feld 1 - YONEX GAINWARD German Open 2022', + 'description': 'md5:2afb5996ceb9ac0b2ac81f563d3a883e', + 'live_status': 'was_live', + 'channel': 'Deutscher Badminton Verband', + 'channel_url': 'https://sportdeutschland.tv/deutscherbadmintonverband', + 'channel_id': '93ca5866-2551-49fc-8424-6db35af58920', + 'display_id': '95c80c52-6b9a-4ae9-9197-984145adfced', + 'duration': 41097, + 'upload_date': '20220309', + 'timestamp': 1646860727.0, + } }] def _real_extract(self, url): display_id = self._match_id(url) - data = self._download_json( - 'https://backend.sportdeutschland.tv/api/permalinks/' + display_id, + meta = self._download_json( + 'https://api.sportdeutschland.tv/api/stateless/frontend/assets/' + display_id, display_id, query={'access_token': 'true'}) - asset = data['asset'] - title = (asset.get('title') or asset['label']).strip() - asset_id = asset.get('id') or asset.get('uuid') + + asset_id = traverse_obj(meta, 'id', 'uuid') + info = { 'id': asset_id, - 'title': title, - 'description': clean_html(asset.get('body') or asset.get('description')) or asset.get('teaser'), - 'duration': int_or_none(asset.get('seconds')), + 'channel_url': format_field(meta, ('profile', 'slug'), 'https://sportdeutschland.tv/%s'), + **traverse_obj(meta, { + 'title': (('title', 'name'), {strip_or_none}), + 'description': 'description', + 'channel': ('profile', 'name'), + 'channel_id': ('profile', 'id'), + 'is_live': 'currently_live', + 'was_live': 'was_live' + }, get_all=False) } - videos = asset.get('videos') or [] + + videos = meta.get('videos') or [] + if len(videos) > 1: - playlist_id = parse_qs(url).get('playlistId', [None])[0] - if not self._yes_playlist(playlist_id, asset_id): - videos = [videos[int(playlist_id)]] - - def entries(): - for i, video in enumerate(videos, 1): - video_id = video.get('uuid') - video_url = video.get('url') - if not (video_id and video_url): - continue - formats = self._extract_m3u8_formats( - video_url.replace('.smil', '.m3u8'), video_id, 'mp4', fatal=False) - if not formats and not self.get_param('ignore_no_formats'): - continue - yield { - 'id': video_id, - 'formats': formats, - 'title': title + ' - ' + (video.get('label') or 'Teil %d' % i), - 'duration': float_or_none(video.get('duration')), - } info.update({ '_type': 'multi_video', - 'entries': entries(), - }) - else: - formats = self._extract_m3u8_formats( - videos[0]['url'].replace('.smil', '.m3u8'), asset_id, 'mp4') - section_title = strip_or_none(try_get(data, lambda x: x['section']['title'])) - info.update({ - 'formats': formats, - 'display_id': asset.get('permalink'), - 'thumbnail': try_get(asset, lambda x: x['images'][0]), - 'categories': [section_title] if section_title else None, - 'view_count': int_or_none(asset.get('views')), - 'is_live': asset.get('is_live') is True, - 'timestamp': parse_iso8601(asset.get('date') or asset.get('published_at')), - }) + 'entries': self.processVideoOrStream(asset_id, video) + } for video in enumerate(videos) if video.get('formats')) + + elif len(videos) == 1: + info.update( + self.processVideoOrStream(asset_id, videos[0]) + ) + + livestream = meta.get('livestream') + + if livestream is not None: + info.update( + self.processVideoOrStream(asset_id, livestream) + ) + return info + + def process_video_or_stream(self, asset_id, video): + video_id = video['id'] + video_src = video['src'] + video_type = video['type'] + + token = self._download_json( + f'https://api.sportdeutschland.tv/api/frontend/asset-token/{asset_id}', + video_id, query={'type': video_type, 'playback_id': video_src})['token'] + formats = self._extract_m3u8_formats(f'https://stream.mux.com/{video_src}.m3u8?token={token}', video_id) + + video_data = { + 'display_id': video_id, + 'formats': formats, + } + if video_type == 'mux_vod': + video_data.update({ + 'duration': video.get('duration'), + 'timestamp': unified_timestamp(video.get('created_at')) + }) + + return video_data
**IMPORTANT**: PRs without the template will be CLOSED ### Description of your *pull request* and other information <!-- Explanation of your *pull request* in arbitrary form goes here. Please **make sure the description explains the purpose and effect** of your *pull request* and is worded well enough to be understood. Provide as much **context and examples** as possible --> - Updated API Url to reflect changes from sportdeutschland.tv - Added token generation for stream API calls - Added support for (currently running) live streams Fixes #3005 The Tests are no longer accurate since the VODs aren't available anymore. I have decided not to include my updated tests in the PR, since they likely will also stop working in the near future. If asked for, I would append them here. <details open><summary>Template</summary> <!-- OPEN is intentional --> <!-- # PLEASE FOLLOW THE GUIDE BELOW - You will be asked some questions, please read them **carefully** and answer honestly - Put an `x` into all the boxes `[ ]` relevant to your *pull request* (like [x]) - Use *Preview* tab to see how your *pull request* will actually look like --> ### Before submitting a *pull request* make sure you have: - [X] At least skimmed through [contributing guidelines](https://github.com/yt-dlp/yt-dlp/blob/master/CONTRIBUTING.md#developer-instructions) including [yt-dlp coding conventions](https://github.com/yt-dlp/yt-dlp/blob/master/CONTRIBUTING.md#yt-dlp-coding-conventions) - [X] [Searched](https://github.com/yt-dlp/yt-dlp/search?q=is%3Apr&type=Issues) the bugtracker for similar pull requests - [X] Checked the code with [flake8](https://pypi.python.org/pypi/flake8) and [ran relevant tests](https://github.com/yt-dlp/yt-dlp/blob/master/CONTRIBUTING.md#developer-instructions) ### In order to be accepted and merged into yt-dlp each piece of code must be in public domain or released under [Unlicense](http://unlicense.org/). Check one of the following options: - [X] I am the original author of this code and I am willing to release it under [Unlicense](http://unlicense.org/) - [ ] I am not the original author of this code but it is in public domain or released under [Unlicense](http://unlicense.org/) (provide reliable evidence) ### What is the purpose of your *pull request*? - [X] Fix or improvement to an extractor (Make sure to add/update tests) - [ ] New extractor ([Piracy websites will not be accepted](https://github.com/yt-dlp/yt-dlp/blob/master/CONTRIBUTING.md#is-the-website-primarily-used-for-piracy)) - [ ] Core bug fix/improvement - [ ] New feature (It is strongly [recommended to open an issue first](https://github.com/yt-dlp/yt-dlp/blob/master/CONTRIBUTING.md#adding-new-feature-or-making-overarching-changes)) </details>
https://api.github.com/repos/yt-dlp/yt-dlp/pulls/6041
2023-01-15T19:04:23Z
2023-02-17T07:44:27Z
2023-02-17T07:44:27Z
2023-03-04T14:20:09Z
2,221
yt-dlp/yt-dlp
8,011
New linear algebra algorithm
diff --git a/linear_algebra/src/python-polynom-for-points.py b/linear_algebra/src/python-polynom-for-points.py new file mode 100644 index 000000000000..c884416b6dad --- /dev/null +++ b/linear_algebra/src/python-polynom-for-points.py @@ -0,0 +1,130 @@ +def points_to_polynomial(coordinates): + """ + coordinates is a two dimensional matrix: [[x, y], [x, y], ...] + number of points you want to use + + >>> print(points_to_polynomial([])) + The program cannot work out a fitting polynomial. + >>> print(points_to_polynomial([[]])) + The program cannot work out a fitting polynomial. + >>> print(points_to_polynomial([[1, 0], [2, 0], [3, 0]])) + f(x)=x^2*0.0+x^1*-0.0+x^0*0.0 + >>> print(points_to_polynomial([[1, 1], [2, 1], [3, 1]])) + f(x)=x^2*0.0+x^1*-0.0+x^0*1.0 + >>> print(points_to_polynomial([[1, 3], [2, 3], [3, 3]])) + f(x)=x^2*0.0+x^1*-0.0+x^0*3.0 + >>> print(points_to_polynomial([[1, 1], [2, 2], [3, 3]])) + f(x)=x^2*0.0+x^1*1.0+x^0*0.0 + >>> print(points_to_polynomial([[1, 1], [2, 4], [3, 9]])) + f(x)=x^2*1.0+x^1*-0.0+x^0*0.0 + >>> print(points_to_polynomial([[1, 3], [2, 6], [3, 11]])) + f(x)=x^2*1.0+x^1*-0.0+x^0*2.0 + >>> print(points_to_polynomial([[1, -3], [2, -6], [3, -11]])) + f(x)=x^2*-1.0+x^1*-0.0+x^0*-2.0 + >>> print(points_to_polynomial([[1, 5], [2, 2], [3, 9]])) + f(x)=x^2*5.0+x^1*-18.0+x^0*18.0 + """ + try: + check = 1 + more_check = 0 + d = coordinates[0][0] + for j in range(len(coordinates)): + if j == 0: + continue + if d == coordinates[j][0]: + more_check += 1 + solved = "x=" + str(coordinates[j][0]) + if more_check == len(coordinates) - 1: + check = 2 + break + elif more_check > 0 and more_check != len(coordinates) - 1: + check = 3 + else: + check = 1 + + if len(coordinates) == 1 and coordinates[0][0] == 0: + check = 2 + solved = "x=0" + except Exception: + check = 3 + + x = len(coordinates) + + if check == 1: + count_of_line = 0 + matrix = [] + # put the x and x to the power values in a matrix + while count_of_line < x: + count_in_line = 0 + a = coordinates[count_of_line][0] + count_line = [] + while count_in_line < x: + count_line.append(a ** (x - (count_in_line + 1))) + count_in_line += 1 + matrix.append(count_line) + count_of_line += 1 + + count_of_line = 0 + # put the y values into a vector + vector = [] + while count_of_line < x: + count_in_line = 0 + vector.append(coordinates[count_of_line][1]) + count_of_line += 1 + + count = 0 + + while count < x: + zahlen = 0 + while zahlen < x: + if count == zahlen: + zahlen += 1 + if zahlen == x: + break + bruch = (matrix[zahlen][count]) / (matrix[count][count]) + for counting_columns, item in enumerate(matrix[count]): + # manipulating all the values in the matrix + matrix[zahlen][counting_columns] -= item * bruch + # manipulating the values in the vector + vector[zahlen] -= vector[count] * bruch + zahlen += 1 + count += 1 + + count = 0 + # make solutions + solution = [] + while count < x: + solution.append(vector[count] / matrix[count][count]) + count += 1 + + count = 0 + solved = "f(x)=" + + while count < x: + remove_e = str(solution[count]).split("E") + if len(remove_e) > 1: + solution[count] = remove_e[0] + "*10^" + remove_e[1] + solved += "x^" + str(x - (count + 1)) + "*" + str(solution[count]) + if count + 1 != x: + solved += "+" + count += 1 + + return solved + + elif check == 2: + return solved + else: + return "The program cannot work out a fitting polynomial." + + +if __name__ == "__main__": + print(points_to_polynomial([])) + print(points_to_polynomial([[]])) + print(points_to_polynomial([[1, 0], [2, 0], [3, 0]])) + print(points_to_polynomial([[1, 1], [2, 1], [3, 1]])) + print(points_to_polynomial([[1, 3], [2, 3], [3, 3]])) + print(points_to_polynomial([[1, 1], [2, 2], [3, 3]])) + print(points_to_polynomial([[1, 1], [2, 4], [3, 9]])) + print(points_to_polynomial([[1, 3], [2, 6], [3, 11]])) + print(points_to_polynomial([[1, -3], [2, -6], [3, -11]])) + print(points_to_polynomial([[1, 5], [2, 2], [3, 9]]))
Hey, I added a new linear algebra algorithm which takes a number of x and y coordinates as input and then outputs a polynomial function that connects them. Thank you for taking a look at it.
https://api.github.com/repos/TheAlgorithms/Python/pulls/1122
2019-08-11T09:00:44Z
2019-08-12T07:13:58Z
2019-08-12T07:13:58Z
2019-08-12T07:13:58Z
1,587
TheAlgorithms/Python
30,342
Fix incorrect output on the genspider command
diff --git a/scrapy/commands/genspider.py b/scrapy/commands/genspider.py index 72248bdede4..5f44daa70d3 100644 --- a/scrapy/commands/genspider.py +++ b/scrapy/commands/genspider.py @@ -98,7 +98,7 @@ def _genspider(self, module, name, domain, template_name, template_file): print(f"Created spider {name!r} using template {template_name!r} ", end=('' if spiders_module else '\n')) if spiders_module: - print("in module:\n {spiders_module.__name__}.{module}") + print(f"in module:\n {spiders_module.__name__}.{module}") def _find_template(self, template): template_file = join(self.templates_dir, f'{template}.tmpl') diff --git a/tests/test_commands.py b/tests/test_commands.py index 85aee55a56d..d3ac05eac44 100644 --- a/tests/test_commands.py +++ b/tests/test_commands.py @@ -389,8 +389,9 @@ def test_arguments(self): def test_template(self, tplname='crawl'): args = [f'--template={tplname}'] if tplname else [] spname = 'test_spider' + spmodule = f"{self.project_name}.spiders.{spname}" p, out, err = self.proc('genspider', spname, 'test.com', *args) - self.assertIn(f"Created spider {spname!r} using template {tplname!r} in module", out) + self.assertIn(f"Created spider {spname!r} using template {tplname!r} in module:{os.linesep} {spmodule}", out) self.assertTrue(exists(join(self.proj_mod_path, 'spiders', 'test_spider.py'))) modify_time_before = getmtime(join(self.proj_mod_path, 'spiders', 'test_spider.py')) p, out, err = self.proc('genspider', spname, 'test.com', *args)
When running inside a project, the `genspider` command is outputting string placeholders rather than their actual contents. Example: ``` $ scrapy genspider example example.com Created spider 'example' using template 'basic' in module: {spiders_module.__name__}.{module} ``` This PR fixes it, by adding the missing f-string prefix to the string that represents that message.
https://api.github.com/repos/scrapy/scrapy/pulls/4874
2020-11-08T22:50:39Z
2020-11-10T12:23:29Z
2020-11-10T12:23:29Z
2020-11-10T12:23:36Z
471
scrapy/scrapy
34,378
UnrecognizedChallenge (fixes #855).
diff --git a/acme/acme/challenges.py b/acme/acme/challenges.py index fbb2e741849..d81e77f83ab 100644 --- a/acme/acme/challenges.py +++ b/acme/acme/challenges.py @@ -25,6 +25,14 @@ class Challenge(jose.TypedJSONObjectWithFields): """ACME challenge.""" TYPES = {} + @classmethod + def from_json(cls, jobj): + try: + return super(Challenge, cls).from_json(jobj) + except jose.UnrecognizedTypeError as error: + logger.debug(error) + return UnrecognizedChallenge.from_json(jobj) + class ContinuityChallenge(Challenge): # pylint: disable=abstract-method """Client validation challenges.""" @@ -34,11 +42,6 @@ class DVChallenge(Challenge): # pylint: disable=abstract-method """Domain validation challenges.""" -class UnrecognizedChallenge(Challenge): - """Unrecognized challenge.""" - typ = "unknown" - - class ChallengeResponse(jose.TypedJSONObjectWithFields): # _fields_to_partial_json | pylint: disable=abstract-method """ACME challenge response.""" @@ -47,6 +50,32 @@ class ChallengeResponse(jose.TypedJSONObjectWithFields): resource = fields.Resource(resource_type) +class UnrecognizedChallenge(Challenge): + """Unrecognized challenge. + + ACME specification defines a generic framework for challenges and + defines some standard challenges that are implemented in this + module. However, other implementations (including peers) might + define additional challenge types, which should be ignored if + unrecognized. + + :ivar jobj: Original JSON decoded object. + + """ + + def __init__(self, jobj): + super(UnrecognizedChallenge, self).__init__() + object.__setattr__(self, "jobj", jobj) + + def to_partial_json(self): + # pylint: disable=no-member + return self.jobj + + @classmethod + def from_json(cls, jobj): + return cls(jobj) + + @Challenge.register class SimpleHTTP(DVChallenge): """ACME "simpleHttp" challenge. diff --git a/acme/acme/challenges_test.py b/acme/acme/challenges_test.py index c82d95e198b..ed44d4c45e1 100644 --- a/acme/acme/challenges_test.py +++ b/acme/acme/challenges_test.py @@ -17,6 +17,32 @@ KEY = test_util.load_rsa_private_key('rsa512_key.pem') +class ChallengeTest(unittest.TestCase): + + def test_from_json_unrecognized(self): + from acme.challenges import Challenge + from acme.challenges import UnrecognizedChallenge + chall = UnrecognizedChallenge({"type": "foo"}) + # pylint: disable=no-member + self.assertEqual(chall, Challenge.from_json(chall.jobj)) + + +class UnrecognizedChallengeTest(unittest.TestCase): + + def setUp(self): + from acme.challenges import UnrecognizedChallenge + self.jobj = {"type": "foo"} + self.chall = UnrecognizedChallenge(self.jobj) + + def test_to_partial_json(self): + self.assertEqual(self.jobj, self.chall.to_partial_json()) + + def test_from_json(self): + from acme.challenges import UnrecognizedChallenge + self.assertEqual( + self.chall, UnrecognizedChallenge.from_json(self.jobj)) + + class SimpleHTTPTest(unittest.TestCase): def setUp(self): diff --git a/acme/acme/messages.py b/acme/acme/messages.py index d6e9952c320..02ae24c8f19 100644 --- a/acme/acme/messages.py +++ b/acme/acme/messages.py @@ -373,19 +373,7 @@ class Authorization(ResourceBody): @challenges.decoder def challenges(value): # pylint: disable=missing-docstring,no-self-argument - # The from_json method raises errors.UnrecognizedTypeError when a - # challenge of unknown type is encountered. We want to ignore this - # case. This forces us to do an explicit iteration, since list - # comprehensions can't handle exceptions. - challs = [] - for chall in value: - try: - challs.append(ChallengeBody.from_json(chall)) - except jose.UnrecognizedTypeError: - challs.append(ChallengeBody( - uri="UNKNOWN", chall=challenges.UnrecognizedChallenge, - status=STATUS_UNKNOWN)) - return tuple(challs) + return tuple(ChallengeBody.from_json(chall) for chall in value) @property def resolved_combinations(self): diff --git a/acme/acme/messages_test.py b/acme/acme/messages_test.py index d7bbdb0e49d..d2d859bc555 100644 --- a/acme/acme/messages_test.py +++ b/acme/acme/messages_test.py @@ -301,19 +301,6 @@ def setUp(self): 'combinations': combinations, } - # For unknown challenge types - self.jmsg_unknown_chall = { - 'resource': 'challenge', - 'uri': 'random_uri', - 'type': 'unknown', - 'tls': True, - } - - self.jobj_from_unknown = { - 'identifier': identifier.to_json(), - 'challenges': [self.jmsg_unknown_chall], - } - def test_from_json(self): from acme.messages import Authorization Authorization.from_json(self.jobj_from) @@ -328,11 +315,6 @@ def test_resolved_combinations(self): (self.challbs[1], self.challbs[2]), )) - def test_unknown_chall_type(self): - """Just make sure an error isn't thrown.""" - from acme.messages import Authorization - Authorization.from_json(self.jobj_from_unknown) - class AuthorizationResourceTest(unittest.TestCase): """Tests for acme.messages.AuthorizationResource."""
Overrides quick fix from #856. cc: @bifurcation, @jdkasten, @bmw
https://api.github.com/repos/certbot/certbot/pulls/860
2015-09-29T07:04:19Z
2015-09-29T15:52:15Z
2015-09-29T15:52:15Z
2016-05-06T19:21:34Z
1,348
certbot/certbot
3,427
Update Active Directory Attack.md
diff --git a/Methodology and Resources/Active Directory Attack.md b/Methodology and Resources/Active Directory Attack.md index c62feae6e7..0de3723d23 100644 --- a/Methodology and Resources/Active Directory Attack.md +++ b/Methodology and Resources/Active Directory Attack.md @@ -2219,6 +2219,21 @@ secretsdump.py -k -no-pass target.lab.local # IP of PC1: 10.0.0.4 ``` +#### Man-in-the-middle RDP connections with pyrdp-mitm +* https://github.com/GoSecure/pyrdp +* https://www.gosecure.net/blog/2018/12/19/rdp-man-in-the-middle-smile-youre-on-camera/ +* Usage +```sh +pyrdp-mitm.py <IP> +pyrdp-mitp.py <IP>:<PORT> # with custom port +pyrdp-mitm.py <IP> -k private_key.pem -c certificate.pem # with custom key and certificate +``` +* Exploitation + * If Network Level Authentication (NLA) is enabled, you will obtain the client's NetNTLMv2 challenge + * If NLA is disabled, you will obtain the password in plaintext + * Other features are available such as keystroke recording +* Alternatives + * S3th: https://github.com/SySS-Research/Seth, performs ARP spoofing prior to launching the RDP listener ### Active Directory Certificate Services
https://api.github.com/repos/swisskyrepo/PayloadsAllTheThings/pulls/572
2022-10-12T17:47:49Z
2022-10-12T19:42:34Z
2022-10-12T19:42:34Z
2022-10-12T19:42:34Z
348
swisskyrepo/PayloadsAllTheThings
8,679
[3.9] Split-out a fourth section in the descriptor HowTo guide (GH-22965)
diff --git a/Doc/howto/descriptor.rst b/Doc/howto/descriptor.rst index bed4078e3a3a9d..f1d1ab1d1d6101 100644 --- a/Doc/howto/descriptor.rst +++ b/Doc/howto/descriptor.rst @@ -13,7 +13,7 @@ Descriptor HowTo Guide :term:`Descriptors <descriptor>` let objects customize attribute lookup, storage, and deletion. -This HowTo guide has three major sections: +This guide has four major sections: 1) The "primer" gives a basic overview, moving gently from simple examples, adding one feature at a time. It is a great place to start. @@ -25,6 +25,11 @@ This HowTo guide has three major sections: detailed mechanics of how descriptors work. Most people don't need this level of detail. +4) The last section has pure Python equivalents for built-in descriptors that + are written in C. Read this if you're curious about how functions turn + into bound methods or about how to implement common tools like + :func:`classmethod`, :func:`staticmethod`, and :func:`property`. + Primer ^^^^^^ @@ -99,7 +104,7 @@ different, updated answers each time:: 3 >>> os.system('touch games/newfile') # Add a fourth file to the directory 0 - >>> g.size + >>> g.size # Automatically updated 4 >>> s.size # The songs directory has twenty files 20 @@ -197,7 +202,7 @@ be recorded, giving each descriptor its own *public_name* and *private_name*:: import logging - logging.basicConfig(level=logging.INFO, force=True) + logging.basicConfig(level=logging.INFO) class LoggedAccess: @@ -259,7 +264,7 @@ A :term:`descriptor` is what we call any object that defines :meth:`__get__`, :meth:`__set__`, or :meth:`__delete__`. Optionally, descriptors can have a :meth:`__set_name__` method. This is only -used in cases where a descriptor needs to know either the class where it is +used in cases where a descriptor needs to know either the class where it was created or the name of class variable it was assigned to. Descriptors get invoked by the dot operator during attribute lookup. If a @@ -318,7 +323,7 @@ managed attribute descriptor:: def validate(self, value): pass -Custom validators need to subclass from :class:`Validator` and supply a +Custom validators need to inherit from :class:`Validator` and must supply a :meth:`validate` method to test various restrictions as needed. @@ -334,8 +339,9 @@ Here are three practical data validation utilities: minimum or maximum. 3) :class:`String` verifies that a value is a :class:`str`. Optionally, it - validates a given minimum or maximum length. Optionally, it can test for - another predicate as well. + validates a given minimum or maximum length. It can validate a + user-defined `predicate + <https://en.wikipedia.org/wiki/Predicate_(mathematical_logic)>`_ as well. :: @@ -398,7 +404,7 @@ Here's how the data validators can be used in a real class:: class Component: name = String(minsize=3, maxsize=10, predicate=str.isupper) - kind = OneOf('plastic', 'metal') + kind = OneOf('wood', 'metal', 'plastic') quantity = Number(minvalue=0) def __init__(self, name, kind, quantity): @@ -426,9 +432,7 @@ Abstract -------- Defines descriptors, summarizes the protocol, and shows how descriptors are -called. Examines a custom descriptor and several built-in Python descriptors -including functions, properties, static methods, and class methods. Shows how -each works by giving a pure Python equivalent and a sample application. +called. Provides an example showing how object relational mappings work. Learning about descriptors not only provides access to a larger toolset, it creates a deeper understanding of how Python works and an appreciation for the @@ -519,24 +523,17 @@ The full C implementation can be found in :c:func:`PyObject_GenericGetAttr()` in It transforms ``A.x`` into ``A.__dict__['x'].__get__(None, A)``. -In pure Python, it looks like this:: - - def __getattribute__(cls, key): - "Emulate type_getattro() in Objects/typeobject.c" - v = object.__getattribute__(cls, key) - if hasattr(v, '__get__'): - return v.__get__(None, cls) - return v +The full C implementation can be found in :c:func:`type_getattro()` in +:source:`Objects/typeobject.c`. **Super**: The machinery is in the custom :meth:`__getattribute__` method for object returned by :class:`super()`. The attribute lookup ``super(A, obj).m`` searches ``obj.__class__.__mro__`` for the base class ``B`` immediately following ``A`` and then returns -``B.__dict__['m'].__get__(obj, A)``. - -If not a descriptor, ``m`` is returned unchanged. If not in the dictionary, -``m`` reverts to a search using :meth:`object.__getattribute__`. +``B.__dict__['m'].__get__(obj, A)``. If not a descriptor, ``m`` is returned +unchanged. If not in the dictionary, ``m`` reverts to a search using +:meth:`object.__getattribute__`. The implementation details are in :c:func:`super_getattro()` in :source:`Objects/typeobject.c`. A pure Python equivalent can be found in @@ -544,9 +541,9 @@ The implementation details are in :c:func:`super_getattro()` in .. _`Guido's Tutorial`: https://www.python.org/download/releases/2.2.3/descrintro/#cooperation -**Summary**: The details listed above show that the mechanism for descriptors is -embedded in the :meth:`__getattribute__()` methods for :class:`object`, -:class:`type`, and :func:`super`. +**Summary**: The mechanism for descriptors is embedded in the +:meth:`__getattribute__()` methods for :class:`object`, :class:`type`, and +:func:`super`. The important points to remember are: @@ -586,15 +583,16 @@ place at the time of class creation. If descriptors are added to the class afterwards, :meth:`__set_name__` will need to be called manually. -Descriptor Example ------------------- +ORM Example +----------- The following code is simplified skeleton showing how data descriptors could be used to implement an `object relational mapping <https://en.wikipedia.org/wiki/Object%E2%80%93relational_mapping>`_. -The essential idea is that instances only hold keys to a database table. The -actual data is stored in an external table that is being dynamically updated:: +The essential idea is that the data is stored in an external database. The +Python instances only hold keys to the database's tables. Descriptors take +care of lookups or updates:: class Field: @@ -609,8 +607,8 @@ actual data is stored in an external table that is being dynamically updated:: conn.execute(self.store, [value, obj.key]) conn.commit() -We can use the :class:`Field` to define "models" that describe the schema for -each table in a database:: +We can use the :class:`Field` class to define "models" that describe the schema +for each table in a database:: class Movie: table = 'Movies' # Table name @@ -650,10 +648,13 @@ it can be updated:: >>> Movie('Star Wars').director 'J.J. Abrams' +Pure Python Equivalents +^^^^^^^^^^^^^^^^^^^^^^^ + The descriptor protocol is simple and offers exciting possibilities. Several -use cases are so common that they have been packaged into individual function -calls. Properties, bound methods, static methods, and class methods are all -based on the descriptor protocol. +use cases are so common that they have been prepackaged into builtin tools. +Properties, bound methods, static methods, and class methods are all based on +the descriptor protocol. Properties @@ -746,7 +747,7 @@ prepended to the other arguments. By convention, the instance is called Methods can be created manually with :class:`types.MethodType` which is roughly equivalent to:: - class Method: + class MethodType: "Emulate Py_MethodType in Objects/classobject.c" def __init__(self, func, obj): @@ -770,7 +771,7 @@ during dotted lookup from an instance. Here's how it works:: "Simulate func_descr_get() in Objects/funcobject.c" if obj is None: return self - return types.MethodType(self, obj) + return MethodType(self, obj) Running the following class in the interpreter shows how the function descriptor works in practice:: @@ -816,8 +817,8 @@ If you have ever wondered where *self* comes from in regular methods or where *cls* comes from in class methods, this is it! -Static Methods and Class Methods --------------------------------- +Static Methods +-------------- Non-data descriptors provide a simple mechanism for variations on the usual patterns of binding functions into methods. @@ -883,6 +884,10 @@ Using the non-data descriptor protocol, a pure Python version of def __get__(self, obj, objtype=None): return self.f + +Class Methods +------------- + Unlike static methods, class methods prepend the class reference to the argument list before calling the function. This format is the same for whether the caller is an object or a class:: @@ -897,12 +902,11 @@ for whether the caller is an object or a class:: >>> print(F().f(3)) ('F', 3) - -This behavior is useful whenever the function only needs to have a class -reference and does not care about any underlying data. One use for -class methods is to create alternate class constructors. The classmethod -:func:`dict.fromkeys` creates a new dictionary from a list of keys. The pure -Python equivalent is:: +This behavior is useful whenever the method only needs to have a class +reference and does rely on data stored in a specific instance. One use for +class methods is to create alternate class constructors. For example, the +classmethod :func:`dict.fromkeys` creates a new dictionary from a list of +keys. The pure Python equivalent is:: class Dict: ... @@ -934,7 +938,7 @@ Using the non-data descriptor protocol, a pure Python version of cls = type(obj) if hasattr(obj, '__get__'): return self.f.__get__(cls) - return types.MethodType(self.f, cls) + return MethodType(self.f, cls) The code path for ``hasattr(obj, '__get__')`` was added in Python 3.9 and makes it possible for :func:`classmethod` to support chained decorators.
(cherry picked from commit e6a7ea4f2e0d6892ebd929235b1333f04b517eec) Co-authored-by: Raymond Hettinger <rhettinger@users.noreply.github.com>
https://api.github.com/repos/python/cpython/pulls/22969
2020-10-25T14:13:02Z
2020-10-25T14:35:57Z
2020-10-25T14:35:57Z
2020-10-25T14:36:08Z
2,565
python/cpython
4,386
Fix DynamoDB local libs
diff --git a/bin/Dockerfile.base b/bin/Dockerfile.base index 70296b4f3109f..e8c93a5f46496 100644 --- a/bin/Dockerfile.base +++ b/bin/Dockerfile.base @@ -33,7 +33,7 @@ RUN apk add --no-cache nss # https://github.com/carlossg/docker-maven/blob/master/jdk-8/Dockerfile) ARG MAVEN_VERSION=3.6.2 ARG USER_HOME_DIR="/root" -ARG SHA=ce50b1c91364cb77efe3776f756a6d92b76d9038b0a0782f7d53acf1e997a14d +ARG SHA=3fbc92d1961482d6fbd57fbf3dd6d27a4de70778528ee3fb44aa7d27eb32dfdc ARG BASE_URL=https://apache.osuosl.org/maven/maven-3/${MAVEN_VERSION}/binaries RUN mkdir -p /usr/share/maven /usr/share/maven/ref \ && curl -fsSL -o /tmp/apache-maven.tar.gz ${BASE_URL}/apache-maven-$MAVEN_VERSION-bin.tar.gz \ @@ -63,6 +63,7 @@ RUN ln -s /usr/bin/python3 /usr/bin/python; ln -s /usr/bin/pip3 /usr/bin/pip RUN pip install supervisor # init environment and cache some dependencies +ARG DYNAMODB_ZIP_URL=https://s3-us-west-2.amazonaws.com/dynamodb-local/dynamodb_local_latest.zip RUN mkdir -p /opt/code/localstack/localstack/infra && \ curl -o /tmp/localstack.es.zip \ https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-6.7.0.zip && \ @@ -81,8 +82,7 @@ RUN mkdir -p /opt/code/localstack/localstack/infra && \ bin/elasticsearch-plugin install analysis-stempel && \ bin/elasticsearch-plugin install analysis-ukrainian) && \ mkdir -p /opt/code/localstack/localstack/infra/dynamodb && \ - curl -o /tmp/localstack.ddb.zip \ - https://s3-us-west-2.amazonaws.com/dynamodb-local/dynamodb_local_latest.zip && \ + curl -o /tmp/localstack.ddb.zip ${DYNAMODB_ZIP_URL} && \ (cd localstack/infra/dynamodb && unzip -q /tmp/localstack.ddb.zip && rm /tmp/localstack.ddb.zip) ADD requirements.txt . RUN (pip install --upgrade pip) && \ diff --git a/localstack/constants.py b/localstack/constants.py index b786d2643a648..80c6bc1ca8363 100644 --- a/localstack/constants.py +++ b/localstack/constants.py @@ -82,11 +82,14 @@ 'mapper-murmur3', 'mapper-size', 'analysis-phonetic', 'analysis-smartcn', 'analysis-stempel', 'analysis-ukrainian'] # Default ES modules to exclude (save apprx 66MB in the final image) ELASTICSEARCH_DELETE_MODULES = ['ingest-geoip'] -DYNAMODB_JAR_URL = 'https://s3-us-west-2.amazonaws.com/dynamodb-local/dynamodb_local_latest.zip' ELASTICMQ_JAR_URL = 'https://s3-eu-west-1.amazonaws.com/softwaremill-public/elasticmq-server-0.15.2.jar' STS_JAR_URL = 'https://repo1.maven.org/maven2/com/amazonaws/aws-java-sdk-sts/1.11.14/aws-java-sdk-sts-1.11.14.jar' STEPFUNCTIONS_ZIP_URL = 'https://s3.amazonaws.com/stepfunctionslocal/StepFunctionsLocal.zip' +# TODO: Temporarily using a fixed version of DDB in Alpine, as we're hitting a SIGSEGV JVM crash with latest +DYNAMODB_JAR_URL_ALPINE = 'https://github.com/whummer/dynamodb-local/raw/master/etc/DynamoDBLocal.zip' +DYNAMODB_JAR_URL = 'https://s3-us-west-2.amazonaws.com/dynamodb-local/dynamodb_local_latest.zip' + # API endpoint for analytics events API_ENDPOINT = os.environ.get('API_ENDPOINT') or 'https://api.localstack.cloud/v1' diff --git a/localstack/dashboard/web/css/style.css b/localstack/dashboard/web/css/style.css index 14fcae6385cb6..c8845107b86b6 100644 --- a/localstack/dashboard/web/css/style.css +++ b/localstack/dashboard/web/css/style.css @@ -8,8 +8,8 @@ body { } #logo { - padding-top: 5px; - padding-bottom: 5px; + padding-top: 7px; + padding-bottom: 8px; padding-left: 20px; } @@ -50,7 +50,7 @@ sidebar div { top: 0px; bottom: 0px; position: absolute; - margin-top: 83px; + margin-top: 55px; } /* elements */ diff --git a/localstack/dashboard/web/index.html b/localstack/dashboard/web/index.html index cf9b7fa525c65..0d922ec13a4c7 100644 --- a/localstack/dashboard/web/index.html +++ b/localstack/dashboard/web/index.html @@ -23,7 +23,8 @@ <div class="aui-header-primary"> <h1 id="logo" class="aui-header-logo aui-header-logo-textonly"> <span class="aui-header-logo-device"> - <img src="img/localstack_small.png" style="height: 30px; padding: 2px; margin-right: 10px;"/></span> + <img src="img/localstack_small.png" style="height: 30px; padding: 2px; margin-right: 10px;"/> + </span> </h1> </div> </div> diff --git a/localstack/dashboard/web/views/infra.html b/localstack/dashboard/web/views/infra.html index 19aa69914b83e..eacf67ff0f657 100644 --- a/localstack/dashboard/web/views/infra.html +++ b/localstack/dashboard/web/views/infra.html @@ -37,11 +37,15 @@ <h2>Settings</h2> </div> </div> - <div style="position: absolute; top: 20px; left: 80px"> + <div style="position: absolute; top: 0px; left: 80px"> <header class="aui-page-header"> <div class="aui-page-header-inner"> <div class="aui-page-header-main"> - <h1 style="margin: 0px">Overview of Deployed Resources</h1> + <h1 style="margin: 3px; float: left">Overview of Deployed Resources</h1> + <span style="float: right; line-height: 50px"> + <img src="https://upload.wikimedia.org/wikipedia/commons/2/24/Warning_icon.svg" style="height: 20px" /> + Please note: This dashboard is outdated and may be removed in a future version. Please check out <a href="https://app.localstack.cloud">LocalStack Pro</a> for a more up-to-date UI. + </span> </div> </div> </header> diff --git a/localstack/services/cloudformation/cloudformation_starter.py b/localstack/services/cloudformation/cloudformation_starter.py index 024418900167a..2b34e46474c51 100644 --- a/localstack/services/cloudformation/cloudformation_starter.py +++ b/localstack/services/cloudformation/cloudformation_starter.py @@ -108,6 +108,22 @@ def fix_ids(obj, **kwargs): return recurse_object(resource_json, fix_ids) +def update_physical_resource_id(resource): + phys_res_id = getattr(resource, 'physical_resource_id', None) + if not phys_res_id: + if isinstance(resource, lambda_models.LambdaFunction): + func_arn = aws_stack.lambda_function_arn(resource.function_name) + resource.function_arn = resource.physical_resource_id = func_arn + elif isinstance(resource, sfn_models.StateMachine): + sm_arn = aws_stack.state_machine_arn(resource.name) + resource.physical_resource_id = sm_arn + elif isinstance(resource, service_models.StepFunctionsActivity): + act_arn = aws_stack.stepfunctions_activity_arn(resource.params.get('Name')) + resource.physical_resource_id = act_arn + else: + LOG.warning('Unable to determine physical_resource_id for resource %s' % type(resource)) + + def apply_patches(): """ Apply patches to make LocalStack seamlessly interact with the moto backend. TODO: Eventually, these patches should be contributed to the upstream repo! """ @@ -195,8 +211,7 @@ def _parse_and_create_resource(logical_id, resource_json, resources_map, region_ # This resource is either not deployable or already exists. Check if it can be updated if not template_deployer.is_updateable(logical_id, resource_wrapped, stack_name): LOG.debug('Resource %s need not be deployed: %s' % (logical_id, resource_json)) - if resource: - return resource + return resource # fix resource ARNs, make sure to convert account IDs 000000000000 to 123456789012 resource_json_arns_fixed = clone(json_safe(convert_objs_to_ids(resource_json))) @@ -215,7 +230,7 @@ def _parse_and_create_resource(logical_id, resource_json, resources_map, region_ # Apply some fixes/patches to the resource names, then deploy resource in LocalStack update_resource_name(resource, resource_json) - LOG.debug('Deploying CloudFormation resource: %s' % resource_json) + LOG.debug('Deploying CloudFormation resource (update=%s): %s' % (update, resource_json)) try: CURRENTLY_UPDATING_RESOURCES[resource_hash_key] = True @@ -303,21 +318,6 @@ def update_resource_id(resource, new_id, props, region_name): else: LOG.warning('Unexpected resource type when updating ID: %s' % type(resource)) - def update_physical_resource_id(resource): - phys_res_id = getattr(resource, 'physical_resource_id', None) - if not phys_res_id: - if isinstance(resource, lambda_models.LambdaFunction): - func_arn = aws_stack.lambda_function_arn(resource.function_name) - resource.function_arn = resource.physical_resource_id = func_arn - elif isinstance(resource, sfn_models.StateMachine): - sm_arn = aws_stack.state_machine_arn(resource.name) - resource.physical_resource_id = sm_arn - elif isinstance(resource, service_models.StepFunctionsActivity): - act_arn = aws_stack.stepfunctions_activity_arn(resource.params.get('Name')) - resource.physical_resource_id = act_arn - else: - LOG.warning('Unable to determine physical_resource_id for resource %s' % type(resource)) - parse_and_create_resource_orig = parsing.parse_and_create_resource parsing.parse_and_create_resource = parse_and_create_resource parse_and_update_resource_orig = parsing.parse_and_update_resource diff --git a/localstack/services/install.py b/localstack/services/install.py index 05ef07e6e31de..b1d1b073038e0 100644 --- a/localstack/services/install.py +++ b/localstack/services/install.py @@ -10,12 +10,13 @@ from localstack.utils import bootstrap from localstack.constants import (DEFAULT_SERVICE_PORTS, ELASTICMQ_JAR_URL, STS_JAR_URL, ELASTICSEARCH_JAR_URL, ELASTICSEARCH_PLUGIN_LIST, ELASTICSEARCH_DELETE_MODULES, - DYNAMODB_JAR_URL, LOCALSTACK_MAVEN_VERSION, STEPFUNCTIONS_ZIP_URL, LOCALSTACK_INFRA_PROCESS) + DYNAMODB_JAR_URL, DYNAMODB_JAR_URL_ALPINE, LOCALSTACK_MAVEN_VERSION, STEPFUNCTIONS_ZIP_URL, + LOCALSTACK_INFRA_PROCESS) if __name__ == '__main__': bootstrap.bootstrap_installation() # flake8: noqa: E402 from localstack.utils.common import ( - download, parallelize, run, mkdir, load_file, save_file, unzip, rm_rf, chmod_r, is_alpine) + download, parallelize, run, mkdir, load_file, save_file, unzip, rm_rf, chmod_r, is_alpine, in_docker) THIS_PATH = os.path.dirname(os.path.realpath(__file__)) ROOT_PATH = os.path.realpath(os.path.join(THIS_PATH, '..')) @@ -34,6 +35,11 @@ # Target version for javac, to ensure compatibility with earlier JREs JAVAC_TARGET_VERSION = '1.8' +# As of 2019-10-09, the DDB fix (see below) doesn't seem to be required anymore +APPLY_DDB_ALPINE_FIX = False +# TODO: 2019-10-09: Temporarily overwriting DDB, as we're hitting a SIGSEGV JVM crash with the latest version +OVERWRITE_DDB_FILES_IN_DOCKER = True + # set up logger LOGGER = logging.getLogger(__name__) @@ -109,18 +115,21 @@ def install_stepfunctions_local(): def install_dynamodb_local(): + if OVERWRITE_DDB_FILES_IN_DOCKER and in_docker(): + rm_rf(INSTALL_DIR_DDB) if not os.path.exists(INSTALL_DIR_DDB): log_install_msg('DynamoDB') # download and extract archive tmp_archive = os.path.join(tempfile.gettempdir(), 'localstack.ddb.zip') - download_and_extract_with_retry(DYNAMODB_JAR_URL, tmp_archive, INSTALL_DIR_DDB) + dynamodb_url = DYNAMODB_JAR_URL_ALPINE if in_docker() else DYNAMODB_JAR_URL + download_and_extract_with_retry(dynamodb_url, tmp_archive, INSTALL_DIR_DDB) # fix for Alpine, otherwise DynamoDBLocal fails with: # DynamoDBLocal_lib/libsqlite4java-linux-amd64.so: __memcpy_chk: symbol not found if is_alpine(): ddb_libs_dir = '%s/DynamoDBLocal_lib' % INSTALL_DIR_DDB patched_marker = '%s/alpine_fix_applied' % ddb_libs_dir - if not os.path.exists(patched_marker): + if APPLY_DDB_ALPINE_FIX and not os.path.exists(patched_marker): patched_lib = ('https://rawgit.com/bhuisgen/docker-alpine/master/alpine-dynamodb/' + 'rootfs/usr/local/dynamodb/DynamoDBLocal_lib/libsqlite4java-linux-amd64.so') patched_jar = ('https://rawgit.com/bhuisgen/docker-alpine/master/alpine-dynamodb/' + diff --git a/localstack/utils/cloudformation/template_deployer.py b/localstack/utils/cloudformation/template_deployer.py index c5a6b8a2d853c..689d7b001fbec 100644 --- a/localstack/utils/cloudformation/template_deployer.py +++ b/localstack/utils/cloudformation/template_deployer.py @@ -283,7 +283,6 @@ def get_service_name(resource): if res_type.endswith('Cognito::UserPool'): return 'cognito-idp' if parts[-2] == 'Cognito': - # TODO add mappings for "cognito-identity" return 'cognito-idp' return parts[1].lower() @@ -544,11 +543,14 @@ def update_resource(resource_id, resources, stack_name): if resource_type not in UPDATEABLE_RESOURCES: LOG.warning('Unable to update resource type "%s", id "%s"' % (resource_type, resource_id)) return + LOG.info('Updating resource %s of type %s' % (resource_id, resource_type)) props = resource['Properties'] if resource_type == 'Lambda::Function': client = aws_stack.connect_to_service('lambda') keys = ('FunctionName', 'Role', 'Handler', 'Description', 'Timeout', 'MemorySize', 'Environment', 'Runtime') update_props = dict([(k, props[k]) for k in keys if k in props]) + if 'Code' in props: + client.update_function_code(FunctionName=props['FunctionName'], **props['Code']) return client.update_function_configuration(**update_props) if resource_type == 'ApiGateway::Method': client = aws_stack.connect_to_service('apigateway')
* Fix DynamoDB local libs (currently breaking builds on `master`) * Minor update to dashboard - add deprecation notice * Small fix in CloudFormation update for Lambda function code
https://api.github.com/repos/localstack/localstack/pulls/1664
2019-10-20T13:56:27Z
2019-10-21T00:34:44Z
2019-10-21T00:34:44Z
2019-10-21T00:34:46Z
3,681
localstack/localstack
28,646
bump mistralai deps
diff --git a/llama-index-integrations/embeddings/llama-index-embeddings-mistralai/pyproject.toml b/llama-index-integrations/embeddings/llama-index-embeddings-mistralai/pyproject.toml index 8096d01f7a566..2045bfe0a1a09 100644 --- a/llama-index-integrations/embeddings/llama-index-embeddings-mistralai/pyproject.toml +++ b/llama-index-integrations/embeddings/llama-index-embeddings-mistralai/pyproject.toml @@ -27,12 +27,12 @@ exclude = ["**/BUILD"] license = "MIT" name = "llama-index-embeddings-mistralai" readme = "README.md" -version = "0.1.3" +version = "0.1.4" [tool.poetry.dependencies] -python = ">=3.8.1,<4.0" +python = ">=3.9,<4.0" llama-index-core = "^0.10.1" -mistralai = "^0.0.11" +mistralai = ">=0.1.3" [tool.poetry.group.dev.dependencies] ipython = "8.10.0" diff --git a/llama-index-integrations/embeddings/llama-index-embeddings-mistralai/tests/BUILD b/llama-index-integrations/embeddings/llama-index-embeddings-mistralai/tests/BUILD index dabf212d7e716..619cac15ff840 100644 --- a/llama-index-integrations/embeddings/llama-index-embeddings-mistralai/tests/BUILD +++ b/llama-index-integrations/embeddings/llama-index-embeddings-mistralai/tests/BUILD @@ -1 +1,3 @@ -python_tests() +python_tests( + interpreter_constraints=["==3.9.*", "==3.10.*"], +) diff --git a/llama-index-integrations/llms/llama-index-llms-mistralai/pyproject.toml b/llama-index-integrations/llms/llama-index-llms-mistralai/pyproject.toml index 7391511e58a14..d538db4ae37c2 100644 --- a/llama-index-integrations/llms/llama-index-llms-mistralai/pyproject.toml +++ b/llama-index-integrations/llms/llama-index-llms-mistralai/pyproject.toml @@ -27,12 +27,12 @@ exclude = ["**/BUILD"] license = "MIT" name = "llama-index-llms-mistralai" readme = "README.md" -version = "0.1.4" +version = "0.1.5" [tool.poetry.dependencies] -python = ">=3.8.1,<4.0" +python = ">=3.9,<4.0" llama-index-core = "^0.10.1" -mistralai = "^0.0.11" +mistralai = ">=0.1.3" [tool.poetry.group.dev.dependencies] ipython = "8.10.0" diff --git a/llama-index-integrations/llms/llama-index-llms-mistralai/tests/BUILD b/llama-index-integrations/llms/llama-index-llms-mistralai/tests/BUILD index dabf212d7e716..619cac15ff840 100644 --- a/llama-index-integrations/llms/llama-index-llms-mistralai/tests/BUILD +++ b/llama-index-integrations/llms/llama-index-llms-mistralai/tests/BUILD @@ -1 +1,3 @@ -python_tests() +python_tests( + interpreter_constraints=["==3.9.*", "==3.10.*"], +)
https://api.github.com/repos/run-llama/llama_index/pulls/11819
2024-03-11T14:26:38Z
2024-03-11T14:37:08Z
2024-03-11T14:37:08Z
2024-03-11T14:37:09Z
883
run-llama/llama_index
6,043
docs: redirect macOS users to different cron guide
diff --git a/certbot/docs/using.rst b/certbot/docs/using.rst index 561782e764a..bdb34399679 100644 --- a/certbot/docs/using.rst +++ b/certbot/docs/using.rst @@ -818,8 +818,13 @@ scheduled task to automatically renew your certificates in the background. If yo whether your system has a pre-installed scheduled task for Certbot, it is safe to follow these instructions to create one. -If you're using Windows, these instructions are not necessary as Certbot on Windows comes with -a scheduled task for automated renewal pre-installed. +.. note:: + If you're using Windows, these instructions are not neccessary as Certbot on Windows comes with + a scheduled task for automated renewal pre-installed. + + If you are using macOS and installed Certbot using Homebrew, follow the instructions at + https://certbot.eff.org/instructions to set up automated renewal. The instructions below + are not applicable on macOS. Run the following line, which will add a cron job to `/etc/crontab`:
Due to macOS having some complications about Certbot from Homebrew being in the PATH, the instructions we have in the Automated Renewal section do not work for them. Instead, send those users to the instruction generator. ---- Fixes https://github.com/certbot/certbot/issues/8974. Don't merge until: - [x] https://github.com/certbot/website/pull/729 is merged ![image](https://user-images.githubusercontent.com/311534/131308925-e24e5d65-7f1a-4139-8760-5e612b64484a.png)
https://api.github.com/repos/certbot/certbot/pulls/9013
2021-08-30T08:20:24Z
2021-09-03T14:49:26Z
2021-09-03T14:49:26Z
2021-09-03T14:49:26Z
252
certbot/certbot
3,028
Reduce ds_id name length
diff --git a/deepspeed/runtime/zero/stage3.py b/deepspeed/runtime/zero/stage3.py index 4132a4527d6a..03813afa4ed1 100644 --- a/deepspeed/runtime/zero/stage3.py +++ b/deepspeed/runtime/zero/stage3.py @@ -864,7 +864,9 @@ def _create_fp32_partitions(self): self.device).clone().float().detach()) self.fp32_partitioned_groups_flat[i].requires_grad = True # keep this in case internal optimizer uses it - self.fp32_partitioned_groups_flat[i].ds_id = '_'.join(map(str, self.fp16_partitioned_groups_flat_id[i])) + ds_id_begin = str(self.fp16_partitioned_groups_flat_id[i][0]) + ds_id_end = str(self.fp16_partitioned_groups_flat_id[i][-1]) + self.fp32_partitioned_groups_flat[i].ds_id = ds_id_begin + '_' + ds_id_end if len(swappable_fp32_tensors) > 0: self.optimizer_swapper.initialize_parameters(parameters=swappable_fp32_tensors,
Fixing issue #5087 . Limited the naming of the ds_id in ZeRO 3 to the first and last parameters of the group instead of every parameter in the group.
https://api.github.com/repos/microsoft/DeepSpeed/pulls/5176
2024-02-23T04:57:48Z
2024-02-23T14:18:17Z
2024-02-23T14:18:17Z
2024-02-23T14:18:17Z
248
microsoft/DeepSpeed
10,834
Count the tokens/second when using --debug
diff --git a/fastchat/serve/inference.py b/fastchat/serve/inference.py index 489b379384..8c4572664a 100644 --- a/fastchat/serve/inference.py +++ b/fastchat/serve/inference.py @@ -4,6 +4,7 @@ import math from typing import Iterable, Optional import sys +import time import warnings import psutil @@ -307,8 +308,12 @@ def chat_loop( chatio.prompt_for_output(conv.roles[1]) output_stream = generate_stream_func(model, tokenizer, gen_params, device) + t = time.time() outputs = chatio.stream_output(output_stream) + t = time.time() - t conv.update_last_message(outputs.strip()) if debug: print("\n", {"prompt": prompt, "outputs": outputs}, "\n") + num_tokens = len(tokenizer.encode(outputs)) + print(f"Tokens per second: {num_tokens / t:.2f}\n")
## Why are these changes needed? We would like to count the tokens/second when debugging a served model on the cli. Result using `llama-7b`: <img width="1360" alt="image" src="https://github.com/lm-sys/FastChat/assets/49086305/65021ce9-75e7-43f3-b716-1e84ce46c075"> ## Related issue number (if applicable) Closes #1268 ## Checks - [x] I've run `format.sh` to lint the changes in this PR. - [x] I've included any doc changes needed. - [ ] I've made sure the relevant tests are passing (if applicable).
https://api.github.com/repos/lm-sys/FastChat/pulls/1573
2023-06-01T20:42:57Z
2023-06-09T01:20:24Z
2023-06-09T01:20:24Z
2023-06-09T01:20:24Z
223
lm-sys/FastChat
41,391
feat(grouping): Enable secondary grouping with upgrade
diff --git a/src/sentry/api/endpoints/project_details.py b/src/sentry/api/endpoints/project_details.py index fb681a400801d..7326c93106699 100644 --- a/src/sentry/api/endpoints/project_details.py +++ b/src/sentry/api/endpoints/project_details.py @@ -260,11 +260,16 @@ def validate_secondaryGroupingExpiry(self, value): raise serializers.ValidationError( f"Grouping expiry must be a numerical value, a UNIX timestamp with second resolution, found {type(value)}" ) - if not (0 < value - time.time() < (91 * 24 * 3600)): + now = time.time() + if value < now: raise serializers.ValidationError( "Grouping expiry must be sometime within the next 90 days and not in the past. Perhaps you specified the timestamp not in seconds?" ) + max_expiry_date = now + (91 * 24 * 3600) + if value > max_expiry_date: + value = max_expiry_date + return value def validate_fingerprintingRules(self, value): diff --git a/src/sentry/api/serializers/models/project.py b/src/sentry/api/serializers/models/project.py index b19baadd56a83..4f1910fd5e5cc 100644 --- a/src/sentry/api/serializers/models/project.py +++ b/src/sentry/api/serializers/models/project.py @@ -648,6 +648,8 @@ class DetailedProjectSerializer(ProjectWithTeamSerializer): "sentry:grouping_config", "sentry:grouping_enhancements", "sentry:grouping_enhancements_base", + "sentry:secondary_grouping_config", + "sentry:secondary_grouping_expiry", "sentry:fingerprinting_rules", "sentry:relay_pii_config", "sentry:dynamic_sampling", @@ -793,6 +795,7 @@ def get_value_with_default(key): "dynamicSampling": get_value_with_default("sentry:dynamic_sampling"), } ) + return data diff --git a/src/sentry/event_manager.py b/src/sentry/event_manager.py index be739ec81a8a8..235fe7e38d1db 100644 --- a/src/sentry/event_manager.py +++ b/src/sentry/event_manager.py @@ -356,7 +356,9 @@ def save(self, project_id, raw=False, assume_normalized=False, start_time=None, secondary_hashes = None try: - if (project.get_option("sentry:secondary_grouping_expiry") or 0) >= time.time(): + secondary_grouping_config = project.get_option("sentry:secondary_grouping_config") + secondary_grouping_expiry = project.get_option("sentry:secondary_grouping_expiry") + if secondary_grouping_config and (secondary_grouping_expiry or 0) >= time.time(): with metrics.timer("event_manager.secondary_grouping"): secondary_event = copy.deepcopy(job["event"]) loader = SecondaryGroupingConfigLoader() diff --git a/static/app/views/settings/projectIssueGrouping/upgradeGrouping.tsx b/static/app/views/settings/projectIssueGrouping/upgradeGrouping.tsx index d8243651cb279..3fc1b9634f4b0 100644 --- a/static/app/views/settings/projectIssueGrouping/upgradeGrouping.tsx +++ b/static/app/views/settings/projectIssueGrouping/upgradeGrouping.tsx @@ -41,9 +41,14 @@ function UpgradeGrouping({ const {riskNote, alertType} = getGroupingRisk(riskLevel); const noUpdates = !latestGroupingConfig; - const newData: Record<string, string> = {}; + const newData: Record<string, string | number> = {}; if (latestGroupingConfig) { + const now = Math.floor(new Date().getTime() / 1000); + const ninety_days = 3600 * 24 * 90; + newData.groupingConfig = latestGroupingConfig.id; + newData.secondaryGroupingConfig = project.groupingConfig; + newData.secondaryGroupingExpiry = now + ninety_days; } const handleUpgrade = async () => { diff --git a/tests/sentry/api/endpoints/test_project_details.py b/tests/sentry/api/endpoints/test_project_details.py index 3990211101c6d..82ff88263b1b7 100644 --- a/tests/sentry/api/endpoints/test_project_details.py +++ b/tests/sentry/api/endpoints/test_project_details.py @@ -1,3 +1,5 @@ +from time import time + import pytest from sentry.api.endpoints.project_details import ( @@ -722,6 +724,32 @@ def test_dynamic_sampling_rule_id_handling(self): new_next_id = saved_config["next_id"] assert new_next_id == 7 + def test_cap_secondary_grouping_expiry(self): + now = time() + + response = self.get_response(self.org_slug, self.proj_slug, secondaryGroupingExpiry=0) + assert response.status_code == 400 + + expiry = int(now + 3600 * 24 * 1) + response = self.get_valid_response( + self.org_slug, self.proj_slug, secondaryGroupingExpiry=expiry + ) + assert response.data["secondaryGroupingExpiry"] == expiry + + expiry = int(now + 3600 * 24 * 89) + response = self.get_valid_response( + self.org_slug, self.proj_slug, secondaryGroupingExpiry=expiry + ) + assert response.data["secondaryGroupingExpiry"] == expiry + + # Larger timestamps are capped to 91 days: + expiry = int(now + 3600 * 24 * 365) + response = self.get_valid_response( + self.org_slug, self.proj_slug, secondaryGroupingExpiry=expiry + ) + expiry = response.data["secondaryGroupingExpiry"] + assert (now + 3600 * 24 * 90) < expiry < (now + 3600 * 24 * 92) + class CopyProjectSettingsTest(APITestCase): endpoint = "sentry-api-0-project-details"
When upgrading to a new grouping strategy, keep the old strategy alive as secondary grouping for 90 days in order to reduce the number of newly created groups. Fix https://getsentry.atlassian.net/browse/INGEST-216
https://api.github.com/repos/getsentry/sentry/pulls/27828
2021-07-29T12:18:22Z
2021-07-30T06:35:16Z
2021-07-30T06:35:16Z
2021-08-14T12:00:57Z
1,373
getsentry/sentry
44,496
[docs] Correcting SLURM options
diff --git a/doc/source/cluster/slurm.rst b/doc/source/cluster/slurm.rst index a9b6f6d99908e..cadc0ba85d692 100644 --- a/doc/source/cluster/slurm.rst +++ b/doc/source/cluster/slurm.rst @@ -52,13 +52,13 @@ You'll need to tell SLURM to allocate nodes specifically for Ray. Ray will then #SBATCH --nodes=4 #SBATCH --exclusive -Important: To ensure that each Ray worker runtime will run on a separate node, set ``tasks-per-node``. +Important: To ensure that each Ray worker runtime will run on a separate node, set ``ntasks-per-node``. .. code-block:: bash - #SBATCH --tasks-per-node=1 + #SBATCH --ntasks-per-node=1 -Since we've set `tasks-per-node = 1`, this will be used to guarantee that each Ray worker runtime will obtain the +Since we've set `ntasks-per-node = 1`, this will be used to guarantee that each Ray worker runtime will obtain the proper resources. In this example, we ask for at least 5 CPUs and 5 GB of memory per node. .. code-block:: bash @@ -106,7 +106,7 @@ Starting the Ray head node After detecting the head node hostname and head node IP, we'll want to create a Ray head node runtime. We'll do this by using ``srun`` as a background task -as a single task/node (recall that ``tasks-per-node=1``). +as a single task/node (recall that ``ntasks-per-node=1``). Below, you'll see that we explicitly specify the number of CPUs (``num-cpus``) and number of GPUs (``num-gpus``) to Ray, as this will prevent Ray from using
there is only ``--ntasks-per-node`` per node option not ``--tasks-per-node`` in SLURM <!-- Thank you for your contribution! Please review https://github.com/ray-project/ray/blob/master/CONTRIBUTING.rst before opening a pull request. --> <!-- Please add a reviewer to the assignee section when you create a PR. If you don't have the access to it, we will shortly find a reviewer and assign them to your PR. --> ## Why are these changes needed? <!-- Please give a short summary of the change and the problem this solves. --> ## Related issue number <!-- For example: "Closes #1234" --> ## Checks - [ ] I've run `scripts/format.sh` to lint the changes in this PR. - [ ] I've included any doc changes needed for https://docs.ray.io/en/master/. - [ ] I've made sure the tests are passing. Note that there might be a few flaky tests, see the recent failures at https://flakey-tests.ray.io/ - Testing Strategy - [ ] Unit tests - [ ] Release tests - [ ] This PR is not tested :(
https://api.github.com/repos/ray-project/ray/pulls/20509
2021-11-17T22:40:33Z
2022-01-12T08:36:40Z
2022-01-12T08:36:40Z
2022-01-12T12:50:46Z
409
ray-project/ray
18,974
✏️ Fix typo in `docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md`
diff --git a/docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md index 935555339a25e..ccef5aef4b27f 100644 --- a/docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md +++ b/docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -35,7 +35,7 @@ It should be a `list` of `Depends()`: {!> ../../../docs_src/dependencies/tutorial006.py!} ``` -These dependencies will be executed/solved the same way normal dependencies. But their value (if they return any) won't be passed to your *path operation function*. +These dependencies will be executed/solved the same way as normal dependencies. But their value (if they return any) won't be passed to your *path operation function*. !!! tip Some editors check for unused function parameters, and show them as errors.
Added 'as' to the phrase 'These dependencies will be executed/solved the same way normal dependencies.'
https://api.github.com/repos/tiangolo/fastapi/pulls/10172
2023-08-30T10:29:17Z
2023-09-02T15:32:49Z
2023-09-02T15:32:48Z
2023-09-02T15:32:49Z
224
tiangolo/fastapi
22,703
Remove unused `time_sync` import
diff --git a/val.py b/val.py index 876fc5bf50b..7b4fab4c63b 100644 --- a/val.py +++ b/val.py @@ -42,7 +42,7 @@ scale_coords, xywh2xyxy, xyxy2xywh) from utils.metrics import ConfusionMatrix, ap_per_class, box_iou from utils.plots import output_to_target, plot_images, plot_val_study -from utils.torch_utils import select_device, smart_inference_mode, time_sync +from utils.torch_utils import select_device, smart_inference_mode def save_one_txt(predn, save_conf, shape, file):
Signed-off-by: Glenn Jocher <glenn.jocher@ultralytics.com> <!-- Thank you for submitting a YOLOv5 🚀 Pull Request! We want to make contributing to YOLOv5 as easy and transparent as possible. A few tips to get you started: - Search existing YOLOv5 [PRs](https://github.com/ultralytics/yolov5/pull) to see if a similar PR already exists. - Link this PR to a YOLOv5 [issue](https://github.com/ultralytics/yolov5/issues) to help us understand what bug fix or feature is being implemented. - Provide before and after profiling/inference/training results to help us quantify the improvement your PR provides (if applicable). Please see our ✅ [Contributing Guide](https://github.com/ultralytics/yolov5/blob/master/CONTRIBUTING.md) for more details. --> ## 🛠️ PR Summary <sub>Made with ❤️ by [Ultralytics Actions](https://github.com/ultralytics/actions)<sub> ### 🌟 Summary Enhanced YOLOv5 validation script for streamlined inference. ### 📊 Key Changes - Removed `time_sync` function import from `utils.torch_utils` in the `val.py` script. ### 🎯 Purpose & Impact - 🎯 **Purpose:** Streamlining the validation code by eliminating unnecessary utilities, potentially reducing clutter and confusion within the codebase. - 💡 **Impact:** Users may experience a slight increase in clarity when navigating the validation script, although the change is minimal and may not have a noticeable impact on the end-user experience. Developers will have a cleaner codebase to work with, ensuring that only essential utilities are imported.
https://api.github.com/repos/ultralytics/yolov5/pulls/9026
2022-08-18T18:22:43Z
2022-08-18T18:26:18Z
2022-08-18T18:26:18Z
2024-01-19T07:12:27Z
151
ultralytics/yolov5
24,838
Added Problem 33
diff --git a/project_euler/problem_33/__init__.py b/project_euler/problem_33/__init__.py new file mode 100644 index 000000000000..8b137891791f --- /dev/null +++ b/project_euler/problem_33/__init__.py @@ -0,0 +1 @@ + diff --git a/project_euler/problem_33/sol1.py b/project_euler/problem_33/sol1.py new file mode 100644 index 000000000000..0992c96935f5 --- /dev/null +++ b/project_euler/problem_33/sol1.py @@ -0,0 +1,55 @@ +""" +Problem: + +The fraction 49/98 is a curious fraction, as an inexperienced +mathematician in attempting to simplify it may incorrectly believe +that 49/98 = 4/8, which is correct, is obtained by cancelling the 9s. + +We shall consider fractions like, 30/50 = 3/5, to be trivial examples. + +There are exactly four non-trivial examples of this type of fraction, +less than one in value, and containing two digits in the numerator +and denominator. + +If the product of these four fractions is given in its lowest common +terms, find the value of the denominator. +""" + + +def isDigitCancelling(num, den): + if num != den: + if num % 10 == den // 10: + if (num // 10) / (den % 10) == num / den: + return True + + +def solve(digit_len: int) -> str: + """ + >>> solve(2) + '16/64 , 19/95 , 26/65 , 49/98' + >>> solve(3) + '16/64 , 19/95 , 26/65 , 49/98' + >>> solve(4) + '16/64 , 19/95 , 26/65 , 49/98' + >>> solve(0) + '' + >>> solve(5) + '16/64 , 19/95 , 26/65 , 49/98' + """ + solutions = [] + den = 11 + last_digit = int("1" + "0" * digit_len) + for num in range(den, last_digit): + while den <= 99: + if (num != den) and (num % 10 == den // 10) and (den % 10 != 0): + if isDigitCancelling(num, den): + solutions.append("{}/{}".format(num, den)) + den += 1 + num += 1 + den = 10 + solutions = " , ".join(solutions) + return solutions + + +if __name__ == "__main__": + print(solve(2))
https://api.github.com/repos/TheAlgorithms/Python/pulls/1440
2019-10-24T15:48:08Z
2019-10-31T12:20:40Z
2019-10-31T12:20:40Z
2019-10-31T12:20:40Z
661
TheAlgorithms/Python
29,425
Remove int type on HTTPAdapter's max_retries argument doc
diff --git a/requests/adapters.py b/requests/adapters.py index 6266d5be30..4f2b23cf03 100644 --- a/requests/adapters.py +++ b/requests/adapters.py @@ -65,7 +65,7 @@ class HTTPAdapter(BaseAdapter): :param pool_connections: The number of urllib3 connection pools to cache. :param pool_maxsize: The maximum number of connections to save in the pool. - :param int max_retries: The maximum number of retries each connection + :param max_retries: The maximum number of retries each connection should attempt. Note, this applies only to failed DNS lookups, socket connections and connection timeouts, never to requests where data has made it to the server. By default, Requests does not retry failed
The argument description says `max_retries` can be an int, or a `urllib3.util.Retry` object. However, the type declared in the doc restricts it to int only. Passing a Retry object causes a warning in PyCharm code inspection. The behaviour described for `max_retries` is accurate: HTTPAdapter passes `max_retries` to `Retry.from_int()`, which just returns the input if `max_retries` is a Retry object.
https://api.github.com/repos/psf/requests/pulls/2984
2016-01-29T23:41:23Z
2016-01-30T02:59:04Z
2016-01-30T02:59:04Z
2021-09-08T05:00:59Z
183
psf/requests
32,775
[extractor/twitter] fix #5565
diff --git a/yt_dlp/extractor/twitter.py b/yt_dlp/extractor/twitter.py index 3c81473dc8f..62b34d0813e 100644 --- a/yt_dlp/extractor/twitter.py +++ b/yt_dlp/extractor/twitter.py @@ -1167,7 +1167,8 @@ def _real_extract(self, url): # XXX: Native downloader does not work formats = self._extract_m3u8_formats( traverse_obj(source, 'noRedirectPlaybackUrl', 'location'), - metadata['media_key'], 'm4a', 'm3u8', live=live_status == 'is_live') + metadata['media_key'], 'm4a', 'm3u8', live=live_status == 'is_live', + headers={'Referer': 'https://twitter.com/'}) for fmt in formats: fmt.update({'vcodec': 'none', 'acodec': 'aac'})
### Description of your *pull request* and other information </details> <!-- Explanation of your *pull request* in arbitrary form goes here. Please **make sure the description explains the purpose and effect** of your *pull request* and is worded well enough to be understood. Provide as much **context and examples** as possible --> Fixes #5565 Added 'Referer' to the m3u8 manifest request headers to avoid 403 errors on some requests <details open><summary>Template</summary> <!-- OPEN is intentional --> <!-- # PLEASE FOLLOW THE GUIDE BELOW - You will be asked some questions, please read them **carefully** and answer honestly - Put an `x` into all the boxes `[ ]` relevant to your *pull request* (like [x]) - Use *Preview* tab to see how your *pull request* will actually look like --> ### Before submitting a *pull request* make sure you have: - [x] At least skimmed through [contributing guidelines](https://github.com/yt-dlp/yt-dlp/blob/master/CONTRIBUTING.md#developer-instructions) including [yt-dlp coding conventions](https://github.com/yt-dlp/yt-dlp/blob/master/CONTRIBUTING.md#yt-dlp-coding-conventions) - [x] [Searched](https://github.com/yt-dlp/yt-dlp/search?q=is%3Apr&type=Issues) the bugtracker for similar pull requests - [x] Checked the code with [flake8](https://pypi.python.org/pypi/flake8) and [ran relevant tests](https://github.com/yt-dlp/yt-dlp/blob/master/CONTRIBUTING.md#developer-instructions) ### In order to be accepted and merged into yt-dlp each piece of code must be in public domain or released under [Unlicense](http://unlicense.org/). Check one of the following options: - [x] I am the original author of this code and I am willing to release it under [Unlicense](http://unlicense.org/) - [ ] I am not the original author of this code but it is in public domain or released under [Unlicense](http://unlicense.org/) (provide reliable evidence) ### What is the purpose of your *pull request*? - [x] Fix or improvement to an extractor (Make sure to add/update tests) - [ ] New extractor ([Piracy websites will not be accepted](https://github.com/yt-dlp/yt-dlp/blob/master/CONTRIBUTING.md#is-the-website-primarily-used-for-piracy)) - [ ] Core bug fix/improvement - [ ] New feature (It is strongly [recommended to open an issue first](https://github.com/yt-dlp/yt-dlp/blob/master/CONTRIBUTING.md#adding-new-feature-or-making-overarching-changes))
https://api.github.com/repos/yt-dlp/yt-dlp/pulls/5580
2022-11-17T22:43:06Z
2022-11-18T01:12:02Z
2022-11-18T01:12:02Z
2022-11-18T18:22:17Z
219
yt-dlp/yt-dlp
8,277
add test extras_require
diff --git a/metagpt/tools/web_browser_engine_selenium.py b/metagpt/tools/web_browser_engine_selenium.py index 8bc81f956..70b651935 100644 --- a/metagpt/tools/web_browser_engine_selenium.py +++ b/metagpt/tools/web_browser_engine_selenium.py @@ -14,6 +14,8 @@ from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.wait import WebDriverWait +from webdriver_manager.core.download_manager import WDMDownloadManager +from webdriver_manager.core.http import WDMHttpClient from metagpt.config import CONFIG from metagpt.utils.parse_html import WebPage @@ -93,6 +95,13 @@ def _scrape_website(self, url): } +class WDMHttpProxyClient(WDMHttpClient): + def get(self, url, **kwargs): + if "proxies" not in kwargs and CONFIG.global_proxy: + kwargs["proxies"] = {"all_proxy": CONFIG.global_proxy} + return super().get(url, **kwargs) + + def _gen_get_driver_func(browser_type, *args, executable_path=None): WebDriver = getattr(importlib.import_module(f"selenium.webdriver.{browser_type}.webdriver"), "WebDriver") Service = getattr(importlib.import_module(f"selenium.webdriver.{browser_type}.service"), "Service") @@ -101,7 +110,7 @@ def _gen_get_driver_func(browser_type, *args, executable_path=None): if not executable_path: module_name, type_name = _webdriver_manager_types[browser_type] DriverManager = getattr(importlib.import_module(module_name), type_name) - driver_manager = DriverManager() + driver_manager = DriverManager(download_manager=WDMDownloadManager(http_client=WDMHttpProxyClient())) # driver_manager.driver_cache.find_driver(driver_manager.driver)) executable_path = driver_manager.install() diff --git a/setup.py b/setup.py index 2163b4233..4c2941a18 100644 --- a/setup.py +++ b/setup.py @@ -22,6 +22,31 @@ def run(self): long_description = (here / "README.md").read_text(encoding="utf-8") requirements = (here / "requirements.txt").read_text(encoding="utf-8").splitlines() + +extras_require = { + "playwright": ["playwright>=1.26", "beautifulsoup4"], + "selenium": ["selenium>4", "webdriver_manager", "beautifulsoup4"], + "search-google": ["google-api-python-client==2.94.0"], + "search-ddg": ["duckduckgo-search==3.8.5"], + "ocr": ["paddlepaddle==2.4.2", "paddleocr>=2.0.1", "tabulate==0.9.0"], + "test": ["pytest", "pytest-cov", "pytest-asyncio", "pytest-mock"], +} + +extras_require["test"] = [ + *set(i for j in extras_require.values() for i in j), + "pytest", + "pytest-asyncio", + "pytest-cov", + "pytest-mock", + "pytest-html", +] + +extras_require["pyppeteer"] = [ + "pyppeteer>=1.0.2" +] # pyppeteer is unmaintained and there are conflicts with dependencies +extras_require["dev"] = (["pylint~=3.0.3", "black~=23.3.0", "isort~=5.12.0", "pre-commit~=3.6.0"],) + + setup( name="metagpt", version="0.5.2", @@ -36,16 +61,7 @@ def run(self): packages=find_packages(exclude=["contrib", "docs", "examples", "tests*"]), python_requires=">=3.9", install_requires=requirements, - extras_require={ - "playwright": ["playwright>=1.26", "beautifulsoup4"], - "selenium": ["selenium>4", "webdriver_manager", "beautifulsoup4"], - "search-google": ["google-api-python-client==2.94.0"], - "search-ddg": ["duckduckgo-search==3.8.5"], - "pyppeteer": ["pyppeteer>=1.0.2"], - "ocr": ["paddlepaddle==2.4.2", "paddleocr>=2.0.1", "tabulate==0.9.0"], - "dev": ["pylint~=3.0.3", "black~=23.3.0", "isort~=5.12.0", "pre-commit~=3.6.0"], - "test": ["pytest", "pytest-cov", "pytest-asyncio", "pytest-mock"], - }, + extras_require=extras_require, cmdclass={ "install_mermaid": InstallMermaidCLI, },
https://api.github.com/repos/geekan/MetaGPT/pulls/645
2023-12-28T10:47:19Z
2023-12-28T15:23:24Z
2023-12-28T15:23:24Z
2024-01-07T10:14:11Z
1,098
geekan/MetaGPT
16,739
Pytest ignore deprecation warnings
diff --git a/lib/pytest.ini b/lib/pytest.ini index 0fb3efde70fe..e7628ae41fa5 100644 --- a/lib/pytest.ini +++ b/lib/pytest.ini @@ -1,3 +1,8 @@ [pytest] markers = slow: marks tests as slow +filterwarnings = + # PyTest filter syntax cheatsheet -> action:message:category:module:line + ignore::UserWarning:altair.*: + ignore::DeprecationWarning:flatbuffers.*: + ignore::DeprecationWarning:keras_preprocessing.*: diff --git a/lib/tests/streamlit/legacy_add_rows_test.py b/lib/tests/streamlit/legacy_add_rows_test.py index a6f9f09c18a2..5176a89dda45 100644 --- a/lib/tests/streamlit/legacy_add_rows_test.py +++ b/lib/tests/streamlit/legacy_add_rows_test.py @@ -16,6 +16,7 @@ from typing import Optional import pandas as pd +import pytest import pyarrow as pa from streamlit.errors import StreamlitAPIException @@ -111,6 +112,7 @@ def test_simple_legacy_add_rows(self): get_script_run_ctx().reset() self.forward_msg_queue.clear() + @pytest.mark.filterwarnings("ignore::FutureWarning") def test_with_index_legacy_add_rows(self): """Test plain old _legacy_add_rows.""" all_methods = self._get_unnamed_data_methods() @@ -139,6 +141,7 @@ def test_with_index_legacy_add_rows(self): get_script_run_ctx().reset() self.forward_msg_queue.clear() + @pytest.mark.filterwarnings("ignore::FutureWarning") def test_with_index_no_data_legacy_add_rows(self): """Test plain old _legacy_add_rows.""" all_methods = self._get_unnamed_data_methods() diff --git a/lib/tests/streamlit/legacy_data_frame_test.py b/lib/tests/streamlit/legacy_data_frame_test.py index c7c486fcebf9..ef2da827484d 100644 --- a/lib/tests/streamlit/legacy_data_frame_test.py +++ b/lib/tests/streamlit/legacy_data_frame_test.py @@ -98,6 +98,7 @@ def test_marshall_pyarrow_table_data(self): with self.assertRaises(StreamlitAPIException): data_frame.marshall_data_frame(pa.Table.from_pandas(df), proto) + @pytest.mark.filterwarnings("ignore::FutureWarning") def test_marshall_index(self): """Test streamlit.data_frame._marshall_index.""" df = pd.DataFrame(data={"col1": [1, 2], "col2": [3, 4]}) @@ -182,6 +183,7 @@ def test_marshall_table(self): truth = [["1", "2"], ["3", "4"]] self.assertEqual(ret, truth) + @pytest.mark.filterwarnings("ignore::DeprecationWarning") def test_marshall_any_array(self): """Test streamlit.data_frame._marshall_any_array.""" # list diff --git a/lib/tests/streamlit/runtime/legacy_caching/hashing_test.py b/lib/tests/streamlit/runtime/legacy_caching/hashing_test.py index 541a597609a9..48c438770c11 100644 --- a/lib/tests/streamlit/runtime/legacy_caching/hashing_test.py +++ b/lib/tests/streamlit/runtime/legacy_caching/hashing_test.py @@ -17,6 +17,7 @@ import functools import hashlib import os +import pytest import re import socket import tempfile @@ -535,6 +536,7 @@ def test_compiled_ffi(self): self.assertIn(get_fqn_type(foo), _FFI_TYPE_NAMES) self.assertEqual(get_hash(foo), get_hash(bar)) + @pytest.mark.filterwarnings("ignore:No driver name specified") def test_sqlite_sqlalchemy_engine(self): """Separate tests for sqlite since it uses a file based and in memory database and has no auth @@ -565,6 +567,7 @@ def test_sqlite_sqlalchemy_engine(self): hash_engine(foo, creator=lambda: True), ) + @pytest.mark.filterwarnings("ignore:No driver name specified") def test_mssql_sqlalchemy_engine(self): """Specialized tests for mssql since it uses a different way of passing connection arguments to the engine @@ -623,6 +626,7 @@ def test_mssql_sqlalchemy_engine(self): ("mssql", "password"), ] ) + @pytest.mark.filterwarnings("ignore:No driver name specified") def test_sqlalchemy_engine(self, dialect, password_key): def connect(): pass
<!-- Before contributing (PLEASE READ!) ⚠️ If your contribution is more than a few lines of code, then prior to starting to code on it please post in the issue saying you want to volunteer, then wait for a positive response. And if there is no issue for it yet, create it first. This helps make sure: 1. Two people aren't working on the same thing 2. This is something Streamlit's maintainers believe should be implemented/fixed 3. Any API, UI, or deeper architectural changes that need to be implemented have been fully thought through by Streamlit's maintainers 4. Your time is well spent! More information in our wiki: https://github.com/streamlit/streamlit/wiki/Contributing --> ## 📚 Context _Please describe the project or issue background here_ - What kind of change does this PR introduce? - [ ] Bugfix - [ ] Feature - [ ] Refactoring - [x] Other, please describe: When devs run `make pytest` they see bunch of Deprecation and Future warnings mostly related to `numpy` and `pandas` usage, these are only Warnings and they are not bugs. This Warnings can be distracting when people work on specific feature unrelated to them. For that reason I propose to supress the warnings which we expect, if we want to get rid of deprecated code let's write issues for it instead of being loud in the tests. What's your opinion on this? ## 🧠 Description of Changes This PR ignores deprecation and future warnings when running `pytest` selectively in places in which they are expected anyway, all other warnings will not be supressed. - _Add bullet points summarizing your changes here_ - [ ] This is a breaking API change - [ ] This is a visible (user-facing) change **Revised:** _Insert screenshot of your updated UI/code here_ **Current:** _Insert screenshot of existing UI/code here_ ## 🧪 Testing Done - [ ] Screenshots included - [ ] Added/Updated unit tests - [ ] Added/Updated e2e tests ## 🌐 References _Does this depend on other work, documents, or tickets?_ - **Issue**: Closes #XXXX --- **Contribution License Agreement** By submitting this pull request you agree that all contributions to this project are made under the Apache 2.0 license.
https://api.github.com/repos/streamlit/streamlit/pulls/5060
2022-07-29T08:58:21Z
2022-08-11T15:56:35Z
2022-08-11T15:56:35Z
2023-10-05T19:28:02Z
1,017
streamlit/streamlit
22,280
Refs #29898 -- Moved django.db.migrations.operations.utils to django.db.migrations.utils.
diff --git a/django/db/migrations/operations/fields.py b/django/db/migrations/operations/fields.py index 728105ea05684..b303f704653c9 100644 --- a/django/db/migrations/operations/fields.py +++ b/django/db/migrations/operations/fields.py @@ -1,9 +1,11 @@ from django.core.exceptions import FieldDoesNotExist +from django.db.migrations.utils import ( + field_is_referenced, field_references, get_references, +) from django.db.models import NOT_PROVIDED from django.utils.functional import cached_property from .base import Operation -from .utils import field_is_referenced, field_references, get_references class FieldOperation(Operation): diff --git a/django/db/migrations/operations/models.py b/django/db/migrations/operations/models.py index a39731e412e55..10f2686dc6f8d 100644 --- a/django/db/migrations/operations/models.py +++ b/django/db/migrations/operations/models.py @@ -1,14 +1,15 @@ from django.db import models from django.db.migrations.operations.base import Operation from django.db.migrations.state import ModelState -from django.db.migrations.utils import resolve_relation +from django.db.migrations.utils import ( + field_references, get_references, resolve_relation, +) from django.db.models.options import normalize_together from django.utils.functional import cached_property from .fields import ( AddField, AlterField, FieldOperation, RemoveField, RenameField, ) -from .utils import field_references, get_references def _check_for_duplicates(arg_name, objs): diff --git a/django/db/migrations/operations/utils.py b/django/db/migrations/operations/utils.py deleted file mode 100644 index 0ea55bd3f769c..0000000000000 --- a/django/db/migrations/operations/utils.py +++ /dev/null @@ -1,74 +0,0 @@ -from collections import namedtuple - -from django.db.migrations.utils import resolve_relation - -FieldReference = namedtuple('FieldReference', 'to through') - - -def field_references( - model_tuple, - field, - reference_model_tuple, - reference_field_name=None, - reference_field=None, -): - """ - Return either False or a FieldReference if `field` references provided - context. - - False positives can be returned if `reference_field_name` is provided - without `reference_field` because of the introspection limitation it - incurs. This should not be an issue when this function is used to determine - whether or not an optimization can take place. - """ - remote_field = field.remote_field - if not remote_field: - return False - references_to = None - references_through = None - if resolve_relation(remote_field.model, *model_tuple) == reference_model_tuple: - to_fields = getattr(field, 'to_fields', None) - if ( - reference_field_name is None or - # Unspecified to_field(s). - to_fields is None or - # Reference to primary key. - (None in to_fields and (reference_field is None or reference_field.primary_key)) or - # Reference to field. - reference_field_name in to_fields - ): - references_to = (remote_field, to_fields) - through = getattr(remote_field, 'through', None) - if through and resolve_relation(through, *model_tuple) == reference_model_tuple: - through_fields = remote_field.through_fields - if ( - reference_field_name is None or - # Unspecified through_fields. - through_fields is None or - # Reference to field. - reference_field_name in through_fields - ): - references_through = (remote_field, through_fields) - if not (references_to or references_through): - return False - return FieldReference(references_to, references_through) - - -def get_references(state, model_tuple, field_tuple=()): - """ - Generator of (model_state, name, field, reference) referencing - provided context. - - If field_tuple is provided only references to this particular field of - model_tuple will be generated. - """ - for state_model_tuple, model_state in state.models.items(): - for name, field in model_state.fields.items(): - reference = field_references(state_model_tuple, field, model_tuple, *field_tuple) - if reference: - yield model_state, name, field, reference - - -def field_is_referenced(state, model_tuple, field_tuple): - """Return whether `field_tuple` is referenced by any state models.""" - return next(get_references(state, model_tuple, field_tuple), None) is not None diff --git a/django/db/migrations/utils.py b/django/db/migrations/utils.py index 7ce2c5bc820d5..97bd96a90a569 100644 --- a/django/db/migrations/utils.py +++ b/django/db/migrations/utils.py @@ -1,8 +1,11 @@ import datetime import re +from collections import namedtuple from django.db.models.fields.related import RECURSIVE_RELATIONSHIP_CONSTANT +FieldReference = namedtuple('FieldReference', 'to through') + COMPILED_REGEX_TYPE = type(re.compile('')) @@ -44,3 +47,72 @@ def resolve_relation(model, app_label=None, model_name=None): ) return app_label, model.lower() return model._meta.app_label, model._meta.model_name + + +def field_references( + model_tuple, + field, + reference_model_tuple, + reference_field_name=None, + reference_field=None, +): + """ + Return either False or a FieldReference if `field` references provided + context. + + False positives can be returned if `reference_field_name` is provided + without `reference_field` because of the introspection limitation it + incurs. This should not be an issue when this function is used to determine + whether or not an optimization can take place. + """ + remote_field = field.remote_field + if not remote_field: + return False + references_to = None + references_through = None + if resolve_relation(remote_field.model, *model_tuple) == reference_model_tuple: + to_fields = getattr(field, 'to_fields', None) + if ( + reference_field_name is None or + # Unspecified to_field(s). + to_fields is None or + # Reference to primary key. + (None in to_fields and (reference_field is None or reference_field.primary_key)) or + # Reference to field. + reference_field_name in to_fields + ): + references_to = (remote_field, to_fields) + through = getattr(remote_field, 'through', None) + if through and resolve_relation(through, *model_tuple) == reference_model_tuple: + through_fields = remote_field.through_fields + if ( + reference_field_name is None or + # Unspecified through_fields. + through_fields is None or + # Reference to field. + reference_field_name in through_fields + ): + references_through = (remote_field, through_fields) + if not (references_to or references_through): + return False + return FieldReference(references_to, references_through) + + +def get_references(state, model_tuple, field_tuple=()): + """ + Generator of (model_state, name, field, reference) referencing + provided context. + + If field_tuple is provided only references to this particular field of + model_tuple will be generated. + """ + for state_model_tuple, model_state in state.models.items(): + for name, field in model_state.fields.items(): + reference = field_references(state_model_tuple, field, model_tuple, *field_tuple) + if reference: + yield model_state, name, field, reference + + +def field_is_referenced(state, model_tuple, field_tuple): + """Return whether `field_tuple` is referenced by any state models.""" + return next(get_references(state, model_tuple, field_tuple), None) is not None
https://api.github.com/repos/django/django/pulls/14551
2021-06-22T07:27:30Z
2021-06-22T07:57:23Z
2021-06-22T07:57:23Z
2021-06-22T08:59:22Z
1,819
django/django
50,825
Add argpars for environment in play.py
diff --git a/gym/utils/play.py b/gym/utils/play.py index 8587f6f8d5a..fa92d3be4f1 100644 --- a/gym/utils/play.py +++ b/gym/utils/play.py @@ -3,6 +3,7 @@ import sys import time import matplotlib +import argparse try: matplotlib.use('GTK3Agg') import matplotlib.pyplot as plt @@ -16,6 +17,10 @@ from pygame.locals import HWSURFACE, DOUBLEBUF, RESIZABLE, VIDEORESIZE from threading import Thread +parser = argparse.ArgumentParser() +parser.add_argument('--env', type=str, default='MontezumaRevengeNoFrameskip-v4', help='Define Environment') +args = parser.parse_args() + def display_arr(screen, arr, video_size, transpose): arr_min, arr_max = arr.min(), arr.max() arr = 255.0 * (arr - arr_min) / (arr_max - arr_min) @@ -182,5 +187,5 @@ def callback(self, obs_t, obs_tp1, action, rew, done, info): if __name__ == '__main__': - env = gym.make("MontezumaRevengeNoFrameskip-v4") + env = gym.make(args.env) play(env, zoom=4, fps=60)
Add an Argpars --env for environment with default set to: MontezumaRevengeNoFrameskip-v4
https://api.github.com/repos/openai/gym/pulls/641
2017-07-05T02:11:00Z
2019-03-07T20:53:01Z
2019-03-07T20:53:01Z
2019-03-07T20:53:01Z
301
openai/gym
5,558
New model added
diff --git a/model_cards/Hate-speech-CNERG/dehatebert-mono-english/README.md b/model_cards/Hate-speech-CNERG/dehatebert-mono-english/README.md new file mode 100644 index 0000000000000..b96c834b86122 --- /dev/null +++ b/model_cards/Hate-speech-CNERG/dehatebert-mono-english/README.md @@ -0,0 +1,2 @@ +This model is used detecting **hatespeech** in **English language**. The mono in the name refers to the monolingual setting, where the model is trained using only English language data. It is finetuned on multilingual bert model. +The model is trained with different learning rates and the best validation score achieved is 0.7069374 for a learning rate of 2e-5. Training code can be found at this [url](https://github.com/punyajoy/DE-LIMIT)
The first model added to the repo
https://api.github.com/repos/huggingface/transformers/pulls/3862
2020-04-20T02:09:56Z
2020-04-20T21:10:02Z
2020-04-20T21:10:02Z
2020-04-20T21:36:42Z
217
huggingface/transformers
12,710
Added test case to knapsack.py
diff --git a/dynamic_programming/knapsack.py b/dynamic_programming/knapsack.py index a1e4f0d80daf..6c9789c972f2 100644 --- a/dynamic_programming/knapsack.py +++ b/dynamic_programming/knapsack.py @@ -12,3 +12,13 @@ def knapsack(W, wt, val, n): dp[i][w] = dp[i-1][w] return dp[n][w] +if __name__ == "__main__": + val = [3,2,4,4] + wt = [4,3,2,3] + W = 6 + n = 4 + ''' + Should give 8 + ''' + print(knapsack(W,wt,val,n)) +
Added a test case to knapsack.py
https://api.github.com/repos/TheAlgorithms/Python/pulls/330
2018-07-22T18:49:20Z
2018-07-22T22:07:27Z
2018-07-22T22:07:27Z
2018-07-22T22:07:27Z
193
TheAlgorithms/Python
29,934
Add IBGE API to Geocoding
diff --git a/README.md b/README.md index ce50e13eb4..236458e9a5 100644 --- a/README.md +++ b/README.md @@ -664,6 +664,7 @@ API | Description | Auth | HTTPS | CORS | | [HelloSalut](https://www.fourtonfish.com/hellosalut/hello/) | Get hello translation following user language | No | Yes | Unknown | | [HERE Maps](https://developer.here.com) | Create/customize digital maps based on HERE Maps data | `apiKey` | Yes | Unknown | | [Hong Kong GeoData Store](https://geodata.gov.hk/gs/) | API for accessing geo-data of Hong Kong | No | Yes | Unknown | +| [IBGE](https://servicodados.ibge.gov.br/api/docs/) | Aggregate services of IBGE (Brazilian Institute of Geography and Statistics) | No | Yes | Unknown | | [IP 2 Country](https://ip2country.info) | Map an IP to a country | No | Yes | Unknown | | [IP Address Details](https://ipinfo.io/) | Find geolocation with ip address | No | Yes | Unknown | | [IP Location](https://ipapi.co/api/#introduction) | Find IP address location information | No | Yes | Yes |
<!-- Thank you for taking the time to work on a Pull Request for this project! --> <!-- To ensure your PR is dealt with swiftly please check the following: --> - [x] My submission is formatted according to the guidelines in the [contributing guide](/CONTRIBUTING.md) - [x] My addition is ordered alphabetically - [x] My submission has a useful description - [x] The description does not end with punctuation - [x] Each table column is padded with one space on either side - [x] I have searched the repository for any relevant issues or pull requests - [x] Any category I am creating has the minimum requirement of 3 items - [x] All changes have been [squashed][squash-link] into a single commit [squash-link]: <https://github.com/todotxt/todo.txt-android/wiki/Squash-All-Commits-Related-to-a-Single-Issue-into-a-Single-Commit>
https://api.github.com/repos/public-apis/public-apis/pulls/2109
2021-10-02T14:36:26Z
2021-10-05T06:40:08Z
2021-10-05T06:40:08Z
2021-10-05T06:40:08Z
288
public-apis/public-apis
35,906
Create patternprint
diff --git a/patternprint b/patternprint new file mode 100644 index 0000000000..82874cefee --- /dev/null +++ b/patternprint @@ -0,0 +1,6 @@ +rows = 6 +for num in range(rows): + for i in range(num): + print(num, end=" ") # print number + # line after each row to display pattern correctly + print(" ")
this program is used to print pattern
https://api.github.com/repos/geekcomputers/Python/pulls/984
2020-10-03T15:49:04Z
2020-10-10T20:18:18Z
2020-10-10T20:18:18Z
2020-10-10T20:18:18Z
104
geekcomputers/Python
31,155
Update CONTRIBUTING.rst to include correct Makefile targets.
diff --git a/CONTRIBUTING.rst b/CONTRIBUTING.rst index 472bddaf42..bc25810f4d 100644 --- a/CONTRIBUTING.rst +++ b/CONTRIBUTING.rst @@ -47,7 +47,7 @@ Go to https://github.com/jakubroztocil/httpie and fork the project repository. # Install dev. requirements and also HTTPie (in editable mode # so that the `http' command will point to your working copy): - make + make init Making Changes @@ -71,12 +71,9 @@ Running all tests: .. code-block:: bash - # Run all tests on the current Python interpreter + # Run all tests on the current Python interpreter with coverage make test - # Run all tests on the current Python with coverage - make test-cover - # Run all tests in all of the supported and available Pythons via Tox make test-tox
Hi, I'm just getting started with developing on HTTPie. I was going through the contributing guide and noticed that a couple of the `make` commands seem a little stale.
https://api.github.com/repos/httpie/cli/pulls/638
2017-12-07T04:41:58Z
2017-12-13T20:14:31Z
2017-12-13T20:14:31Z
2017-12-15T13:30:26Z
230
httpie/cli
34,085
Test dnf before yum
diff --git a/bootstrap/_rpm_common.sh b/bootstrap/_rpm_common.sh index 9f670da6e87..e4219d06bdc 100755 --- a/bootstrap/_rpm_common.sh +++ b/bootstrap/_rpm_common.sh @@ -4,12 +4,13 @@ # - Fedora 22 (x64) # - Centos 7 (x64: on AWS EC2 t2.micro, DigitalOcean droplet) -if type yum 2>/dev/null -then - tool=yum -elif type dnf 2>/dev/null +if type dnf 2>/dev/null then tool=dnf +elif type yum 2>/dev/null +then + tool=yum + else echo "Neither yum nor dnf found. Aborting bootstrap!" exit 1
yum may still be installed (by default in recent Fedoras) and will display a deprecation and migration message. On the other hand, dnf either is or isn't installed and the test will proceed as intended. (dnf is the modern replacement for yum.)
https://api.github.com/repos/certbot/certbot/pulls/1519
2015-11-16T22:37:43Z
2015-12-02T02:15:26Z
2015-12-02T02:15:26Z
2015-12-02T02:15:26Z
188
certbot/certbot
564
[3.5] bpo-33127: Compatibility patch for LibreSSL 2.7.0 (GH-6210)
diff --git a/Misc/NEWS.d/next/Library/2018-03-24-15-08-24.bpo-33127.olJmHv.rst b/Misc/NEWS.d/next/Library/2018-03-24-15-08-24.bpo-33127.olJmHv.rst new file mode 100644 index 00000000000000..635aabbde0311b --- /dev/null +++ b/Misc/NEWS.d/next/Library/2018-03-24-15-08-24.bpo-33127.olJmHv.rst @@ -0,0 +1 @@ +The ssl module now compiles with LibreSSL 2.7.1. diff --git a/Modules/_ssl.c b/Modules/_ssl.c index f721391d9db930..b9369b817df3fa 100644 --- a/Modules/_ssl.c +++ b/Modules/_ssl.c @@ -101,6 +101,12 @@ struct py_ssl_library_code { #if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && !defined(LIBRESSL_VERSION_NUMBER) # define OPENSSL_VERSION_1_1 1 +# define PY_OPENSSL_1_1_API 1 +#endif + +/* LibreSSL 2.7.0 provides necessary OpenSSL 1.1.0 APIs */ +#if defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER >= 0x2070000fL +# define PY_OPENSSL_1_1_API 1 #endif /* Openssl comes with TLSv1.1 and TLSv1.2 between 1.0.0h and 1.0.1 @@ -129,16 +135,18 @@ struct py_ssl_library_code { #define INVALID_SOCKET (-1) #endif -#ifdef OPENSSL_VERSION_1_1 -/* OpenSSL 1.1.0+ */ -#ifndef OPENSSL_NO_SSL2 -#define OPENSSL_NO_SSL2 -#endif -#else /* OpenSSL < 1.1.0 */ -#if defined(WITH_THREAD) +/* OpenSSL 1.0.2 and LibreSSL needs extra code for locking */ +#ifndef OPENSSL_VERSION_1_1 #define HAVE_OPENSSL_CRYPTO_LOCK #endif +#if defined(OPENSSL_VERSION_1_1) && !defined(OPENSSL_NO_SSL2) +#define OPENSSL_NO_SSL2 +#endif + +#ifndef PY_OPENSSL_1_1_API +/* OpenSSL 1.1 API shims for OpenSSL < 1.1.0 and LibreSSL < 2.7.0 */ + #define TLS_method SSLv23_method static int X509_NAME_ENTRY_set(const X509_NAME_ENTRY *ne) @@ -187,7 +195,8 @@ static X509_VERIFY_PARAM *X509_STORE_get0_param(X509_STORE *store) { return store->param; } -#endif /* OpenSSL < 1.1.0 or LibreSSL */ + +#endif /* OpenSSL < 1.1.0 or LibreSSL < 2.7.0 */ enum py_ssl_error {
LibreSSL 2.7 introduced OpenSSL 1.1.0 API. The ssl module now detects LibreSSL 2.7 and only provides API shims for OpenSSL < 1.1.0 and LibreSSL < 2.7. Documentation updates and fixes for failing tests will be provided in another patch set. Signed-off-by: Christian Heimes <christian@python.org> <!-- issue-number: [bpo-33127](https://bugs.python.org/issue33127) --> https://bugs.python.org/issue33127 <!-- /issue-number -->
https://api.github.com/repos/python/cpython/pulls/10994
2018-12-06T15:37:43Z
2019-03-01T07:36:01Z
2019-03-01T07:36:01Z
2019-03-10T20:27:04Z
696
python/cpython
4,148
Warn users if sse flows are received without streaming, refs #4469
diff --git a/CHANGELOG.md b/CHANGELOG.md index 6a5add7bb0..6307983a94 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ ([#5227](https://github.com/mitmproxy/mitmproxy/issues/5227), @mhils) * Console Performance Improvements ([#3427](https://github.com/mitmproxy/mitmproxy/issues/3427), @BkPHcgQL3V) +* Warn users if server side event responses are received without streaming. + ([#4469](https://github.com/mitmproxy/mitmproxy/issues/4469), @mhils) * Add flatpak support to the browser addon ([#5200](https://github.com/mitmproxy/mitmproxy/issues/5200), @pauloromeira) * Add example addon to dump contents to files based on a filter expression diff --git a/docs/src/content/overview-features.md b/docs/src/content/overview-features.md index 725234f957..f635436a2a 100644 --- a/docs/src/content/overview-features.md +++ b/docs/src/content/overview-features.md @@ -358,7 +358,8 @@ By default, mitmproxy will read an entire request/response, perform any indicated manipulations on it, and then send the message on to the other party. This can be problematic when downloading or uploading large files. When streaming is enabled, message bodies are not buffered on the proxy but instead -sent directly to the server/client. HTTP headers are still fully buffered before +sent directly to the server/client. This currently means that the message body +will not be accessible within mitmproxy. HTTP headers are still fully buffered before being sent. Request/response streaming is enabled by specifying a size cutoff in the diff --git a/mitmproxy/addons/server_side_events.py b/mitmproxy/addons/server_side_events.py new file mode 100644 index 0000000000..43084f1bfc --- /dev/null +++ b/mitmproxy/addons/server_side_events.py @@ -0,0 +1,19 @@ +from mitmproxy import ctx, http + + +class ServerSideEvents: + """ + Server-Side Events are currently swallowed if there's no streaming, + see https://github.com/mitmproxy/mitmproxy/issues/4469. + + Until this bug is fixed, this addon warns the user about this. + """ + + def response(self, flow: http.HTTPFlow): + assert flow.response + is_sse = flow.response.headers.get("content-type", "").startswith("text/event-stream") + if is_sse and not flow.response.stream: + ctx.log.warn( + "mitmproxy currently does not support server side events. As a workaround, you can enable response " + "streaming for such flows: https://github.com/mitmproxy/mitmproxy/issues/4469" + ) diff --git a/test/mitmproxy/addons/test_server_side_events.py b/test/mitmproxy/addons/test_server_side_events.py new file mode 100644 index 0000000000..f152dc62ba --- /dev/null +++ b/test/mitmproxy/addons/test_server_side_events.py @@ -0,0 +1,12 @@ +from mitmproxy.addons.server_side_events import ServerSideEvents +from mitmproxy.test import taddons +from mitmproxy.test.tflow import tflow + + +async def test_simple(): + s = ServerSideEvents() + with taddons.context() as tctx: + f = tflow(resp=True) + f.response.headers["content-type"] = "text/event-stream" + s.response(f) + await tctx.master.await_log("mitmproxy currently does not support server side events.") diff --git a/test/mitmproxy/tools/console/test_common.py b/test/mitmproxy/tools/console/test_common.py index 181a368ac8..e684c43f0f 100644 --- a/test/mitmproxy/tools/console/test_common.py +++ b/test/mitmproxy/tools/console/test_common.py @@ -39,6 +39,7 @@ def test_format_keyvals(): def test_truncated_text(): + urwid.set_encoding("utf8") half_width_text = common.TruncatedText("Half-width", []) full_width_text = common.TruncatedText("FULL-WIDTH", []) assert half_width_text.render((10,))
https://api.github.com/repos/mitmproxy/mitmproxy/pulls/5249
2022-04-06T09:50:43Z
2022-04-06T10:51:59Z
2022-04-06T10:51:59Z
2022-04-06T11:04:38Z
1,005
mitmproxy/mitmproxy
28,164
Fix index buffer bug
diff --git a/manimlib/camera/camera.py b/manimlib/camera/camera.py index 4dfc994ca2..3dbab48da4 100644 --- a/manimlib/camera/camera.py +++ b/manimlib/camera/camera.py @@ -415,7 +415,7 @@ def get_render_group( if indices is None: ibo = None elif single_use: - ibo = self.ctx.buffer(indices) + ibo = self.ctx.buffer(indices.astype(np.uint32)) else: # The vao.render call is strangely longer # when an index buffer is used, so if the diff --git a/manimlib/mobject/mobject.py b/manimlib/mobject/mobject.py index e33c1a7f08..300a279ed3 100644 --- a/manimlib/mobject/mobject.py +++ b/manimlib/mobject/mobject.py @@ -238,7 +238,7 @@ def clear_points(self) -> None: self.resize_points(0) def get_num_points(self) -> int: - return len(self.data["points"]) + return len(self.get_points()) def get_all_points(self) -> Vect3Array: if self.submobjects: @@ -247,7 +247,7 @@ def get_all_points(self) -> Vect3Array: return self.get_points() def has_points(self) -> bool: - return self.data["points"].size > 0 + return len(self.get_points()) > 0 def get_bounding_box(self) -> Vect3Array: if self.needs_new_bounding_box: diff --git a/manimlib/mobject/numbers.py b/manimlib/mobject/numbers.py index 7effabea86..b012886819 100644 --- a/manimlib/mobject/numbers.py +++ b/manimlib/mobject/numbers.py @@ -111,12 +111,12 @@ def get_num_string(self, number: float | complex) -> str: num_string = num_string.replace("-", "–") return num_string - def init_data(self) -> None: - super().init_data() - self.data["font_size"] = np.array([self.font_size], dtype=float) + def init_uniforms(self) -> None: + super().init_uniforms() + self.uniforms["font_size"] = self.font_size def get_font_size(self) -> int: - return int(self.data["font_size"][0]) + return int(self.uniforms["font_size"]) def get_formatter(self, **kwargs) -> str: """ @@ -167,7 +167,7 @@ def set_value(self, number: float | complex): return self def _handle_scale_side_effects(self, scale_factor: float) -> None: - self.data["font_size"] *= scale_factor + self.uniforms["font_size"] *= scale_factor def get_value(self) -> float | complex: return self.number diff --git a/manimlib/mobject/types/vectorized_mobject.py b/manimlib/mobject/types/vectorized_mobject.py index 52c7692ab9..4ad9cdec10 100644 --- a/manimlib/mobject/types/vectorized_mobject.py +++ b/manimlib/mobject/types/vectorized_mobject.py @@ -720,7 +720,7 @@ def get_nth_curve_function(self, n: int) -> Callable[[float], Vect3]: return bezier(self.get_nth_curve_points(n)) def get_num_curves(self) -> int: - return len(self.data["points"]) // 2 + return self.get_num_points() // 2 def quick_point_from_proportion(self, alpha: float) -> Vect3: # Assumes all curves have the same length, so is inaccurate
Small fix from an oversight in https://github.com/3b1b/manim/pull/1959 (Along with some small tweaks)
https://api.github.com/repos/3b1b/manim/pulls/1964
2023-01-16T05:07:35Z
2023-01-16T05:08:25Z
2023-01-16T05:08:25Z
2023-01-16T05:08:26Z
851
3b1b/manim
18,419
Add .NET references
diff --git a/Insecure Deserialization/README.md b/Insecure Deserialization/README.md index aa058259f5..514fd13e3f 100644 --- a/Insecure Deserialization/README.md +++ b/Insecure Deserialization/README.md @@ -12,6 +12,7 @@ Check the following sub-sections, located in other files : ## References * [Github - ysoserial](https://github.com/frohoff/ysoserial) +* [Github - ysoserial.net](https://github.com/pwntester/ysoserial.net) * [Java-Deserialization-Cheat-Sheet - GrrrDog](https://github.com/GrrrDog/Java-Deserialization-Cheat-Sheet/blob/master/README.md) * [Understanding & practicing java deserialization exploits](https://diablohorn.com/2017/09/09/understanding-practicing-java-deserialization-exploits/) * [How i found a 1500$ worth Deserialization vulnerability - @D0rkerDevil](https://medium.com/@D0rkerDevil/how-i-found-a-1500-worth-deserialization-vulnerability-9ce753416e0a) @@ -25,4 +26,5 @@ Check the following sub-sections, located in other files : * [Instagram's Million Dollar Bug](http://www.exfiltrated.com/research-Instagram-RCE.php) by Wesley Wineberg * [(Ruby Cookie Deserialization RCE on facebooksearch.algolia.com](https://hackerone.com/reports/134321) by Michiel Prins (michiel) * [Java deserialization](https://seanmelia.wordpress.com/2016/07/22/exploiting-java-deserialization-via-jboss/) by meals -* [Diving into unserialize() - Sep 19- Vickie Li](https://medium.com/swlh/diving-into-unserialize-3586c1ec97e) \ No newline at end of file +* [Diving into unserialize() - Sep 19- Vickie Li](https://medium.com/swlh/diving-into-unserialize-3586c1ec97e) +* [.NET Gadgets](https://www.blackhat.com/docs/us-17/thursday/us-17-Munoz-Friday-The-13th-Json-Attacks.pdf) by Alvaro Muñoz (@pwntester) & OleksandrMirosh
https://api.github.com/repos/swisskyrepo/PayloadsAllTheThings/pulls/98
2019-10-03T00:23:58Z
2019-10-03T14:13:26Z
2019-10-03T14:13:26Z
2019-10-03T14:13:26Z
527
swisskyrepo/PayloadsAllTheThings
8,573
Add nginx log files for LFI log poisoning
diff --git a/Directory Traversal/README.md b/Directory Traversal/README.md index 7de4fc123b..b746ffa7b7 100644 --- a/Directory Traversal/README.md +++ b/Directory Traversal/README.md @@ -111,6 +111,8 @@ The following log files are controllable and can be included with an evil payloa /var/log/httpd/error_log /usr/local/apache/log/error_log /usr/local/apache2/log/error_log +/var/log/nginx/access.log +/var/log/nginx/error.log /var/log/vsftpd.log /var/log/sshd.log /var/log/mail diff --git a/File Inclusion/Intruders/JHADDIX_LFI.txt b/File Inclusion/Intruders/JHADDIX_LFI.txt index 6f10e3ffe2..75b06325f3 100644 --- a/File Inclusion/Intruders/JHADDIX_LFI.txt +++ b/File Inclusion/Intruders/JHADDIX_LFI.txt @@ -666,6 +666,18 @@ users/.htpasswd /var/log/news/news.notice /var/log/news/suck.err /var/log/news/suck.notice +/var/log/nginx/access_log +/var/log/nginx/access.log +../../../../../../../var/log/nginx/access_log +../../../../../../../var/log/nginx/access.log +../../../../../var/log/nginx/access_log +../../../../../var/log/nginx/access.log +/var/log/nginx/error_log +/var/log/nginx/error.log +../../../../../../../var/log/nginx/error_log +../../../../../../../var/log/nginx/error.log +../../../../../var/log/nginx/error_log +../../../../../var/log/nginx/error.log /var/log/poplog /var/log/POPlog /var/log/proftpd diff --git a/File Inclusion/Intruders/Linux-files.txt b/File Inclusion/Intruders/Linux-files.txt index 601422b8b1..c43cc4a639 100644 --- a/File Inclusion/Intruders/Linux-files.txt +++ b/File Inclusion/Intruders/Linux-files.txt @@ -55,4 +55,8 @@ /var/log/apache/error.log /var/log/apache/error_log /var/log/httpd/error_log -/var/log/httpd/access_log \ No newline at end of file +/var/log/httpd/access_log +/var/log/nginx/access_log +/var/log/nginx/access.log +/var/log/nginx/error_log +/var/log/nginx/error.log \ No newline at end of file diff --git a/File Inclusion/Intruders/List_Of_File_To_Include.txt b/File Inclusion/Intruders/List_Of_File_To_Include.txt index 884f448954..0ad6dcb385 100644 --- a/File Inclusion/Intruders/List_Of_File_To_Include.txt +++ b/File Inclusion/Intruders/List_Of_File_To_Include.txt @@ -765,6 +765,20 @@ php://input /var/log/mysql/mysql-slow.log /var/log/mysql/mysql-slow.log /var/log/mysql/mysql-slow.log%00 +/var/log/nginx/access_log +/var/log/nginx/access_log +/var/log/nginx/access_log +/var/log/nginx/access.log +/var/log/nginx/access.log +/var/log/nginx/access_log%00 +/var/log/nginx/access.log%00 +/var/log/nginx/error_log +/var/log/nginx/error_log +/var/log/nginx/error.log +/var/log/nginx/error.log +/var/log/nginx/error.log +/var/log/nginx/error_log%00 +/var/log/nginx/error.log%00 /var/log/proftpd /var/log/proftpd /var/log/proftpd%00 diff --git a/File Inclusion/Intruders/List_Of_File_To_Include_NullByteAdded.txt b/File Inclusion/Intruders/List_Of_File_To_Include_NullByteAdded.txt index d4f2edf0a5..4f764a8d63 100644 --- a/File Inclusion/Intruders/List_Of_File_To_Include_NullByteAdded.txt +++ b/File Inclusion/Intruders/List_Of_File_To_Include_NullByteAdded.txt @@ -41,6 +41,10 @@ /var/log/httpd/error_log%00 /var/log/httpd/access_log%00 /var/log/httpd/error_log%00 +/var/log/nginx/access_log%00 +/var/log/nginx/access.log%00 +/var/log/nginx/error_log%00 +/var/log/nginx/error.log%00 /apache/logs/error.log%00 /apache/logs/access.log%00 /apache/logs/error.log%00 diff --git a/File Inclusion/Intruders/Mac-files.txt b/File Inclusion/Intruders/Mac-files.txt index 9a1dd6920d..99fdad9807 100644 --- a/File Inclusion/Intruders/Mac-files.txt +++ b/File Inclusion/Intruders/Mac-files.txt @@ -3,4 +3,6 @@ /private/var/log/appstore.log /var/log/apache2/error_log /var/log/apache2/access_log -/usr/local/nginx/conf/nginx.conf \ No newline at end of file +/usr/local/nginx/conf/nginx.conf +/var/log/nginx/error_log +/var/log/nginx/access_log \ No newline at end of file diff --git a/File Inclusion/README.md b/File Inclusion/README.md index 36103638a4..6c54db95d3 100644 --- a/File Inclusion/README.md +++ b/File Inclusion/README.md @@ -253,6 +253,8 @@ Just append your PHP code into the log file by doing a request to the service (A ```powershell http://example.com/index.php?page=/var/log/apache/access.log http://example.com/index.php?page=/var/log/apache/error.log +http://example.com/index.php?page=/var/log/nginx/access.log +http://example.com/index.php?page=/var/log/nginx/error.log http://example.com/index.php?page=/var/log/vsftpd.log http://example.com/index.php?page=/var/log/sshd.log http://example.com/index.php?page=/var/log/mail
An example of where these new includes could be useful is the DC: 5 box on VulnHub.
https://api.github.com/repos/swisskyrepo/PayloadsAllTheThings/pulls/71
2019-05-30T10:04:05Z
2019-05-30T10:33:24Z
2019-05-30T10:33:24Z
2019-05-30T10:33:33Z
1,379
swisskyrepo/PayloadsAllTheThings
8,304
✨ Import and re-export data structures from Starlette, used by Request properties, on `fastapi.datastructures`
diff --git a/fastapi/datastructures.py b/fastapi/datastructures.py index 6a44a7df4ff33..b1317128707b6 100644 --- a/fastapi/datastructures.py +++ b/fastapi/datastructures.py @@ -1,5 +1,10 @@ from typing import Any, Callable, Iterable, Type, TypeVar +from starlette.datastructures import URL as URL # noqa: F401 +from starlette.datastructures import Address as Address # noqa: F401 +from starlette.datastructures import FormData as FormData # noqa: F401 +from starlette.datastructures import Headers as Headers # noqa: F401 +from starlette.datastructures import QueryParams as QueryParams # noqa: F401 from starlette.datastructures import State as State # noqa: F401 from starlette.datastructures import UploadFile as StarletteUploadFile
Closes https://github.com/tiangolo/fastapi/issues/1871
https://api.github.com/repos/tiangolo/fastapi/pulls/1872
2020-08-10T14:16:13Z
2021-07-29T15:30:18Z
2021-07-29T15:30:18Z
2021-07-29T15:30:19Z
197
tiangolo/fastapi
23,054
Fix SelectJmes documentation
diff --git a/scrapy/loader/processors.py b/scrapy/loader/processors.py index 3b221acaf43..bf7c74bfef3 100644 --- a/scrapy/loader/processors.py +++ b/scrapy/loader/processors.py @@ -78,7 +78,7 @@ def __init__(self, json_path): def __call__(self, value): """Query value for the jmespath query and return answer - :param str value: a string with JSON data to extract from + :param value: a data structure (dict, list) to extract from :return: Element extracted according to jmespath query """ return self.compiled_path.search(value)
Docstring says it takes a json string, but it actually takes a loaded data structure.
https://api.github.com/repos/scrapy/scrapy/pulls/1320
2015-06-25T18:15:07Z
2015-06-25T18:20:46Z
2015-06-25T18:20:46Z
2015-06-25T18:20:56Z
158
scrapy/scrapy
34,641
Change grafana config so anonymous access works by default
diff --git a/dashboard/modules/metrics/export/grafana/grafana.ini b/dashboard/modules/metrics/export/grafana/grafana.ini index 281e2becb941f..e349fc5b29076 100644 --- a/dashboard/modules/metrics/export/grafana/grafana.ini +++ b/dashboard/modules/metrics/export/grafana/grafana.ini @@ -3,7 +3,7 @@ allow_embedding = true [auth.anonymous] enabled = true -org_name = ray +org_name = Main Org. org_role = Viewer [paths]
Signed-off-by: Alan Guo <aguo@anyscale.com> <!-- Thank you for your contribution! Please review https://github.com/ray-project/ray/blob/master/CONTRIBUTING.rst before opening a pull request. --> <!-- Please add a reviewer to the assignee section when you create a PR. If you don't have the access to it, we will shortly find a reviewer and assign them to your PR. --> ## Why are these changes needed? THis makes it so anonymous mode on grafana works correctly. Anonymous mode can only work if there is an actual org set up. "Main Org." is the default name of orgs that come with Grafana. <!-- Please give a short summary of the change and the problem this solves. --> ## Related issue number <!-- For example: "Closes #1234" --> ## Checks - [x] I've signed off every commit(by using the -s flag, i.e., `git commit -s`) in this PR. - [x] I've run `scripts/format.sh` to lint the changes in this PR. - [ ] I've included any doc changes needed for https://docs.ray.io/en/master/. - [ ] I've made sure the tests are passing. Note that there might be a few flaky tests, see the recent failures at https://flakey-tests.ray.io/ - Testing Strategy - [ ] Unit tests - [ ] Release tests - [ ] This PR is not tested :(
https://api.github.com/repos/ray-project/ray/pulls/30303
2022-11-15T19:23:45Z
2022-11-17T01:33:13Z
2022-11-17T01:33:13Z
2022-11-17T01:33:13Z
126
ray-project/ray
19,201
support stable-vicuna model
diff --git a/fastchat/conversation.py b/fastchat/conversation.py index 7bd836a287..f00efbd6e3 100644 --- a/fastchat/conversation.py +++ b/fastchat/conversation.py @@ -1129,6 +1129,20 @@ def get_conv_template(name: str) -> Conversation: ) ) +# Stable Vicuna default template +# source: https://huggingface.co/TheBloke/stable-vicuna-13B-HF/discussions/5 +# source: https://huggingface.co/spaces/CarperAI/StableVicuna/blob/main/app.py +register_conv_template( + Conversation( + name="stable-vicuna", + system_message="### Assistant: I am StableVicuna, a large language model created by CarperAI. I am here to chat!\n", + roles=("### Human", "### Assistant"), + sep_style=SeparatorStyle.ADD_COLON_TWO, + sep="\n", + sep2="\n\n", + ) +) + register_conv_template( Conversation( name="vigogne_chat_v3", diff --git a/fastchat/model/model_adapter.py b/fastchat/model/model_adapter.py index b6812e7de8..d3647ead99 100644 --- a/fastchat/model/model_adapter.py +++ b/fastchat/model/model_adapter.py @@ -1784,6 +1784,22 @@ def get_default_conv_template(self, model_path: str) -> Conversation: return get_conv_template("llama-2") +class StableVicunaAdapter(BaseModelAdapter): + """The model adapter for StableVicuna""" + + def match(self, model_path: str): + return "stable-vicuna" in model_path.lower() + + def load_model(self, model_path: str, from_pretrained_kwargs: dict): + model, tokenizer = super().load_model(model_path, from_pretrained_kwargs) + model.config.eos_token_id = tokenizer.eos_token_id + model.config.pad_token_id = tokenizer.pad_token_id + return model, tokenizer + + def get_default_conv_template(self, model_path: str) -> Conversation: + return get_conv_template("stable-vicuna") + + class PhindCodeLlamaAdapter(CodeLlamaAdapter): """The model adapter for Phind-CodeLlama (e.g., Phind/Phind-CodeLlama-34B-v2)""" @@ -1867,6 +1883,7 @@ def get_default_conv_template(self, model_path: str) -> Conversation: # Note: the registration order matters. # The one registered earlier has a higher matching priority. register_model_adapter(PeftModelAdapter) +register_model_adapter(StableVicunaAdapter) register_model_adapter(VicunaAdapter) register_model_adapter(AiroborosAdapter) register_model_adapter(LongChatAdapter) diff --git a/fastchat/model/model_registry.py b/fastchat/model/model_registry.py index 840d91da46..5bef2996f5 100644 --- a/fastchat/model/model_registry.py +++ b/fastchat/model/model_registry.py @@ -348,6 +348,12 @@ def get_model_info(name: str) -> ModelInfo: "https://huggingface.co/bofenghuang/vigogne-2-7b-chat", "Vigogne-Chat is a French large language model (LLM) optimized for instruction-following and multi-turn dialogues, developed by Bofeng Huang", ) +register_model_info( + ["stable-vicuna-13B-HF"], + "stable-vicuna", + "https://huggingface.co/TheBloke/stable-vicuna-13B-HF", + "StableVicuna is a Vicuna model fine-tuned using RLHF via PPO on various conversational and instructional datasets.", +) register_model_info( ["deluxe-chat-v1", "deluxe-chat-v1.1"], "DeluxeChat",
<!-- Thank you for your contribution! --> <!-- Please add a reviewer to the assignee section when you create a PR. If you don't have the access to it, we will shortly find a reviewer and assign them to your PR. --> ## Why are these changes needed? Supports stable-vicuna model. ## Related issue number (if applicable) Closes #829 ## Checks - [x] I've run `format.sh` to lint the changes in this PR. - [ ] I've included any doc changes needed. - [ ] I've made sure the relevant tests are passing (if applicable). --- I tried to add a new model by following the steps from the guide. However, I think there are some ambiguities in my PR. 1. The original StableVicuna from HF (https://huggingface.co/spaces/CarperAI/StableVicuna) is paused. I am concerned about whether it is appropriate to use the quantized model from TheBloke (https://huggingface.co/TheBloke/stable-vicuna-13B-HF). 2. Regarding the conversation template format, I found the demo code at https://huggingface.co/spaces/CarperAI/StableVicuna/blob/main/app.py, but I'm unsure if I have applied it correctly. If anyone reviews my code and provides the correct guidance, I will make the necessary fixes. Thank you.
https://api.github.com/repos/lm-sys/FastChat/pulls/2696
2023-11-18T13:31:10Z
2023-11-23T00:11:44Z
2023-11-23T00:11:44Z
2023-11-23T00:11:44Z
874
lm-sys/FastChat
41,072
Add new notebook links in the docs
diff --git a/notebooks/README.md b/notebooks/README.md index d42b0502f82df..911b4ba5e9dab 100644 --- a/notebooks/README.md +++ b/notebooks/README.md @@ -35,6 +35,9 @@ Pull Request so it can be included under the Community notebooks. | [How to fine-tune a model on language modeling](https://github.com/huggingface/notebooks/blob/master/examples/language_modeling.ipynb) | Show how to preprocess the data and fine-tune a pretrained model on a causal or masked LM task. | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/master/examples/language_modeling.ipynb)| | [How to fine-tune a model on token classification](https://github.com/huggingface/notebooks/blob/master/examples/token_classification.ipynb) | Show how to preprocess the data and fine-tune a pretrained model on a token classification task (NER, PoS). | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/master/examples/token_classification.ipynb)| | [How to fine-tune a model on question answering](https://github.com/huggingface/notebooks/blob/master/examples/question_answering.ipynb) | Show how to preprocess the data and fine-tune a pretrained model on SQUAD. | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/master/examples/question_answering.ipynb)| +| [How to fine-tune a model on multiple choice](https://github.com/huggingface/notebooks/blob/master/examples/multiple_choice.ipynb) | Show how to preprocess the data and fine-tune a pretrained model on SWAG. | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/master/examples/multiple_choice.ipynb)| +| [How to fine-tune a model on translation](https://github.com/huggingface/notebooks/blob/master/examples/translation.ipynb) | Show how to preprocess the data and fine-tune a pretrained model on WMT. | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/master/examples/translation.ipynb)| +| [How to fine-tune a model on summarization](https://github.com/huggingface/notebooks/blob/master/examples/question_answering.ipynb) | Show how to preprocess the data and fine-tune a pretrained model on XSUM. | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/master/examples/summarization.ipynb)| | [How to train a language model from scratch](https://github.com/huggingface/blog/blob/master/notebooks/01_how_to_train.ipynb)| Highlight all the steps to effectively train Transformer model on custom data | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/blog/blob/master/notebooks/01_how_to_train.ipynb)| | [How to generate text](https://github.com/huggingface/blog/blob/master/notebooks/02_how_to_generate.ipynb)| How to use different decoding methods for language generation with transformers | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/blog/blob/master/notebooks/02_how_to_generate.ipynb)| | [How to export model to ONNX](https://github.com/huggingface/transformers/blob/master/notebooks/04-onnx-export.ipynb) | Highlight how to export and run inference workloads through ONNX |
# What does this PR do? This PR adds links to the three missing tasks in the notebooks page: multiple choice, translation and summarization.
https://api.github.com/repos/huggingface/transformers/pulls/10876
2021-03-23T23:46:22Z
2021-03-24T13:45:08Z
2021-03-24T13:45:08Z
2021-03-24T13:45:09Z
943
huggingface/transformers
12,780
Add HQQ quant loader for ooba
diff --git a/README.md b/README.md index ad8087ee60..d75121ea5a 100644 --- a/README.md +++ b/README.md @@ -305,6 +305,12 @@ List of command-line flags |-------------|-------------| | `--model_type MODEL_TYPE` | Model type of pre-quantized model. Currently gpt2, gptj, gptneox, falcon, llama, mpt, starcoder (gptbigcode), dollyv2, and replit are supported. | +#### HQQ + +| Flag | Description | +|-------------|-------------| +| `--hqq-backend` | Backend for the HQQ loader. Valid options: PYTORCH, PYTORCH_COMPILE, ATEN. | + #### DeepSpeed | Flag | Description | diff --git a/modules/loaders.py b/modules/loaders.py index 9f1c70d121..a532830b54 100644 --- a/modules/loaders.py +++ b/modules/loaders.py @@ -155,6 +155,11 @@ 'trust_remote_code', 'no_use_fast', 'no_flash_attn', + ], + 'HQQ': [ + 'hqq_backend', + 'trust_remote_code', + 'no_use_fast', ] }) @@ -503,6 +508,43 @@ 'skip_special_tokens', 'auto_max_new_tokens', }, + 'HQQ': { + 'temperature', + 'temperature_last', + 'top_p', + 'min_p', + 'top_k', + 'typical_p', + 'epsilon_cutoff', + 'eta_cutoff', + 'tfs', + 'top_a', + 'repetition_penalty', + 'presence_penalty', + 'frequency_penalty', + 'repetition_penalty_range', + 'encoder_repetition_penalty', + 'no_repeat_ngram_size', + 'min_length', + 'seed', + 'do_sample', + 'penalty_alpha', + 'num_beams', + 'length_penalty', + 'early_stopping', + 'mirostat_mode', + 'mirostat_tau', + 'mirostat_eta', + 'grammar_file_row', + 'grammar_string', + 'guidance_scale', + 'negative_prompt', + 'ban_eos_token', + 'custom_token_bans', + 'add_bos_token', + 'skip_special_tokens', + 'auto_max_new_tokens', + }, } loaders_model_types = { diff --git a/modules/models.py b/modules/models.py index 49e5f818fa..5a23f7433e 100644 --- a/modules/models.py +++ b/modules/models.py @@ -73,6 +73,7 @@ def load_model(model_name, loader=None): 'ctransformers': ctransformers_loader, 'AutoAWQ': AutoAWQ_loader, 'QuIP#': QuipSharp_loader, + 'HQQ': HQQ_loader, } metadata = get_model_metadata(model_name) @@ -411,6 +412,18 @@ def ExLlamav2_HF_loader(model_name): return Exllamav2HF.from_pretrained(model_name) +def HQQ_loader(model_name): + from hqq.engine.hf import HQQModelForCausalLM + from hqq.core.quantize import HQQLinear, HQQBackend + + logger.info(f"Loading HQQ model with backend: {shared.args.hqq_backend}") + + model_dir = Path(f'{shared.args.model_dir}/{model_name}') + model = HQQModelForCausalLM.from_quantized(str(model_dir)) + HQQLinear.set_backend(getattr(HQQBackend, shared.args.hqq_backend)) + return model + + def RWKV_loader(model_name): ''' This loader is not currently maintained as RWKV can now be loaded diff --git a/modules/models_settings.py b/modules/models_settings.py index 156c05d941..4e1fb1ad38 100644 --- a/modules/models_settings.py +++ b/modules/models_settings.py @@ -163,6 +163,8 @@ def infer_loader(model_name, model_settings): loader = 'RWKV' elif re.match(r'.*exl2', model_name.lower()): loader = 'ExLlamav2_HF' + elif re.match(r'.*-hqq', model_name.lower()): + return 'HQQ' else: loader = 'Transformers' diff --git a/modules/shared.py b/modules/shared.py index edd74af132..5afcaebf4c 100644 --- a/modules/shared.py +++ b/modules/shared.py @@ -144,6 +144,9 @@ parser.add_argument('--checkpoint', type=str, help='The path to the quantized checkpoint file. If not specified, it will be automatically detected.') parser.add_argument('--monkey-patch', action='store_true', help='Apply the monkey patch for using LoRAs with quantized models.') +# HQQ +parser.add_argument('--hqq-backend', type=str, default='PYTORCH_COMPILE', help='Backend for the HQQ loader. Valid options: PYTORCH, PYTORCH_COMPILE, ATEN.') + # DeepSpeed parser.add_argument('--deepspeed', action='store_true', help='Enable the use of DeepSpeed ZeRO-3 for inference via the Transformers integration.') parser.add_argument('--nvme-offload-dir', type=str, help='DeepSpeed: Directory to use for ZeRO-3 NVME offloading.') @@ -246,6 +249,8 @@ def fix_loader_name(name): return 'AutoAWQ' elif name in ['quip#', 'quip-sharp', 'quipsharp', 'quip_sharp']: return 'QuIP#' + elif name in ['hqq']: + return 'HQQ' def add_extension(name, last=False): diff --git a/modules/ui.py b/modules/ui.py index 285e2fc3c6..aa735d24f0 100644 --- a/modules/ui.py +++ b/modules/ui.py @@ -91,6 +91,7 @@ def list_model_elements(): 'rope_freq_base', 'numa', 'logits_all', + 'hqq_backend', ] if is_torch_xpu_available(): for i in range(torch.xpu.device_count()): diff --git a/modules/ui_model_menu.py b/modules/ui_model_menu.py index 7f81ca2d1b..ae50f69793 100644 --- a/modules/ui_model_menu.py +++ b/modules/ui_model_menu.py @@ -84,6 +84,7 @@ def create_ui(): shared.gradio['transformers_info'] = gr.Markdown('load-in-4bit params:') shared.gradio['compute_dtype'] = gr.Dropdown(label="compute_dtype", choices=["bfloat16", "float16", "float32"], value=shared.args.compute_dtype) shared.gradio['quant_type'] = gr.Dropdown(label="quant_type", choices=["nf4", "fp4"], value=shared.args.quant_type) + shared.gradio['hqq_backend'] = gr.Dropdown(label="hqq_backend", choices=["PYTORCH", "PYTORCH_COMPILE", "ATEN"], value=shared.args.hqq_backend) shared.gradio['n_gpu_layers'] = gr.Slider(label="n-gpu-layers", minimum=0, maximum=128, value=shared.args.n_gpu_layers) shared.gradio['n_ctx'] = gr.Slider(minimum=0, maximum=shared.settings['truncation_length_max'], step=256, label="n_ctx", value=shared.args.n_ctx, info='Context length. Try lowering this if you run out of memory while loading the model.') diff --git a/requirements.txt b/requirements.txt index 827e7654ab..1275378398 100644 --- a/requirements.txt +++ b/requirements.txt @@ -4,6 +4,7 @@ datasets einops exllamav2==0.0.11; platform_system != "Darwin" and platform_machine != "x86_64" gradio==3.50.* +hqq==0.1.1 markdown numpy==1.24.* optimum==1.15.* diff --git a/requirements_amd.txt b/requirements_amd.txt index bd8ccbd623..62c9e8896c 100644 --- a/requirements_amd.txt +++ b/requirements_amd.txt @@ -4,6 +4,7 @@ datasets einops exllamav2==0.0.11 gradio==3.50.* +hqq==0.1.1 markdown numpy==1.24.* optimum==1.15.* diff --git a/requirements_amd_noavx2.txt b/requirements_amd_noavx2.txt index d7e517066a..1d17ca68b3 100644 --- a/requirements_amd_noavx2.txt +++ b/requirements_amd_noavx2.txt @@ -4,6 +4,7 @@ datasets einops exllamav2==0.0.11 gradio==3.50.* +hqq==0.1.1 markdown numpy==1.24.* optimum==1.15.* diff --git a/requirements_apple_intel.txt b/requirements_apple_intel.txt index f0ed23411c..55fc0d2ce9 100644 --- a/requirements_apple_intel.txt +++ b/requirements_apple_intel.txt @@ -4,6 +4,7 @@ datasets einops exllamav2==0.0.11 gradio==3.50.* +hqq==0.1.1 markdown numpy==1.24.* optimum==1.15.* diff --git a/requirements_apple_silicon.txt b/requirements_apple_silicon.txt index 201a55a89c..a161eb30c7 100644 --- a/requirements_apple_silicon.txt +++ b/requirements_apple_silicon.txt @@ -4,6 +4,7 @@ datasets einops exllamav2==0.0.11 gradio==3.50.* +hqq==0.1.1 markdown numpy==1.24.* optimum==1.15.* diff --git a/requirements_cpu_only.txt b/requirements_cpu_only.txt index 7bd9da9e0c..7e71bc38c5 100644 --- a/requirements_cpu_only.txt +++ b/requirements_cpu_only.txt @@ -4,6 +4,7 @@ datasets einops exllamav2==0.0.11 gradio==3.50.* +hqq==0.1.1 markdown numpy==1.24.* optimum==1.15.* diff --git a/requirements_cpu_only_noavx2.txt b/requirements_cpu_only_noavx2.txt index d9b73ef9e1..6f38369f5a 100644 --- a/requirements_cpu_only_noavx2.txt +++ b/requirements_cpu_only_noavx2.txt @@ -4,6 +4,7 @@ datasets einops exllamav2==0.0.11 gradio==3.50.* +hqq==0.1.1 markdown numpy==1.24.* optimum==1.15.* diff --git a/requirements_noavx2.txt b/requirements_noavx2.txt index a193967dc1..f705d92c72 100644 --- a/requirements_noavx2.txt +++ b/requirements_noavx2.txt @@ -4,6 +4,7 @@ datasets einops exllamav2==0.0.11; platform_system != "Darwin" and platform_machine != "x86_64" gradio==3.50.* +hqq==0.1.1 markdown numpy==1.24.* optimum==1.15.* diff --git a/requirements_nowheels.txt b/requirements_nowheels.txt index 4c1161f985..1270bf5045 100644 --- a/requirements_nowheels.txt +++ b/requirements_nowheels.txt @@ -4,6 +4,7 @@ datasets einops exllamav2==0.0.11 gradio==3.50.* +hqq==0.1.1 markdown numpy==1.24.* optimum==1.15.*
## Checklist: - [x] I have read the [Contributing guidelines](https://github.com/oobabooga/text-generation-webui/wiki/Contributing-guidelines). HQQ quant code: https://github.com/mobiusml/hqq HQQ quant blog: https://mobiusml.github.io/hqq_blog/ HQQ quant for Mixtral 2b: https://huggingface.co/mobiuslabsgmbh/Mixtral-8x7B-Instruct-v0.1-hf-2bit_g16_s128-HQQ it can load the whole Mixtral using 2bit with 24GB VRAM
https://api.github.com/repos/oobabooga/text-generation-webui/pulls/4888
2023-12-11T22:15:31Z
2023-12-19T00:23:16Z
2023-12-19T00:23:16Z
2023-12-19T09:43:51Z
2,782
oobabooga/text-generation-webui
26,788
update yixia_download url match rule, fix #1346
diff --git a/src/you_get/extractors/yixia.py b/src/you_get/extractors/yixia.py index ca5c4bd6ab..7d5ba29089 100644 --- a/src/you_get/extractors/yixia.py +++ b/src/you_get/extractors/yixia.py @@ -51,11 +51,11 @@ def yixia_download(url, output_dir = '.', merge = True, info_only = False, **kwa yixia_download_by_scid = yixia_miaopai_download_by_scid site_info = "Yixia Miaopai" - if re.match(r'http://www.miaopai.com/show/channel/\w+', url): #PC + if re.match(r'http://www.miaopai.com/show/channel/.+', url): #PC scid = match1(url, r'http://www.miaopai.com/show/channel/(.+)\.htm') - elif re.match(r'http://www.miaopai.com/show/\w+', url): #PC + elif re.match(r'http://www.miaopai.com/show/.+', url): #PC scid = match1(url, r'http://www.miaopai.com/show/(.+)\.htm') - elif re.match(r'http://m.miaopai.com/show/channel/\w+', url): #Mobile + elif re.match(r'http://m.miaopai.com/show/channel/.+', url): #Mobile scid = match1(url, r'http://m.miaopai.com/show/channel/(.+)\.htm') elif 'xiaokaxiu.com' in hostname: #Xiaokaxiu
Miaopai has two styles of URL 1. http://www.miaopai.com/show/-FIqw~8q9R1qq~gSm0tUGA__.htm 2. http://www.miaopai.com/show/KDzmatlzeXnYSve4Z1Bdjg__.htm and `\w` can't match style 1, so i changed `\w+` to `.+`, this could fix problem in #1346 ping @cnbeining @soimort <!-- Reviewable:start --> --- This change is [<img src="https://reviewable.io/review_button.svg" height="34" align="absmiddle" alt="Reviewable"/>](https://reviewable.io/reviews/soimort/you-get/1513) <!-- Reviewable:end -->
https://api.github.com/repos/soimort/you-get/pulls/1513
2016-11-14T13:58:03Z
2016-11-15T08:13:15Z
2016-11-15T08:13:15Z
2016-11-15T08:13:16Z
384
soimort/you-get
20,931
hitbtc BDP -> BidiPass
diff --git a/js/hitbtc.js b/js/hitbtc.js index 3ceefe778ea4..5bc3b8fd7b8a 100644 --- a/js/hitbtc.js +++ b/js/hitbtc.js @@ -188,6 +188,7 @@ module.exports = class hitbtc extends Exchange { 'commonCurrencies': { 'AUTO': 'Cube', 'BCC': 'BCC', // initial symbol for Bitcoin Cash, now inactive + 'BDP': 'BidiPass', 'BET': 'DAO.Casino', 'BOX': 'BOX Token', 'CPT': 'Cryptaur', // conflict with CPT = Contents Protocol https://github.com/ccxt/ccxt/issues/4920 and https://github.com/ccxt/ccxt/issues/6081
https://coinmarketcap.com/currencies/bidipass/markets/ conflict with https://coinmarketcap.com/currencies/big-data-protocol/markets/
https://api.github.com/repos/ccxt/ccxt/pulls/9699
2021-07-30T18:31:43Z
2021-07-30T20:25:19Z
2021-07-30T20:25:19Z
2021-07-30T20:25:19Z
181
ccxt/ccxt
13,566
read_files_in_dir: closedir before return
diff --git a/selfdrive/common/util.cc b/selfdrive/common/util.cc index 689a6a90bb1098..4d366a0394cc97 100644 --- a/selfdrive/common/util.cc +++ b/selfdrive/common/util.cc @@ -83,6 +83,7 @@ int read_files_in_dir(std::string path, std::map<std::string, std::string> *cont } } + closedir(d); return 0; }
https://api.github.com/repos/commaai/openpilot/pulls/20903
2021-05-14T15:57:33Z
2021-05-15T00:33:46Z
2021-05-15T00:33:46Z
2021-05-15T13:54:58Z
108
commaai/openpilot
9,357
chore: add user survey over README
diff --git a/.github/images/banner.svg b/.github/images/survey.svg similarity index 76% rename from .github/images/banner.svg rename to .github/images/survey.svg index d135bfdb45c19..33e290692b744 100644 --- a/.github/images/banner.svg +++ b/.github/images/survey.svg @@ -11,8 +11,8 @@ } </style> <p> - <a href="https://events.localstack.cloud/"> - 📢 "event banner text" 🚀 + <a href="https://form.typeform.com/to/REn2U10O"> + Looking to accelerate your dev &amp; test loops on cloud? Fill out our user feedback and win a Pro license key for six months 🚀 </a> </p> </div> diff --git a/README.md b/README.md index 11643ba695611..8b47f9a4ad52c 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,4 @@ +<a href="https://form.typeform.com/to/REn2U10O/"><img src="./.github/images/survey.svg"></a> <p align="center"> <img src="https://raw.githubusercontent.com/localstack/localstack/master/doc/localstack-readme-header.png" alt="LocalStack - A fully functional local cloud stack"> </p>
**Please refer to the contribution guidelines in the README when submitting PRs.**
https://api.github.com/repos/localstack/localstack/pulls/5975
2022-05-02T07:54:09Z
2022-05-02T09:24:11Z
2022-05-02T09:24:11Z
2022-05-02T09:24:14Z
324
localstack/localstack
28,980
build(deps): bump google-api-python-client from 2.112.0 to 2.113.0
diff --git a/requirements_with_versions.txt b/requirements_with_versions.txt index 2f1ceb7c9f..cfd26d1f21 100644 --- a/requirements_with_versions.txt +++ b/requirements_with_versions.txt @@ -58,7 +58,7 @@ requests-mock==1.11.0 pyglet==2.0.10 urllib3==2.1.0 thirdai==0.7.26 -google-api-python-client==2.112.0 +google-api-python-client==2.113.0 sound==0.1.0 xlwt==1.3.0 pygame==2.5.2
Bumps [google-api-python-client](https://github.com/googleapis/google-api-python-client) from 2.112.0 to 2.113.0. <details> <summary>Release notes</summary> <p><em>Sourced from <a href="https://github.com/googleapis/google-api-python-client/releases">google-api-python-client's releases</a>.</em></p> <blockquote> <h2>v2.113.0</h2> <h2><a href="https://github.com/googleapis/google-api-python-client/compare/v2.112.0...v2.113.0">2.113.0</a> (2024-01-08)</h2> <h3>Features</h3> <ul> <li><strong>androidmanagement:</strong> Update the api <a href="https://togithub.com/googleapis/google-api-python-client/commit/037725556e801716476aa30d305bf0c22a0ca1ff">https://togithub.com/googleapis/google-api-python-client/commit/037725556e801716476aa30d305bf0c22a0ca1ff</a> (<a href="https://github.com/googleapis/google-api-python-client/commit/4d8cae1ed91271f38e1d2cb8c51f40d7c01b7e1c">4d8cae1</a>)</li> <li><strong>batch:</strong> Update the api <a href="https://togithub.com/googleapis/google-api-python-client/commit/a89b34ff2849ca76e6ed148da0d8662ba931e6d2">https://togithub.com/googleapis/google-api-python-client/commit/a89b34ff2849ca76e6ed148da0d8662ba931e6d2</a> (<a href="https://github.com/googleapis/google-api-python-client/commit/4d8cae1ed91271f38e1d2cb8c51f40d7c01b7e1c">4d8cae1</a>)</li> <li><strong>bigtableadmin:</strong> Update the api <a href="https://togithub.com/googleapis/google-api-python-client/commit/0ea4a0684a6ebdbfa16b9c1e7c97b9c2e229eec9">https://togithub.com/googleapis/google-api-python-client/commit/0ea4a0684a6ebdbfa16b9c1e7c97b9c2e229eec9</a> (<a href="https://github.com/googleapis/google-api-python-client/commit/4d8cae1ed91271f38e1d2cb8c51f40d7c01b7e1c">4d8cae1</a>)</li> <li><strong>compute:</strong> Update the api <a href="https://togithub.com/googleapis/google-api-python-client/commit/349d798f89928f721bfa3a76369165064218ad3a">https://togithub.com/googleapis/google-api-python-client/commit/349d798f89928f721bfa3a76369165064218ad3a</a> (<a href="https://github.com/googleapis/google-api-python-client/commit/4d8cae1ed91271f38e1d2cb8c51f40d7c01b7e1c">4d8cae1</a>)</li> <li><strong>connectors:</strong> Update the api <a href="https://togithub.com/googleapis/google-api-python-client/commit/713f174ca4d6d5e4abebccfd5a1255cb23e067ff">https://togithub.com/googleapis/google-api-python-client/commit/713f174ca4d6d5e4abebccfd5a1255cb23e067ff</a> (<a href="https://github.com/googleapis/google-api-python-client/commit/4d8cae1ed91271f38e1d2cb8c51f40d7c01b7e1c">4d8cae1</a>)</li> <li><strong>contactcenterinsights:</strong> Update the api <a href="https://togithub.com/googleapis/google-api-python-client/commit/4e87587c8f9a78242cd90719f332f6495aad32b1">https://togithub.com/googleapis/google-api-python-client/commit/4e87587c8f9a78242cd90719f332f6495aad32b1</a> (<a href="https://github.com/googleapis/google-api-python-client/commit/4d8cae1ed91271f38e1d2cb8c51f40d7c01b7e1c">4d8cae1</a>)</li> <li><strong>content:</strong> Update the api <a href="https://togithub.com/googleapis/google-api-python-client/commit/b327676b520c18cb9faa6182e0ea9b4ddd24d858">https://togithub.com/googleapis/google-api-python-client/commit/b327676b520c18cb9faa6182e0ea9b4ddd24d858</a> (<a href="https://github.com/googleapis/google-api-python-client/commit/4d8cae1ed91271f38e1d2cb8c51f40d7c01b7e1c">4d8cae1</a>)</li> <li><strong>customsearch:</strong> Update the api <a href="https://togithub.com/googleapis/google-api-python-client/commit/2b392dc7d678d32cb37dc295d13f0b2e9bd1b7d6">https://togithub.com/googleapis/google-api-python-client/commit/2b392dc7d678d32cb37dc295d13f0b2e9bd1b7d6</a> (<a href="https://github.com/googleapis/google-api-python-client/commit/4d8cae1ed91271f38e1d2cb8c51f40d7c01b7e1c">4d8cae1</a>)</li> <li><strong>displayvideo:</strong> Update the api <a href="https://togithub.com/googleapis/google-api-python-client/commit/7f470af6609fff74d13a77f947153e74456e25fa">https://togithub.com/googleapis/google-api-python-client/commit/7f470af6609fff74d13a77f947153e74456e25fa</a> (<a href="https://github.com/googleapis/google-api-python-client/commit/4d8cae1ed91271f38e1d2cb8c51f40d7c01b7e1c">4d8cae1</a>)</li> <li><strong>firestore:</strong> Update the api <a href="https://togithub.com/googleapis/google-api-python-client/commit/6dd096bde699d361dcc8e9f25ead6708e62a8ef2">https://togithub.com/googleapis/google-api-python-client/commit/6dd096bde699d361dcc8e9f25ead6708e62a8ef2</a> (<a href="https://github.com/googleapis/google-api-python-client/commit/4d8cae1ed91271f38e1d2cb8c51f40d7c01b7e1c">4d8cae1</a>)</li> <li><strong>script:</strong> Update the api <a href="https://togithub.com/googleapis/google-api-python-client/commit/f2b8610145128f9cf545a11a0c71c25e9ef9711c">https://togithub.com/googleapis/google-api-python-client/commit/f2b8610145128f9cf545a11a0c71c25e9ef9711c</a> (<a href="https://github.com/googleapis/google-api-python-client/commit/4d8cae1ed91271f38e1d2cb8c51f40d7c01b7e1c">4d8cae1</a>)</li> <li><strong>storage:</strong> Update the api <a href="https://togithub.com/googleapis/google-api-python-client/commit/67a8550057c5f66e03632bf0f2d9b42fcb39b660">https://togithub.com/googleapis/google-api-python-client/commit/67a8550057c5f66e03632bf0f2d9b42fcb39b660</a> (<a href="https://github.com/googleapis/google-api-python-client/commit/4d8cae1ed91271f38e1d2cb8c51f40d7c01b7e1c">4d8cae1</a>)</li> </ul> </blockquote> </details> <details> <summary>Changelog</summary> <p><em>Sourced from <a href="https://github.com/googleapis/google-api-python-client/blob/main/CHANGELOG.md">google-api-python-client's changelog</a>.</em></p> <blockquote> <h2><a href="https://github.com/googleapis/google-api-python-client/compare/v2.112.0...v2.113.0">2.113.0</a> (2024-01-08)</h2> <h3>Features</h3> <ul> <li><strong>androidmanagement:</strong> Update the api <a href="https://togithub.com/googleapis/google-api-python-client/commit/037725556e801716476aa30d305bf0c22a0ca1ff">https://togithub.com/googleapis/google-api-python-client/commit/037725556e801716476aa30d305bf0c22a0ca1ff</a> (<a href="https://github.com/googleapis/google-api-python-client/commit/4d8cae1ed91271f38e1d2cb8c51f40d7c01b7e1c">4d8cae1</a>)</li> <li><strong>batch:</strong> Update the api <a href="https://togithub.com/googleapis/google-api-python-client/commit/a89b34ff2849ca76e6ed148da0d8662ba931e6d2">https://togithub.com/googleapis/google-api-python-client/commit/a89b34ff2849ca76e6ed148da0d8662ba931e6d2</a> (<a href="https://github.com/googleapis/google-api-python-client/commit/4d8cae1ed91271f38e1d2cb8c51f40d7c01b7e1c">4d8cae1</a>)</li> <li><strong>bigtableadmin:</strong> Update the api <a href="https://togithub.com/googleapis/google-api-python-client/commit/0ea4a0684a6ebdbfa16b9c1e7c97b9c2e229eec9">https://togithub.com/googleapis/google-api-python-client/commit/0ea4a0684a6ebdbfa16b9c1e7c97b9c2e229eec9</a> (<a href="https://github.com/googleapis/google-api-python-client/commit/4d8cae1ed91271f38e1d2cb8c51f40d7c01b7e1c">4d8cae1</a>)</li> <li><strong>compute:</strong> Update the api <a href="https://togithub.com/googleapis/google-api-python-client/commit/349d798f89928f721bfa3a76369165064218ad3a">https://togithub.com/googleapis/google-api-python-client/commit/349d798f89928f721bfa3a76369165064218ad3a</a> (<a href="https://github.com/googleapis/google-api-python-client/commit/4d8cae1ed91271f38e1d2cb8c51f40d7c01b7e1c">4d8cae1</a>)</li> <li><strong>connectors:</strong> Update the api <a href="https://togithub.com/googleapis/google-api-python-client/commit/713f174ca4d6d5e4abebccfd5a1255cb23e067ff">https://togithub.com/googleapis/google-api-python-client/commit/713f174ca4d6d5e4abebccfd5a1255cb23e067ff</a> (<a href="https://github.com/googleapis/google-api-python-client/commit/4d8cae1ed91271f38e1d2cb8c51f40d7c01b7e1c">4d8cae1</a>)</li> <li><strong>contactcenterinsights:</strong> Update the api <a href="https://togithub.com/googleapis/google-api-python-client/commit/4e87587c8f9a78242cd90719f332f6495aad32b1">https://togithub.com/googleapis/google-api-python-client/commit/4e87587c8f9a78242cd90719f332f6495aad32b1</a> (<a href="https://github.com/googleapis/google-api-python-client/commit/4d8cae1ed91271f38e1d2cb8c51f40d7c01b7e1c">4d8cae1</a>)</li> <li><strong>content:</strong> Update the api <a href="https://togithub.com/googleapis/google-api-python-client/commit/b327676b520c18cb9faa6182e0ea9b4ddd24d858">https://togithub.com/googleapis/google-api-python-client/commit/b327676b520c18cb9faa6182e0ea9b4ddd24d858</a> (<a href="https://github.com/googleapis/google-api-python-client/commit/4d8cae1ed91271f38e1d2cb8c51f40d7c01b7e1c">4d8cae1</a>)</li> <li><strong>customsearch:</strong> Update the api <a href="https://togithub.com/googleapis/google-api-python-client/commit/2b392dc7d678d32cb37dc295d13f0b2e9bd1b7d6">https://togithub.com/googleapis/google-api-python-client/commit/2b392dc7d678d32cb37dc295d13f0b2e9bd1b7d6</a> (<a href="https://github.com/googleapis/google-api-python-client/commit/4d8cae1ed91271f38e1d2cb8c51f40d7c01b7e1c">4d8cae1</a>)</li> <li><strong>displayvideo:</strong> Update the api <a href="https://togithub.com/googleapis/google-api-python-client/commit/7f470af6609fff74d13a77f947153e74456e25fa">https://togithub.com/googleapis/google-api-python-client/commit/7f470af6609fff74d13a77f947153e74456e25fa</a> (<a href="https://github.com/googleapis/google-api-python-client/commit/4d8cae1ed91271f38e1d2cb8c51f40d7c01b7e1c">4d8cae1</a>)</li> <li><strong>firestore:</strong> Update the api <a href="https://togithub.com/googleapis/google-api-python-client/commit/6dd096bde699d361dcc8e9f25ead6708e62a8ef2">https://togithub.com/googleapis/google-api-python-client/commit/6dd096bde699d361dcc8e9f25ead6708e62a8ef2</a> (<a href="https://github.com/googleapis/google-api-python-client/commit/4d8cae1ed91271f38e1d2cb8c51f40d7c01b7e1c">4d8cae1</a>)</li> <li><strong>script:</strong> Update the api <a href="https://togithub.com/googleapis/google-api-python-client/commit/f2b8610145128f9cf545a11a0c71c25e9ef9711c">https://togithub.com/googleapis/google-api-python-client/commit/f2b8610145128f9cf545a11a0c71c25e9ef9711c</a> (<a href="https://github.com/googleapis/google-api-python-client/commit/4d8cae1ed91271f38e1d2cb8c51f40d7c01b7e1c">4d8cae1</a>)</li> <li><strong>storage:</strong> Update the api <a href="https://togithub.com/googleapis/google-api-python-client/commit/67a8550057c5f66e03632bf0f2d9b42fcb39b660">https://togithub.com/googleapis/google-api-python-client/commit/67a8550057c5f66e03632bf0f2d9b42fcb39b660</a> (<a href="https://github.com/googleapis/google-api-python-client/commit/4d8cae1ed91271f38e1d2cb8c51f40d7c01b7e1c">4d8cae1</a>)</li> </ul> </blockquote> </details> <details> <summary>Commits</summary> <ul> <li><a href="https://github.com/googleapis/google-api-python-client/commit/61d563a9ed005fe1e64e5a3add819cd6716ff5b7"><code>61d563a</code></a> chore(main): release 2.113.0 (<a href="https://redirect.github.com/googleapis/google-api-python-client/issues/2313">#2313</a>)</li> <li><a href="https://github.com/googleapis/google-api-python-client/commit/4d8cae1ed91271f38e1d2cb8c51f40d7c01b7e1c"><code>4d8cae1</code></a> chore: Update discovery artifacts (<a href="https://redirect.github.com/googleapis/google-api-python-client/issues/2312">#2312</a>)</li> <li><a href="https://github.com/googleapis/google-api-python-client/commit/b982e82b6285fd9e5893c3fcab69c31cf3b459bb"><code>b982e82</code></a> chore(deps): update all dependencies (<a href="https://redirect.github.com/googleapis/google-api-python-client/issues/2306">#2306</a>)</li> <li>See full diff in <a href="https://github.com/googleapis/google-api-python-client/compare/v2.112.0...v2.113.0">compare view</a></li> </ul> </details> <br /> [![Dependabot compatibility score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=google-api-python-client&package-manager=pip&previous-version=2.112.0&new-version=2.113.0)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores) Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`. [//]: # (dependabot-automerge-start) [//]: # (dependabot-automerge-end) --- <details> <summary>Dependabot commands and options</summary> <br /> You can trigger Dependabot actions by commenting on this PR: - `@dependabot rebase` will rebase this PR - `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it - `@dependabot merge` will merge this PR after your CI passes on it - `@dependabot squash and merge` will squash and merge this PR after your CI passes on it - `@dependabot cancel merge` will cancel a previously requested merge and block automerging - `@dependabot reopen` will reopen this PR if it is closed - `@dependabot close` will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually - `@dependabot show <dependency name> ignore conditions` will show all of the ignore conditions of the specified dependency - `@dependabot ignore this major version` will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself) - `@dependabot ignore this minor version` will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself) - `@dependabot ignore this dependency` will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself) </details>
https://api.github.com/repos/geekcomputers/Python/pulls/2092
2024-01-11T18:36:53Z
2024-01-12T21:32:04Z
2024-01-12T21:32:04Z
2024-01-12T21:32:12Z
151
geekcomputers/Python
31,438
Update latency vs throughput blog link
diff --git a/README.md b/README.md index 9f0be48611..0e2c40ec67 100644 --- a/README.md +++ b/README.md @@ -433,7 +433,7 @@ Generally, you should aim for **maximal throughput** with **acceptable latency** ### Source(s) and further reading -* [Understanding latency vs throughput](https://community.cadence.com/cadence_blogs_8/b/sd/archive/2010/09/13/understanding-latency-vs-throughput) +* [Understanding latency vs throughput](https://community.cadence.com/cadence_blogs_8/b/fv/posts/understanding-latency-vs-throughput) ## Availability vs consistency
## Review the Contributing Guidelines Before submitting a pull request, verify it meets all requirements in the [Contributing Guidelines](https://github.com/donnemartin/system-design-primer/blob/master/CONTRIBUTING.md). ### Translations See the [Contributing Guidelines](https://github.com/donnemartin/system-design-primer/blob/master/CONTRIBUTING.md). Verify you've: * Tagged the [language maintainer](https://github.com/donnemartin/system-design-primer/blob/master/TRANSLATIONS.md) * Prefixed the title with a language code * Example: "ja: Fix ..."
https://api.github.com/repos/donnemartin/system-design-primer/pulls/716
2022-11-06T18:02:12Z
2022-11-13T21:04:18Z
2022-11-13T21:04:18Z
2022-11-13T21:04:30Z
162
donnemartin/system-design-primer
36,706
Fix broken link for xlsxwriter
diff --git a/README.md b/README.md index 16df7591a..280f4c488 100644 --- a/README.md +++ b/README.md @@ -225,7 +225,7 @@ Inspired by [awesome-php](https://github.com/ziadoz/awesome-php). * [python-docx](https://github.com/python-openxml/python-docx) - Reads, queries and modifies Microsoft Word 2007/2008 docx files. * [relatorio](http://relatorio.tryton.org/) - Templating OpenDocument files. * [unoconv](https://github.com/dagwieers/unoconv) - Convert between any document format supported by LibreOffice/OpenOffice. - * [XlsxWriter](https://xlsxwriter.readthedocs.org/en/latest/) - A Python module for creating Excel .xlsx files. + * [XlsxWriter](https://xlsxwriter.readthedocs.io) - A Python module for creating Excel .xlsx files. * [xlwings](http://xlwings.org/) - A BSD-licensed library that makes it easy to call Python from Excel and vice versa. * [xlwt](https://github.com/python-excel/xlwt) / [xlrd](https://github.com/python-excel/xlrd) - Writing and reading data and formatting information from Excel files. * PDF
Fix a link
https://api.github.com/repos/vinta/awesome-python/pulls/637
2016-05-09T09:22:21Z
2016-05-09T09:32:31Z
2016-05-09T09:32:31Z
2016-05-09T09:32:31Z
297
vinta/awesome-python
27,118
Add support for Videomega
diff --git a/README.md b/README.md index bbb090a8e9..b480f114ad 100644 --- a/README.md +++ b/README.md @@ -298,6 +298,7 @@ Use `--url`/`-u` to get a list of downloadable resource URLs extracted from the | Vine | <https://vine.co/> |✓| | | | Vimeo | <https://vimeo.com/> |✓| | | | Vidto | <http://vidto.me/> |✓| | | +| Videomega | <http://videomega.tv/> |✓| | | | Veoh | <http://www.veoh.com/> |✓| | | | **Tumblr** | <https://www.tumblr.com/> |✓|✓|✓| | TED | <http://www.ted.com/> |✓| | | diff --git a/src/you_get/common.py b/src/you_get/common.py index fd956408ad..8b73088b69 100755 --- a/src/you_get/common.py +++ b/src/you_get/common.py @@ -66,6 +66,7 @@ 'tumblr' : 'tumblr', 'twimg' : 'twitter', 'twitter' : 'twitter', + 'videomega' : 'videomega', 'vidto' : 'vidto', 'vimeo' : 'vimeo', 'weibo' : 'miaopai', diff --git a/src/you_get/extractors/__init__.py b/src/you_get/extractors/__init__.py index 380c573606..7b3c6a7162 100755 --- a/src/you_get/extractors/__init__.py +++ b/src/you_get/extractors/__init__.py @@ -58,6 +58,7 @@ from .tumblr import * from .twitter import * from .veoh import * +from .videomega import * from .vimeo import * from .vine import * from .vk import * diff --git a/src/you_get/extractors/videomega.py b/src/you_get/extractors/videomega.py new file mode 100644 index 0000000000..75e88cd97d --- /dev/null +++ b/src/you_get/extractors/videomega.py @@ -0,0 +1,47 @@ +#!/usr/bin/env python + +from ..common import * +from ..extractor import VideoExtractor + +import ssl + +class Videomega(VideoExtractor): + name = "Videomega" + + stream_types = [ + {'id': 'original'} + ] + + def prepare(self, **kwargs): + # Hot-plug cookie handler + ssl_context = request.HTTPSHandler( + context=ssl.SSLContext(ssl.PROTOCOL_TLSv1)) + cookie_handler = request.HTTPCookieProcessor() + opener = request.build_opener(ssl_context, cookie_handler) + opener.addheaders = [('Referer', self.url), + ('Cookie', 'noadvtday=0')] + request.install_opener(opener) + + ref = match1(self.url, r'ref=(\w+)') + php_url = 'http://videomega.tv/view.php?ref=' + ref + content = get_content(php_url) + + self.title = match1(content, r'<title>(.*)</title>') + js = match1(content, r'(eval.*)') + t = match1(js, r'\$\("\d+"\)\.\d+\("\d+","([^"]+)"\)') + t = re.sub(r'(\w)', r'{\1}', t) + t = t.translate({87 + i: str(i) for i in range(10, 36)}) + s = match1(js, r"'([^']+)'\.split").split('|') + self.streams['original'] = { + 'url': t.format(*s) + } + + def extract(self, **kwargs): + for i in self.streams: + s = self.streams[i] + _, s['container'], s['size'] = url_info(s['url']) + s['src'] = [s['url']] + +site = Videomega() +download = site.download_by_url +download_playlist = site.download_by_url
![such-av s](https://cloud.githubusercontent.com/assets/342945/12064381/0e709074-afc2-11e5-96de-d604d64a6008.jpg) Example links: - http://videomega.tv/?ref=9r9sx4xGOGGOGx4xs9r9 - http://videomega.tv/?ref=UKRPMV8QG00GQ8VMPRKU - http://videomega.tv/?ref=E1OMPDO446644ODPMO1E - <del>(NSFW!) http://videomega.tv/?ref=Q379OGDTS66STDGO973Q</del> <!-- Reviewable:start --> [<img src="https://reviewable.io/review_button.png" height=40 alt="Review on Reviewable"/>](https://reviewable.io/reviews/soimort/you-get/850) <!-- Reviewable:end -->
https://api.github.com/repos/soimort/you-get/pulls/850
2015-12-31T12:26:51Z
2015-12-31T14:23:30Z
2015-12-31T14:23:30Z
2015-12-31T14:31:25Z
997
soimort/you-get
20,985
filter ublox packets for sidebar
diff --git a/selfdrive/ui/ui.cc b/selfdrive/ui/ui.cc index 7b001179216eda..2562e338fb180f 100644 --- a/selfdrive/ui/ui.cc +++ b/selfdrive/ui/ui.cc @@ -470,10 +470,11 @@ void handle_message(UIState *s, Message * msg) { } else if (eventd.which == cereal_Event_ubloxGnss) { struct cereal_UbloxGnss datad; cereal_read_UbloxGnss(&datad, eventd.ubloxGnss); - struct cereal_UbloxGnss_MeasurementReport reportdatad; - cereal_read_UbloxGnss_MeasurementReport(&reportdatad, datad.measurementReport); - - s->scene.satelliteCount = reportdatad.numMeas; + if (datad.which == cereal_UbloxGnss_measurementReport) { + struct cereal_UbloxGnss_MeasurementReport reportdatad; + cereal_read_UbloxGnss_MeasurementReport(&reportdatad, datad.measurementReport); + s->scene.satelliteCount = reportdatad.numMeas; + } } else if (eventd.which == cereal_Event_health) { struct cereal_HealthData datad; cereal_read_HealthData(&datad, eventd.health);
https://api.github.com/repos/commaai/openpilot/pulls/1233
2020-03-11T21:03:51Z
2020-03-11T21:28:30Z
2020-03-11T21:28:30Z
2020-03-11T21:28:34Z
306
commaai/openpilot
9,442
Preserve Python 3.9 compatibility
diff --git a/modules/shared.py b/modules/shared.py index fa080458567..e53b1e113c7 100644 --- a/modules/shared.py +++ b/modules/shared.py @@ -15,6 +15,7 @@ from modules import localization, script_loading, errors, ui_components, shared_items, cmd_args from modules.paths_internal import models_path, script_path, data_path, sd_configs_path, sd_default_config, sd_model_file, default_sd_model_file, extensions_dir, extensions_builtin_dir # noqa: F401 from ldm.models.diffusion.ddpm import LatentDiffusion +from typing import Optional demo = None @@ -113,7 +114,7 @@ class State: time_start = None server_start = None _server_command_signal = threading.Event() - _server_command: str | None = None + _server_command: Optional[str] = None @property def need_restart(self) -> bool: @@ -131,14 +132,14 @@ def server_command(self): return self._server_command @server_command.setter - def server_command(self, value: str | None) -> None: + def server_command(self, value: Optional[str]) -> None: """ Set the server command to `value` and signal that it's been set. """ self._server_command = value self._server_command_signal.set() - def wait_for_server_command(self, timeout: float | None = None) -> str | None: + def wait_for_server_command(self, timeout: Optional[float] = None) -> Optional[str]: """ Wait for server command to get set; return and clear the value and signal. """
**Describe what this pull request is trying to achieve.** The dev branch currently does not launch due to a TypeError in Python 3.9 environments (e.g. Colab Pro, Paperspace Gradient). This is because of newer Optional type syntax usage in `shared.py` added by #10458. This PR changes three lines to use `typing.Optional` instead to preserve backwards compatibility. **Additional notes and description of your changes** It's a minor syntax change and I've tested launch and restarts to be working but please ensure everything is correct as I'm not really a programmer. Thank you. **Environment this was tested in** - OS: Linux (Paperspace Gradient) - Browser: Firefox - Graphics card: Nvidia RTX A4000
https://api.github.com/repos/AUTOMATIC1111/stable-diffusion-webui/pulls/10578
2023-05-20T17:49:37Z
2023-05-20T19:11:03Z
2023-05-20T19:11:03Z
2023-05-20T21:15:36Z
376
AUTOMATIC1111/stable-diffusion-webui
40,581
This code is more elegant
diff --git a/abstract_factory.py b/abstract_factory.py index 7ecf0fc3..72d57043 100644 --- a/abstract_factory.py +++ b/abstract_factory.py @@ -7,20 +7,17 @@ import random - class PetShop: """A pet shop""" def __init__(self, animal_factory=None): - """pet_factory is our abstract factory. - We can set it at will.""" + """pet_factory is our abstract factory. We can set it at will.""" self.pet_factory = animal_factory def show_pet(self): - """Creates and shows a pet using the - abstract factory""" + """Creates and shows a pet using the abstract factory""" pet = self.pet_factory.get_pet() print("We have a lovely {}".format(pet)) @@ -55,19 +52,12 @@ class DogFactory: def get_pet(self): return Dog() - def get_food(self): - return "dog food" - class CatFactory: def get_pet(self): return Cat() - def get_food(self): - return "cat food" - - # Create the proper family def get_factory(): """Let's be dynamic!""" @@ -76,9 +66,8 @@ def get_factory(): # Show pets with various factories if __name__ == "__main__": - shop = PetShop() for i in range(3): - shop.pet_factory = get_factory() + shop = PetShop(get_factory()) shop.show_pet() print("=" * 20) diff --git a/adapter.py b/adapter.py index 2db7faa1..1620ce4c 100644 --- a/adapter.py +++ b/adapter.py @@ -5,39 +5,28 @@ import os - class Dog(object): - def __init__(self): self.name = "Dog" - def bark(self): return "woof!" - class Cat(object): - def __init__(self): self.name = "Cat" - def meow(self): return "meow!" - class Human(object): - def __init__(self): self.name = "Human" - def speak(self): return "'hello'" class Car(object): - def __init__(self): self.name = "Car" - def make_noise(self, octane_level): return "vroom{0}".format("!" * octane_level) diff --git a/chain.py b/chain.py index 37cad8d9..6698f8f9 100644 --- a/chain.py +++ b/chain.py @@ -3,69 +3,50 @@ """http://www.testingperspective.com/wiki/doku.php/collaboration/chetan/designpatternsinpython/chain-of-responsibilitypattern""" - class Handler: - - def __init__(self): - self._successor = None - - def successor(self, successor): - self._successor = successor - - def handle(self, request): + def __init__(self,successor): + self._successor = successor; + def handle(self,request): + i = self._handle(request) + if not i: + self._successor.handle(request) + def _handle(self, request): raise NotImplementedError('Must provide implementation in subclass.') class ConcreteHandler1(Handler): - def handle(self, request): + def _handle(self, request): if 0 < request <= 10: print('request {} handled in handler 1'.format(request)) - elif self._successor: - self._successor.handle(request) - - + return True + class ConcreteHandler2(Handler): - - def handle(self, request): + + def _handle(self, request): if 10 < request <= 20: print('request {} handled in handler 2'.format(request)) - elif self._successor: - self._successor.handle(request) - - + return True + class ConcreteHandler3(Handler): - - def handle(self, request): + + def _handle(self, request): if 20 < request <= 30: print('request {} handled in handler 3'.format(request)) - elif self._successor: - self._successor.handle(request) - - + return True class DefaultHandler(Handler): - - def handle(self, request): - print('end of chain, no handler for {}'.format(request)) + + def _handle(self, request): + print('end of chain, no handler for {}'.format(request)) + return True class Client: - def __init__(self): - h1 = ConcreteHandler1() - h2 = ConcreteHandler2() - h3 = ConcreteHandler3() - h4 = DefaultHandler() - - h1.successor(h2) - h2.successor(h3) - h3.successor(h4) - - self.handlers = (h1, h2, h3, h4,) - + self.handler = ConcreteHandler1(ConcreteHandler3(ConcreteHandler2(DefaultHandler(None)))) def delegate(self, requests): for request in requests: - self.handlers[0].handle(request) + self.handler.handle(request) if __name__ == "__main__": diff --git a/command.py b/command.py index 9aab10f6..727f42cb 100644 --- a/command.py +++ b/command.py @@ -11,9 +11,6 @@ def __init__(self, src, dest): self.dest = dest def execute(self): - self() - - def __call__(self): print('renaming {} to {}'.format(self.src, self.dest)) os.rename(self.src, self.dest) diff --git a/composite.py b/composite.py index 9b8cc56f..d49fc55b 100644 --- a/composite.py +++ b/composite.py @@ -5,11 +5,10 @@ A class which defines a composite object which can store hieararchical dictionaries with names. -This class is same as a hiearchical dictionary, but it -provides methods to add/access/modify children by name, -like a Composite. +This class is same as a hiearchical dictionary, but it provides methods +to add/access/modify children by name, like a Composite. -Created Anand B Pillai <abpillai@gmail.com> +Created Anand B Pillai <abpillai@gmail.com> """ __author__ = "Anand B Pillai" @@ -18,8 +17,10 @@ def normalize(val): - """ Normalize a string so that it can be used as an attribute - to a Python object """ + """Normalize a string so that it can be used as an attribute to a Python + + object + """ if val.find('-') != -1: val = val.replace('-', '_') @@ -38,8 +39,7 @@ def denormalize(val): class SpecialDict(dict): - """ A dictionary type which allows direct attribute - access to its keys """ + """A dictionary type which allows direct attribute access to its keys """ def __getattr__(self, name): @@ -127,11 +127,13 @@ def isLeaf(self): return not self._children def getName(self): + """ Return the name of this ConfigInfo object """ return self._name def getIndex(self, child): + """ Return the index of the child ConfigInfo object 'child' """ if child in self._children: @@ -145,17 +147,17 @@ def getDict(self): return self[self._name] def getProperty(self, child, key): - """ Return the value for the property for child - 'child' with key 'key' """ + + """Return the value for the property for child 'child' with key 'key' """ # First get the child's dictionary childDict = self.getInfoDict(child) if childDict: return childDict.get(key, None) - def setProperty(self, child, key, value): - """ Set the value for the property 'key' for - the child 'child' to 'value' """ + def setProperty(self, child, key, value): + + """Set the value for the property 'key' for the child 'child' to 'value' """ # First get the child's dictionary childDict = self.getInfoDict(child) @@ -163,11 +165,13 @@ def setProperty(self, child, key, value): childDict[key] = value def getChildren(self): + """ Return the list of immediate children of this object """ return self._children def getAllChildren(self): + """ Return the list of all children of this object """ l = [] @@ -178,6 +182,7 @@ def getAllChildren(self): return l def getChild(self, name): + """ Return the immediate child object with the given name """ for child in self._children: @@ -185,6 +190,7 @@ def getChild(self, name): return child def findChild(self, name): + """ Return the child with the given name from the tree """ # Note - this returns the first child of the given name @@ -196,6 +202,7 @@ def findChild(self, name): return child def findChildren(self, name): + """ Return a list of children with the given name from the tree """ # Note: this returns a list of all the children of a given @@ -210,6 +217,7 @@ def findChildren(self, name): return children def getPropertyDict(self): + """ Return the property dictionary """ d = self.getChild('__properties') @@ -219,6 +227,7 @@ def getPropertyDict(self): return {} def getParent(self): + """ Return the person who created me """ return self._father diff --git a/foo.txt b/foo.txt deleted file mode 100644 index 5aecc849..00000000 --- a/foo.txt +++ /dev/null @@ -1 +0,0 @@ -All krakens crush undead, evil sails. diff --git a/iterator.py b/iterator.py deleted file mode 100644 index 3aa36b8d..00000000 --- a/iterator.py +++ /dev/null @@ -1,37 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -"""http://ginstrom.com/scribbles/2007/10/08/design-patterns-python-style/ - -Implementation of the iterator pattern with a generator""" - - -def count_to(count): - """Counts by word numbers, up to a maximum of five""" - numbers = ["one", "two", "three", "four", "five"] - # enumerate() returns a tuple containing a count (from start which - # defaults to 0) and the values obtained from iterating over sequence - for pos, number in zip(range(count), numbers): - yield number - -# Test the generator -count_to_two = lambda: count_to(2) -count_to_five = lambda: count_to(5) - -print('Counting to two...') -for number in count_to_two(): - print(number, end=' ') - -print() - -print('Counting to five...') -for number in count_to_five(): - print(number, end=' ') - -print() - -### OUTPUT ### -# Counting to two... -# one two -# Counting to five... -# one two three four five diff --git a/publish_subscribe.py b/publish_subscribe.py index e88dd4f3..522e9ea4 100644 --- a/publish_subscribe.py +++ b/publish_subscribe.py @@ -10,9 +10,8 @@ class Provider: def __init__(self): - self.msg_queue = [] - self.subscribers = {} - + self.subscribe_queue = {} + self.msg_queue=[] def notify(self, msg): self.msg_queue.append(msg) @@ -25,12 +24,14 @@ def subscribe(self, msg, subscriber): def unsubscribe(self, msg, subscriber): self.subscribers[msg].remove(subscriber) + if !self.subscribe[msg]: + del self.subscribe[msg] def update(self): for msg in self.msg_queue: - if msg in self.subscribers: - for sub in self.subscribers[msg]: - sub.run(msg) + if msg in self.subscribers.keys(): + for suber in self.subscribers[msg]: + suber.get(msg) self.msg_queue = [] @@ -52,7 +53,7 @@ def __init__(self, name, msg_center): def subscribe(self, msg): self.provider.subscribe(msg, self) - def run(self, msg): + def get(self, msg): print("{} got {}".format(self.name, msg))
output has not changed
https://api.github.com/repos/faif/python-patterns/pulls/61
2014-09-02T07:34:05Z
2014-09-06T17:40:09Z
2014-09-06T17:40:09Z
2014-09-06T17:40:09Z
2,930
faif/python-patterns
33,653
Update README.md
diff --git a/README.md b/README.md index 3d477e83..43b3f0a4 100644 --- a/README.md +++ b/README.md @@ -264,7 +264,7 @@ Further resources: * [Touchstone](https://github.com/ptaoussanis/touchstone) - Clojure A/B testing library. * [Clojush](https://github.com/lspector/Clojush) - The Push programming language and the PushGP genetic programming system implemented in Clojure. -* [Infer](https://github.com/aria42/infer) - Inference and machine learning in Clojure. +* [Infer](https://github.com/aria42/infer) - Inference and machine learning in Clojure. **[Deprecated]** * [Clj-ML](https://github.com/antoniogarrote/clj-ml) - A machine learning library for Clojure built on top of Weka and friends. * [DL4CLJ](https://github.com/engagor/dl4clj/) - Clojure wrapper for Deeplearning4j. * [Encog](https://github.com/jimpil/enclog) - Clojure wrapper for Encog (v3) (Machine-Learning framework that specializes in neural-nets).
Last commit over 8 years ago: https://github.com/aria42/infer
https://api.github.com/repos/josephmisiti/awesome-machine-learning/pulls/571
2018-12-16T21:47:43Z
2018-12-26T13:11:24Z
2018-12-26T13:11:24Z
2018-12-26T13:11:24Z
287
josephmisiti/awesome-machine-learning
51,822
Implement basic status filter for StepFunctions list-executions
diff --git a/localstack/services/stepfunctions/provider.py b/localstack/services/stepfunctions/provider.py index 838dcf35f2781..e27df1d9ddbb1 100644 --- a/localstack/services/stepfunctions/provider.py +++ b/localstack/services/stepfunctions/provider.py @@ -5,7 +5,7 @@ import re from typing import Final, Optional -from localstack.aws.api import RequestContext +from localstack.aws.api import CommonServiceException, RequestContext from localstack.aws.api.stepfunctions import ( Arn, ConflictException, @@ -422,6 +422,17 @@ def describe_execution( execution: Execution = self._get_execution(context=context, execution_arn=execution_arn) return execution.to_describe_output() + @staticmethod + def _list_execution_filter( + ex: Execution, state_machine_arn: str | None, status_filter: str | None + ) -> bool: + if state_machine_arn and ex.state_machine.arn != state_machine_arn: + return False + + if not status_filter: + return True + return ex.exec_status == status_filter + def list_executions( self, context: RequestContext, @@ -439,11 +450,38 @@ def list_executions( if state_machine is None: self._raise_state_machine_does_not_exist(state_machine_arn) - # TODO: add support for paging and filtering. + # TODO: add support for paging + + allowed_execution_status = [ + ExecutionStatus.SUCCEEDED, + ExecutionStatus.TIMED_OUT, + ExecutionStatus.PENDING_REDRIVE, + ExecutionStatus.ABORTED, + ExecutionStatus.FAILED, + ExecutionStatus.RUNNING, + ] + + validation_errors = [] + + if status_filter and status_filter not in allowed_execution_status: + validation_errors.append( + f"Value '{status_filter}' at 'statusFilter' failed to satisfy constraint: Member must satisfy enum value set: [{', '.join(allowed_execution_status)}]" + ) + + if not state_machine_arn and not map_run_arn: + validation_errors.append("Must provide a StateMachine ARN or MapRun ARN") + + if validation_errors: + errors_message = "; ".join(validation_errors) + message = f"{len(validation_errors)} validation {'errors' if len(validation_errors) > 1 else 'error'} detected: {errors_message}" + raise CommonServiceException(message=message, code="ValidationException") + executions: ExecutionList = [ execution.to_execution_list_item() for execution in self.get_store(context).executions.values() - if execution.state_machine.arn == state_machine_arn + if self._list_execution_filter( + execution, state_machine_arn=state_machine_arn, status_filter=status_filter + ) ] return ListExecutionsOutput(executions=executions) diff --git a/tests/aws/services/stepfunctions/utils.py b/tests/aws/services/stepfunctions/utils.py index 48ae7096700da..40c245ee948de 100644 --- a/tests/aws/services/stepfunctions/utils.py +++ b/tests/aws/services/stepfunctions/utils.py @@ -155,6 +155,28 @@ def _check_last_is_success(events: HistoryEventList) -> bool: ) +def await_list_execution_status( + stepfunctions_client, state_machine_arn: str, execution_arn: str, status: str +): + """required as there is some eventual consistency in list_executions vs describe_execution and get_execution_history""" + + def _run_check(): + list_resp = stepfunctions_client.list_executions( + stateMachineArn=state_machine_arn, statusFilter=status + ) + for execution in list_resp.get("executions", []): + if execution["executionArn"] != execution_arn or execution["status"] != status: + continue + return True + return False + + success = poll_condition(condition=_run_check, timeout=120, interval=1) + if not success: + LOG.warning( + f"Timed out whilst awaiting for execution status {status} to satisfy condition for execution '{execution_arn}'." + ) + + def await_execution_terminated(stepfunctions_client, execution_arn: str): def _check_last_is_terminal(events: HistoryEventList) -> bool: if len(events) > 0: diff --git a/tests/aws/services/stepfunctions/v2/test_sfn_api.py b/tests/aws/services/stepfunctions/v2/test_sfn_api.py index 7125592742bb8..fd696d1bb42cc 100644 --- a/tests/aws/services/stepfunctions/v2/test_sfn_api.py +++ b/tests/aws/services/stepfunctions/v2/test_sfn_api.py @@ -2,6 +2,7 @@ import pytest import yaml +from botocore.exceptions import ClientError from localstack_snapshot.snapshots.transformer import RegexTransformer from localstack.aws.api.lambda_ import Runtime @@ -14,6 +15,7 @@ await_execution_started, await_execution_success, await_execution_terminated, + await_list_execution_status, await_state_machine_listed, await_state_machine_not_listed, ) @@ -1003,3 +1005,55 @@ def test_get_execution_history_invalid_arn(self, sfn_snapshot, aws_client): sfn_snapshot.match( "exception", {"exception_typename": exc.typename, "exception_value": exc.value} ) + + @markers.snapshot.skip_snapshot_verify(paths=["$..redriveCount"]) + @markers.aws.validated + def test_state_machine_status_filter( + self, create_iam_role_for_sfn, create_state_machine, sfn_snapshot, aws_client + ): + snf_role_arn = create_iam_role_for_sfn() + sfn_snapshot.add_transformer(RegexTransformer(snf_role_arn, "snf_role_arn")) + + sm_name = f"statemachine_{short_uid()}" + definition = BaseTemplate.load_sfn_template(BaseTemplate.BASE_PASS_RESULT) + definition_str = json.dumps(definition) + + creation_resp = create_state_machine( + name=sm_name, definition=definition_str, roleArn=snf_role_arn + ) + sfn_snapshot.add_transformer(sfn_snapshot.transform.sfn_sm_create_arn(creation_resp, 0)) + sfn_snapshot.match("creation_resp", creation_resp) + state_machine_arn = creation_resp["stateMachineArn"] + + list_response = aws_client.stepfunctions.list_executions( + stateMachineArn=state_machine_arn, statusFilter="SUCCEEDED" + ) + sfn_snapshot.match("list_before_execution", list_response) + + exec_resp = aws_client.stepfunctions.start_execution(stateMachineArn=state_machine_arn) + sfn_snapshot.add_transformer(sfn_snapshot.transform.sfn_sm_exec_arn(exec_resp, 0)) + sfn_snapshot.match("exec_resp", exec_resp) + execution_arn = exec_resp["executionArn"] + + await_list_execution_status( + stepfunctions_client=aws_client.stepfunctions, + state_machine_arn=state_machine_arn, + execution_arn=execution_arn, + status="SUCCEEDED", + ) + + list_response = aws_client.stepfunctions.list_executions( + stateMachineArn=state_machine_arn, statusFilter="SUCCEEDED" + ) + sfn_snapshot.match("list_succeeded_when_complete", list_response) + + list_response = aws_client.stepfunctions.list_executions( + stateMachineArn=state_machine_arn, statusFilter="RUNNING" + ) + sfn_snapshot.match("list_running_when_complete", list_response) + + with pytest.raises(ClientError) as e: + aws_client.stepfunctions.list_executions( + stateMachineArn=state_machine_arn, statusFilter="succeeded" + ) + sfn_snapshot.match("list_executions_filter_exc", e.value.response) diff --git a/tests/aws/services/stepfunctions/v2/test_sfn_api.snapshot.json b/tests/aws/services/stepfunctions/v2/test_sfn_api.snapshot.json index d2a0023b2eacd..10c0db34669b4 100644 --- a/tests/aws/services/stepfunctions/v2/test_sfn_api.snapshot.json +++ b/tests/aws/services/stepfunctions/v2/test_sfn_api.snapshot.json @@ -1614,5 +1614,68 @@ "exception_value": "An error occurred (InvalidArn) when calling the DescribeExecution operation: Invalid Arn: 'Invalid ARN prefix: invalid_state_machine_arn'" } } + }, + "tests/aws/services/stepfunctions/v2/test_sfn_api.py::TestSnfApi::test_state_machine_status_filter": { + "recorded-date": "14-03-2024, 21:58:24", + "recorded-content": { + "creation_resp": { + "creationDate": "datetime", + "stateMachineArn": "arn:aws:states:<region>:111111111111:stateMachine:<ArnPart_0idx>", + "ResponseMetadata": { + "HTTPHeaders": {}, + "HTTPStatusCode": 200 + } + }, + "list_before_execution": { + "executions": [], + "ResponseMetadata": { + "HTTPHeaders": {}, + "HTTPStatusCode": 200 + } + }, + "exec_resp": { + "executionArn": "arn:aws:states:<region>:111111111111:execution:<ArnPart_0idx>:<ExecArnPart_0idx>", + "startDate": "datetime", + "ResponseMetadata": { + "HTTPHeaders": {}, + "HTTPStatusCode": 200 + } + }, + "list_succeeded_when_complete": { + "executions": [ + { + "executionArn": "arn:aws:states:<region>:111111111111:execution:<ArnPart_0idx>:<ExecArnPart_0idx>", + "name": "<ExecArnPart_0idx>", + "redriveCount": 0, + "startDate": "datetime", + "stateMachineArn": "arn:aws:states:<region>:111111111111:stateMachine:<ArnPart_0idx>", + "status": "SUCCEEDED", + "stopDate": "datetime" + } + ], + "ResponseMetadata": { + "HTTPHeaders": {}, + "HTTPStatusCode": 200 + } + }, + "list_running_when_complete": { + "executions": [], + "ResponseMetadata": { + "HTTPHeaders": {}, + "HTTPStatusCode": 200 + } + }, + "list_executions_filter_exc": { + "Error": { + "Code": "ValidationException", + "Message": "1 validation error detected: Value 'succeeded' at 'statusFilter' failed to satisfy constraint: Member must satisfy enum value set: [SUCCEEDED, TIMED_OUT, PENDING_REDRIVE, ABORTED, FAILED, RUNNING]" + }, + "message": "1 validation error detected: Value 'succeeded' at 'statusFilter' failed to satisfy constraint: Member must satisfy enum value set: [SUCCEEDED, TIMED_OUT, PENDING_REDRIVE, ABORTED, FAILED, RUNNING]", + "ResponseMetadata": { + "HTTPHeaders": {}, + "HTTPStatusCode": 400 + } + } + } } } diff --git a/tests/aws/services/stepfunctions/v2/test_sfn_api.validation.json b/tests/aws/services/stepfunctions/v2/test_sfn_api.validation.json index a0c73197d33ba..586bd546dacdd 100644 --- a/tests/aws/services/stepfunctions/v2/test_sfn_api.validation.json +++ b/tests/aws/services/stepfunctions/v2/test_sfn_api.validation.json @@ -89,6 +89,9 @@ "tests/aws/services/stepfunctions/v2/test_sfn_api.py::TestSnfApi::test_start_execution": { "last_validated_date": "2023-06-22T11:52:39+00:00" }, + "tests/aws/services/stepfunctions/v2/test_sfn_api.py::TestSnfApi::test_state_machine_status_filter": { + "last_validated_date": "2024-03-14T21:59:25+00:00" + }, "tests/aws/services/stepfunctions/v2/test_sfn_api.py::TestSnfApi::test_stop_execution": { "last_validated_date": "2023-06-22T11:53:24+00:00" }
## Motivation v2 stepfunctions provider `list-executions` should support `statusFilter` ... not yet implmented ## Changes * added basic statusFilter to localstack/services/stepfunctions/provider.py * new test `tests/aws/services/stepfunctions/v2/test_sfn_api.py::TestSnfApi::test_state_machine_status_filter` ## Testing basic coverage `tests/aws/services/stepfunctions/v2/test_sfn_api.py::TestSnfApi::test_state_machine_status_filter`
https://api.github.com/repos/localstack/localstack/pulls/9833
2023-12-10T16:07:37Z
2024-03-14T22:19:33Z
2024-03-14T22:19:33Z
2024-03-18T22:57:43Z
2,822
localstack/localstack
29,341
[fix] typo
diff --git a/CppCoreGuidelines.md b/CppCoreGuidelines.md index cbdf109c1..3ab0801ed 100644 --- a/CppCoreGuidelines.md +++ b/CppCoreGuidelines.md @@ -252,7 +252,7 @@ Tools that implement these rules shall respect the following syntax to explicitl [[suppress(tag)]] -where "tag" is the anchor name of the item where the Enrocement rule appears (e.g., for C.134 it is "Rh-public"), or the name of a profile group-of-rules ("types", "bounds", or "lifetime"). +where "tag" is the anchor name of the item where the Enforcement rule appears (e.g., for C.134 it is "Rh-public"), or the name of a profile group-of-rules ("types", "bounds", or "lifetime"). ## <a name="SS-struct"></a> In.struct: The structure of this document
https://api.github.com/repos/isocpp/CppCoreGuidelines/pulls/449
2015-12-11T14:31:35Z
2015-12-11T14:47:05Z
2015-12-11T14:47:05Z
2015-12-11T14:47:10Z
209
isocpp/CppCoreGuidelines
15,858
Added length unit conversions
diff --git a/conversions/length_conversions.py b/conversions/length_conversions.py new file mode 100644 index 000000000000..811a9a916b70 --- /dev/null +++ b/conversions/length_conversions.py @@ -0,0 +1,108 @@ +""" +Conversion of length units. +Available Units:- Metre,Kilometre,Feet,Inch,Centimeter,Yard,Foot,Mile,Millimeter + +USAGE : +-> Import this file into their respective project. +-> Use the function length_conversion() for conversion of length units. +-> Parameters : + -> value : The number of from units you want to convert + -> from_type : From which type you want to convert + -> to_type : To which type you want to convert + +REFERENCES : +-> Wikipedia reference: https://en.wikipedia.org/wiki/Meter +-> Wikipedia reference: https://en.wikipedia.org/wiki/Kilometer +-> Wikipedia reference: https://en.wikipedia.org/wiki/Feet +-> Wikipedia reference: https://en.wikipedia.org/wiki/Inch +-> Wikipedia reference: https://en.wikipedia.org/wiki/Centimeter +-> Wikipedia reference: https://en.wikipedia.org/wiki/Yard +-> Wikipedia reference: https://en.wikipedia.org/wiki/Foot +-> Wikipedia reference: https://en.wikipedia.org/wiki/Mile +-> Wikipedia reference: https://en.wikipedia.org/wiki/Millimeter +""" + +from collections import namedtuple + +from_to = namedtuple("from_to", "from_ to") + +METRIC_CONVERSION = { + "meter": from_to(1, 1), + "kilometer": from_to(1000, 0.001), + "feet": from_to(0.3048, 3.28084), + "inch": from_to(0.0254, 39.3701), + "centimeter": from_to(0.01, 100), + "yard": from_to(0.9144, 1.09361), + "foot": from_to(0.3048, 3.28084), + "mile": from_to(1609.34, 0.000621371), + "millimeter": from_to(0.001, 1000), +} + + +def length_conversion(value: float, from_type: str, to_type: str) -> float: + """ + Conversion between length units. + + >>> length_conversion(4, "meter", "feet") + 13.12336 + >>> length_conversion(1, "meter", "kilometer") + 0.001 + >>> length_conversion(1, "kilometer", "inch") + 39370.1 + >>> length_conversion(3, "kilometer", "mile") + 1.8641130000000001 + >>> length_conversion(2, "feet", "meter") + 0.6096 + >>> length_conversion(4, "feet", "yard") + 1.333329312 + >>> length_conversion(1, "inch", "meter") + 0.0254 + >>> length_conversion(2, "inch", "mile") + 3.15656468e-05 + >>> length_conversion(2, "centimeter", "millimeter") + 20.0 + >>> length_conversion(2, "centimeter", "yard") + 0.0218722 + >>> length_conversion(4, "yard", "meter") + 3.6576 + >>> length_conversion(4, "yard", "kilometer") + 0.0036576 + >>> length_conversion(3, "foot", "meter") + 0.9144000000000001 + >>> length_conversion(3, "foot", "inch") + 36.00001944 + >>> length_conversion(4, "mile", "kilometer") + 6.43736 + >>> length_conversion(2, "mile", "inch") + 126719.753468 + >>> length_conversion(3, "millimeter", "centimeter") + 0.3 + >>> length_conversion(3, "millimeter", "inch") + 0.1181103 + >>> length_conversion(4, "wrongUnit", "inch") + Traceback (most recent call last): + File "/usr/lib/python3.8/doctest.py", line 1336, in __run + exec(compile(example.source, filename, "single", + File "<doctest __main__.length_conversion[18]>", line 1, in <module> + length_conversion(4, "wrongUnit", "inch") + File "<string>", line 85, in length_conversion + ValueError: Invalid 'from_type' value: 'wrongUnit' Supported values are: + meter, kilometer, feet, inch, centimeter, yard, foot, mile, millimeter + """ + if from_type not in METRIC_CONVERSION: + raise ValueError( + f"Invalid 'from_type' value: {from_type!r} Supported values are:\n" + + ", ".join(METRIC_CONVERSION) + ) + if to_type not in METRIC_CONVERSION: + raise ValueError( + f"Invalid 'to_type' value: {to_type!r}. Supported values are:\n" + + ", ".join(METRIC_CONVERSION) + ) + return value * METRIC_CONVERSION[from_type].from_ * METRIC_CONVERSION[to_type].to + + +if __name__ == "__main__": + import doctest + + doctest.testmod()
Conversion of length units were added with respective tests being implemented and passed. Available Units:- Metre,Kilometre,Feet,Inch,Centimeter,Yard,Foot,Mile,Millimeter ### **Describe your change:** * [x] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [x] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
https://api.github.com/repos/TheAlgorithms/Python/pulls/5373
2021-10-17T10:58:53Z
2021-10-19T05:26:04Z
2021-10-19T05:26:04Z
2021-10-19T05:26:04Z
1,299
TheAlgorithms/Python
30,249
test using os.path.sep not hardcoded /
diff --git a/certbot/tests/cert_manager_test.py b/certbot/tests/cert_manager_test.py index bffa5298fcb..e04e25da8b6 100644 --- a/certbot/tests/cert_manager_test.py +++ b/certbot/tests/cert_manager_test.py @@ -383,7 +383,7 @@ def test_rename_cert_bad_new_certname(self, mock_check, unused_get_utility): mock_config.new_certname = "example.org" self.assertRaises(errors.ConfigurationError, self._call, mock_config) - mock_config.new_certname = "one/two" + mock_config.new_certname = "one{0}two".format(os.path.sep) self.assertRaises(errors.ConfigurationError, self._call, mock_config)
https://api.github.com/repos/certbot/certbot/pulls/3920
2016-12-16T03:19:49Z
2016-12-16T03:41:42Z
2016-12-16T03:41:42Z
2017-01-05T22:51:34Z
171
certbot/certbot
3,273
Added PLE env to scoreboard (from https://github.com/lusob/gym-ple)
diff --git a/gym/scoreboard/__init__.py b/gym/scoreboard/__init__.py index fae7b8f88af..12282f4f09f 100644 --- a/gym/scoreboard/__init__.py +++ b/gym/scoreboard/__init__.py @@ -83,6 +83,12 @@ description='Environments to test various AI safety properties.' ) +add_group( + id='ple', + name='PLE', + description='Reach high scores in pygame games.', +) + # classic control add_task( @@ -706,6 +712,33 @@ """, ) +# ple +for id in sorted(['Catcher-v0', 'MonsterKong-v0', 'FlappyBird-v0', 'PixelCopter-v0', 'PuckWorld-v0', 'RaycastMaze-v0', 'Snake-v0', 'WaterWorld-v0']): + try: + split = id.split("-") + game = split[0] + if len(split) == 2: + ob_type = 'image' + else: + ob_type = 'ram' + except ValueError as e: + raise ValueError('{}: id={}'.format(e, id)) + ob_desc = ram_desc if ob_type == "ram" else image_desc + add_task( + id=id, + group='ple', + contributor='lusob', + summary="Maximize score in the game %(game)s, with %(ob_type)s as input"%dict(game=game, ob_type="RAM" if ob_type=="ram" else "screen images"), + description="""\ + Maximize your score in the pygame game %(game)s. +%(ob_desc)s. +"""%dict(game=game, ob_desc=ob_desc), + background="""\ +Every game environment adapts an existent game made with the pygame framework. +To run this you'll need to install gym-ple from https://github.com/lusob/gym-ple. +""", + ) + # doom add_task( id='meta-Doom-v0',
https://api.github.com/repos/openai/gym/pulls/299
2016-08-18T15:14:56Z
2016-08-24T01:02:09Z
2016-08-24T01:02:09Z
2016-08-24T18:34:00Z
469
openai/gym
5,332
If a snap build times out, dump the logs
diff --git a/tools/snap/build_remote.py b/tools/snap/build_remote.py index 6ab80669c09..7a4eea1b006 100755 --- a/tools/snap/build_remote.py +++ b/tools/snap/build_remote.py @@ -253,6 +253,12 @@ def main(): process.join(args.timeout) if process.is_alive(): + for target in targets: + if target == 'certbot': + workspace = CERTBOT_DIR + else: + workspace = join(CERTBOT_DIR, target) + _dump_failed_build_logs(target, archs, status, workspace) raise ValueError(f"Timeout out reached ({args.timeout} seconds) during the build!") build_success = True
Not super clean, but might help debugging the repeated snap timeouts
https://api.github.com/repos/certbot/certbot/pulls/9340
2022-07-06T00:05:06Z
2022-07-07T21:31:48Z
2022-07-07T21:31:48Z
2022-07-07T21:31:49Z
164
certbot/certbot
1,152
Mark Nginx as Alpha
diff --git a/letsencrypt-nginx/letsencrypt_nginx/configurator.py b/letsencrypt-nginx/letsencrypt_nginx/configurator.py index 2899e1f767f..3f6d6f327bb 100644 --- a/letsencrypt-nginx/letsencrypt_nginx/configurator.py +++ b/letsencrypt-nginx/letsencrypt_nginx/configurator.py @@ -56,7 +56,7 @@ class NginxConfigurator(common.Plugin): zope.interface.implements(interfaces.IAuthenticator, interfaces.IInstaller) zope.interface.classProvides(interfaces.IPluginFactory) - description = "Nginx Web Server" + description = "Nginx Web Server - Alpha" @classmethod def add_parser_arguments(cls, add):
Fixes #821.
https://api.github.com/repos/certbot/certbot/pulls/861
2015-09-29T18:07:01Z
2015-09-29T18:12:19Z
2015-09-29T18:12:19Z
2016-05-06T19:22:29Z
173
certbot/certbot
3,426
Add `requests` to requirements.txt
diff --git a/requirements.txt b/requirements.txt index a80d4678994..22b51fc490e 100755 --- a/requirements.txt +++ b/requirements.txt @@ -6,6 +6,7 @@ numpy>=1.18.5 opencv-python>=4.1.2 Pillow>=7.1.2 PyYAML>=5.3.1 +requests>=2.23.0 scipy>=1.4.1 torch>=1.7.0 torchvision>=0.8.1 @@ -16,7 +17,7 @@ tensorboard>=2.4.1 # wandb # Plotting ------------------------------------ -pandas +pandas>=1.1.4 seaborn>=0.11.0 # Export --------------------------------------
1. Requests added to requirements.txt. That might not be included in all docker base images, adding it to the requirements is safer. 2. Added a minimum version to Pandas. It's a good practice to have versions for all dependencies. ## 🛠️ PR Summary <sub>Made with ❤️ by [Ultralytics Actions](https://github.com/ultralytics/actions)<sub> ### 🌟 Summary Enhancement of dependencies in the YOLOv5 project's requirements. ### 📊 Key Changes - Added `requests` library with a minimum version of 2.23.0. - Specified a minimum version of 1.1.4 for the `pandas` library. ### 🎯 Purpose & Impact - Including `requests` likely aims to facilitate web requests capabilities for tasks such as downloading data or interacting with web services. - Pinning a minimum version for `pandas` ensures compatibility and stability when using data frames for analysis and plotting. - These changes may result in more robust code and fewer bugs for users due to better control over the package environment. Users will need to ensure they have these versions when installing or upgrading the YOLOv5 dependencies.
https://api.github.com/repos/ultralytics/yolov5/pulls/5112
2021-10-09T18:00:01Z
2021-10-09T22:51:01Z
2021-10-09T22:51:01Z
2024-01-19T15:11:48Z
174
ultralytics/yolov5
25,284
Add support for `IterableDataset` to `TorchDataLoaderAdapter`.
diff --git a/keras/backend/jax/trainer.py b/keras/backend/jax/trainer.py index 5adb37de133..ec58eb9cc96 100644 --- a/keras/backend/jax/trainer.py +++ b/keras/backend/jax/trainer.py @@ -334,7 +334,7 @@ def fit( (x, y, sample_weight), validation_split=validation_split ) - if validation_data: + if validation_data is not None: ( val_x, val_y, @@ -428,7 +428,9 @@ def fit( epoch_logs = self.get_metrics_result() # Run validation. - if validation_data and self._should_eval(epoch, validation_freq): + if validation_data is not None and self._should_eval( + epoch, validation_freq + ): # Create JAXEpochIterator for evaluation and cache it. if getattr(self, "_eval_epoch_iterator", None) is None: self._eval_epoch_iterator = JAXEpochIterator( diff --git a/keras/backend/tensorflow/trainer.py b/keras/backend/tensorflow/trainer.py index 0bcef10a089..f688ca32fcc 100644 --- a/keras/backend/tensorflow/trainer.py +++ b/keras/backend/tensorflow/trainer.py @@ -277,7 +277,7 @@ def fit( (x, y, sample_weight), validation_split=validation_split ) - if validation_data: + if validation_data is not None: ( val_x, val_y, @@ -331,7 +331,9 @@ def fit( epoch_logs = self.get_metrics_result() # Run validation. - if validation_data and self._should_eval(epoch, validation_freq): + if validation_data is not None and self._should_eval( + epoch, validation_freq + ): # Create EpochIterator for evaluation and cache it. if getattr(self, "_eval_epoch_iterator", None) is None: self._eval_epoch_iterator = TFEpochIterator( diff --git a/keras/backend/torch/trainer.py b/keras/backend/torch/trainer.py index 1557e18f1cb..062b8e914a3 100644 --- a/keras/backend/torch/trainer.py +++ b/keras/backend/torch/trainer.py @@ -197,7 +197,7 @@ def fit( (x, y, sample_weight), validation_split=validation_split ) - if validation_data: + if validation_data is not None: ( val_x, val_y, @@ -260,7 +260,9 @@ def fit( self.eval() # Run validation. - if validation_data and self._should_eval(epoch, validation_freq): + if validation_data is not None and self._should_eval( + epoch, validation_freq + ): # Create TorchEpochIterator for evaluation and cache it. if getattr(self, "_eval_epoch_iterator", None) is None: self._eval_epoch_iterator = TorchEpochIterator( diff --git a/keras/trainers/data_adapters/tf_dataset_adapter.py b/keras/trainers/data_adapters/tf_dataset_adapter.py index e872ab153f8..b5a91f6662e 100644 --- a/keras/trainers/data_adapters/tf_dataset_adapter.py +++ b/keras/trainers/data_adapters/tf_dataset_adapter.py @@ -75,7 +75,7 @@ def num_batches(self): else: # However, in the case of `DistributedDataset`, it's a np.int64. cardinality = int(cardinality) - # Return None for Unknown and Infiite cardinality datasets + # Return None for Unknown and Infinite cardinality datasets if cardinality < 0: return None return cardinality diff --git a/keras/trainers/data_adapters/torch_data_loader_adapter.py b/keras/trainers/data_adapters/torch_data_loader_adapter.py index 32747b85093..39ade188952 100644 --- a/keras/trainers/data_adapters/torch_data_loader_adapter.py +++ b/keras/trainers/data_adapters/torch_data_loader_adapter.py @@ -20,8 +20,14 @@ def __init__(self, dataloader): self._dataloader = dataloader self._batch_size = dataloader.batch_size - self._size = len(dataloader) - self._partial_batch_size = len(dataloader.dataset) % self._batch_size + self._num_batches = None + self._partial_batch_size = None + if hasattr(dataloader.dataset, "__len__"): + self._num_batches = len(dataloader) + if self._batch_size is not None: + self._partial_batch_size = ( + len(dataloader.dataset) % self._batch_size + ) def get_numpy_iterator(self): for batch in self._dataloader: @@ -70,7 +76,7 @@ def get_tensor_spec(x): @property def num_batches(self): - return self._size + return self._num_batches @property def batch_size(self): diff --git a/keras/trainers/data_adapters/torch_data_loader_adapter_test.py b/keras/trainers/data_adapters/torch_data_loader_adapter_test.py index 80932dc14e6..1d340be780e 100644 --- a/keras/trainers/data_adapters/torch_data_loader_adapter_test.py +++ b/keras/trainers/data_adapters/torch_data_loader_adapter_test.py @@ -1,3 +1,5 @@ +import math + import jax import numpy as np import tensorflow as tf @@ -18,9 +20,9 @@ class TestTorchDataLoaderAdapter(testing.TestCase, parameterized.TestCase): def test_basic_dataloader(self, iterator_type): x = torch.normal(2, 3, size=(34, 4)) y = torch.normal(1, 3, size=(34, 2)) - base_ds = torch.utils.data.TensorDataset(x, y) - base_dataloader = torch.utils.data.DataLoader(base_ds, batch_size=16) - adapter = TorchDataLoaderAdapter(base_dataloader) + ds = torch.utils.data.TensorDataset(x, y) + dataloader = torch.utils.data.DataLoader(ds, batch_size=16) + adapter = TorchDataLoaderAdapter(dataloader) self.assertEqual(adapter.num_batches, 3) self.assertEqual(adapter.batch_size, 16) @@ -53,3 +55,89 @@ def test_basic_dataloader(self, iterator_type): else: self.assertEqual(bx.shape, (2, 4)) self.assertEqual(by.shape, (2, 2)) + + @parameterized.named_parameters( + named_product( + batch_size=[None, 3], + implements_len=[True, False], + iterator_type=["np", "tf", "jax", "torch"], + ) + ) + def test_dataloader_iterable_dataset( + self, batch_size, implements_len, iterator_type + ): + + class TestIterableDataset(torch.utils.data.IterableDataset): + def __init__(self): + self.x = torch.normal(2, 3, size=(16, 4)) + self.y = torch.normal(1, 3, size=(16, 2)) + + def __iter__(self): + for _ in range(10): + yield (self.x, self.y) + + class TestIterableDatasetWithLen(TestIterableDataset): + def __len__(self): + return 10 + + ds = ( + TestIterableDatasetWithLen() + if implements_len + else TestIterableDataset() + ) + dataloader = torch.utils.data.DataLoader(ds, batch_size=batch_size) + adapter = TorchDataLoaderAdapter(dataloader) + + if implements_len and batch_size: + self.assertEqual(adapter.num_batches, math.ceil(10 / batch_size)) + self.assertEqual(adapter.batch_size, batch_size) + self.assertEqual(adapter.has_partial_batch, True) + self.assertEqual(adapter.partial_batch_size, 10 % batch_size) + elif implements_len: + self.assertEqual(adapter.num_batches, 10) + self.assertEqual(adapter.batch_size, None) + self.assertEqual(adapter.has_partial_batch, None) + self.assertEqual(adapter.partial_batch_size, None) + else: + self.assertIsNone(adapter.num_batches) + self.assertEqual(adapter.batch_size, batch_size) + self.assertIsNone(adapter.has_partial_batch) + self.assertIsNone(adapter.partial_batch_size) + + if iterator_type == "np": + it = adapter.get_numpy_iterator() + expected_class = np.ndarray + elif iterator_type == "tf": + it = adapter.get_tf_dataset() + expected_class = tf.Tensor + elif iterator_type == "jax": + it = adapter.get_jax_iterator() + expected_class = jax.Array + elif iterator_type == "torch": + it = adapter.get_torch_dataloader() + expected_class = torch.Tensor + + batch_count = 0 + for i, batch in enumerate(it): + batch_count += 1 + self.assertEqual(len(batch), 2) + bx, by = batch + self.assertIsInstance(bx, expected_class) + self.assertIsInstance(by, expected_class) + self.assertEqual(bx.dtype, by.dtype) + self.assertContainsExactSubsequence(str(bx.dtype), "float32") + if batch_size: + if i < 3: + self.assertEqual(bx.shape, (batch_size, 16, 4)) + self.assertEqual(by.shape, (batch_size, 16, 2)) + else: + self.assertEqual(bx.shape, (10 % batch_size, 16, 4)) + self.assertEqual(by.shape, (10 % batch_size, 16, 2)) + else: + self.assertEqual(bx.shape, (16, 4)) + self.assertEqual(by.shape, (16, 2)) + + if batch_size: + self.assertEqual(batch_count, math.ceil(10 / batch_size)) + else: + self.assertEqual(batch_count, 10)
Fixes https://github.com/keras-team/keras/issues/19156 The `IterableDataset` can optionally implement `__len__`.
https://api.github.com/repos/keras-team/keras/pulls/19176
2024-02-13T18:01:31Z
2024-02-14T00:04:37Z
2024-02-14T00:04:37Z
2024-02-14T01:58:49Z
2,286
keras-team/keras
47,119
Fix skip_teardown and force_synth usage in CDK tests
diff --git a/tests/aws/services/stepfunctions/v2/services/test_ecs_task_service.py b/tests/aws/services/stepfunctions/v2/services/test_ecs_task_service.py index 2c78b1f83a10b..ed01626a472a6 100644 --- a/tests/aws/services/stepfunctions/v2/services/test_ecs_task_service.py +++ b/tests/aws/services/stepfunctions/v2/services/test_ecs_task_service.py @@ -58,7 +58,7 @@ class TestTaskServiceECS: @pytest.fixture(scope="class", autouse=False) def infrastructure_test_run_task(self, aws_client, infrastructure_setup): - infra = infrastructure_setup(namespace="StepFunctionsEcsTask", force_synth=True) + infra = infrastructure_setup(namespace="StepFunctionsEcsTask", force_synth=False) stack = cdk.Stack(infra.cdk_app, self.STACK_NAME) # cluster setup @@ -105,7 +105,7 @@ def infrastructure_test_run_task(self, aws_client, infrastructure_setup): @pytest.fixture(scope="class", autouse=False) def infrastructure_test_run_task_raise_failure(self, aws_client, infrastructure_setup): - infra = infrastructure_setup(namespace="StepFunctionsEcsTask", force_synth=True) + infra = infrastructure_setup(namespace="StepFunctionsEcsTask", force_synth=False) stack = cdk.Stack(infra.cdk_app, self.STACK_NAME) # cluster setup @@ -152,7 +152,7 @@ def infrastructure_test_run_task_raise_failure(self, aws_client, infrastructure_ @pytest.fixture(scope="class", autouse=False) def infrastructure_test_run_task_sync(self, aws_client, infrastructure_setup): - infra = infrastructure_setup(namespace="StepFunctionsEcsTask", force_synth=True) + infra = infrastructure_setup(namespace="StepFunctionsEcsTask", force_synth=False) stack = cdk.Stack(infra.cdk_app, self.STACK_NAME) # cluster setup @@ -199,7 +199,7 @@ def infrastructure_test_run_task_sync(self, aws_client, infrastructure_setup): @pytest.fixture(scope="class", autouse=False) def infrastructure_test_run_task_sync_raise_failure(self, aws_client, infrastructure_setup): - infra = infrastructure_setup(namespace="StepFunctionsEcsTask", force_synth=True) + infra = infrastructure_setup(namespace="StepFunctionsEcsTask", force_synth=False) stack = cdk.Stack(infra.cdk_app, self.STACK_NAME) # cluster setup
## Motivation While working on another sample I've noticed some cases where we forgot to disable the `skip_teardown` and `force_synth` flags. ## Changes - Removes any `force_synth=True` and `skip_teardown=True` cases.
https://api.github.com/repos/localstack/localstack/pulls/10445
2024-03-13T09:41:44Z
2024-03-19T09:48:45Z
2024-03-19T09:48:45Z
2024-03-19T09:48:46Z
543
localstack/localstack
28,633
add warning about Python2.7 support drop
diff --git a/README.rst b/README.rst index 4df228acd4c49..eb1957686acaf 100644 --- a/README.rst +++ b/README.rst @@ -53,6 +53,9 @@ scikit-learn requires: - NumPy (>= 1.8.2) - SciPy (>= 0.13.3) +**Scikit-learn 0.20 is the last version to support Python2.7.** +Scikit-learn 0.21 and later will require Python 3.5 or newer. + For running the examples Matplotlib >= 1.3.1 is required. A few examples require scikit-image >= 0.9.3 and a few examples require pandas >= 0.13.1. diff --git a/doc/index.rst b/doc/index.rst index dadab9aa86b10..0de085b1d7216 100644 --- a/doc/index.rst +++ b/doc/index.rst @@ -207,6 +207,10 @@ <li><em>On-going development:</em> <a href="/dev/whats_new.html"><em>What's new</em> (Changelog)</a> </li> + <li><strong>Scikit-learn 0.21 will drop support for Python 2.7 and Python 3.4.</strong> + </li> + <li><em>July 2018.</em> scikit-learn 0.20 is available for download (<a href="whats_new.html#version-0-20">Changelog</a>). + </li> <li><em>July 2018.</em> scikit-learn 0.19.2 is available for download (<a href="whats_new.html#version-0-19">Changelog</a>). </li> <li><em>October 2017.</em> scikit-learn 0.19.1 is available for download (<a href="whats_new.html#version-0-19">Changelog</a>). @@ -215,12 +219,6 @@ </li> <li><em>June 2017.</em> scikit-learn 0.18.2 is available for download (<a href="whats_new/v0.18.html#version-0-18-2">Changelog</a>). </li> - <li><em>September 2016.</em> scikit-learn 0.18.0 is available for download (<a href="whats_new/v0.18.html#version-0-18">Changelog</a>). - </li> - <li><em>November 2015.</em> scikit-learn 0.17.0 is available for download (<a href="whats_new/v0.17.html">Changelog</a>). - </li> - <li><em>March 2015.</em> scikit-learn 0.16.0 is available for download (<a href="whats_new/v0.16.html">Changelog</a>). - </li> </ul> </div> diff --git a/doc/install.rst b/doc/install.rst index 20a409a6872d4..89c1aca455c7f 100644 --- a/doc/install.rst +++ b/doc/install.rst @@ -21,6 +21,12 @@ Scikit-learn requires: - NumPy (>= 1.8.2), - SciPy (>= 0.13.3). + +.. warning:: + + Scikit-learn 0.20 is the last version to support Python 2.7 and Python 3.4. + Scikit-learn 0.21 will require Python 3.5 or newer. + If you already have a working installation of numpy and scipy, the easiest way to install scikit-learn is using ``pip`` :: diff --git a/doc/whats_new/v0.20.rst b/doc/whats_new/v0.20.rst index 0df0635d57c75..fbe99ab0c3859 100644 --- a/doc/whats_new/v0.20.rst +++ b/doc/whats_new/v0.20.rst @@ -11,6 +11,11 @@ This release packs in a mountain of bug fixes, features and enhancements for the Scikit-learn library, and improvements to the documentation and examples. Thanks to our many contributors! +.. warning:: + + Version 0.20 is the last version of scikit-learn to support Python 2.7 and Python 3.4. + Scikit-learn 0.21 will require Python 3.5 or higher. + Highlights ----------
Fixes #11115. Says we'll drop 2.7 and 3.4 for sklearn 0.21
https://api.github.com/repos/scikit-learn/scikit-learn/pulls/11545
2018-07-15T23:11:53Z
2018-07-17T10:48:43Z
2018-07-17T10:48:43Z
2018-07-31T04:31:41Z
1,074
scikit-learn/scikit-learn
46,197
[MRG] Speed up plot_digits_linkage.py example #21598
diff --git a/examples/cluster/plot_digits_linkage.py b/examples/cluster/plot_digits_linkage.py index 925f5c122d73f..e13e83047fee3 100644 --- a/examples/cluster/plot_digits_linkage.py +++ b/examples/cluster/plot_digits_linkage.py @@ -12,10 +12,18 @@ What this example shows us is the behavior "rich getting richer" of agglomerative clustering that tends to create uneven cluster sizes. + This behavior is pronounced for the average linkage strategy, -that ends up with a couple of singleton clusters, while in the case -of single linkage we get a single central cluster with all other clusters -being drawn from noise points around the fringes. +that ends up with a couple of clusters with few datapoints. + +The case of single linkage is even more pathologic with a very +large cluster covering most digits, an intermediate size (clean) +cluster with most zero digits and all other clusters being drawn +from noise points around the fringes. + +The other linkage strategies lead to more evenly distributed +clusters that are therefore likely to be less sensible to a +random resampling of the dataset. """ @@ -25,7 +33,6 @@ from time import time import numpy as np -from scipy import ndimage from matplotlib import pyplot as plt from sklearn import manifold, datasets @@ -36,22 +43,6 @@ np.random.seed(0) -def nudge_images(X, y): - # Having a larger dataset shows more clearly the behavior of the - # methods, but we multiply the size of the dataset only by 2, as the - # cost of the hierarchical clustering methods are strongly - # super-linear in n_samples - shift = lambda x: ndimage.shift( - x.reshape((8, 8)), 0.3 * np.random.normal(size=2), mode="constant" - ).ravel() - X = np.concatenate([X, np.apply_along_axis(shift, 1, X)]) - Y = np.concatenate([y, y], axis=0) - return X, Y - - -X, y = nudge_images(X, y) - - # ---------------------------------------------------------------------- # Visualize the clustering def plot_clustering(X_red, labels, title=None):
#### Reference Issues/PRs #21598 #### What does this implement/fix? Explain your changes. Speeds up `../examples/cluster/plot_digits_linkage.py` from 32 sec to 20 sec by reducing the number of digits dataset samples from 1800 to 800. Additionally, increased the font size of the numbers and added a random state for `manifold.SpectralEmbedding`. Before: ![image](https://user-images.githubusercontent.com/19868916/141824100-0ef53b96-c2aa-417f-a47c-2a307ce8b5cb.png) After: ![image](https://user-images.githubusercontent.com/19868916/142369693-4cec8105-9351-4213-ada9-e34872b97743.png) #### Any other comments? Nil
https://api.github.com/repos/scikit-learn/scikit-learn/pulls/21678
2021-11-15T17:12:02Z
2021-11-19T09:27:29Z
2021-11-19T09:27:29Z
2021-11-22T15:49:30Z
502
scikit-learn/scikit-learn
46,790
Add AzureHound examples
diff --git a/Methodology and Resources/Cloud - Azure Pentest.md b/Methodology and Resources/Cloud - Azure Pentest.md index 08800ad232..d6721d2f0b 100644 --- a/Methodology and Resources/Cloud - Azure Pentest.md +++ b/Methodology and Resources/Cloud - Azure Pentest.md @@ -90,11 +90,27 @@ ``` * [**BloodHoundAD/AzureHound**](https://github.com/BloodHoundAD/AzureHound) - Azure Data Exporter for BloodHound ```powershell + # First, retrieve a refresh token (-r) if username/password isn't supported. + # An access token (-j) isn't recommended because it can expire before the end of azurehound execution + Install-Module AADInternals -Scope CurrentUser + Import-Module AADInternals + $rt = (Get-AADIntAccessToken -ClientId "1950a258-227b-4e31-a9cf-717495945fc2" -Resource "https://graph.microsoft.com" -PRTToken (Get-AADIntUserPRTToken) -IncludeRefreshToken $true)[1] + + # Second, launch azurehound collector + ## Connects on your Azure account using the refresh token provided and the tenant of the account + ## and collects every possible objects in contoso.microsoft.com. Results are stored in json + ./azurehound -r $rt --tenant "contoso.onmicrosoft.com" list -o azurehound-scan.json --tenant "contoso.microsoft.com" + ## Sets configuration file with connection variables and other things (not required) ./azurehound configure + ## Collects every objects on all accessible tenants using username/password and prints it to stdout ./azurehound -u "MattNelson@contoso.onmicrosoft.com" -p "MyVerySecurePassword123" --tenant "contoso.onmicrosoft.com" list + ## Collects every objects on a specific tenant using username/password and stores it in json ./azurehound -u "phisheduser@contoso.onmicrosoft.com" -p "Password1" list -o initial-scan.json --tenant "contoso.onmicrosoft.com" + ## Collects every objects on all tenants accessible using Service Principal secret ./azurehound -a "6b5adee8-..." -s "<secret>" --tenant "contoso.onmicrosoft.com" list + ## Collects AzureAD info (all except AzureRM info) using JWT access token ./azurehound -j "ey..." --tenant "contoso.onmicrosoft.com" list az-ad + ## Collects every users using refresh token ./azurehound -r "0.ARwA6Wg..." --tenant "contoso.onmicrosoft.com" list users # List of collections @@ -1137,4 +1153,4 @@ Using [https://autologon.microsoftazuread-sso.com/](https://autologon.microsofta * [AZURE AD INTRODUCTION FOR RED TEAMERS - Written by Aymeric Palhière (bak) - 2020-04-20](https://www.synacktiv.com/posts/pentest/azure-ad-introduction-for-red-teamers.html) * [Impersonating Office 365 Users With Mimikatz - January 15, 2017 - Michael Grafnetter](https://www.dsinternals.com/en/impersonating-office-365-users-mimikatz/) * [The Art of the Device Code Phish - Bobby Cooke](https://0xboku.com/2021/07/12/ArtOfDeviceCodePhish.html) -* [AZURE AD cheatsheet - BlackWasp](https://hideandsec.sh/books/cheatsheets-82c/page/azure-ad) \ No newline at end of file +* [AZURE AD cheatsheet - BlackWasp](https://hideandsec.sh/books/cheatsheets-82c/page/azure-ad)
https://api.github.com/repos/swisskyrepo/PayloadsAllTheThings/pulls/596
2022-11-04T14:09:49Z
2022-11-04T15:42:49Z
2022-11-04T15:42:49Z
2022-11-07T10:50:21Z
880
swisskyrepo/PayloadsAllTheThings
8,650
Bump actions/checkout from 3.3.0 to 3.5.0
diff --git a/.github/workflows/publish.yaml b/.github/workflows/publish.yaml index ef277f0050..6b0c11cf36 100644 --- a/.github/workflows/publish.yaml +++ b/.github/workflows/publish.yaml @@ -9,7 +9,7 @@ jobs: outputs: hash: ${{ steps.hash.outputs.hash }} steps: - - uses: actions/checkout@ac593985615ec2ede58e132d2e21d2b1cbd6127c + - uses: actions/checkout@8f4b7f84864484a7bf31766abe9204da3cbe65b3 - uses: actions/setup-python@d27e3f3d7c64b4bbf8e4abfb9b63b83e846e0435 with: python-version: '3.x' diff --git a/.github/workflows/tests.yaml b/.github/workflows/tests.yaml index 73a32f29c8..090bb4e1d6 100644 --- a/.github/workflows/tests.yaml +++ b/.github/workflows/tests.yaml @@ -37,7 +37,7 @@ jobs: - {name: 'Pallets Development Versions', python: '3.7', os: ubuntu-latest, tox: py37-dev} - {name: Typing, python: '3.11', os: ubuntu-latest, tox: typing} steps: - - uses: actions/checkout@ac593985615ec2ede58e132d2e21d2b1cbd6127c + - uses: actions/checkout@8f4b7f84864484a7bf31766abe9204da3cbe65b3 - uses: actions/setup-python@d27e3f3d7c64b4bbf8e4abfb9b63b83e846e0435 with: python-version: ${{ matrix.python }}
Bumps [actions/checkout](https://github.com/actions/checkout) from 3.3.0 to 3.5.0. <details> <summary>Release notes</summary> <p><em>Sourced from <a href="https://github.com/actions/checkout/releases">actions/checkout's releases</a>.</em></p> <blockquote> <h2>v3.5.0</h2> <h2>What's Changed</h2> <ul> <li>Add new public key for known_hosts by <a href="https://github.com/cdb"><code>@​cdb</code></a> in <a href="https://redirect.github.com/actions/checkout/pull/1237">actions/checkout#1237</a></li> </ul> <h2>New Contributors</h2> <ul> <li><a href="https://github.com/cdb"><code>@​cdb</code></a> made their first contribution in <a href="https://redirect.github.com/actions/checkout/pull/1237">actions/checkout#1237</a></li> </ul> <p><strong>Full Changelog</strong>: <a href="https://github.com/actions/checkout/compare/v3.4.0...v3.5.0">https://github.com/actions/checkout/compare/v3.4.0...v3.5.0</a></p> <h2>v3.4.0</h2> <h2>What's Changed</h2> <ul> <li>Upgrade codeql actions to v2 by <a href="https://github.com/Link"><code>@​Link</code></a>- in <a href="https://redirect.github.com/actions/checkout/pull/1209">actions/checkout#1209</a></li> <li>Upgrade dependencies by <a href="https://github.com/Link"><code>@​Link</code></a>- in <a href="https://redirect.github.com/actions/checkout/pull/1210">actions/checkout#1210</a></li> <li>Backfill changelog and bump actions/io by <a href="https://github.com/cory-miller"><code>@​cory-miller</code></a> in <a href="https://redirect.github.com/actions/checkout/pull/1225">actions/checkout#1225</a></li> </ul> <h2>New Contributors</h2> <ul> <li><a href="https://github.com/Link"><code>@​Link</code></a>- made their first contribution in <a href="https://redirect.github.com/actions/checkout/pull/1209">actions/checkout#1209</a></li> </ul> <p><strong>Full Changelog</strong>: <a href="https://github.com/actions/checkout/compare/v3.3.0...v3.4.0">https://github.com/actions/checkout/compare/v3.3.0...v3.4.0</a></p> </blockquote> </details> <details> <summary>Changelog</summary> <p><em>Sourced from <a href="https://github.com/actions/checkout/blob/main/CHANGELOG.md">actions/checkout's changelog</a>.</em></p> <blockquote> <h1>Changelog</h1> <h2>v3.4.0</h2> <ul> <li><a href="https://redirect.github.com/actions/checkout/pull/1209">Upgrade codeql actions to v2</a></li> <li><a href="https://redirect.github.com/actions/checkout/pull/1210">Upgrade dependencies</a></li> <li><a href="https://redirect.github.com/actions/checkout/pull/1225">Upgrade <code>@​actions/io</code></a></li> </ul> <h2>v3.3.0</h2> <ul> <li><a href="https://redirect.github.com/actions/checkout/pull/1045">Implement branch list using callbacks from exec function</a></li> <li><a href="https://redirect.github.com/actions/checkout/pull/1050">Add in explicit reference to private checkout options</a></li> <li>[Fix comment typos (that got added in <a href="https://redirect.github.com/actions/checkout/issues/770">#770</a>)](<a href="https://redirect.github.com/actions/checkout/pull/1057">actions/checkout#1057</a>)</li> </ul> <h2>v3.2.0</h2> <ul> <li><a href="https://redirect.github.com/actions/checkout/pull/942">Add GitHub Action to perform release</a></li> <li><a href="https://redirect.github.com/actions/checkout/pull/967">Fix status badge</a></li> <li><a href="https://redirect.github.com/actions/checkout/pull/1002">Replace datadog/squid with ubuntu/squid Docker image</a></li> <li><a href="https://redirect.github.com/actions/checkout/pull/964">Wrap pipeline commands for submoduleForeach in quotes</a></li> <li><a href="https://redirect.github.com/actions/checkout/pull/1029">Update <code>@​actions/io</code> to 1.1.2</a></li> <li><a href="https://redirect.github.com/actions/checkout/pull/1039">Upgrading version to 3.2.0</a></li> </ul> <h2>v3.1.0</h2> <ul> <li><a href="https://redirect.github.com/actions/checkout/pull/939">Use <code>@​actions/core</code> <code>saveState</code> and <code>getState</code></a></li> <li><a href="https://redirect.github.com/actions/checkout/pull/922">Add <code>github-server-url</code> input</a></li> </ul> <h2>v3.0.2</h2> <ul> <li><a href="https://redirect.github.com/actions/checkout/pull/770">Add input <code>set-safe-directory</code></a></li> </ul> <h2>v3.0.1</h2> <ul> <li><a href="https://redirect.github.com/actions/checkout/pull/762">Fixed an issue where checkout failed to run in container jobs due to the new git setting <code>safe.directory</code></a></li> <li><a href="https://redirect.github.com/actions/checkout/pull/744">Bumped various npm package versions</a></li> </ul> <h2>v3.0.0</h2> <ul> <li><a href="https://redirect.github.com/actions/checkout/pull/689">Update to node 16</a></li> </ul> <h2>v2.3.1</h2> <ul> <li><a href="https://redirect.github.com/actions/checkout/pull/284">Fix default branch resolution for .wiki and when using SSH</a></li> </ul> <h2>v2.3.0</h2> <ul> <li><a href="https://redirect.github.com/actions/checkout/pull/278">Fallback to the default branch</a></li> </ul> <h2>v2.2.0</h2> <ul> <li><a href="https://redirect.github.com/actions/checkout/pull/258">Fetch all history for all tags and branches when fetch-depth=0</a></li> </ul> <h2>v2.1.1</h2> <ul> <li>Changes to support GHES (<a href="https://redirect.github.com/actions/checkout/pull/236">here</a> and <a href="https://redirect.github.com/actions/checkout/pull/248">here</a>)</li> </ul> <!-- raw HTML omitted --> </blockquote> <p>... (truncated)</p> </details> <details> <summary>Commits</summary> <ul> <li><a href="https://github.com/actions/checkout/commit/8f4b7f84864484a7bf31766abe9204da3cbe65b3"><code>8f4b7f8</code></a> Add new public key for known_hosts (<a href="https://redirect.github.com/actions/checkout/issues/1237">#1237</a>)</li> <li><a href="https://github.com/actions/checkout/commit/cd6a9fd49371476d813e892956e2e920fcc3fb7e"><code>cd6a9fd</code></a> Update update-main-version.yml</li> <li><a href="https://github.com/actions/checkout/commit/24cb9080177205b6e8c946b17badbe402adc938f"><code>24cb908</code></a> Bump <code>@​actions/io</code> to v1.1.3 (<a href="https://redirect.github.com/actions/checkout/issues/1225">#1225</a>)</li> <li><a href="https://github.com/actions/checkout/commit/27135e314dd1818f797af1db9dae03a9f045786b"><code>27135e3</code></a> Upgrade dependencies (<a href="https://redirect.github.com/actions/checkout/issues/1210">#1210</a>)</li> <li><a href="https://github.com/actions/checkout/commit/7b187184d12a8f064f797aeb51e4873c109637c7"><code>7b18718</code></a> Upgrade codeql actions to v2 (<a href="https://redirect.github.com/actions/checkout/issues/1209">#1209</a>)</li> <li>See full diff in <a href="https://github.com/actions/checkout/compare/ac593985615ec2ede58e132d2e21d2b1cbd6127c...8f4b7f84864484a7bf31766abe9204da3cbe65b3">compare view</a></li> </ul> </details> <br /> [![Dependabot compatibility score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=actions/checkout&package-manager=github_actions&previous-version=3.3.0&new-version=3.5.0)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores) Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`. [//]: # (dependabot-automerge-start) [//]: # (dependabot-automerge-end) --- <details> <summary>Dependabot commands and options</summary> <br /> You can trigger Dependabot actions by commenting on this PR: - `@dependabot rebase` will rebase this PR - `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it - `@dependabot merge` will merge this PR after your CI passes on it - `@dependabot squash and merge` will squash and merge this PR after your CI passes on it - `@dependabot cancel merge` will cancel a previously requested merge and block automerging - `@dependabot reopen` will reopen this PR if it is closed - `@dependabot close` will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually - `@dependabot ignore this major version` will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself) - `@dependabot ignore this minor version` will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself) - `@dependabot ignore this dependency` will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself) </details>
https://api.github.com/repos/pallets/flask/pulls/5039
2023-04-01T16:57:07Z
2023-04-03T13:18:45Z
2023-04-03T13:18:45Z
2023-04-18T00:05:33Z
444
pallets/flask
20,691
bpo-47117: Don't crash if we fail to decode characters when the tokenizer buffers are uninitialized
diff --git a/Misc/NEWS.d/next/Core and Builtins/2022-03-26-15-45-57.bpo-47117.60W6GQ.rst b/Misc/NEWS.d/next/Core and Builtins/2022-03-26-15-45-57.bpo-47117.60W6GQ.rst new file mode 100644 index 00000000000000..5098ed86d07935 --- /dev/null +++ b/Misc/NEWS.d/next/Core and Builtins/2022-03-26-15-45-57.bpo-47117.60W6GQ.rst @@ -0,0 +1,2 @@ +Fix a crash if we fail to decode characters in interactive mode if the +tokenizer buffers are uninitialized. Patch by Pablo Galindo. diff --git a/Parser/pegen_errors.c b/Parser/pegen_errors.c index 0be9df0ae55357..489699679633e9 100644 --- a/Parser/pegen_errors.c +++ b/Parser/pegen_errors.c @@ -248,7 +248,12 @@ get_error_line_from_tokenizer_buffers(Parser *p, Py_ssize_t lineno) assert((p->tok->fp == NULL && p->tok->str != NULL) || p->tok->fp == stdin); char *cur_line = p->tok->fp_interactive ? p->tok->interactive_src_start : p->tok->str; - assert(cur_line != NULL); + if (cur_line == NULL) { + assert(p->tok->fp_interactive); + // We can reach this point if the tokenizer buffers for interactive source have not been + // initialized because we failed to decode the original source with the given locale. + return PyUnicode_FromStringAndSize("", 0); + } Py_ssize_t relative_lineno = p->starting_lineno ? lineno - p->starting_lineno + 1 : lineno; const char* buf_end = p->tok->fp_interactive ? p->tok->interactive_src_end : p->tok->inp; @@ -311,7 +316,7 @@ _PyPegen_raise_error_known_location(Parser *p, PyObject *errtype, goto error; } - if (p->tok->fp_interactive) { + if (p->tok->fp_interactive && p->tok->interactive_src_start != NULL) { error_line = get_error_line_from_tokenizer_buffers(p, lineno); } else if (p->start_rule == Py_file_input) {
<!-- Thanks for your contribution! Please read this comment in its entirety. It's quite important. # Pull Request title It should be in the following format: ``` bpo-NNNN: Summary of the changes made ``` Where: bpo-NNNN refers to the issue number in the https://bugs.python.org. Most PRs will require an issue number. Trivial changes, like fixing a typo, do not need an issue. # Backport Pull Request title If this is a backport PR (PR made against branches other than `main`), please ensure that the PR title is in the following format: ``` [X.Y] <title from the original PR> (GH-NNNN) ``` Where: [X.Y] is the branch name, e.g. [3.6]. GH-NNNN refers to the PR number from `main`. --> <!-- issue-number: [bpo-47117](https://bugs.python.org/issue47117) --> https://bugs.python.org/issue47117 <!-- /issue-number --> Automerge-Triggered-By: GH:pablogsal
https://api.github.com/repos/python/cpython/pulls/32129
2022-03-26T15:46:29Z
2022-03-26T16:29:03Z
2022-03-26T16:29:03Z
2022-03-26T17:26:48Z
569
python/cpython
4,243
Add back mismatched indices
diff --git a/manimlib/animation/transform_matching_parts.py b/manimlib/animation/transform_matching_parts.py index e82bafafe8..ef62ff7d2a 100644 --- a/manimlib/animation/transform_matching_parts.py +++ b/manimlib/animation/transform_matching_parts.py @@ -192,6 +192,8 @@ def add_anims(anim_class, indices_lists_pairs): target_indices_lists, target_indices ) if not source_indices_lists or not target_indices_lists: + source_indices.extend(it.chain(*source_indices_lists)) + target_indices.extend(it.chain(*target_indices_lists)) continue anims.append(anim_class( source.build_parts_from_indices_lists(source_indices_lists),
## Motivation Fix a bug in `TransformMatchingStrings` class. ## Proposed changes - M `manimlib/animation/transform_matching_parts.py`: Add back mismatched indices.
https://api.github.com/repos/3b1b/manim/pulls/1820
2022-05-24T14:44:04Z
2022-05-25T06:12:54Z
2022-05-25T06:12:54Z
2022-05-28T04:45:15Z
162
3b1b/manim
18,555
Polish Python 2 removal
diff --git a/httpie/downloads.py b/httpie/downloads.py index 22e2d4a97f..f9a66f5ed3 100644 --- a/httpie/downloads.py +++ b/httpie/downloads.py @@ -1,10 +1,7 @@ -# coding=utf-8 """ Download mode implementation. """ -from __future__ import division - import errno import mimetypes import os @@ -131,7 +128,7 @@ def filename_from_url(url: str, content_type: Optional[str]) -> str: else: ext = mimetypes.guess_extension(content_type) - if ext == '.htm': # Python 3 + if ext == '.htm': ext = '.html' if ext: diff --git a/httpie/models.py b/httpie/models.py index d496f81a0d..c30f06e188 100644 --- a/httpie/models.py +++ b/httpie/models.py @@ -63,16 +63,10 @@ def headers(self): status_line = f'HTTP/{version} {original.status} {original.reason}' headers = [status_line] - try: - # `original.msg` is a `http.client.HTTPMessage` on Python 3 - # `_headers` is a 2-tuple - headers.extend( - '%s: %s' % header for header in original.msg._headers) - except AttributeError: - # and a `httplib.HTTPMessage` on Python 2.x - # `headers` is a list of `name: val<CRLF>`. - headers.extend(h.strip() for h in original.msg.headers) - + # `original.msg` is a `http.client.HTTPMessage` + # `_headers` is a 2-tuple + headers.extend( + f'{header[0]}: {header[1]}' for header in original.msg._headers) return '\r\n'.join(headers) @property @@ -116,10 +110,6 @@ def headers(self): headers.insert(0, request_line) headers = '\r\n'.join(headers).strip() - - if isinstance(headers, bytes): - # Python < 3 - headers = headers.decode('utf8') return headers @property diff --git a/httpie/output/formatters/colors.py b/httpie/output/formatters/colors.py index 384eefdf8b..ff182d2387 100644 --- a/httpie/output/formatters/colors.py +++ b/httpie/output/formatters/colors.py @@ -1,5 +1,3 @@ -from __future__ import absolute_import - import json from typing import Optional, Type diff --git a/httpie/output/formatters/json.py b/httpie/output/formatters/json.py index 63ce593039..65cbcd1989 100644 --- a/httpie/output/formatters/json.py +++ b/httpie/output/formatters/json.py @@ -1,4 +1,3 @@ -from __future__ import absolute_import import json from ...plugins import FormatterPlugin diff --git a/httpie/output/writer.py b/httpie/output/writer.py index 83e478ce5f..380e62eb30 100644 --- a/httpie/output/writer.py +++ b/httpie/output/writer.py @@ -58,7 +58,7 @@ def write_stream( ): """Write the output stream.""" try: - # Writing bytes so we use the buffer interface (Python 3). + # Writing bytes so we use the buffer interface. buf = outfile.buffer except AttributeError: buf = outfile @@ -76,7 +76,7 @@ def write_stream_with_colors_win_py3( ): """Like `write`, but colorized chunks are written as text directly to `outfile` to ensure it gets processed by colorama. - Applies only to Windows with Python 3 and colorized terminal output. + Applies only to Windows and colorized terminal output. """ color = b'\x1b[' diff --git a/httpie/utils.py b/httpie/utils.py index e7ebf68a9b..c7d1beab59 100644 --- a/httpie/utils.py +++ b/httpie/utils.py @@ -1,5 +1,3 @@ -from __future__ import division - import json import mimetypes import time @@ -25,8 +23,6 @@ def humanize_bytes(n, precision=2): # URL: https://code.activestate.com/recipes/577081/ """Return a humanized string representation of a number of bytes. - Assumes `from __future__ import division`. - >>> humanize_bytes(1) '1 B' >>> humanize_bytes(1024, precision=1) diff --git a/tests/test_sessions.py b/tests/test_sessions.py index ce4c222e21..5718832e8d 100644 --- a/tests/test_sessions.py +++ b/tests/test_sessions.py @@ -1,4 +1,3 @@ -# coding=utf-8 import json import os import shutil @@ -193,7 +192,7 @@ def test_session_unicode(self, httpbin): # FIXME: Authorization *sometimes* is not present on Python3 assert (r2.json['headers']['Authorization'] - == HTTPBasicAuth.make_header(u'test', UNICODE)) + == HTTPBasicAuth.make_header('test', UNICODE)) # httpbin doesn't interpret utf8 headers assert UNICODE in r2 diff --git a/tests/test_unicode.py b/tests/test_unicode.py index f5884301dc..4201e7fe88 100644 --- a/tests/test_unicode.py +++ b/tests/test_unicode.py @@ -1,4 +1,3 @@ -# coding=utf-8 """ Various unicode handling related tests. diff --git a/tests/utils/__init__.py b/tests/utils/__init__.py index e336e75914..b46b7794af 100644 --- a/tests/utils/__init__.py +++ b/tests/utils/__init__.py @@ -1,4 +1,3 @@ -# coding=utf-8 """Utilities for HTTPie test suite.""" import re import shlex
https://api.github.com/repos/httpie/cli/pulls/1070
2021-05-27T10:26:44Z
2021-05-27T11:05:41Z
2021-05-27T11:05:41Z
2021-05-27T11:14:38Z
1,380
httpie/cli
34,064
Fix table of contents
diff --git a/Methodology and Resources/Bind Shell Cheatsheet.md b/Methodology and Resources/Bind Shell Cheatsheet.md index 399c3581ae..c51bb7ebf0 100644 --- a/Methodology and Resources/Bind Shell Cheatsheet.md +++ b/Methodology and Resources/Bind Shell Cheatsheet.md @@ -2,7 +2,7 @@ ## Summary -* [Reverse Shell](#reverse-shell) +* [Bind Shell](#bind-shell) * [Perl](#perl) * [Python](#python) * [PHP](#php)
https://api.github.com/repos/swisskyrepo/PayloadsAllTheThings/pulls/296
2020-12-02T13:21:02Z
2020-12-07T16:21:03Z
2020-12-07T16:21:03Z
2020-12-07T16:24:18Z
138
swisskyrepo/PayloadsAllTheThings
8,335
MNT Remove setuptools dependency in our test suite
diff --git a/sklearn/tests/test_common.py b/sklearn/tests/test_common.py index 9ff5bf21c9a7d..a5f485ee1a882 100644 --- a/sklearn/tests/test_common.py +++ b/sklearn/tests/test_common.py @@ -217,6 +217,9 @@ def test_import_all_consistency(): for modname in submods + ["sklearn"]: if ".tests." in modname: continue + # Avoid test suite depending on setuptools + if modname == "sklearn._build_utils.pre_build_helpers": + continue if IS_PYPY and ( "_svmlight_format_io" in modname or "feature_extraction._hashing_fast" in modname diff --git a/sklearn/tests/test_docstring_parameters.py b/sklearn/tests/test_docstring_parameters.py index 9169f24310856..e6d2ade736f4a 100644 --- a/sklearn/tests/test_docstring_parameters.py +++ b/sklearn/tests/test_docstring_parameters.py @@ -154,29 +154,6 @@ def test_docstring_parameters(): raise AssertionError("Docstring Error:\n" + msg) -@ignore_warnings(category=FutureWarning) -def test_tabs(): - # Test that there are no tabs in our source files - for importer, modname, ispkg in walk_packages(sklearn.__path__, prefix="sklearn."): - if IS_PYPY and ( - "_svmlight_format_io" in modname - or "feature_extraction._hashing_fast" in modname - ): - continue - - # because we don't import - mod = importlib.import_module(modname) - - try: - source = inspect.getsource(mod) - except IOError: # user probably should have run "make clean" - continue - assert "\t" not in source, ( - '"%s" has tabs, please remove them ', - "or add it to the ignore list" % modname, - ) - - def _construct_searchcv_instance(SearchCV): return SearchCV(LogisticRegression(), {"C": [0.1, 1]})
This was noticed when working on Python 3.12 wheels in https://github.com/scikit-learn/scikit-learn/pull/27027. In Python 3.12 setuptools is not a core dependency `venv` (see [this](https://docs.python.org/3.12/library/venv.html#creating-virtual-environments)). As noted in https://github.com/scikit-learn/scikit-learn/pull/27027#issuecomment-1715046845, our test suite should not depend on setuptools. This PR: - remove `test_tabs` which is not useful since we are using black - avoids importing `sklearn._build_utils.pre_build_helpers` (which is the only module depending on setuptools) to check its `__all__` in test_import_all_consistency`
https://api.github.com/repos/scikit-learn/scikit-learn/pulls/27355
2023-09-13T09:55:00Z
2023-09-15T15:43:20Z
2023-09-15T15:43:20Z
2023-09-19T13:01:52Z
494
scikit-learn/scikit-learn
46,435
Fix problems with different test ordering
diff --git a/certbot/tests/cli_test.py b/certbot/tests/cli_test.py index 32aada811c2..b0eb965426b 100644 --- a/certbot/tests/cli_test.py +++ b/certbot/tests/cli_test.py @@ -1,12 +1,11 @@ """Tests for certbot.cli.""" import argparse -import functools import unittest import os import tempfile -import six import mock +import six from six.moves import reload_module # pylint: disable=import-error from certbot import cli @@ -14,9 +13,8 @@ from certbot import errors from certbot.plugins import disco -def reset_set_by_cli(): - '''Reset the state of the `set_by_cli` function''' - cli.set_by_cli.detector = None +PLUGINS = disco.PluginsRegistry.find_all() + class TestReadFile(unittest.TestCase): '''Test cli.read_file''' @@ -43,13 +41,13 @@ class ParseTest(unittest.TestCase): _multiprocess_can_split_ = True - @classmethod - def setUpClass(cls): - cls.plugins = disco.PluginsRegistry.find_all() - cls.parse = functools.partial(cli.prepare_and_parse_args, cls.plugins) - def setUp(self): - reset_set_by_cli() + reload_module(cli) + + @staticmethod + def parse(*args, **kwargs): + """Get result of cli.prepare_and_parse_args.""" + return cli.prepare_and_parse_args(PLUGINS, *args, **kwargs) def _help_output(self, args): "Run a command, and return the ouput string for scrutiny" @@ -88,7 +86,7 @@ def test_help(self): self.assertTrue("{0}" not in out) out = self._help_output(['-h', 'nginx']) - if "nginx" in self.plugins: + if "nginx" in PLUGINS: # may be false while building distributions without plugins self.assertTrue("--nginx-ctl" in out) self.assertTrue("--webroot-path" not in out) @@ -96,7 +94,7 @@ def test_help(self): out = self._help_output(['-h']) self.assertTrue("letsencrypt-auto" not in out) # test cli.cli_command - if "nginx" in self.plugins: + if "nginx" in PLUGINS: self.assertTrue("Use the Nginx plugin" in out) else: self.assertTrue("(the certbot nginx plugin is not" in out) diff --git a/certbot/tests/hook_test.py b/certbot/tests/hook_test.py index 87c86ad5cba..0fbb91492a3 100644 --- a/certbot/tests/hook_test.py +++ b/certbot/tests/hook_test.py @@ -5,16 +5,14 @@ import unittest import mock +from six.moves import reload_module # pylint: disable=import-error from certbot import errors from certbot import hooks class HookTest(unittest.TestCase): def setUp(self): - pass - - def tearDown(self): - pass + reload_module(hooks) @mock.patch('certbot.hooks._prog') def test_validate_hooks(self, mock_prog): @@ -47,7 +45,6 @@ def _test_a_hook(self, config, hook_function, calls_expected, **kwargs): return mock_logger.warning def test_pre_hook(self): - hooks.pre_hook.already = set() config = mock.MagicMock(pre_hook="true") self._test_a_hook(config, hooks.pre_hook, 1) self._test_a_hook(config, hooks.pre_hook, 0) diff --git a/certbot/tests/main_test.py b/certbot/tests/main_test.py index 01ec2f0611d..087a3615dcf 100644 --- a/certbot/tests/main_test.py +++ b/certbot/tests/main_test.py @@ -12,6 +12,7 @@ import pytz import six +from six.moves import reload_module # pylint: disable=import-error from acme import jose @@ -434,10 +435,9 @@ def setUp(self): '--logs-dir', self.logs_dir, '--text'] def tearDown(self): - shutil.rmtree(self.tmp_dir) # Reset globals in cli - # pylint: disable=protected-access - cli._parser = cli.set_by_cli.detector = None + reload_module(cli) + shutil.rmtree(self.tmp_dir) def _call(self, args, stdout=None): "Run the cli with output streams and actual client mocked out" @@ -874,8 +874,9 @@ def test_renew_no_hook_validation(self): test_util.make_lineage(self, 'sample-renewal.conf') args = ["renew", "--dry-run", "--post-hook=no-such-command", "--disable-hook-validation"] - self._test_renewal_common(True, [], args=args, should_renew=True, - error_expected=False) + with mock.patch("certbot.hooks.post_hook"): + self._test_renewal_common(True, [], args=args, should_renew=True, + error_expected=False) @mock.patch("certbot.cli.set_by_cli") def test_ancient_webroot_renewal_conf(self, mock_set_by_cli):
I went through our unit tests and looked at all non-constant global/static variables that I'm aware of. The ones I looked at are in `certbot/cli.py` and `certbot/hooks.py`. These variables are now properly cleaned up during tests so they don't affect other tests.
https://api.github.com/repos/certbot/certbot/pulls/4043
2017-01-13T01:49:08Z
2017-01-13T20:16:09Z
2017-01-13T20:16:09Z
2017-01-13T20:16:14Z
1,177
certbot/certbot
3,235
support xpu for ocr
diff --git a/tools/infer/utility.py b/tools/infer/utility.py index 6bcab27088..0bbc3b1db0 100644 --- a/tools/infer/utility.py +++ b/tools/infer/utility.py @@ -33,6 +33,7 @@ def init_args(): parser = argparse.ArgumentParser() # params for prediction engine parser.add_argument("--use_gpu", type=str2bool, default=True) + parser.add_argument("--use_xpu", type=str2bool, default=False) parser.add_argument("--ir_optim", type=str2bool, default=True) parser.add_argument("--use_tensorrt", type=str2bool, default=False) parser.add_argument("--min_subgraph_size", type=int, default=15) @@ -277,6 +278,8 @@ def create_predictor(args, mode, logger): config.set_trt_dynamic_shape_info( min_input_shape, max_input_shape, opt_input_shape) + elif args.use_xpu: + config.enable_xpu(10 * 1024 * 1024) else: config.disable_gpu() if hasattr(args, "cpu_threads"): @@ -630,7 +633,6 @@ def get_rotate_crop_image(img, points): def check_gpu(use_gpu): if use_gpu and not paddle.is_compiled_with_cuda(): - use_gpu = False return use_gpu diff --git a/tools/program.py b/tools/program.py index 1dfd06af8d..ae22d69acd 100755 --- a/tools/program.py +++ b/tools/program.py @@ -128,20 +128,25 @@ def merge_config(config): cur = cur[sub_key] -def check_gpu(use_gpu): +def check_device(use_gpu, use_xpu=False): """ Log error and exit when set use_gpu=true in paddlepaddle cpu version. """ - err = "Config use_gpu cannot be set as true while you are " \ - "using paddlepaddle cpu version ! \nPlease try: \n" \ - "\t1. Install paddlepaddle-gpu to run model on GPU \n" \ - "\t2. Set use_gpu as false in config file to run " \ + err = "Config {} cannot be set as true while your paddle " \ + "is not compiled with {} ! \nPlease try: \n" \ + "\t1. Install paddlepaddle to run model on {} \n" \ + "\t2. Set {} as false in config file to run " \ "model on CPU" try: + if use_gpu and use_xpu: + print("use_xpu and use_gpu can not both be ture.") if use_gpu and not paddle.is_compiled_with_cuda(): - print(err) + print(err.format("use_gpu", "cuda", "gpu", "use_gpu")) + sys.exit(1) + if use_xpu and not paddle.device.is_compiled_with_xpu(): + print(err.format("use_xpu", "xpu", "xpu", "use_xpu")) sys.exit(1) except Exception as e: pass @@ -266,7 +271,7 @@ def train(config, stats['lr'] = lr train_stats.update(stats) - if cal_metric_during_train and model_type is not "det": # only rec and cls need + if cal_metric_during_train and model_type is not "det": # only rec and cls need batch = [item.numpy() for item in batch] if model_type in ['table', 'kie']: eval_class(preds, batch) @@ -497,7 +502,7 @@ def preprocess(is_train=False): # check if set use_gpu=True in paddlepaddle cpu version use_gpu = config['Global']['use_gpu'] - check_gpu(use_gpu) + use_xpu = config['Global'].get('use_xpu', False) alg = config['Architecture']['algorithm'] assert alg in [ @@ -511,7 +516,13 @@ def preprocess(is_train=False): windows_not_support_list)) sys.exit() - device = 'gpu:{}'.format(dist.ParallelEnv().dev_id) if use_gpu else 'cpu' + if use_xpu: + device = 'xpu:{0}'.format(os.getenv('FLAGS_selected_xpus', 0)) + else: + device = 'gpu:{}'.format(dist.ParallelEnv() + .dev_id) if use_gpu else 'cpu' + check_device(use_gpu, use_xpu) + device = paddle.set_device(device) config['Global']['distributed'] = dist.get_world_size() != 1
use method : ``` python3.7 tools/train.py -c xxx.yaml -o Global.use_gpu=False Global.use_xpu=True ```
https://api.github.com/repos/PaddlePaddle/PaddleOCR/pulls/5967
2022-04-14T03:03:56Z
2022-04-14T03:13:17Z
2022-04-14T03:13:17Z
2022-05-12T12:15:53Z
1,034
PaddlePaddle/PaddleOCR
41,789