hexsha
stringlengths
40
40
repo
stringlengths
5
114
path
stringlengths
4
295
license
listlengths
1
10
language
stringclasses
5 values
identifier
stringlengths
1
116
original_docstring
stringlengths
133
7.85k
docstring
stringlengths
7
2.1k
docstring_tokens
listlengths
3
399
code
stringlengths
350
22.6k
code_tokens
listlengths
20
3.22k
short_docstring
stringlengths
0
1.32k
short_docstring_tokens
listlengths
0
359
comment
listlengths
0
1.22k
parameters
listlengths
0
13
docstring_params
dict
has_error
bool
1 class
ast_depth
int64
13
29
code_length
int64
151
3k
original_docstring_length
int64
76
449
f63a8d808cd9ea26c4519284d24017eeb26b7197
Cimpress-MCP/LambdaWrap
lib/lambda_wrap/environment.rb
[ "Apache-2.0" ]
Ruby
Environment
# Environment class to pass to the deploy and teardown # # @!attribute [r] name # @return [String] The descriptive name of the environment. # # @!attribute [r] description # @return [String] The description of the environment. # # @!attribute [r] variables # @return [Hash] The Hash of environment variables to deploy with the environment. # # @since 1.0
Environment class to pass to the deploy and teardown
[ "Environment", "class", "to", "pass", "to", "the", "deploy", "and", "teardown" ]
class Environment attr_reader :name attr_reader :description attr_reader :variables # Constructor # # @param name [String] Name of the environment. Corresponds to the Lambda Alias and API Gateway Stage. # Must be at least 3 characters, and no more than 20 characters. # @param variables [Hash] Environment variables to pass to the API Gateway stage. Must be a flat hash. # Each key must be Alphanumeric (underscores allowed) and no more than 64 characters. Values can have # most special characters, and no more than 512 characters. # @param description [String] Description of the environment for Stage & Alias descriptions. Must not # exceed 256 characters. def initialize(name, variables = {}, description = 'Managed by LambdaWrap') raise ArgumentError, 'name must be provided (String)!' unless name && name.is_a?(String) # Max Alias Name length is 20 characters. raise ArgumentError, "Invalid name format: #{name}" unless /^[a-zA-Z0-9\-\_]{3,20}$/ =~ name @name = name raise ArgumentError, 'Variables must be a Hash!' unless variables.is_a?(Hash) variables.each do |key, value| next if /^[0-9a-zA-Z\_]{1,64}$/ =~ key && /^[A-Za-z0-9\-.\_~:\/?#&=,]{1,512}$/ =~ value && value.is_a?(String) raise ArgumentError, "Invalid Format of variables hash: #{key} => #{value}" end variables[:environment] = name unless variables[:environment] @variables = variables raise ArgumentError, 'Description must be a String!' unless description.is_a?(String) raise ArgumentError, 'Description too long (Max 256)' unless description.length < 256 @description = description end def to_s return @name if @name && @name.is_a?(String) super end end
[ "class", "Environment", "attr_reader", ":name", "attr_reader", ":description", "attr_reader", ":variables", "def", "initialize", "(", "name", ",", "variables", "=", "{", "}", ",", "description", "=", "'Managed by LambdaWrap'", ")", "raise", "ArgumentError", ",", "'name must be provided (String)!'", "unless", "name", "&&", "name", ".", "is_a?", "(", "String", ")", "raise", "ArgumentError", ",", "\"Invalid name format: #{name}\"", "unless", "/", "^[a-zA-Z0-9", "\\-", "\\_", "]{3,20}$", "/", "=~", "name", "@name", "=", "name", "raise", "ArgumentError", ",", "'Variables must be a Hash!'", "unless", "variables", ".", "is_a?", "(", "Hash", ")", "variables", ".", "each", "do", "|", "key", ",", "value", "|", "next", "if", "/", "^[0-9a-zA-Z", "\\_", "]{1,64}$", "/", "=~", "key", "&&", "/", "^[A-Za-z0-9", "\\-", ".", "\\_", "~:", "\\/", "?#&=,]{1,512}$", "/", "=~", "value", "&&", "value", ".", "is_a?", "(", "String", ")", "raise", "ArgumentError", ",", "\"Invalid Format of variables hash: #{key} => #{value}\"", "end", "variables", "[", ":environment", "]", "=", "name", "unless", "variables", "[", ":environment", "]", "@variables", "=", "variables", "raise", "ArgumentError", ",", "'Description must be a String!'", "unless", "description", ".", "is_a?", "(", "String", ")", "raise", "ArgumentError", ",", "'Description too long (Max 256)'", "unless", "description", ".", "length", "<", "256", "@description", "=", "description", "end", "def", "to_s", "return", "@name", "if", "@name", "&&", "@name", ".", "is_a?", "(", "String", ")", "super", "end", "end" ]
Environment class to pass to the deploy and teardown
[ "Environment", "class", "to", "pass", "to", "the", "deploy", "and", "teardown" ]
[ "# Constructor", "#", "# @param name [String] Name of the environment. Corresponds to the Lambda Alias and API Gateway Stage.", "# Must be at least 3 characters, and no more than 20 characters.", "# @param variables [Hash] Environment variables to pass to the API Gateway stage. Must be a flat hash.", "# Each key must be Alphanumeric (underscores allowed) and no more than 64 characters. Values can have", "# most special characters, and no more than 512 characters.", "# @param description [String] Description of the environment for Stage & Alias descriptions. Must not", "# exceed 256 characters.", "# Max Alias Name length is 20 characters." ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [ { "identifier": "!attribute", "docstring": "[r] name @return [String] The descriptive name of the environment.", "docstring_tokens": [ "[", "r", "]", "name", "@return", "[", "String", "]", "The", "descriptive", "name", "of", "the", "environment", "." ] }, { "identifier": "!attribute", "docstring": "[r] description @return [String] The description of the environment.", "docstring_tokens": [ "[", "r", "]", "description", "@return", "[", "String", "]", "The", "description", "of", "the", "environment", "." ] }, { "identifier": "!attribute", "docstring": "[r] variables @return [Hash] The Hash of environment variables to deploy with the environment.", "docstring_tokens": [ "[", "r", "]", "variables", "@return", "[", "Hash", "]", "The", "Hash", "of", "environment", "variables", "to", "deploy", "with", "the", "environment", "." ] }, { "identifier": "since", "docstring": null, "docstring_tokens": [ "None" ] } ] }
false
13
457
94
e9cc72f623bac13c4f3eda3c684a78df2f1801ed
artlebedev/idea-parser3
main/src/ru/artlebedev/idea/plugins/parser/editor/settings/ParserProjectConfigurationForm.java
[ "Apache-2.0" ]
Java
ParserProjectConfigurationForm
/** * idea-parser3: the most advanced parser3 ide. * <p/> * Copyright 2011 <a href="mailto:[email protected]">Valeriy Yatsko</a> * Copyright 2006 <a href="mailto:[email protected]">Jay Bird</a> * Copyright 2006-2011 ArtLebedev Studio * <p/> * 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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. */
idea-parser3: the most advanced parser3 ide. Copyright 2011 Valeriy Yatsko Copyright 2006 Jay Bird Copyright 2006-2011 ArtLebedev Studio Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
[ "idea", "-", "parser3", ":", "the", "most", "advanced", "parser3", "ide", ".", "Copyright", "2011", "Valeriy", "Yatsko", "Copyright", "2006", "Jay", "Bird", "Copyright", "2006", "-", "2011", "ArtLebedev", "Studio", "Licensed", "under", "the", "Apache", "License", "Version", "2", ".", "0", "(", "the", "\"", "License", "\"", ")", ";", "you", "may", "not", "use", "this", "file", "except", "in", "compliance", "with", "the", "License", "." ]
public class ParserProjectConfigurationForm implements ActionListener, ListSelectionListener { private JPanel rootComponent; private JList pathList; private JButton addButton; private JButton removeButton; private JPanel listPlace; DefaultListModel model = new DefaultListModel(); public JPanel getRootComponent() { return rootComponent; } public void setData(ParserProjectConfiguration data) { List<String> paths = data.getClassPaths(); for (String path : paths) { model.addElement(path); } } public void getData(ParserProjectConfiguration data) { data.setClassPaths(getListValues()); } private List<String> getListValues() { List<String> result = new ArrayList<String>(); Object[] paths = model.toArray(); for (Object path : paths) { result.add((String) path); } return result; } public boolean isModified(ParserProjectConfiguration data) { return !data.getClassPaths().equals(getListValues()); } public void actionPerformed(ActionEvent actionEvent) { if (actionEvent.getActionCommand().equals("remove")) { int index = pathList.getSelectedIndex(); model.remove(index); int size = model.getSize(); if (size == 0) { removeButton.setEnabled(false); } else { if (index == model.getSize()) { index--; } pathList.setSelectedIndex(index); pathList.ensureIndexIsVisible(index); } } } public void setUp(final Project project) { pathList = new JList(model); pathList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); pathList.addListSelectionListener(this); JScrollPane pane = new JScrollPane(pathList); GridConstraints myConstraints = new GridConstraints(); myConstraints.setFill(GridConstraints.FILL_BOTH); listPlace.add(pane, myConstraints); // pane.set removeButton.setActionCommand("remove"); removeButton.addActionListener(this); MouseListener addClickListener = new MouseAdapter() { public void mouseClicked(MouseEvent mouseEvent) { FileChooserDescriptor descriptor = FileChooserDescriptorFactory.createSingleFolderDescriptor(); descriptor.setTitle("Parser class path"); descriptor.setDescription("Pick up a directory to add it to parser class path"); VirtualFile[] files = FileChooser.chooseFiles(descriptor, project, null); if (files.length != 0) { model.addElement(files[0].getPath()); } } }; addButton.addMouseListener(addClickListener); } public void valueChanged(ListSelectionEvent listSelectionEvent) { if (pathList.getSelectedIndex() == -1) { removeButton.setEnabled(false); } else { removeButton.setEnabled(true); } } }
[ "public", "class", "ParserProjectConfigurationForm", "implements", "ActionListener", ",", "ListSelectionListener", "{", "private", "JPanel", "rootComponent", ";", "private", "JList", "pathList", ";", "private", "JButton", "addButton", ";", "private", "JButton", "removeButton", ";", "private", "JPanel", "listPlace", ";", "DefaultListModel", "model", "=", "new", "DefaultListModel", "(", ")", ";", "public", "JPanel", "getRootComponent", "(", ")", "{", "return", "rootComponent", ";", "}", "public", "void", "setData", "(", "ParserProjectConfiguration", "data", ")", "{", "List", "<", "String", ">", "paths", "=", "data", ".", "getClassPaths", "(", ")", ";", "for", "(", "String", "path", ":", "paths", ")", "{", "model", ".", "addElement", "(", "path", ")", ";", "}", "}", "public", "void", "getData", "(", "ParserProjectConfiguration", "data", ")", "{", "data", ".", "setClassPaths", "(", "getListValues", "(", ")", ")", ";", "}", "private", "List", "<", "String", ">", "getListValues", "(", ")", "{", "List", "<", "String", ">", "result", "=", "new", "ArrayList", "<", "String", ">", "(", ")", ";", "Object", "[", "]", "paths", "=", "model", ".", "toArray", "(", ")", ";", "for", "(", "Object", "path", ":", "paths", ")", "{", "result", ".", "add", "(", "(", "String", ")", "path", ")", ";", "}", "return", "result", ";", "}", "public", "boolean", "isModified", "(", "ParserProjectConfiguration", "data", ")", "{", "return", "!", "data", ".", "getClassPaths", "(", ")", ".", "equals", "(", "getListValues", "(", ")", ")", ";", "}", "public", "void", "actionPerformed", "(", "ActionEvent", "actionEvent", ")", "{", "if", "(", "actionEvent", ".", "getActionCommand", "(", ")", ".", "equals", "(", "\"", "remove", "\"", ")", ")", "{", "int", "index", "=", "pathList", ".", "getSelectedIndex", "(", ")", ";", "model", ".", "remove", "(", "index", ")", ";", "int", "size", "=", "model", ".", "getSize", "(", ")", ";", "if", "(", "size", "==", "0", ")", "{", "removeButton", ".", "setEnabled", "(", "false", ")", ";", "}", "else", "{", "if", "(", "index", "==", "model", ".", "getSize", "(", ")", ")", "{", "index", "--", ";", "}", "pathList", ".", "setSelectedIndex", "(", "index", ")", ";", "pathList", ".", "ensureIndexIsVisible", "(", "index", ")", ";", "}", "}", "}", "public", "void", "setUp", "(", "final", "Project", "project", ")", "{", "pathList", "=", "new", "JList", "(", "model", ")", ";", "pathList", ".", "setSelectionMode", "(", "ListSelectionModel", ".", "SINGLE_SELECTION", ")", ";", "pathList", ".", "addListSelectionListener", "(", "this", ")", ";", "JScrollPane", "pane", "=", "new", "JScrollPane", "(", "pathList", ")", ";", "GridConstraints", "myConstraints", "=", "new", "GridConstraints", "(", ")", ";", "myConstraints", ".", "setFill", "(", "GridConstraints", ".", "FILL_BOTH", ")", ";", "listPlace", ".", "add", "(", "pane", ",", "myConstraints", ")", ";", "removeButton", ".", "setActionCommand", "(", "\"", "remove", "\"", ")", ";", "removeButton", ".", "addActionListener", "(", "this", ")", ";", "MouseListener", "addClickListener", "=", "new", "MouseAdapter", "(", ")", "{", "public", "void", "mouseClicked", "(", "MouseEvent", "mouseEvent", ")", "{", "FileChooserDescriptor", "descriptor", "=", "FileChooserDescriptorFactory", ".", "createSingleFolderDescriptor", "(", ")", ";", "descriptor", ".", "setTitle", "(", "\"", "Parser class path", "\"", ")", ";", "descriptor", ".", "setDescription", "(", "\"", "Pick up a directory to add it to parser class path", "\"", ")", ";", "VirtualFile", "[", "]", "files", "=", "FileChooser", ".", "chooseFiles", "(", "descriptor", ",", "project", ",", "null", ")", ";", "if", "(", "files", ".", "length", "!=", "0", ")", "{", "model", ".", "addElement", "(", "files", "[", "0", "]", ".", "getPath", "(", ")", ")", ";", "}", "}", "}", ";", "addButton", ".", "addMouseListener", "(", "addClickListener", ")", ";", "}", "public", "void", "valueChanged", "(", "ListSelectionEvent", "listSelectionEvent", ")", "{", "if", "(", "pathList", ".", "getSelectedIndex", "(", ")", "==", "-", "1", ")", "{", "removeButton", ".", "setEnabled", "(", "false", ")", ";", "}", "else", "{", "removeButton", ".", "setEnabled", "(", "true", ")", ";", "}", "}", "}" ]
idea-parser3: the most advanced parser3 ide.
[ "idea", "-", "parser3", ":", "the", "most", "advanced", "parser3", "ide", "." ]
[ "//\t\tpane.set" ]
[ { "param": "ActionListener, ListSelectionListener", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "ActionListener, ListSelectionListener", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
18
553
214
9779ca729d68f6f3903f8ec0a5df1ff1364f10e4
aTiKhan/CommunityServer
module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/Message/SIP_t_NameAddress.cs
[ "ECL-2.0", "Apache-2.0", "MIT" ]
C#
SIP_t_NameAddress
/// <summary> /// Implements SIP "name-addr" value. Defined in RFC 3261. /// </summary> /// <remarks> /// <code> /// RFC 3261 Syntax: /// name-addr = [ display-name ] LAQUOT addr-spec RAQUOT /// addr-spec = SIP-URI / SIPS-URI / absoluteURI /// </code> /// </remarks>
Implements SIP "name-addr" value. Defined in RFC 3261.
[ "Implements", "SIP", "\"", "name", "-", "addr", "\"", "value", ".", "Defined", "in", "RFC", "3261", "." ]
public class SIP_t_NameAddress { #region Members private string m_DisplayName = ""; private AbsoluteUri m_pUri; #endregion #region Properties public string DisplayName { get { return m_DisplayName; } set { if (value == null) { value = ""; } m_DisplayName = value; } } public AbsoluteUri Uri { get { return m_pUri; } set { if (value == null) { throw new ArgumentNullException("value"); } m_pUri = value; } } public bool IsSipOrSipsUri { get { return IsSipUri || IsSecureSipUri; } } public bool IsSipUri { get { if (m_pUri.Scheme == UriSchemes.sip) { return true; } return false; } } public bool IsSecureSipUri { get { if (m_pUri.Scheme == UriSchemes.sips) { return true; } return false; } } public bool IsMailToUri { get { if (m_pUri.Scheme == UriSchemes.mailto) { return true; } return false; } } #endregion #region Constructor public SIP_t_NameAddress() {} public SIP_t_NameAddress(string value) { Parse(value); } public SIP_t_NameAddress(string displayName, AbsoluteUri uri) { if (uri == null) { throw new ArgumentNullException("uri"); } DisplayName = displayName; Uri = uri; } #endregion #region Methods public void Parse(string value) { if (value == null) { throw new ArgumentNullException("reader"); } Parse(new StringReader(value)); } public void Parse(StringReader reader) { if (reader == null) { throw new ArgumentNullException("reader"); } reader.ReadToFirstChar(); if (reader.StartsWith("<")) { m_pUri = AbsoluteUri.Parse(reader.ReadParenthesized()); } else { string word = reader.ReadWord(); if (word == null) { throw new SIP_ParseException("Invalid 'name-addr' or 'addr-spec' value !"); } reader.ReadToFirstChar(); if (reader.StartsWith("<")) { m_DisplayName = word; m_pUri = AbsoluteUri.Parse(reader.ReadParenthesized()); } else { m_pUri = AbsoluteUri.Parse(word); } } } public string ToStringValue() { if (string.IsNullOrEmpty(m_DisplayName)) { return "<" + m_pUri + ">"; } else { return TextUtils.QuoteString(m_DisplayName) + " <" + m_pUri + ">"; } } #endregion }
[ "public", "class", "SIP_t_NameAddress", "{", "region", " Members", "private", "string", "m_DisplayName", "=", "\"", "\"", ";", "private", "AbsoluteUri", "m_pUri", ";", "endregion", "region", " Properties", "public", "string", "DisplayName", "{", "get", "{", "return", "m_DisplayName", ";", "}", "set", "{", "if", "(", "value", "==", "null", ")", "{", "value", "=", "\"", "\"", ";", "}", "m_DisplayName", "=", "value", ";", "}", "}", "public", "AbsoluteUri", "Uri", "{", "get", "{", "return", "m_pUri", ";", "}", "set", "{", "if", "(", "value", "==", "null", ")", "{", "throw", "new", "ArgumentNullException", "(", "\"", "value", "\"", ")", ";", "}", "m_pUri", "=", "value", ";", "}", "}", "public", "bool", "IsSipOrSipsUri", "{", "get", "{", "return", "IsSipUri", "||", "IsSecureSipUri", ";", "}", "}", "public", "bool", "IsSipUri", "{", "get", "{", "if", "(", "m_pUri", ".", "Scheme", "==", "UriSchemes", ".", "sip", ")", "{", "return", "true", ";", "}", "return", "false", ";", "}", "}", "public", "bool", "IsSecureSipUri", "{", "get", "{", "if", "(", "m_pUri", ".", "Scheme", "==", "UriSchemes", ".", "sips", ")", "{", "return", "true", ";", "}", "return", "false", ";", "}", "}", "public", "bool", "IsMailToUri", "{", "get", "{", "if", "(", "m_pUri", ".", "Scheme", "==", "UriSchemes", ".", "mailto", ")", "{", "return", "true", ";", "}", "return", "false", ";", "}", "}", "endregion", "region", " Constructor", "public", "SIP_t_NameAddress", "(", ")", "{", "}", "public", "SIP_t_NameAddress", "(", "string", "value", ")", "{", "Parse", "(", "value", ")", ";", "}", "public", "SIP_t_NameAddress", "(", "string", "displayName", ",", "AbsoluteUri", "uri", ")", "{", "if", "(", "uri", "==", "null", ")", "{", "throw", "new", "ArgumentNullException", "(", "\"", "uri", "\"", ")", ";", "}", "DisplayName", "=", "displayName", ";", "Uri", "=", "uri", ";", "}", "endregion", "region", " Methods", "public", "void", "Parse", "(", "string", "value", ")", "{", "if", "(", "value", "==", "null", ")", "{", "throw", "new", "ArgumentNullException", "(", "\"", "reader", "\"", ")", ";", "}", "Parse", "(", "new", "StringReader", "(", "value", ")", ")", ";", "}", "public", "void", "Parse", "(", "StringReader", "reader", ")", "{", "if", "(", "reader", "==", "null", ")", "{", "throw", "new", "ArgumentNullException", "(", "\"", "reader", "\"", ")", ";", "}", "reader", ".", "ReadToFirstChar", "(", ")", ";", "if", "(", "reader", ".", "StartsWith", "(", "\"", "<", "\"", ")", ")", "{", "m_pUri", "=", "AbsoluteUri", ".", "Parse", "(", "reader", ".", "ReadParenthesized", "(", ")", ")", ";", "}", "else", "{", "string", "word", "=", "reader", ".", "ReadWord", "(", ")", ";", "if", "(", "word", "==", "null", ")", "{", "throw", "new", "SIP_ParseException", "(", "\"", "Invalid 'name-addr' or 'addr-spec' value !", "\"", ")", ";", "}", "reader", ".", "ReadToFirstChar", "(", ")", ";", "if", "(", "reader", ".", "StartsWith", "(", "\"", "<", "\"", ")", ")", "{", "m_DisplayName", "=", "word", ";", "m_pUri", "=", "AbsoluteUri", ".", "Parse", "(", "reader", ".", "ReadParenthesized", "(", ")", ")", ";", "}", "else", "{", "m_pUri", "=", "AbsoluteUri", ".", "Parse", "(", "word", ")", ";", "}", "}", "}", "public", "string", "ToStringValue", "(", ")", "{", "if", "(", "string", ".", "IsNullOrEmpty", "(", "m_DisplayName", ")", ")", "{", "return", "\"", "<", "\"", "+", "m_pUri", "+", "\"", ">", "\"", ";", "}", "else", "{", "return", "TextUtils", ".", "QuoteString", "(", "m_DisplayName", ")", "+", "\"", " <", "\"", "+", "m_pUri", "+", "\"", ">", "\"", ";", "}", "}", "endregion", "}" ]
Implements SIP "name-addr" value.
[ "Implements", "SIP", "\"", "name", "-", "addr", "\"", "value", "." ]
[ "/// <summary>", "/// Gets or sets display name.", "/// </summary>", "/// <summary>", "/// Gets or sets URI. This can be SIP-URI / SIPS-URI / absoluteURI.", "/// Examples: sip:[email protected],sips:[email protected],mailto:[email protected], .... .", "/// </summary>", "/// <exception cref=\"ArgumentNullException\">Is raised when null reference passed.</exception>", "/// <summary>", "/// Gets if current URI is sip or sips URI.", "/// </summary>", "/// <summary>", "/// Gets if current URI is SIP uri.", "/// </summary>", "/// <summary>", "/// Gets if current URI is SIPS uri.", "/// </summary>", "/// <summary>", "/// Gets if current URI is MAILTO uri.", "/// </summary>", "/// <summary>", "/// Default constructor.", "/// </summary>", "/// <summary>", "/// Default constructor.", "/// </summary>", "/// <param name=\"value\">SIP <b>name-addr</b> value.</param>", "/// <exception cref=\"ArgumentNullException\">Raised when <b>reader</b> is null.</exception>", "/// <exception cref=\"SIP_ParseException\">Raised when invalid SIP message.</exception>", "/// <summary>", "/// Default constructor.", "/// </summary>", "/// <param name=\"displayName\">Display name.</param>", "/// <param name=\"uri\">Uri.</param>", "/// <exception cref=\"ArgumentNullException\">Is raised when <b>uri</b> is null reference.</exception>", "/// <summary>", "/// Parses \"name-addr\" or \"addr-spec\" from specified value.", "/// </summary>", "/// <param name=\"value\">SIP \"name-addr\" or \"addr-spec\" value.</param>", "/// <exception cref=\"ArgumentNullException\">Raised when <b>reader</b> is null.</exception>", "/// <exception cref=\"SIP_ParseException\">Raised when invalid SIP message.</exception>", "/// <summary>", "/// Parses \"name-addr\" or \"addr-spec\" from specified reader.", "/// </summary>", "/// <param name=\"reader\">Reader from where to parse.</param>", "/// <exception cref=\"ArgumentNullException\">Raised when <b>reader</b> is null.</exception>", "/// <exception cref=\"SIP_ParseException\">Raised when invalid SIP message.</exception>", "/* RFC 3261.\n name-addr = [ display-name ] LAQUOT addr-spec RAQUOT\n addr-spec = SIP-URI / SIPS-URI / absoluteURI\n */", "// LAQUOT addr-spec RAQUOT", "// name-addr", "// addr-spec", "/// <summary>", "/// Converts this to valid name-addr or addr-spec string as needed.", "/// </summary>", "/// <returns>Returns name-addr or addr-spec string.</returns>", "/* RFC 3261.\n name-addr = [ display-name ] LAQUOT addr-spec RAQUOT\n addr-spec = SIP-URI / SIPS-URI / absoluteURI\n */", "// addr-spec", "// name-addr" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [ { "identifier": "remarks", "docstring": "RFC 3261 Syntax:\nname-addr = [ display-name ] LAQUOT addr-spec RAQUOT\naddr-spec = SIP-URI / SIPS-URI / absoluteURI", "docstring_tokens": [ "RFC", "3261", "Syntax", ":", "name", "-", "addr", "=", "[", "display", "-", "name", "]", "LAQUOT", "addr", "-", "spec", "RAQUOT", "addr", "-", "spec", "=", "SIP", "-", "URI", "/", "SIPS", "-", "URI", "/", "absoluteURI" ] } ] }
false
16
659
88
e851d52723e1fdd1ce7c0875adcf8154781888d3
szymek22/AxonFramework
core/src/main/java/org/axonframework/common/property/PropertyAccessStrategy.java
[ "Apache-2.0" ]
Java
PropertyAccessStrategy
/** * Abstract Strategy that provides access to all PropertyAccessStrategy implementations. * <p/> * Application developers may provide custom PropertyAccessStrategy implementations using the ServiceLoader * mechanism. To do so, place a file called {@code org.axonframework.common.property.PropertyAccessStrategy} * in the {@code META-INF/services} folder. In this file, place the fully qualified class names of all available * implementations. * <p/> * The factory implementations must be public, non-abstract, have a default public constructor and extend the * PropertyAccessStrategy class. * <p/> * Note that this class is not considered public API and may undergo incompatible changes between versions. * * @author Maxim Fedorov * @author Allard Buijze * @see java.util.ServiceLoader * @see java.util.ServiceLoader#load(Class) * @since 2.0 */
Abstract Strategy that provides access to all PropertyAccessStrategy implementations. Application developers may provide custom PropertyAccessStrategy implementations using the ServiceLoader mechanism. To do so, place a file called org.axonframework.common.property.PropertyAccessStrategy in the META-INF/services folder. In this file, place the fully qualified class names of all available implementations. The factory implementations must be public, non-abstract, have a default public constructor and extend the PropertyAccessStrategy class. Note that this class is not considered public API and may undergo incompatible changes between versions.
[ "Abstract", "Strategy", "that", "provides", "access", "to", "all", "PropertyAccessStrategy", "implementations", ".", "Application", "developers", "may", "provide", "custom", "PropertyAccessStrategy", "implementations", "using", "the", "ServiceLoader", "mechanism", ".", "To", "do", "so", "place", "a", "file", "called", "org", ".", "axonframework", ".", "common", ".", "property", ".", "PropertyAccessStrategy", "in", "the", "META", "-", "INF", "/", "services", "folder", ".", "In", "this", "file", "place", "the", "fully", "qualified", "class", "names", "of", "all", "available", "implementations", ".", "The", "factory", "implementations", "must", "be", "public", "non", "-", "abstract", "have", "a", "default", "public", "constructor", "and", "extend", "the", "PropertyAccessStrategy", "class", ".", "Note", "that", "this", "class", "is", "not", "considered", "public", "API", "and", "may", "undergo", "incompatible", "changes", "between", "versions", "." ]
public abstract class PropertyAccessStrategy implements Comparable<PropertyAccessStrategy> { private static final ServiceLoader<PropertyAccessStrategy> LOADER = ServiceLoader.load(PropertyAccessStrategy.class); private static final SortedSet<PropertyAccessStrategy> STRATEGIES = new ConcurrentSkipListSet<>(); static { for (PropertyAccessStrategy factory : LOADER) { STRATEGIES.add(factory); } } /** * Registers a PropertyAccessStrategy implementation at runtime. * Annotated handlers that have already been inspected will not be able to use the newly added strategy. * * @param strategy implementation to register */ public static void register(PropertyAccessStrategy strategy) { STRATEGIES.add(strategy); } /** * Removes all strategies registered using the {@link #register(PropertyAccessStrategy)} method. * * @param strategy The strategy instance to unregister */ public static void unregister(PropertyAccessStrategy strategy) { STRATEGIES.remove(strategy); } /** * Iterates over all known PropertyAccessStrategy implementations to create a {@link Property} instance for the * given parameters. Strategies are invoked in the order they are found on the classpath. The first to provide a * suitable Property instance will be used. * * @param targetClass class that contains property * @param propertyName name of the property to create propertyReader for * @param <T> Thy type defining the property * @return suitable {@link Property}, or {@code null} if none is found */ public static <T> Property<T> getProperty(Class<? extends T> targetClass, String propertyName) { Property<T> property = null; Iterator<PropertyAccessStrategy> strategies = STRATEGIES.iterator(); while (property == null && strategies.hasNext()) { property = strategies.next().propertyFor(targetClass, propertyName); } return property; } @Override public final int compareTo(PropertyAccessStrategy o) { if (o == this) { return 0; } final int diff = o.getPriority() - getPriority(); if (diff == 0) { // we don't want equality... return getClass().getName().compareTo(o.getClass().getName()); } return diff; } /** * The priority of this strategy. In general, implementations that have a higher certainty to provide a good * Property instance for any given property name should have a higher priority. When two instances have the same * priority, their relative order is undefined. * <p/> * The JavaBean Property strategy has a value of 0. To ensure evaluation before that strategy, use any value higher * than that number, otherwise lower. * * @return a value reflecting relative priority, {@code Integer.MAX_VALUE} being evaluated first */ protected abstract int getPriority(); /** * Returns a Property instance for the given {@code property}, defined in given * {@code targetClass}, or {@code null} if no such property is found on the class. * * @param targetClass The class on which to find the property * @param property The name of the property to find * @param <T> The type of class on which to find the property * @return the Property instance providing access to the property value, or {@code null} if property could not * be found. */ protected abstract <T> Property<T> propertyFor(Class<? extends T> targetClass, String property); }
[ "public", "abstract", "class", "PropertyAccessStrategy", "implements", "Comparable", "<", "PropertyAccessStrategy", ">", "{", "private", "static", "final", "ServiceLoader", "<", "PropertyAccessStrategy", ">", "LOADER", "=", "ServiceLoader", ".", "load", "(", "PropertyAccessStrategy", ".", "class", ")", ";", "private", "static", "final", "SortedSet", "<", "PropertyAccessStrategy", ">", "STRATEGIES", "=", "new", "ConcurrentSkipListSet", "<", ">", "(", ")", ";", "static", "{", "for", "(", "PropertyAccessStrategy", "factory", ":", "LOADER", ")", "{", "STRATEGIES", ".", "add", "(", "factory", ")", ";", "}", "}", "/**\n * Registers a PropertyAccessStrategy implementation at runtime.\n * Annotated handlers that have already been inspected will not be able to use the newly added strategy.\n *\n * @param strategy implementation to register\n */", "public", "static", "void", "register", "(", "PropertyAccessStrategy", "strategy", ")", "{", "STRATEGIES", ".", "add", "(", "strategy", ")", ";", "}", "/**\n * Removes all strategies registered using the {@link #register(PropertyAccessStrategy)} method.\n *\n * @param strategy The strategy instance to unregister\n */", "public", "static", "void", "unregister", "(", "PropertyAccessStrategy", "strategy", ")", "{", "STRATEGIES", ".", "remove", "(", "strategy", ")", ";", "}", "/**\n * Iterates over all known PropertyAccessStrategy implementations to create a {@link Property} instance for the\n * given parameters. Strategies are invoked in the order they are found on the classpath. The first to provide a\n * suitable Property instance will be used.\n *\n * @param targetClass class that contains property\n * @param propertyName name of the property to create propertyReader for\n * @param <T> Thy type defining the property\n * @return suitable {@link Property}, or {@code null} if none is found\n */", "public", "static", "<", "T", ">", "Property", "<", "T", ">", "getProperty", "(", "Class", "<", "?", "extends", "T", ">", "targetClass", ",", "String", "propertyName", ")", "{", "Property", "<", "T", ">", "property", "=", "null", ";", "Iterator", "<", "PropertyAccessStrategy", ">", "strategies", "=", "STRATEGIES", ".", "iterator", "(", ")", ";", "while", "(", "property", "==", "null", "&&", "strategies", ".", "hasNext", "(", ")", ")", "{", "property", "=", "strategies", ".", "next", "(", ")", ".", "propertyFor", "(", "targetClass", ",", "propertyName", ")", ";", "}", "return", "property", ";", "}", "@", "Override", "public", "final", "int", "compareTo", "(", "PropertyAccessStrategy", "o", ")", "{", "if", "(", "o", "==", "this", ")", "{", "return", "0", ";", "}", "final", "int", "diff", "=", "o", ".", "getPriority", "(", ")", "-", "getPriority", "(", ")", ";", "if", "(", "diff", "==", "0", ")", "{", "return", "getClass", "(", ")", ".", "getName", "(", ")", ".", "compareTo", "(", "o", ".", "getClass", "(", ")", ".", "getName", "(", ")", ")", ";", "}", "return", "diff", ";", "}", "/**\n * The priority of this strategy. In general, implementations that have a higher certainty to provide a good\n * Property instance for any given property name should have a higher priority. When two instances have the same\n * priority, their relative order is undefined.\n * <p/>\n * The JavaBean Property strategy has a value of 0. To ensure evaluation before that strategy, use any value higher\n * than that number, otherwise lower.\n *\n * @return a value reflecting relative priority, {@code Integer.MAX_VALUE} being evaluated first\n */", "protected", "abstract", "int", "getPriority", "(", ")", ";", "/**\n * Returns a Property instance for the given {@code property}, defined in given\n * {@code targetClass}, or {@code null} if no such property is found on the class.\n *\n * @param targetClass The class on which to find the property\n * @param property The name of the property to find\n * @param <T> The type of class on which to find the property\n * @return the Property instance providing access to the property value, or {@code null} if property could not\n * be found.\n */", "protected", "abstract", "<", "T", ">", "Property", "<", "T", ">", "propertyFor", "(", "Class", "<", "?", "extends", "T", ">", "targetClass", ",", "String", "property", ")", ";", "}" ]
Abstract Strategy that provides access to all PropertyAccessStrategy implementations.
[ "Abstract", "Strategy", "that", "provides", "access", "to", "all", "PropertyAccessStrategy", "implementations", "." ]
[ "// we don't want equality..." ]
[ { "param": "Comparable<PropertyAccessStrategy>", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Comparable<PropertyAccessStrategy>", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
13
756
184
52885737beb243dee705f189e1b96fc4a76f0f76
xuefengwork/weka
src/main/java/weka/filters/unsupervised/attribute/RemoveByName.java
[ "PostgreSQL", "DOC" ]
Java
RemoveByName
/** * <!-- globalinfo-start --> Removes attributes based on a regular expression * matched against their names. * <p/> * <!-- globalinfo-end --> * * <!-- options-start --> Valid options are: * <p/> * * <pre> * -D * Turns on output of debugging information. * </pre> * * <pre> * -E &lt;regular expression&gt; * The regular expression to match the attribute names against. * (default: ^.*id$) * </pre> * * <pre> * -V * Flag for inverting the matching sense. If set, attributes are kept * instead of deleted. * (default: off) * </pre> * * <!-- options-end --> * * @author FracPete (fracpete at waikato dot ac dot nz) * @version $Revision: 14508 $ */
Removes attributes based on a regular expression matched against their names. Valid options are: -D Turns on output of debugging information. -E <regular expression> The regular expression to match the attribute names against. -V Flag for inverting the matching sense. If set, attributes are kept instead of deleted. (default: off) @author FracPete (fracpete at waikato dot ac dot nz) @version $Revision: 14508 $
[ "Removes", "attributes", "based", "on", "a", "regular", "expression", "matched", "against", "their", "names", ".", "Valid", "options", "are", ":", "-", "D", "Turns", "on", "output", "of", "debugging", "information", ".", "-", "E", "<regular", "expression", ">", "The", "regular", "expression", "to", "match", "the", "attribute", "names", "against", ".", "-", "V", "Flag", "for", "inverting", "the", "matching", "sense", ".", "If", "set", "attributes", "are", "kept", "instead", "of", "deleted", ".", "(", "default", ":", "off", ")", "@author", "FracPete", "(", "fracpete", "at", "waikato", "dot", "ac", "dot", "nz", ")", "@version", "$Revision", ":", "14508", "$" ]
public class RemoveByName extends SimpleStreamFilter implements WeightedInstancesHandler, WeightedAttributesHandler { /** for serialization. */ private static final long serialVersionUID = -3335106965521265631L; /** the default expression. */ public final static String DEFAULT_EXPRESSION = "^.*id$"; /** the regular expression for selecting the attributes by name. */ protected String m_Expression = DEFAULT_EXPRESSION; /** whether to invert the matching sense. */ protected boolean m_InvertSelection; /** the Remove filter used internally for removing the attributes. */ protected Remove m_Remove; /** * Returns a string describing this classifier. * * @return a description of the classifier suitable for displaying in the * explorer/experimenter gui */ @Override public String globalInfo() { return "Removes attributes based on a regular expression matched against " + "their names but will not remove the class attribute."; } /** * Gets an enumeration describing the available options. * * @return an enumeration of all the available options. */ @Override public Enumeration<Option> listOptions() { Vector<Option> result = new Vector<Option>(2); result.addElement(new Option( "\tThe regular expression to match the attribute names against.\n" + "\t(default: " + DEFAULT_EXPRESSION + ")", "E", 1, "-E <regular expression>")); result.addElement(new Option( "\tFlag for inverting the matching sense. If set, attributes are kept\n" + "\tinstead of deleted.\n" + "\t(default: off)", "V", 0, "-V")); result.addAll(Collections.list(super.listOptions())); return result.elements(); } /** * returns the options of the current setup. * * @return the current options */ @Override public String[] getOptions() { Vector<String> result = new Vector<String>(); result.add("-E"); result.add("" + getExpression()); if (getInvertSelection()) { result.add("-V"); } Collections.addAll(result, super.getOptions()); return result.toArray(new String[result.size()]); } /** * Parses the options for this object. * <p/> * * <!-- options-start --> Valid options are: * <p/> * * <pre> * -D * Turns on output of debugging information. * </pre> * * <pre> * -E &lt;regular expression&gt; * The regular expression to match the attribute names against. * (default: ^.*id$) * </pre> * * <pre> * -V * Flag for inverting the matching sense. If set, attributes are kept * instead of deleted. * (default: off) * </pre> * * <!-- options-end --> * * @param options the options to use * @throws Exception if the option setting fails */ @Override public void setOptions(String[] options) throws Exception { String tmpStr = Utils.getOption("E", options); if (tmpStr.length() != 0) { setExpression(tmpStr); } else { setExpression(DEFAULT_EXPRESSION); } setInvertSelection(Utils.getFlag("V", options)); super.setOptions(options); Utils.checkForRemainingOptions(options); } /** * Sets the regular expression to match the attribute names against. * * @param value the regular expression */ public void setExpression(String value) { m_Expression = value; } /** * Returns the regular expression in use. * * @return the regular expression */ public String getExpression() { return m_Expression; } /** * Returns the tip text for this property. * * @return tip text for this property suitable for displaying in the * explorer/experimenter gui */ public String expressionTipText() { return "The regular expression to match the attribute names against."; } /** * Set whether selected columns should be removed or kept. If true the * selected columns are kept and unselected columns are deleted. If false * selected columns are deleted and unselected columns are kept. * * @param value the new invert setting */ public void setInvertSelection(boolean value) { m_InvertSelection = value; } /** * Get whether the supplied columns are to be removed or kept. * * @return true if the supplied columns will be kept */ public boolean getInvertSelection() { return m_InvertSelection; } /** * Returns the tip text for this property. * * @return tip text for this property suitable for displaying in the * explorer/experimenter gui */ public String invertSelectionTipText() { return "Determines whether action is to select or delete." + " If set to true, only the specified attributes will be kept;" + " If set to false, specified attributes will be deleted."; } /** * Determines the output format based on the input format and returns this. In * case the output format cannot be returned immediately, i.e., * immediateOutputFormat() returns false, then this method will be called from * batchFinished(). * * @param inputFormat the input format to base the output format on * @return the output format * @throws Exception in case the determination goes wrong */ @Override protected Instances determineOutputFormat(Instances inputFormat) throws Exception { // determine indices Vector<Integer> indices = new Vector<Integer>(); for (int i = 0; i < inputFormat.numAttributes(); i++) { // always leave class if set if ((i == inputFormat.classIndex())) { if (getInvertSelection()) { indices.add(i); } continue; } if (inputFormat.attribute(i).name().matches(m_Expression)) { indices.add(i); } } int[] attributes = new int[indices.size()]; for (int i = 0; i < indices.size(); i++) { attributes[i] = indices.get(i); } m_Remove = new Remove(); m_Remove.setAttributeIndicesArray(attributes); m_Remove.setInvertSelection(getInvertSelection()); m_Remove.setInputFormat(inputFormat); return m_Remove.getOutputFormat(); } /** * Returns the Capabilities of this filter. * * @return the capabilities of this object * @see Capabilities */ @Override public Capabilities getCapabilities() { Capabilities result; result = new Remove().getCapabilities(); result.setOwner(this); return result; } /** * processes the given instance (may change the provided instance) and returns * the modified version. * * @param instance the instance to process * @return the modified data * @throws Exception in case the processing goes wrong */ @Override protected Instance process(Instance instance) throws Exception { m_Remove.input(instance); return m_Remove.output(); } /** * Returns the revision string. * * @return the revision */ @Override public String getRevision() { return RevisionUtils.extract("$Revision: 14508 $"); } /** * runs the filter with the given arguments. * * @param args the commandline arguments */ public static void main(String[] args) { runFilter(new RemoveByName(), args); } }
[ "public", "class", "RemoveByName", "extends", "SimpleStreamFilter", "implements", "WeightedInstancesHandler", ",", "WeightedAttributesHandler", "{", "/** for serialization. */", "private", "static", "final", "long", "serialVersionUID", "=", "-", "3335106965521265631L", ";", "/** the default expression. */", "public", "final", "static", "String", "DEFAULT_EXPRESSION", "=", "\"", "^.*id$", "\"", ";", "/** the regular expression for selecting the attributes by name. */", "protected", "String", "m_Expression", "=", "DEFAULT_EXPRESSION", ";", "/** whether to invert the matching sense. */", "protected", "boolean", "m_InvertSelection", ";", "/** the Remove filter used internally for removing the attributes. */", "protected", "Remove", "m_Remove", ";", "/**\n * Returns a string describing this classifier.\n * \n * @return a description of the classifier suitable for displaying in the\n * explorer/experimenter gui\n */", "@", "Override", "public", "String", "globalInfo", "(", ")", "{", "return", "\"", "Removes attributes based on a regular expression matched against ", "\"", "+", "\"", "their names but will not remove the class attribute.", "\"", ";", "}", "/**\n * Gets an enumeration describing the available options.\n * \n * @return an enumeration of all the available options.\n */", "@", "Override", "public", "Enumeration", "<", "Option", ">", "listOptions", "(", ")", "{", "Vector", "<", "Option", ">", "result", "=", "new", "Vector", "<", "Option", ">", "(", "2", ")", ";", "result", ".", "addElement", "(", "new", "Option", "(", "\"", "\\t", "The regular expression to match the attribute names against.", "\\n", "\"", "+", "\"", "\\t", "(default: ", "\"", "+", "DEFAULT_EXPRESSION", "+", "\"", ")", "\"", ",", "\"", "E", "\"", ",", "1", ",", "\"", "-E <regular expression>", "\"", ")", ")", ";", "result", ".", "addElement", "(", "new", "Option", "(", "\"", "\\t", "Flag for inverting the matching sense. If set, attributes are kept", "\\n", "\"", "+", "\"", "\\t", "instead of deleted.", "\\n", "\"", "+", "\"", "\\t", "(default: off)", "\"", ",", "\"", "V", "\"", ",", "0", ",", "\"", "-V", "\"", ")", ")", ";", "result", ".", "addAll", "(", "Collections", ".", "list", "(", "super", ".", "listOptions", "(", ")", ")", ")", ";", "return", "result", ".", "elements", "(", ")", ";", "}", "/**\n * returns the options of the current setup.\n * \n * @return the current options\n */", "@", "Override", "public", "String", "[", "]", "getOptions", "(", ")", "{", "Vector", "<", "String", ">", "result", "=", "new", "Vector", "<", "String", ">", "(", ")", ";", "result", ".", "add", "(", "\"", "-E", "\"", ")", ";", "result", ".", "add", "(", "\"", "\"", "+", "getExpression", "(", ")", ")", ";", "if", "(", "getInvertSelection", "(", ")", ")", "{", "result", ".", "add", "(", "\"", "-V", "\"", ")", ";", "}", "Collections", ".", "addAll", "(", "result", ",", "super", ".", "getOptions", "(", ")", ")", ";", "return", "result", ".", "toArray", "(", "new", "String", "[", "result", ".", "size", "(", ")", "]", ")", ";", "}", "/**\n * Parses the options for this object.\n * <p/>\n * \n * <!-- options-start --> Valid options are:\n * <p/>\n * \n * <pre>\n * -D\n * Turns on output of debugging information.\n * </pre>\n * \n * <pre>\n * -E &lt;regular expression&gt;\n * The regular expression to match the attribute names against.\n * (default: ^.*id$)\n * </pre>\n * \n * <pre>\n * -V\n * Flag for inverting the matching sense. If set, attributes are kept\n * instead of deleted.\n * (default: off)\n * </pre>\n * \n * <!-- options-end -->\n * \n * @param options the options to use\n * @throws Exception if the option setting fails\n */", "@", "Override", "public", "void", "setOptions", "(", "String", "[", "]", "options", ")", "throws", "Exception", "{", "String", "tmpStr", "=", "Utils", ".", "getOption", "(", "\"", "E", "\"", ",", "options", ")", ";", "if", "(", "tmpStr", ".", "length", "(", ")", "!=", "0", ")", "{", "setExpression", "(", "tmpStr", ")", ";", "}", "else", "{", "setExpression", "(", "DEFAULT_EXPRESSION", ")", ";", "}", "setInvertSelection", "(", "Utils", ".", "getFlag", "(", "\"", "V", "\"", ",", "options", ")", ")", ";", "super", ".", "setOptions", "(", "options", ")", ";", "Utils", ".", "checkForRemainingOptions", "(", "options", ")", ";", "}", "/**\n * Sets the regular expression to match the attribute names against.\n * \n * @param value the regular expression\n */", "public", "void", "setExpression", "(", "String", "value", ")", "{", "m_Expression", "=", "value", ";", "}", "/**\n * Returns the regular expression in use.\n * \n * @return the regular expression\n */", "public", "String", "getExpression", "(", ")", "{", "return", "m_Expression", ";", "}", "/**\n * Returns the tip text for this property.\n * \n * @return tip text for this property suitable for displaying in the\n * explorer/experimenter gui\n */", "public", "String", "expressionTipText", "(", ")", "{", "return", "\"", "The regular expression to match the attribute names against.", "\"", ";", "}", "/**\n * Set whether selected columns should be removed or kept. If true the\n * selected columns are kept and unselected columns are deleted. If false\n * selected columns are deleted and unselected columns are kept.\n * \n * @param value the new invert setting\n */", "public", "void", "setInvertSelection", "(", "boolean", "value", ")", "{", "m_InvertSelection", "=", "value", ";", "}", "/**\n * Get whether the supplied columns are to be removed or kept.\n * \n * @return true if the supplied columns will be kept\n */", "public", "boolean", "getInvertSelection", "(", ")", "{", "return", "m_InvertSelection", ";", "}", "/**\n * Returns the tip text for this property.\n * \n * @return tip text for this property suitable for displaying in the\n * explorer/experimenter gui\n */", "public", "String", "invertSelectionTipText", "(", ")", "{", "return", "\"", "Determines whether action is to select or delete.", "\"", "+", "\"", " If set to true, only the specified attributes will be kept;", "\"", "+", "\"", " If set to false, specified attributes will be deleted.", "\"", ";", "}", "/**\n * Determines the output format based on the input format and returns this. In\n * case the output format cannot be returned immediately, i.e.,\n * immediateOutputFormat() returns false, then this method will be called from\n * batchFinished().\n * \n * @param inputFormat the input format to base the output format on\n * @return the output format\n * @throws Exception in case the determination goes wrong\n */", "@", "Override", "protected", "Instances", "determineOutputFormat", "(", "Instances", "inputFormat", ")", "throws", "Exception", "{", "Vector", "<", "Integer", ">", "indices", "=", "new", "Vector", "<", "Integer", ">", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "inputFormat", ".", "numAttributes", "(", ")", ";", "i", "++", ")", "{", "if", "(", "(", "i", "==", "inputFormat", ".", "classIndex", "(", ")", ")", ")", "{", "if", "(", "getInvertSelection", "(", ")", ")", "{", "indices", ".", "add", "(", "i", ")", ";", "}", "continue", ";", "}", "if", "(", "inputFormat", ".", "attribute", "(", "i", ")", ".", "name", "(", ")", ".", "matches", "(", "m_Expression", ")", ")", "{", "indices", ".", "add", "(", "i", ")", ";", "}", "}", "int", "[", "]", "attributes", "=", "new", "int", "[", "indices", ".", "size", "(", ")", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "indices", ".", "size", "(", ")", ";", "i", "++", ")", "{", "attributes", "[", "i", "]", "=", "indices", ".", "get", "(", "i", ")", ";", "}", "m_Remove", "=", "new", "Remove", "(", ")", ";", "m_Remove", ".", "setAttributeIndicesArray", "(", "attributes", ")", ";", "m_Remove", ".", "setInvertSelection", "(", "getInvertSelection", "(", ")", ")", ";", "m_Remove", ".", "setInputFormat", "(", "inputFormat", ")", ";", "return", "m_Remove", ".", "getOutputFormat", "(", ")", ";", "}", "/**\n * Returns the Capabilities of this filter.\n * \n * @return the capabilities of this object\n * @see Capabilities\n */", "@", "Override", "public", "Capabilities", "getCapabilities", "(", ")", "{", "Capabilities", "result", ";", "result", "=", "new", "Remove", "(", ")", ".", "getCapabilities", "(", ")", ";", "result", ".", "setOwner", "(", "this", ")", ";", "return", "result", ";", "}", "/**\n * processes the given instance (may change the provided instance) and returns\n * the modified version.\n * \n * @param instance the instance to process\n * @return the modified data\n * @throws Exception in case the processing goes wrong\n */", "@", "Override", "protected", "Instance", "process", "(", "Instance", "instance", ")", "throws", "Exception", "{", "m_Remove", ".", "input", "(", "instance", ")", ";", "return", "m_Remove", ".", "output", "(", ")", ";", "}", "/**\n * Returns the revision string.\n * \n * @return the revision\n */", "@", "Override", "public", "String", "getRevision", "(", ")", "{", "return", "RevisionUtils", ".", "extract", "(", "\"", "$Revision: 14508 $", "\"", ")", ";", "}", "/**\n * runs the filter with the given arguments.\n * \n * @param args the commandline arguments\n */", "public", "static", "void", "main", "(", "String", "[", "]", "args", ")", "{", "runFilter", "(", "new", "RemoveByName", "(", ")", ",", "args", ")", ";", "}", "}" ]
<!-- globalinfo-start --> Removes attributes based on a regular expression matched against their names.
[ "<!", "--", "globalinfo", "-", "start", "--", ">", "Removes", "attributes", "based", "on", "a", "regular", "expression", "matched", "against", "their", "names", "." ]
[ "// determine indices", "// always leave class if set" ]
[ { "param": "SimpleStreamFilter", "type": null }, { "param": "WeightedInstancesHandler, WeightedAttributesHandler", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "SimpleStreamFilter", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "WeightedInstancesHandler, WeightedAttributesHandler", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
14
1,705
198
213e424edfecb5b7369f7352249482767508cc7a
framework-projects/spring-framework
spring-messaging/src/main/java/org/springframework/messaging/converter/KotlinSerializationJsonMessageConverter.java
[ "Apache-2.0" ]
Java
KotlinSerializationJsonMessageConverter
/** * Implementation of {@link MessageConverter} that can read and write JSON * using <a href="https://github.com/Kotlin/kotlinx.serialization">kotlinx.serialization</a>. * * <p>This converter can be used to bind {@code @Serializable} Kotlin classes. * * @author Sebastien Deleuze * @since 5.3 */
Implementation of MessageConverter that can read and write JSON using kotlinx.serialization. This converter can be used to bind Kotlin classes. @author Sebastien Deleuze @since 5.3
[ "Implementation", "of", "MessageConverter", "that", "can", "read", "and", "write", "JSON", "using", "kotlinx", ".", "serialization", ".", "This", "converter", "can", "be", "used", "to", "bind", "Kotlin", "classes", ".", "@author", "Sebastien", "Deleuze", "@since", "5", ".", "3" ]
public class KotlinSerializationJsonMessageConverter extends AbstractJsonMessageConverter { private static final Map<Type, KSerializer<Object>> serializerCache = new ConcurrentReferenceHashMap<>(); private final Json json; /** * Construct a new {@code KotlinSerializationJsonMessageConverter} with default configuration. */ public KotlinSerializationJsonMessageConverter() { this(Json.Default); } /** * Construct a new {@code KotlinSerializationJsonMessageConverter} with the given delegate. * @param json the Json instance to use */ public KotlinSerializationJsonMessageConverter(Json json) { this.json = json; } @Override protected Object fromJson(Reader reader, Type resolvedType) { try { return fromJson(FileCopyUtils.copyToString(reader), resolvedType); } catch (IOException ex) { throw new MessageConversionException("Could not read JSON: " + ex.getMessage(), ex); } } @Override protected Object fromJson(String payload, Type resolvedType) { return this.json.decodeFromString(serializer(resolvedType), payload); } @Override protected void toJson(Object payload, Type resolvedType, Writer writer) { try { writer.write(toJson(payload, resolvedType).toCharArray()); } catch (IOException ex) { throw new MessageConversionException("Could not write JSON: " + ex.getMessage(), ex); } } @Override protected String toJson(Object payload, Type resolvedType) { return this.json.encodeToString(serializer(resolvedType), payload); } /** * Tries to find a serializer that can marshall or unmarshall instances of the given type * using kotlinx.serialization. If no serializer can be found, an exception is thrown. * <p>Resolved serializers are cached and cached results are returned on successive calls. * @param type the type to find a serializer for * @return a resolved serializer for the given type * @throws RuntimeException if no serializer supporting the given type can be found */ private KSerializer<Object> serializer(Type type) { KSerializer<Object> serializer = serializerCache.get(type); if (serializer == null) { serializer = SerializersKt.serializer(type); serializerCache.put(type, serializer); } return serializer; } }
[ "public", "class", "KotlinSerializationJsonMessageConverter", "extends", "AbstractJsonMessageConverter", "{", "private", "static", "final", "Map", "<", "Type", ",", "KSerializer", "<", "Object", ">", ">", "serializerCache", "=", "new", "ConcurrentReferenceHashMap", "<", ">", "(", ")", ";", "private", "final", "Json", "json", ";", "/**\n\t * Construct a new {@code KotlinSerializationJsonMessageConverter} with default configuration.\n\t */", "public", "KotlinSerializationJsonMessageConverter", "(", ")", "{", "this", "(", "Json", ".", "Default", ")", ";", "}", "/**\n\t * Construct a new {@code KotlinSerializationJsonMessageConverter} with the given delegate.\n\t * @param json the Json instance to use\n\t */", "public", "KotlinSerializationJsonMessageConverter", "(", "Json", "json", ")", "{", "this", ".", "json", "=", "json", ";", "}", "@", "Override", "protected", "Object", "fromJson", "(", "Reader", "reader", ",", "Type", "resolvedType", ")", "{", "try", "{", "return", "fromJson", "(", "FileCopyUtils", ".", "copyToString", "(", "reader", ")", ",", "resolvedType", ")", ";", "}", "catch", "(", "IOException", "ex", ")", "{", "throw", "new", "MessageConversionException", "(", "\"", "Could not read JSON: ", "\"", "+", "ex", ".", "getMessage", "(", ")", ",", "ex", ")", ";", "}", "}", "@", "Override", "protected", "Object", "fromJson", "(", "String", "payload", ",", "Type", "resolvedType", ")", "{", "return", "this", ".", "json", ".", "decodeFromString", "(", "serializer", "(", "resolvedType", ")", ",", "payload", ")", ";", "}", "@", "Override", "protected", "void", "toJson", "(", "Object", "payload", ",", "Type", "resolvedType", ",", "Writer", "writer", ")", "{", "try", "{", "writer", ".", "write", "(", "toJson", "(", "payload", ",", "resolvedType", ")", ".", "toCharArray", "(", ")", ")", ";", "}", "catch", "(", "IOException", "ex", ")", "{", "throw", "new", "MessageConversionException", "(", "\"", "Could not write JSON: ", "\"", "+", "ex", ".", "getMessage", "(", ")", ",", "ex", ")", ";", "}", "}", "@", "Override", "protected", "String", "toJson", "(", "Object", "payload", ",", "Type", "resolvedType", ")", "{", "return", "this", ".", "json", ".", "encodeToString", "(", "serializer", "(", "resolvedType", ")", ",", "payload", ")", ";", "}", "/**\n\t * Tries to find a serializer that can marshall or unmarshall instances of the given type\n\t * using kotlinx.serialization. If no serializer can be found, an exception is thrown.\n\t * <p>Resolved serializers are cached and cached results are returned on successive calls.\n\t * @param type the type to find a serializer for\n\t * @return a resolved serializer for the given type\n\t * @throws RuntimeException if no serializer supporting the given type can be found\n\t */", "private", "KSerializer", "<", "Object", ">", "serializer", "(", "Type", "type", ")", "{", "KSerializer", "<", "Object", ">", "serializer", "=", "serializerCache", ".", "get", "(", "type", ")", ";", "if", "(", "serializer", "==", "null", ")", "{", "serializer", "=", "SerializersKt", ".", "serializer", "(", "type", ")", ";", "serializerCache", ".", "put", "(", "type", ",", "serializer", ")", ";", "}", "return", "serializer", ";", "}", "}" ]
Implementation of {@link MessageConverter} that can read and write JSON using <a href="https://github.com/Kotlin/kotlinx.serialization">kotlinx.serialization</a>.
[ "Implementation", "of", "{", "@link", "MessageConverter", "}", "that", "can", "read", "and", "write", "JSON", "using", "<a", "href", "=", "\"", "https", ":", "//", "github", ".", "com", "/", "Kotlin", "/", "kotlinx", ".", "serialization", "\"", ">", "kotlinx", ".", "serialization<", "/", "a", ">", "." ]
[]
[ { "param": "AbstractJsonMessageConverter", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "AbstractJsonMessageConverter", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
14
478
78
f962d6d84e73e3fbacff4f3d4ae8e67bcd158773
KevRitchie/efcore
src/EFCore.SqlServer/Query/Internal/SqlServerDateTimeMethodTranslator.cs
[ "MIT" ]
C#
SqlServerDateTimeMethodTranslator
/// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary>
This is an internal API that supports the Entity Framework Core infrastructure and not subject to the same compatibility standards as public APIs. It may be changed or removed without notice in any release. You should only use it directly in your code with extreme caution and knowing that doing so can result in application failures when updating to a new Entity Framework Core release.
[ "This", "is", "an", "internal", "API", "that", "supports", "the", "Entity", "Framework", "Core", "infrastructure", "and", "not", "subject", "to", "the", "same", "compatibility", "standards", "as", "public", "APIs", ".", "It", "may", "be", "changed", "or", "removed", "without", "notice", "in", "any", "release", ".", "You", "should", "only", "use", "it", "directly", "in", "your", "code", "with", "extreme", "caution", "and", "knowing", "that", "doing", "so", "can", "result", "in", "application", "failures", "when", "updating", "to", "a", "new", "Entity", "Framework", "Core", "release", "." ]
public class SqlServerDateTimeMethodTranslator : IMethodCallTranslator { private readonly Dictionary<MethodInfo, string> _methodInfoDatePartMapping = new() { { typeof(DateTime).GetRuntimeMethod(nameof(DateTime.AddYears), new[] { typeof(int) })!, "year" }, { typeof(DateTime).GetRuntimeMethod(nameof(DateTime.AddMonths), new[] { typeof(int) })!, "month" }, { typeof(DateTime).GetRuntimeMethod(nameof(DateTime.AddDays), new[] { typeof(double) })!, "day" }, { typeof(DateTime).GetRuntimeMethod(nameof(DateTime.AddHours), new[] { typeof(double) })!, "hour" }, { typeof(DateTime).GetRuntimeMethod(nameof(DateTime.AddMinutes), new[] { typeof(double) })!, "minute" }, { typeof(DateTime).GetRuntimeMethod(nameof(DateTime.AddSeconds), new[] { typeof(double) })!, "second" }, { typeof(DateTime).GetRuntimeMethod(nameof(DateTime.AddMilliseconds), new[] { typeof(double) })!, "millisecond" }, { typeof(DateTimeOffset).GetRuntimeMethod(nameof(DateTimeOffset.AddYears), new[] { typeof(int) })!, "year" }, { typeof(DateTimeOffset).GetRuntimeMethod(nameof(DateTimeOffset.AddMonths), new[] { typeof(int) })!, "month" }, { typeof(DateTimeOffset).GetRuntimeMethod(nameof(DateTimeOffset.AddDays), new[] { typeof(double) })!, "day" }, { typeof(DateTimeOffset).GetRuntimeMethod(nameof(DateTimeOffset.AddHours), new[] { typeof(double) })!, "hour" }, { typeof(DateTimeOffset).GetRuntimeMethod(nameof(DateTimeOffset.AddMinutes), new[] { typeof(double) })!, "minute" }, { typeof(DateTimeOffset).GetRuntimeMethod(nameof(DateTimeOffset.AddSeconds), new[] { typeof(double) })!, "second" }, { typeof(DateTimeOffset).GetRuntimeMethod(nameof(DateTimeOffset.AddMilliseconds), new[] { typeof(double) })!, "millisecond" } }; private static readonly MethodInfo AtTimeZoneDateTimeOffsetMethodInfo = typeof(SqlServerDbFunctionsExtensions) .GetRuntimeMethod( nameof(SqlServerDbFunctionsExtensions.AtTimeZone), new[] { typeof(DbFunctions), typeof(DateTimeOffset), typeof(string) })!; private static readonly MethodInfo AtTimeZoneDateTimeMethodInfo = typeof(SqlServerDbFunctionsExtensions) .GetRuntimeMethod( nameof(SqlServerDbFunctionsExtensions.AtTimeZone), new[] { typeof(DbFunctions), typeof(DateTime), typeof(string) })!; private readonly ISqlExpressionFactory _sqlExpressionFactory; private readonly IRelationalTypeMappingSource _typeMappingSource; public SqlServerDateTimeMethodTranslator( ISqlExpressionFactory sqlExpressionFactory, IRelationalTypeMappingSource typeMappingSource) { _sqlExpressionFactory = sqlExpressionFactory; _typeMappingSource = typeMappingSource; } public virtual SqlExpression? Translate( SqlExpression? instance, MethodInfo method, IReadOnlyList<SqlExpression> arguments, IDiagnosticsLogger<DbLoggerCategory.Query> logger) { if (_methodInfoDatePartMapping.TryGetValue(method, out var datePart) && instance != null) { if (datePart != "year" && datePart != "month" && arguments[0] is SqlConstantExpression sqlConstant && sqlConstant.Value is double doubleValue && (doubleValue >= int.MaxValue || doubleValue <= int.MinValue)) { return null; } if (instance is SqlConstantExpression instanceConstant) { instance = instanceConstant.ApplyTypeMapping(_typeMappingSource.FindMapping(typeof(DateTime), "datetime")); } return _sqlExpressionFactory.Function( "DATEADD", new[] { _sqlExpressionFactory.Fragment(datePart), _sqlExpressionFactory.Convert(arguments[0], typeof(int)), instance }, nullable: true, argumentsPropagateNullability: new[] { false, true, true }, instance.Type, instance.TypeMapping); } if (method == AtTimeZoneDateTimeOffsetMethodInfo || method == AtTimeZoneDateTimeMethodInfo) { var (operand, timeZone) = (arguments[1], arguments[2]); RelationalTypeMapping? resultTypeMapping = null; if (operand.TypeMapping is { } operandTypeMapping) { switch (operandTypeMapping.StoreTypeNameBase) { case "datetimeoffset": resultTypeMapping = operandTypeMapping; break; case "datetime" or "datetime2" or "smalldatetime": resultTypeMapping = _typeMappingSource.FindMapping( typeof(DateTimeOffset), "datetimeoffset", precision: operandTypeMapping.Precision); break; default: Check.DebugAssert( false, $"Unknown operand type mapping '{operandTypeMapping.StoreTypeNameBase}' when translating EF.Functions.AtTimeZone"); break; } } if (operand is SqlConstantExpression) { operand = _sqlExpressionFactory.Convert(operand, operand.Type); } return new AtTimeZoneExpression( operand, _sqlExpressionFactory.ApplyTypeMapping(timeZone, _typeMappingSource.FindMapping("varchar")), typeof(DateTimeOffset), resultTypeMapping); } return null; } }
[ "public", "class", "SqlServerDateTimeMethodTranslator", ":", "IMethodCallTranslator", "{", "private", "readonly", "Dictionary", "<", "MethodInfo", ",", "string", ">", "_methodInfoDatePartMapping", "=", "new", "(", ")", "{", "{", "typeof", "(", "DateTime", ")", ".", "GetRuntimeMethod", "(", "nameof", "(", "DateTime", ".", "AddYears", ")", ",", "new", "[", "]", "{", "typeof", "(", "int", ")", "}", ")", "!", ",", "\"", "year", "\"", "}", ",", "{", "typeof", "(", "DateTime", ")", ".", "GetRuntimeMethod", "(", "nameof", "(", "DateTime", ".", "AddMonths", ")", ",", "new", "[", "]", "{", "typeof", "(", "int", ")", "}", ")", "!", ",", "\"", "month", "\"", "}", ",", "{", "typeof", "(", "DateTime", ")", ".", "GetRuntimeMethod", "(", "nameof", "(", "DateTime", ".", "AddDays", ")", ",", "new", "[", "]", "{", "typeof", "(", "double", ")", "}", ")", "!", ",", "\"", "day", "\"", "}", ",", "{", "typeof", "(", "DateTime", ")", ".", "GetRuntimeMethod", "(", "nameof", "(", "DateTime", ".", "AddHours", ")", ",", "new", "[", "]", "{", "typeof", "(", "double", ")", "}", ")", "!", ",", "\"", "hour", "\"", "}", ",", "{", "typeof", "(", "DateTime", ")", ".", "GetRuntimeMethod", "(", "nameof", "(", "DateTime", ".", "AddMinutes", ")", ",", "new", "[", "]", "{", "typeof", "(", "double", ")", "}", ")", "!", ",", "\"", "minute", "\"", "}", ",", "{", "typeof", "(", "DateTime", ")", ".", "GetRuntimeMethod", "(", "nameof", "(", "DateTime", ".", "AddSeconds", ")", ",", "new", "[", "]", "{", "typeof", "(", "double", ")", "}", ")", "!", ",", "\"", "second", "\"", "}", ",", "{", "typeof", "(", "DateTime", ")", ".", "GetRuntimeMethod", "(", "nameof", "(", "DateTime", ".", "AddMilliseconds", ")", ",", "new", "[", "]", "{", "typeof", "(", "double", ")", "}", ")", "!", ",", "\"", "millisecond", "\"", "}", ",", "{", "typeof", "(", "DateTimeOffset", ")", ".", "GetRuntimeMethod", "(", "nameof", "(", "DateTimeOffset", ".", "AddYears", ")", ",", "new", "[", "]", "{", "typeof", "(", "int", ")", "}", ")", "!", ",", "\"", "year", "\"", "}", ",", "{", "typeof", "(", "DateTimeOffset", ")", ".", "GetRuntimeMethod", "(", "nameof", "(", "DateTimeOffset", ".", "AddMonths", ")", ",", "new", "[", "]", "{", "typeof", "(", "int", ")", "}", ")", "!", ",", "\"", "month", "\"", "}", ",", "{", "typeof", "(", "DateTimeOffset", ")", ".", "GetRuntimeMethod", "(", "nameof", "(", "DateTimeOffset", ".", "AddDays", ")", ",", "new", "[", "]", "{", "typeof", "(", "double", ")", "}", ")", "!", ",", "\"", "day", "\"", "}", ",", "{", "typeof", "(", "DateTimeOffset", ")", ".", "GetRuntimeMethod", "(", "nameof", "(", "DateTimeOffset", ".", "AddHours", ")", ",", "new", "[", "]", "{", "typeof", "(", "double", ")", "}", ")", "!", ",", "\"", "hour", "\"", "}", ",", "{", "typeof", "(", "DateTimeOffset", ")", ".", "GetRuntimeMethod", "(", "nameof", "(", "DateTimeOffset", ".", "AddMinutes", ")", ",", "new", "[", "]", "{", "typeof", "(", "double", ")", "}", ")", "!", ",", "\"", "minute", "\"", "}", ",", "{", "typeof", "(", "DateTimeOffset", ")", ".", "GetRuntimeMethod", "(", "nameof", "(", "DateTimeOffset", ".", "AddSeconds", ")", ",", "new", "[", "]", "{", "typeof", "(", "double", ")", "}", ")", "!", ",", "\"", "second", "\"", "}", ",", "{", "typeof", "(", "DateTimeOffset", ")", ".", "GetRuntimeMethod", "(", "nameof", "(", "DateTimeOffset", ".", "AddMilliseconds", ")", ",", "new", "[", "]", "{", "typeof", "(", "double", ")", "}", ")", "!", ",", "\"", "millisecond", "\"", "}", "}", ";", "private", "static", "readonly", "MethodInfo", "AtTimeZoneDateTimeOffsetMethodInfo", "=", "typeof", "(", "SqlServerDbFunctionsExtensions", ")", ".", "GetRuntimeMethod", "(", "nameof", "(", "SqlServerDbFunctionsExtensions", ".", "AtTimeZone", ")", ",", "new", "[", "]", "{", "typeof", "(", "DbFunctions", ")", ",", "typeof", "(", "DateTimeOffset", ")", ",", "typeof", "(", "string", ")", "}", ")", "!", ";", "private", "static", "readonly", "MethodInfo", "AtTimeZoneDateTimeMethodInfo", "=", "typeof", "(", "SqlServerDbFunctionsExtensions", ")", ".", "GetRuntimeMethod", "(", "nameof", "(", "SqlServerDbFunctionsExtensions", ".", "AtTimeZone", ")", ",", "new", "[", "]", "{", "typeof", "(", "DbFunctions", ")", ",", "typeof", "(", "DateTime", ")", ",", "typeof", "(", "string", ")", "}", ")", "!", ";", "private", "readonly", "ISqlExpressionFactory", "_sqlExpressionFactory", ";", "private", "readonly", "IRelationalTypeMappingSource", "_typeMappingSource", ";", "public", "SqlServerDateTimeMethodTranslator", "(", "ISqlExpressionFactory", "sqlExpressionFactory", ",", "IRelationalTypeMappingSource", "typeMappingSource", ")", "{", "_sqlExpressionFactory", "=", "sqlExpressionFactory", ";", "_typeMappingSource", "=", "typeMappingSource", ";", "}", "public", "virtual", "SqlExpression", "?", "Translate", "(", "SqlExpression", "?", "instance", ",", "MethodInfo", "method", ",", "IReadOnlyList", "<", "SqlExpression", ">", "arguments", ",", "IDiagnosticsLogger", "<", "DbLoggerCategory", ".", "Query", ">", "logger", ")", "{", "if", "(", "_methodInfoDatePartMapping", ".", "TryGetValue", "(", "method", ",", "out", "var", "datePart", ")", "&&", "instance", "!=", "null", ")", "{", "if", "(", "datePart", "!=", "\"", "year", "\"", "&&", "datePart", "!=", "\"", "month", "\"", "&&", "arguments", "[", "0", "]", "is", "SqlConstantExpression", "sqlConstant", "&&", "sqlConstant", ".", "Value", "is", "double", "doubleValue", "&&", "(", "doubleValue", ">=", "int", ".", "MaxValue", "||", "doubleValue", "<=", "int", ".", "MinValue", ")", ")", "{", "return", "null", ";", "}", "if", "(", "instance", "is", "SqlConstantExpression", "instanceConstant", ")", "{", "instance", "=", "instanceConstant", ".", "ApplyTypeMapping", "(", "_typeMappingSource", ".", "FindMapping", "(", "typeof", "(", "DateTime", ")", ",", "\"", "datetime", "\"", ")", ")", ";", "}", "return", "_sqlExpressionFactory", ".", "Function", "(", "\"", "DATEADD", "\"", ",", "new", "[", "]", "{", "_sqlExpressionFactory", ".", "Fragment", "(", "datePart", ")", ",", "_sqlExpressionFactory", ".", "Convert", "(", "arguments", "[", "0", "]", ",", "typeof", "(", "int", ")", ")", ",", "instance", "}", ",", "nullable", ":", "true", ",", "argumentsPropagateNullability", ":", "new", "[", "]", "{", "false", ",", "true", ",", "true", "}", ",", "instance", ".", "Type", ",", "instance", ".", "TypeMapping", ")", ";", "}", "if", "(", "method", "==", "AtTimeZoneDateTimeOffsetMethodInfo", "||", "method", "==", "AtTimeZoneDateTimeMethodInfo", ")", "{", "var", "(", "operand", ",", "timeZone", ")", "=", "(", "arguments", "[", "1", "]", ",", "arguments", "[", "2", "]", ")", ";", "RelationalTypeMapping", "?", "resultTypeMapping", "=", "null", ";", "if", "(", "operand", ".", "TypeMapping", "is", "{", "}", "operandTypeMapping", ")", "{", "switch", "(", "operandTypeMapping", ".", "StoreTypeNameBase", ")", "{", "case", "\"", "datetimeoffset", "\"", ":", "resultTypeMapping", "=", "operandTypeMapping", ";", "break", ";", "case", "\"", "datetime", "\"", "or", "\"", "datetime2", "\"", "or", "\"", "smalldatetime", "\"", ":", "resultTypeMapping", "=", "_typeMappingSource", ".", "FindMapping", "(", "typeof", "(", "DateTimeOffset", ")", ",", "\"", "datetimeoffset", "\"", ",", "precision", ":", "operandTypeMapping", ".", "Precision", ")", ";", "break", ";", "default", ":", "Check", ".", "DebugAssert", "(", "false", ",", "$\"", "Unknown operand type mapping '", "{", "operandTypeMapping", ".", "StoreTypeNameBase", "}", "' when translating EF.Functions.AtTimeZone", "\"", ")", ";", "break", ";", "}", "}", "if", "(", "operand", "is", "SqlConstantExpression", ")", "{", "operand", "=", "_sqlExpressionFactory", ".", "Convert", "(", "operand", ",", "operand", ".", "Type", ")", ";", "}", "return", "new", "AtTimeZoneExpression", "(", "operand", ",", "_sqlExpressionFactory", ".", "ApplyTypeMapping", "(", "timeZone", ",", "_typeMappingSource", ".", "FindMapping", "(", "\"", "varchar", "\"", ")", ")", ",", "typeof", "(", "DateTimeOffset", ")", ",", "resultTypeMapping", ")", ";", "}", "return", "null", ";", "}", "}" ]
This is an internal API that supports the Entity Framework Core infrastructure and not subject to the same compatibility standards as public APIs.
[ "This", "is", "an", "internal", "API", "that", "supports", "the", "Entity", "Framework", "Core", "infrastructure", "and", "not", "subject", "to", "the", "same", "compatibility", "standards", "as", "public", "APIs", "." ]
[ "/// <summary>", "/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to", "/// the same compatibility standards as public APIs. It may be changed or removed without notice in", "/// any release. You should only use it directly in your code with extreme caution and knowing that", "/// doing so can result in application failures when updating to a new Entity Framework Core release.", "/// </summary>", "/// <summary>", "/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to", "/// the same compatibility standards as public APIs. It may be changed or removed without notice in", "/// any release. You should only use it directly in your code with extreme caution and knowing that", "/// doing so can result in application failures when updating to a new Entity Framework Core release.", "/// </summary>", "// DateAdd does not accept number argument outside of int range", "// AddYears/AddMonths take int argument so no need to check for range", "// The AT TIME ZONE construct bubbles up the precision of its operand, so when invoked over datetime2(2) it returns a", "// datetimeoffset(2). So if the operand has a type mapping, bubble it up accordingly, otherwise allow the result type mapping", "// to be inferred.", "// Our constant representation for datetime/datetimeoffset is an untyped string literal, which the AT TIME ZONE expression", "// does not accept. Type it explicitly." ]
[ { "param": "IMethodCallTranslator", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "IMethodCallTranslator", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
19
1,070
87
c65b54cf2cec627f5e52cf16a29f27f43a74530e
jessicarychen/598project
mllib/target/java/org/apache/spark/ml/feature/StandardScaler.java
[ "BSD-3-Clause-Open-MPI", "PSF-2.0", "Apache-2.0", "BSD-2-Clause", "MIT", "MIT-0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause-Clear", "PostgreSQL", "BSD-3-Clause" ]
Java
StandardScaler
/** * Standardizes features by removing the mean and scaling to unit variance using column summary * statistics on the samples in the training set. * <p> * The "unit std" is computed using the * <a href="https://en.wikipedia.org/wiki/Standard_deviation#Corrected_sample_standard_deviation"> * corrected sample standard deviation</a>, * which is computed as the square root of the unbiased sample variance. */
Standardizes features by removing the mean and scaling to unit variance using column summary statistics on the samples in the training set. The "unit std" is computed using the corrected sample standard deviation, which is computed as the square root of the unbiased sample variance.
[ "Standardizes", "features", "by", "removing", "the", "mean", "and", "scaling", "to", "unit", "variance", "using", "column", "summary", "statistics", "on", "the", "samples", "in", "the", "training", "set", ".", "The", "\"", "unit", "std", "\"", "is", "computed", "using", "the", "corrected", "sample", "standard", "deviation", "which", "is", "computed", "as", "the", "square", "root", "of", "the", "unbiased", "sample", "variance", "." ]
public class StandardScaler extends org.apache.spark.ml.Estimator<org.apache.spark.ml.feature.StandardScalerModel> implements org.apache.spark.ml.feature.StandardScalerParams, org.apache.spark.ml.util.DefaultParamsWritable { static public org.apache.spark.ml.feature.StandardScaler load (java.lang.String path) { throw new RuntimeException(); } static public java.lang.String toString () { throw new RuntimeException(); } static public org.apache.spark.ml.param.Param<?>[] params () { throw new RuntimeException(); } static public java.lang.String explainParam (org.apache.spark.ml.param.Param<?> param) { throw new RuntimeException(); } static public java.lang.String explainParams () { throw new RuntimeException(); } static public final boolean isSet (org.apache.spark.ml.param.Param<?> param) { throw new RuntimeException(); } static public final boolean isDefined (org.apache.spark.ml.param.Param<?> param) { throw new RuntimeException(); } static public boolean hasParam (java.lang.String paramName) { throw new RuntimeException(); } static public org.apache.spark.ml.param.Param<java.lang.Object> getParam (java.lang.String paramName) { throw new RuntimeException(); } static public final <T extends java.lang.Object> org.apache.spark.ml.param.Params set (org.apache.spark.ml.param.Param<T> param, T value) { throw new RuntimeException(); } static protected final org.apache.spark.ml.param.Params set (java.lang.String param, Object value) { throw new RuntimeException(); } static protected final org.apache.spark.ml.param.Params set (org.apache.spark.ml.param.ParamPair<?> paramPair) { throw new RuntimeException(); } static public final <T extends java.lang.Object> scala.Option<T> get (org.apache.spark.ml.param.Param<T> param) { throw new RuntimeException(); } static public final org.apache.spark.ml.param.Params clear (org.apache.spark.ml.param.Param<?> param) { throw new RuntimeException(); } static public final <T extends java.lang.Object> T getOrDefault (org.apache.spark.ml.param.Param<T> param) { throw new RuntimeException(); } static protected final <T extends java.lang.Object> T $ (org.apache.spark.ml.param.Param<T> param) { throw new RuntimeException(); } static protected final <T extends java.lang.Object> org.apache.spark.ml.param.Params setDefault (org.apache.spark.ml.param.Param<T> param, T value) { throw new RuntimeException(); } static protected final org.apache.spark.ml.param.Params setDefault (scala.collection.Seq<org.apache.spark.ml.param.ParamPair<?>> paramPairs) { throw new RuntimeException(); } static public final <T extends java.lang.Object> scala.Option<T> getDefault (org.apache.spark.ml.param.Param<T> param) { throw new RuntimeException(); } static public final <T extends java.lang.Object> boolean hasDefault (org.apache.spark.ml.param.Param<T> param) { throw new RuntimeException(); } static protected final <T extends org.apache.spark.ml.param.Params> T defaultCopy (org.apache.spark.ml.param.ParamMap extra) { throw new RuntimeException(); } static public final org.apache.spark.ml.param.ParamMap extractParamMap (org.apache.spark.ml.param.ParamMap extra) { throw new RuntimeException(); } static public final org.apache.spark.ml.param.ParamMap extractParamMap () { throw new RuntimeException(); } static protected <T extends org.apache.spark.ml.param.Params> T copyValues (T to, org.apache.spark.ml.param.ParamMap extra) { throw new RuntimeException(); } static protected <T extends org.apache.spark.ml.param.Params> org.apache.spark.ml.param.ParamMap copyValues$default$2 () { throw new RuntimeException(); } static protected java.lang.String logName () { throw new RuntimeException(); } static protected org.slf4j.Logger log () { throw new RuntimeException(); } static protected void logInfo (scala.Function0<java.lang.String> msg) { throw new RuntimeException(); } static protected void logDebug (scala.Function0<java.lang.String> msg) { throw new RuntimeException(); } static protected void logTrace (scala.Function0<java.lang.String> msg) { throw new RuntimeException(); } static protected void logWarning (scala.Function0<java.lang.String> msg) { throw new RuntimeException(); } static protected void logError (scala.Function0<java.lang.String> msg) { throw new RuntimeException(); } static protected void logInfo (scala.Function0<java.lang.String> msg, java.lang.Throwable throwable) { throw new RuntimeException(); } static protected void logDebug (scala.Function0<java.lang.String> msg, java.lang.Throwable throwable) { throw new RuntimeException(); } static protected void logTrace (scala.Function0<java.lang.String> msg, java.lang.Throwable throwable) { throw new RuntimeException(); } static protected void logWarning (scala.Function0<java.lang.String> msg, java.lang.Throwable throwable) { throw new RuntimeException(); } static protected void logError (scala.Function0<java.lang.String> msg, java.lang.Throwable throwable) { throw new RuntimeException(); } static protected boolean isTraceEnabled () { throw new RuntimeException(); } static protected void initializeLogIfNecessary (boolean isInterpreter) { throw new RuntimeException(); } static protected boolean initializeLogIfNecessary (boolean isInterpreter, boolean silent) { throw new RuntimeException(); } static protected boolean initializeLogIfNecessary$default$2 () { throw new RuntimeException(); } static public final org.apache.spark.ml.param.Param<java.lang.String> inputCol () { throw new RuntimeException(); } static public final java.lang.String getInputCol () { throw new RuntimeException(); } static public final org.apache.spark.ml.param.Param<java.lang.String> outputCol () { throw new RuntimeException(); } static public final java.lang.String getOutputCol () { throw new RuntimeException(); } static public org.apache.spark.ml.param.BooleanParam withMean () { throw new RuntimeException(); } static public boolean getWithMean () { throw new RuntimeException(); } static public org.apache.spark.ml.param.BooleanParam withStd () { throw new RuntimeException(); } static public boolean getWithStd () { throw new RuntimeException(); } static protected org.apache.spark.sql.types.StructType validateAndTransformSchema (org.apache.spark.sql.types.StructType schema) { throw new RuntimeException(); } static public void save (java.lang.String path) throws java.io.IOException { throw new RuntimeException(); } static public org.apache.spark.ml.util.MLWriter write () { throw new RuntimeException(); } public java.lang.String uid () { throw new RuntimeException(); } // not preceding public StandardScaler (java.lang.String uid) { throw new RuntimeException(); } public StandardScaler () { throw new RuntimeException(); } /** @group setParam */ public org.apache.spark.ml.feature.StandardScaler setInputCol (java.lang.String value) { throw new RuntimeException(); } /** @group setParam */ public org.apache.spark.ml.feature.StandardScaler setOutputCol (java.lang.String value) { throw new RuntimeException(); } /** @group setParam */ public org.apache.spark.ml.feature.StandardScaler setWithMean (boolean value) { throw new RuntimeException(); } /** @group setParam */ public org.apache.spark.ml.feature.StandardScaler setWithStd (boolean value) { throw new RuntimeException(); } public org.apache.spark.ml.feature.StandardScalerModel fit (org.apache.spark.sql.Dataset<?> dataset) { throw new RuntimeException(); } public org.apache.spark.sql.types.StructType transformSchema (org.apache.spark.sql.types.StructType schema) { throw new RuntimeException(); } public org.apache.spark.ml.feature.StandardScaler copy (org.apache.spark.ml.param.ParamMap extra) { throw new RuntimeException(); } }
[ "public", "class", "StandardScaler", "extends", "org", ".", "apache", ".", "spark", ".", "ml", ".", "Estimator", "<", "org", ".", "apache", ".", "spark", ".", "ml", ".", "feature", ".", "StandardScalerModel", ">", "implements", "org", ".", "apache", ".", "spark", ".", "ml", ".", "feature", ".", "StandardScalerParams", ",", "org", ".", "apache", ".", "spark", ".", "ml", ".", "util", ".", "DefaultParamsWritable", "{", "static", "public", "org", ".", "apache", ".", "spark", ".", "ml", ".", "feature", ".", "StandardScaler", "load", "(", "java", ".", "lang", ".", "String", "path", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "static", "public", "java", ".", "lang", ".", "String", "toString", "(", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "static", "public", "org", ".", "apache", ".", "spark", ".", "ml", ".", "param", ".", "Param", "<", "?", ">", "[", "]", "params", "(", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "static", "public", "java", ".", "lang", ".", "String", "explainParam", "(", "org", ".", "apache", ".", "spark", ".", "ml", ".", "param", ".", "Param", "<", "?", ">", "param", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "static", "public", "java", ".", "lang", ".", "String", "explainParams", "(", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "static", "public", "final", "boolean", "isSet", "(", "org", ".", "apache", ".", "spark", ".", "ml", ".", "param", ".", "Param", "<", "?", ">", "param", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "static", "public", "final", "boolean", "isDefined", "(", "org", ".", "apache", ".", "spark", ".", "ml", ".", "param", ".", "Param", "<", "?", ">", "param", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "static", "public", "boolean", "hasParam", "(", "java", ".", "lang", ".", "String", "paramName", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "static", "public", "org", ".", "apache", ".", "spark", ".", "ml", ".", "param", ".", "Param", "<", "java", ".", "lang", ".", "Object", ">", "getParam", "(", "java", ".", "lang", ".", "String", "paramName", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "static", "public", "final", "<", "T", "extends", "java", ".", "lang", ".", "Object", ">", "org", ".", "apache", ".", "spark", ".", "ml", ".", "param", ".", "Params", "set", "(", "org", ".", "apache", ".", "spark", ".", "ml", ".", "param", ".", "Param", "<", "T", ">", "param", ",", "T", "value", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "static", "protected", "final", "org", ".", "apache", ".", "spark", ".", "ml", ".", "param", ".", "Params", "set", "(", "java", ".", "lang", ".", "String", "param", ",", "Object", "value", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "static", "protected", "final", "org", ".", "apache", ".", "spark", ".", "ml", ".", "param", ".", "Params", "set", "(", "org", ".", "apache", ".", "spark", ".", "ml", ".", "param", ".", "ParamPair", "<", "?", ">", "paramPair", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "static", "public", "final", "<", "T", "extends", "java", ".", "lang", ".", "Object", ">", "scala", ".", "Option", "<", "T", ">", "get", "(", "org", ".", "apache", ".", "spark", ".", "ml", ".", "param", ".", "Param", "<", "T", ">", "param", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "static", "public", "final", "org", ".", "apache", ".", "spark", ".", "ml", ".", "param", ".", "Params", "clear", "(", "org", ".", "apache", ".", "spark", ".", "ml", ".", "param", ".", "Param", "<", "?", ">", "param", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "static", "public", "final", "<", "T", "extends", "java", ".", "lang", ".", "Object", ">", "T", "getOrDefault", "(", "org", ".", "apache", ".", "spark", ".", "ml", ".", "param", ".", "Param", "<", "T", ">", "param", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "static", "protected", "final", "<", "T", "extends", "java", ".", "lang", ".", "Object", ">", "T", "$", "(", "org", ".", "apache", ".", "spark", ".", "ml", ".", "param", ".", "Param", "<", "T", ">", "param", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "static", "protected", "final", "<", "T", "extends", "java", ".", "lang", ".", "Object", ">", "org", ".", "apache", ".", "spark", ".", "ml", ".", "param", ".", "Params", "setDefault", "(", "org", ".", "apache", ".", "spark", ".", "ml", ".", "param", ".", "Param", "<", "T", ">", "param", ",", "T", "value", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "static", "protected", "final", "org", ".", "apache", ".", "spark", ".", "ml", ".", "param", ".", "Params", "setDefault", "(", "scala", ".", "collection", ".", "Seq", "<", "org", ".", "apache", ".", "spark", ".", "ml", ".", "param", ".", "ParamPair", "<", "?", ">", ">", "paramPairs", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "static", "public", "final", "<", "T", "extends", "java", ".", "lang", ".", "Object", ">", "scala", ".", "Option", "<", "T", ">", "getDefault", "(", "org", ".", "apache", ".", "spark", ".", "ml", ".", "param", ".", "Param", "<", "T", ">", "param", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "static", "public", "final", "<", "T", "extends", "java", ".", "lang", ".", "Object", ">", "boolean", "hasDefault", "(", "org", ".", "apache", ".", "spark", ".", "ml", ".", "param", ".", "Param", "<", "T", ">", "param", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "static", "protected", "final", "<", "T", "extends", "org", ".", "apache", ".", "spark", ".", "ml", ".", "param", ".", "Params", ">", "T", "defaultCopy", "(", "org", ".", "apache", ".", "spark", ".", "ml", ".", "param", ".", "ParamMap", "extra", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "static", "public", "final", "org", ".", "apache", ".", "spark", ".", "ml", ".", "param", ".", "ParamMap", "extractParamMap", "(", "org", ".", "apache", ".", "spark", ".", "ml", ".", "param", ".", "ParamMap", "extra", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "static", "public", "final", "org", ".", "apache", ".", "spark", ".", "ml", ".", "param", ".", "ParamMap", "extractParamMap", "(", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "static", "protected", "<", "T", "extends", "org", ".", "apache", ".", "spark", ".", "ml", ".", "param", ".", "Params", ">", "T", "copyValues", "(", "T", "to", ",", "org", ".", "apache", ".", "spark", ".", "ml", ".", "param", ".", "ParamMap", "extra", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "static", "protected", "<", "T", "extends", "org", ".", "apache", ".", "spark", ".", "ml", ".", "param", ".", "Params", ">", "org", ".", "apache", ".", "spark", ".", "ml", ".", "param", ".", "ParamMap", "copyValues$default$2", "(", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "static", "protected", "java", ".", "lang", ".", "String", "logName", "(", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "static", "protected", "org", ".", "slf4j", ".", "Logger", "log", "(", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "static", "protected", "void", "logInfo", "(", "scala", ".", "Function0", "<", "java", ".", "lang", ".", "String", ">", "msg", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "static", "protected", "void", "logDebug", "(", "scala", ".", "Function0", "<", "java", ".", "lang", ".", "String", ">", "msg", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "static", "protected", "void", "logTrace", "(", "scala", ".", "Function0", "<", "java", ".", "lang", ".", "String", ">", "msg", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "static", "protected", "void", "logWarning", "(", "scala", ".", "Function0", "<", "java", ".", "lang", ".", "String", ">", "msg", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "static", "protected", "void", "logError", "(", "scala", ".", "Function0", "<", "java", ".", "lang", ".", "String", ">", "msg", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "static", "protected", "void", "logInfo", "(", "scala", ".", "Function0", "<", "java", ".", "lang", ".", "String", ">", "msg", ",", "java", ".", "lang", ".", "Throwable", "throwable", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "static", "protected", "void", "logDebug", "(", "scala", ".", "Function0", "<", "java", ".", "lang", ".", "String", ">", "msg", ",", "java", ".", "lang", ".", "Throwable", "throwable", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "static", "protected", "void", "logTrace", "(", "scala", ".", "Function0", "<", "java", ".", "lang", ".", "String", ">", "msg", ",", "java", ".", "lang", ".", "Throwable", "throwable", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "static", "protected", "void", "logWarning", "(", "scala", ".", "Function0", "<", "java", ".", "lang", ".", "String", ">", "msg", ",", "java", ".", "lang", ".", "Throwable", "throwable", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "static", "protected", "void", "logError", "(", "scala", ".", "Function0", "<", "java", ".", "lang", ".", "String", ">", "msg", ",", "java", ".", "lang", ".", "Throwable", "throwable", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "static", "protected", "boolean", "isTraceEnabled", "(", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "static", "protected", "void", "initializeLogIfNecessary", "(", "boolean", "isInterpreter", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "static", "protected", "boolean", "initializeLogIfNecessary", "(", "boolean", "isInterpreter", ",", "boolean", "silent", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "static", "protected", "boolean", "initializeLogIfNecessary$default$2", "(", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "static", "public", "final", "org", ".", "apache", ".", "spark", ".", "ml", ".", "param", ".", "Param", "<", "java", ".", "lang", ".", "String", ">", "inputCol", "(", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "static", "public", "final", "java", ".", "lang", ".", "String", "getInputCol", "(", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "static", "public", "final", "org", ".", "apache", ".", "spark", ".", "ml", ".", "param", ".", "Param", "<", "java", ".", "lang", ".", "String", ">", "outputCol", "(", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "static", "public", "final", "java", ".", "lang", ".", "String", "getOutputCol", "(", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "static", "public", "org", ".", "apache", ".", "spark", ".", "ml", ".", "param", ".", "BooleanParam", "withMean", "(", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "static", "public", "boolean", "getWithMean", "(", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "static", "public", "org", ".", "apache", ".", "spark", ".", "ml", ".", "param", ".", "BooleanParam", "withStd", "(", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "static", "public", "boolean", "getWithStd", "(", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "static", "protected", "org", ".", "apache", ".", "spark", ".", "sql", ".", "types", ".", "StructType", "validateAndTransformSchema", "(", "org", ".", "apache", ".", "spark", ".", "sql", ".", "types", ".", "StructType", "schema", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "static", "public", "void", "save", "(", "java", ".", "lang", ".", "String", "path", ")", "throws", "java", ".", "io", ".", "IOException", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "static", "public", "org", ".", "apache", ".", "spark", ".", "ml", ".", "util", ".", "MLWriter", "write", "(", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "public", "java", ".", "lang", ".", "String", "uid", "(", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "public", "StandardScaler", "(", "java", ".", "lang", ".", "String", "uid", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "public", "StandardScaler", "(", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "/** @group setParam */", "public", "org", ".", "apache", ".", "spark", ".", "ml", ".", "feature", ".", "StandardScaler", "setInputCol", "(", "java", ".", "lang", ".", "String", "value", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "/** @group setParam */", "public", "org", ".", "apache", ".", "spark", ".", "ml", ".", "feature", ".", "StandardScaler", "setOutputCol", "(", "java", ".", "lang", ".", "String", "value", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "/** @group setParam */", "public", "org", ".", "apache", ".", "spark", ".", "ml", ".", "feature", ".", "StandardScaler", "setWithMean", "(", "boolean", "value", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "/** @group setParam */", "public", "org", ".", "apache", ".", "spark", ".", "ml", ".", "feature", ".", "StandardScaler", "setWithStd", "(", "boolean", "value", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "public", "org", ".", "apache", ".", "spark", ".", "ml", ".", "feature", ".", "StandardScalerModel", "fit", "(", "org", ".", "apache", ".", "spark", ".", "sql", ".", "Dataset", "<", "?", ">", "dataset", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "public", "org", ".", "apache", ".", "spark", ".", "sql", ".", "types", ".", "StructType", "transformSchema", "(", "org", ".", "apache", ".", "spark", ".", "sql", ".", "types", ".", "StructType", "schema", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "public", "org", ".", "apache", ".", "spark", ".", "ml", ".", "feature", ".", "StandardScaler", "copy", "(", "org", ".", "apache", ".", "spark", ".", "ml", ".", "param", ".", "ParamMap", "extra", ")", "{", "throw", "new", "RuntimeException", "(", ")", ";", "}", "}" ]
Standardizes features by removing the mean and scaling to unit variance using column summary statistics on the samples in the training set.
[ "Standardizes", "features", "by", "removing", "the", "mean", "and", "scaling", "to", "unit", "variance", "using", "column", "summary", "statistics", "on", "the", "samples", "in", "the", "training", "set", "." ]
[ "// not preceding" ]
[ { "param": "org.apache.spark.ml.feature.StandardScalerParams, org.apache.spark.ml.util.DefaultParamsWritable", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "org.apache.spark.ml.feature.StandardScalerParams, org.apache.spark.ml.util.DefaultParamsWritable", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
14
1,674
89
ee90c6956f0dc99366ccab186ad3232e1f325b8b
ndtung01061999/catiny
src/main/java/com/regitiny/catiny/service/PermissionQueryService.java
[ "Unlicense" ]
Java
PermissionQueryService
/** * Service for executing complex queries for {@link Permission} entities in the database. * The main input is a {@link PermissionCriteria} which gets converted to {@link Specification}, * in a way that all the filters must apply. * It returns a {@link List} of {@link PermissionDTO} or a {@link Page} of {@link PermissionDTO} which fulfills the criteria. */
Service for executing complex queries for Permission entities in the database. The main input is a PermissionCriteria which gets converted to Specification, in a way that all the filters must apply. It returns a List of PermissionDTO or a Page of PermissionDTO which fulfills the criteria.
[ "Service", "for", "executing", "complex", "queries", "for", "Permission", "entities", "in", "the", "database", ".", "The", "main", "input", "is", "a", "PermissionCriteria", "which", "gets", "converted", "to", "Specification", "in", "a", "way", "that", "all", "the", "filters", "must", "apply", ".", "It", "returns", "a", "List", "of", "PermissionDTO", "or", "a", "Page", "of", "PermissionDTO", "which", "fulfills", "the", "criteria", "." ]
@Service @Transactional(readOnly = true) @GeneratedByJHipster public class PermissionQueryService extends QueryService<Permission> { private final Logger log = LoggerFactory.getLogger(PermissionQueryService.class); private final PermissionRepository permissionRepository; private final PermissionMapper permissionMapper; private final PermissionSearchRepository permissionSearchRepository; public PermissionQueryService( PermissionRepository permissionRepository, PermissionMapper permissionMapper, PermissionSearchRepository permissionSearchRepository ) { this.permissionRepository = permissionRepository; this.permissionMapper = permissionMapper; this.permissionSearchRepository = permissionSearchRepository; } /** * Return a {@link List} of {@link PermissionDTO} which matches the criteria from the database. * @param criteria The object which holds all the filters, which the entities should match. * @return the matching entities. */ @Transactional(readOnly = true) public List<PermissionDTO> findByCriteria(PermissionCriteria criteria) { log.debug("find by criteria : {}", criteria); final Specification<Permission> specification = createSpecification(criteria); return permissionMapper.toDto(permissionRepository.findAll(specification)); } /** * Return a {@link Page} of {@link PermissionDTO} which matches the criteria from the database. * @param criteria The object which holds all the filters, which the entities should match. * @param page The page, which should be returned. * @return the matching entities. */ @Transactional(readOnly = true) public Page<PermissionDTO> findByCriteria(PermissionCriteria criteria, Pageable page) { log.debug("find by criteria : {}, page: {}", criteria, page); final Specification<Permission> specification = createSpecification(criteria); return permissionRepository.findAll(specification, page).map(permissionMapper::toDto); } /** * Return the number of matching entities in the database. * @param criteria The object which holds all the filters, which the entities should match. * @return the number of matching entities. */ @Transactional(readOnly = true) public long countByCriteria(PermissionCriteria criteria) { log.debug("count by criteria : {}", criteria); final Specification<Permission> specification = createSpecification(criteria); return permissionRepository.count(specification); } /** * Function to convert {@link PermissionCriteria} to a {@link Specification} * @param criteria The object which holds all the filters, which the entities should match. * @return the matching {@link Specification} of the entity. */ protected Specification<Permission> createSpecification(PermissionCriteria criteria) { Specification<Permission> specification = Specification.where(null); if (criteria != null) { if (criteria.getId() != null) { specification = specification.and(buildRangeSpecification(criteria.getId(), Permission_.id)); } if (criteria.getUuid() != null) { specification = specification.and(buildSpecification(criteria.getUuid(), Permission_.uuid)); } if (criteria.getRead() != null) { specification = specification.and(buildSpecification(criteria.getRead(), Permission_.read)); } if (criteria.getWrite() != null) { specification = specification.and(buildSpecification(criteria.getWrite(), Permission_.write)); } if (criteria.getShare() != null) { specification = specification.and(buildSpecification(criteria.getShare(), Permission_.share)); } if (criteria.getDelete() != null) { specification = specification.and(buildSpecification(criteria.getDelete(), Permission_.delete)); } if (criteria.getAdd() != null) { specification = specification.and(buildSpecification(criteria.getAdd(), Permission_.add)); } if (criteria.getLevel() != null) { specification = specification.and(buildRangeSpecification(criteria.getLevel(), Permission_.level)); } if (criteria.getBaseInfoId() != null) { specification = specification.and( buildSpecification(criteria.getBaseInfoId(), root -> root.join(Permission_.baseInfo, JoinType.LEFT).get(BaseInfo_.id)) ); } if (criteria.getMasterUserId() != null) { specification = specification.and( buildSpecification(criteria.getMasterUserId(), root -> root.join(Permission_.masterUser, JoinType.LEFT).get(MasterUser_.id)) ); } } return specification; } }
[ "@", "Service", "@", "Transactional", "(", "readOnly", "=", "true", ")", "@", "GeneratedByJHipster", "public", "class", "PermissionQueryService", "extends", "QueryService", "<", "Permission", ">", "{", "private", "final", "Logger", "log", "=", "LoggerFactory", ".", "getLogger", "(", "PermissionQueryService", ".", "class", ")", ";", "private", "final", "PermissionRepository", "permissionRepository", ";", "private", "final", "PermissionMapper", "permissionMapper", ";", "private", "final", "PermissionSearchRepository", "permissionSearchRepository", ";", "public", "PermissionQueryService", "(", "PermissionRepository", "permissionRepository", ",", "PermissionMapper", "permissionMapper", ",", "PermissionSearchRepository", "permissionSearchRepository", ")", "{", "this", ".", "permissionRepository", "=", "permissionRepository", ";", "this", ".", "permissionMapper", "=", "permissionMapper", ";", "this", ".", "permissionSearchRepository", "=", "permissionSearchRepository", ";", "}", "/**\n * Return a {@link List} of {@link PermissionDTO} which matches the criteria from the database.\n * @param criteria The object which holds all the filters, which the entities should match.\n * @return the matching entities.\n */", "@", "Transactional", "(", "readOnly", "=", "true", ")", "public", "List", "<", "PermissionDTO", ">", "findByCriteria", "(", "PermissionCriteria", "criteria", ")", "{", "log", ".", "debug", "(", "\"", "find by criteria : {}", "\"", ",", "criteria", ")", ";", "final", "Specification", "<", "Permission", ">", "specification", "=", "createSpecification", "(", "criteria", ")", ";", "return", "permissionMapper", ".", "toDto", "(", "permissionRepository", ".", "findAll", "(", "specification", ")", ")", ";", "}", "/**\n * Return a {@link Page} of {@link PermissionDTO} which matches the criteria from the database.\n * @param criteria The object which holds all the filters, which the entities should match.\n * @param page The page, which should be returned.\n * @return the matching entities.\n */", "@", "Transactional", "(", "readOnly", "=", "true", ")", "public", "Page", "<", "PermissionDTO", ">", "findByCriteria", "(", "PermissionCriteria", "criteria", ",", "Pageable", "page", ")", "{", "log", ".", "debug", "(", "\"", "find by criteria : {}, page: {}", "\"", ",", "criteria", ",", "page", ")", ";", "final", "Specification", "<", "Permission", ">", "specification", "=", "createSpecification", "(", "criteria", ")", ";", "return", "permissionRepository", ".", "findAll", "(", "specification", ",", "page", ")", ".", "map", "(", "permissionMapper", "::", "toDto", ")", ";", "}", "/**\n * Return the number of matching entities in the database.\n * @param criteria The object which holds all the filters, which the entities should match.\n * @return the number of matching entities.\n */", "@", "Transactional", "(", "readOnly", "=", "true", ")", "public", "long", "countByCriteria", "(", "PermissionCriteria", "criteria", ")", "{", "log", ".", "debug", "(", "\"", "count by criteria : {}", "\"", ",", "criteria", ")", ";", "final", "Specification", "<", "Permission", ">", "specification", "=", "createSpecification", "(", "criteria", ")", ";", "return", "permissionRepository", ".", "count", "(", "specification", ")", ";", "}", "/**\n * Function to convert {@link PermissionCriteria} to a {@link Specification}\n * @param criteria The object which holds all the filters, which the entities should match.\n * @return the matching {@link Specification} of the entity.\n */", "protected", "Specification", "<", "Permission", ">", "createSpecification", "(", "PermissionCriteria", "criteria", ")", "{", "Specification", "<", "Permission", ">", "specification", "=", "Specification", ".", "where", "(", "null", ")", ";", "if", "(", "criteria", "!=", "null", ")", "{", "if", "(", "criteria", ".", "getId", "(", ")", "!=", "null", ")", "{", "specification", "=", "specification", ".", "and", "(", "buildRangeSpecification", "(", "criteria", ".", "getId", "(", ")", ",", "Permission_", ".", "id", ")", ")", ";", "}", "if", "(", "criteria", ".", "getUuid", "(", ")", "!=", "null", ")", "{", "specification", "=", "specification", ".", "and", "(", "buildSpecification", "(", "criteria", ".", "getUuid", "(", ")", ",", "Permission_", ".", "uuid", ")", ")", ";", "}", "if", "(", "criteria", ".", "getRead", "(", ")", "!=", "null", ")", "{", "specification", "=", "specification", ".", "and", "(", "buildSpecification", "(", "criteria", ".", "getRead", "(", ")", ",", "Permission_", ".", "read", ")", ")", ";", "}", "if", "(", "criteria", ".", "getWrite", "(", ")", "!=", "null", ")", "{", "specification", "=", "specification", ".", "and", "(", "buildSpecification", "(", "criteria", ".", "getWrite", "(", ")", ",", "Permission_", ".", "write", ")", ")", ";", "}", "if", "(", "criteria", ".", "getShare", "(", ")", "!=", "null", ")", "{", "specification", "=", "specification", ".", "and", "(", "buildSpecification", "(", "criteria", ".", "getShare", "(", ")", ",", "Permission_", ".", "share", ")", ")", ";", "}", "if", "(", "criteria", ".", "getDelete", "(", ")", "!=", "null", ")", "{", "specification", "=", "specification", ".", "and", "(", "buildSpecification", "(", "criteria", ".", "getDelete", "(", ")", ",", "Permission_", ".", "delete", ")", ")", ";", "}", "if", "(", "criteria", ".", "getAdd", "(", ")", "!=", "null", ")", "{", "specification", "=", "specification", ".", "and", "(", "buildSpecification", "(", "criteria", ".", "getAdd", "(", ")", ",", "Permission_", ".", "add", ")", ")", ";", "}", "if", "(", "criteria", ".", "getLevel", "(", ")", "!=", "null", ")", "{", "specification", "=", "specification", ".", "and", "(", "buildRangeSpecification", "(", "criteria", ".", "getLevel", "(", ")", ",", "Permission_", ".", "level", ")", ")", ";", "}", "if", "(", "criteria", ".", "getBaseInfoId", "(", ")", "!=", "null", ")", "{", "specification", "=", "specification", ".", "and", "(", "buildSpecification", "(", "criteria", ".", "getBaseInfoId", "(", ")", ",", "root", "->", "root", ".", "join", "(", "Permission_", ".", "baseInfo", ",", "JoinType", ".", "LEFT", ")", ".", "get", "(", "BaseInfo_", ".", "id", ")", ")", ")", ";", "}", "if", "(", "criteria", ".", "getMasterUserId", "(", ")", "!=", "null", ")", "{", "specification", "=", "specification", ".", "and", "(", "buildSpecification", "(", "criteria", ".", "getMasterUserId", "(", ")", ",", "root", "->", "root", ".", "join", "(", "Permission_", ".", "masterUser", ",", "JoinType", ".", "LEFT", ")", ".", "get", "(", "MasterUser_", ".", "id", ")", ")", ")", ";", "}", "}", "return", "specification", ";", "}", "}" ]
Service for executing complex queries for {@link Permission} entities in the database.
[ "Service", "for", "executing", "complex", "queries", "for", "{", "@link", "Permission", "}", "entities", "in", "the", "database", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
20
906
80
1545b799265033c5ef76d01161eab6d5220dd5a1
wangfei1988/TicTacToe
Assets/IntelliMediaCore/Source/Unity/Common/UnityListBox.cs
[ "BSD-2-Clause" ]
C#
UnityListBox
/// <summary> /// The purpose of this button is to wrap the Unity 3D button and properly handle mouse presses /// for buttons that overlap. /// http://forum.unity3d.com/threads/96563-corrected-GUI.Button-code-%28works-properly-with-layered-controls%29?p=629284#post629284 /// </summary>
The purpose of this button is to wrap the Unity 3D button and properly handle mouse presses for buttons that overlap.
[ "The", "purpose", "of", "this", "button", "is", "to", "wrap", "the", "Unity", "3D", "button", "and", "properly", "handle", "mouse", "presses", "for", "buttons", "that", "overlap", "." ]
public class UnityListBox<T> { public Texture2D background; public GUIStyle titleStyle; public GUIStyle buttonStyle; public string Title { get; set; } public IEnumerable<T> Items { get; set; } public T SelectedValue { get; set; } private Vector2 scrollPos = new Vector2(0, 0); public void Draw(UnityEngine.Rect bounds) { if (background != null) { GUI.DrawTexture(bounds, background); } GUILayout.BeginArea(bounds); scrollPos = GUILayout.BeginScrollView(scrollPos); GUILayout.BeginVertical(); if (!string.IsNullOrEmpty(Title)) { GUILayout.Label(Title, titleStyle); GUILayout.Space(20); } foreach (T item in Items) { if (item != null) { if (GUILayout.Toggle((item.Equals(SelectedValue)), item.ToString(), buttonStyle, GUILayout.Height(buttonStyle.fontSize), GUILayout.Width(bounds.width))) { SelectedValue = item; } } } GUILayout.EndScrollView(); GUILayout.EndVertical(); GUILayout.EndArea(); } }
[ "public", "class", "UnityListBox", "<", "T", ">", "{", "public", "Texture2D", "background", ";", "public", "GUIStyle", "titleStyle", ";", "public", "GUIStyle", "buttonStyle", ";", "public", "string", "Title", "{", "get", ";", "set", ";", "}", "public", "IEnumerable", "<", "T", ">", "Items", "{", "get", ";", "set", ";", "}", "public", "T", "SelectedValue", "{", "get", ";", "set", ";", "}", "private", "Vector2", "scrollPos", "=", "new", "Vector2", "(", "0", ",", "0", ")", ";", "public", "void", "Draw", "(", "UnityEngine", ".", "Rect", "bounds", ")", "{", "if", "(", "background", "!=", "null", ")", "{", "GUI", ".", "DrawTexture", "(", "bounds", ",", "background", ")", ";", "}", "GUILayout", ".", "BeginArea", "(", "bounds", ")", ";", "scrollPos", "=", "GUILayout", ".", "BeginScrollView", "(", "scrollPos", ")", ";", "GUILayout", ".", "BeginVertical", "(", ")", ";", "if", "(", "!", "string", ".", "IsNullOrEmpty", "(", "Title", ")", ")", "{", "GUILayout", ".", "Label", "(", "Title", ",", "titleStyle", ")", ";", "GUILayout", ".", "Space", "(", "20", ")", ";", "}", "foreach", "(", "T", "item", "in", "Items", ")", "{", "if", "(", "item", "!=", "null", ")", "{", "if", "(", "GUILayout", ".", "Toggle", "(", "(", "item", ".", "Equals", "(", "SelectedValue", ")", ")", ",", "item", ".", "ToString", "(", ")", ",", "buttonStyle", ",", "GUILayout", ".", "Height", "(", "buttonStyle", ".", "fontSize", ")", ",", "GUILayout", ".", "Width", "(", "bounds", ".", "width", ")", ")", ")", "{", "SelectedValue", "=", "item", ";", "}", "}", "}", "GUILayout", ".", "EndScrollView", "(", ")", ";", "GUILayout", ".", "EndVertical", "(", ")", ";", "GUILayout", ".", "EndArea", "(", ")", ";", "}", "}" ]
The purpose of this button is to wrap the Unity 3D button and properly handle mouse presses for buttons that overlap.
[ "The", "purpose", "of", "this", "button", "is", "to", "wrap", "the", "Unity", "3D", "button", "and", "properly", "handle", "mouse", "presses", "for", "buttons", "that", "overlap", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
17
239
90
2fe481e768b9b84a68de4fd92e1fcaaaf9e0db02
TomAlanCarroll/kinectlogin
Microsoft.Kinect.Toolkit/Properties/Resources.Designer.cs
[ "Apache-2.0" ]
C#
Resources
/// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project.
A strongly-typed resource class, for looking up localized strings, etc.
[ "A", "strongly", "-", "typed", "resource", "class", "for", "looking", "up", "localized", "strings", "etc", "." ]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Microsoft.Kinect.Toolkit.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } internal static string DelegateCommandCastException { get { return ResourceManager.GetString("DelegateCommandCastException", resourceCulture); } } internal static string MessageAllSet { get { return ResourceManager.GetString("MessageAllSet", resourceCulture); } } internal static string MessageAllSetListening { get { return ResourceManager.GetString("MessageAllSetListening", resourceCulture); } } internal static string MessageConflict { get { return ResourceManager.GetString("MessageConflict", resourceCulture); } } internal static string MessageError { get { return ResourceManager.GetString("MessageError", resourceCulture); } } internal static string MessageInitializing { get { return ResourceManager.GetString("MessageInitializing", resourceCulture); } } internal static string MessageInsufficientBandwidth { get { return ResourceManager.GetString("MessageInsufficientBandwidth", resourceCulture); } } internal static string MessageNoAvailableSensors { get { return ResourceManager.GetString("MessageNoAvailableSensors", resourceCulture); } } internal static string MessageNotGenuine { get { return ResourceManager.GetString("MessageNotGenuine", resourceCulture); } } internal static string MessageNotPowered { get { return ResourceManager.GetString("MessageNotPowered", resourceCulture); } } internal static string MessageNotSupported { get { return ResourceManager.GetString("MessageNotSupported", resourceCulture); } } internal static string MoreInformationConflict { get { return ResourceManager.GetString("MoreInformationConflict", resourceCulture); } } internal static string MoreInformationError { get { return ResourceManager.GetString("MoreInformationError", resourceCulture); } } internal static string MoreInformationInsufficientBandwidth { get { return ResourceManager.GetString("MoreInformationInsufficientBandwidth", resourceCulture); } } internal static string MoreInformationNoAvailableSensors { get { return ResourceManager.GetString("MoreInformationNoAvailableSensors", resourceCulture); } } internal static string MoreInformationNotGenuine { get { return ResourceManager.GetString("MoreInformationNotGenuine", resourceCulture); } } internal static string MoreInformationNotPowered { get { return ResourceManager.GetString("MoreInformationNotPowered", resourceCulture); } } internal static string MoreInformationNotSupported { get { return ResourceManager.GetString("MoreInformationNotSupported", resourceCulture); } } internal static string NoDefaultBrowserAvailable { get { return ResourceManager.GetString("NoDefaultBrowserAvailable", resourceCulture); } } }
[ "[", "global", "::", "System", ".", "CodeDom", ".", "Compiler", ".", "GeneratedCodeAttribute", "(", "\"", "System.Resources.Tools.StronglyTypedResourceBuilder", "\"", ",", "\"", "4.0.0.0", "\"", ")", "]", "[", "global", "::", "System", ".", "Diagnostics", ".", "DebuggerNonUserCodeAttribute", "(", ")", "]", "[", "global", "::", "System", ".", "Runtime", ".", "CompilerServices", ".", "CompilerGeneratedAttribute", "(", ")", "]", "internal", "class", "Resources", "{", "private", "static", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "resourceMan", ";", "private", "static", "global", "::", "System", ".", "Globalization", ".", "CultureInfo", "resourceCulture", ";", "[", "global", "::", "System", ".", "Diagnostics", ".", "CodeAnalysis", ".", "SuppressMessageAttribute", "(", "\"", "Microsoft.Performance", "\"", ",", "\"", "CA1811:AvoidUncalledPrivateCode", "\"", ")", "]", "internal", "Resources", "(", ")", "{", "}", "[", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableAttribute", "(", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableState", ".", "Advanced", ")", "]", "internal", "static", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "ResourceManager", "{", "get", "{", "if", "(", "object", ".", "ReferenceEquals", "(", "resourceMan", ",", "null", ")", ")", "{", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "temp", "=", "new", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "(", "\"", "Microsoft.Kinect.Toolkit.Properties.Resources", "\"", ",", "typeof", "(", "Resources", ")", ".", "Assembly", ")", ";", "resourceMan", "=", "temp", ";", "}", "return", "resourceMan", ";", "}", "}", "[", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableAttribute", "(", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableState", ".", "Advanced", ")", "]", "internal", "static", "global", "::", "System", ".", "Globalization", ".", "CultureInfo", "Culture", "{", "get", "{", "return", "resourceCulture", ";", "}", "set", "{", "resourceCulture", "=", "value", ";", "}", "}", "internal", "static", "string", "DelegateCommandCastException", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "DelegateCommandCastException", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "MessageAllSet", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "MessageAllSet", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "MessageAllSetListening", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "MessageAllSetListening", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "MessageConflict", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "MessageConflict", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "MessageError", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "MessageError", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "MessageInitializing", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "MessageInitializing", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "MessageInsufficientBandwidth", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "MessageInsufficientBandwidth", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "MessageNoAvailableSensors", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "MessageNoAvailableSensors", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "MessageNotGenuine", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "MessageNotGenuine", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "MessageNotPowered", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "MessageNotPowered", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "MessageNotSupported", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "MessageNotSupported", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "MoreInformationConflict", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "MoreInformationConflict", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "MoreInformationError", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "MoreInformationError", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "MoreInformationInsufficientBandwidth", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "MoreInformationInsufficientBandwidth", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "MoreInformationNoAvailableSensors", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "MoreInformationNoAvailableSensors", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "MoreInformationNotGenuine", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "MoreInformationNotGenuine", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "MoreInformationNotPowered", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "MoreInformationNotPowered", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "MoreInformationNotSupported", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "MoreInformationNotSupported", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "NoDefaultBrowserAvailable", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "NoDefaultBrowserAvailable", "\"", ",", "resourceCulture", ")", ";", "}", "}", "}" ]
A strongly-typed resource class, for looking up localized strings, etc.
[ "A", "strongly", "-", "typed", "resource", "class", "for", "looking", "up", "localized", "strings", "etc", "." ]
[ "/// <summary>", "/// Returns the cached ResourceManager instance used by this class.", "/// </summary>", "/// <summary>", "/// Overrides the current thread's CurrentUICulture property for all", "/// resource lookups using this strongly typed resource class.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Parameter of type {0} not of of expected type {1}.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to All set!.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Kinect is listening.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to This Kinect is being used by another application..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Oops, there is an error..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Initializing....", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Too many USB devices! Please unplug one or more..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Kinect required.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to This sensor is not genuine!.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Plug my power cord in!.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Kinect for Xbox not supported..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to This application needs a Kinect for Windows sensor in order to function. However, another application is using the Kinect Sensor..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to The Kinect Sensor is plugged in, however an error has occurred. For steps to resolve, please click the &quot;Help&quot; link..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to The Kinect Sensor needs the majority of the USB Bandwidth of a USB Controller. If other devices are in contention for that bandwidth, the Kinect Sensor may not be able to function..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to This application needs a Kinect for Windows sensor in order to function. Please plug one into the PC..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to This application needs a genuine Kinect for Windows sensor in order to function. Please plug one into the PC..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to The Kinect Sensor is plugged into the computer with its USB connection, but the power plug appears to be not powered..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to This application needs a Kinect for Windows sensor in order to function. Please plug one into the PC..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Unable to launch the default web browser. Trying to navigate to: {0}.", "/// </summary>" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
17
804
84
2cd5f9b08e6b4cf5fe528d291c95a91683852b37
lastaflute/lasta-thymeleaf
src/main/java/org/lastaflute/thymeleaf/expression/ClassificationExpressionObject.java
[ "Apache-2.0" ]
Java
ClassificationExpressionObject
/** * Utility methods for Classification objects.<br> * <pre> * Usage: * &lt;select&gt; * &lt;option th:each="cdef : ${#cls.listAll('MemberStatus')}" th:value="${cdef.code()}" th:text="${cdef.alias()}"&gt;&lt;/option&gt; * &lt;/select&gt; * * The result of processing this example will be as expected. * &lt;select&gt; * &lt;option value="FML"&gt;Formalized&lt;/option&gt; * &lt;option value="WDL"&gt;Withdrawal&lt;/option&gt; * &lt;option value="PRV"&gt;Provisional&lt;/option&gt; * &lt;/select&gt; * </pre> * @author schatten * @author jflute */
The result of processing this example will be as expected.
[ "The", "result", "of", "processing", "this", "example", "will", "be", "as", "expected", "." ]
public class ClassificationExpressionObject { // =================================================================================== // Definition // ========== public static final String GROUP_DELIMITER = "."; // =================================================================================== // Attribute // ========= private final IExpressionContext context; // =================================================================================== // Constructor // =========== public ClassificationExpressionObject(IExpressionContext context) { this.context = context; } // =================================================================================== // Expression // ========== // ----------------------------------------------------- // list() // ------ /** * Get list of specified classification. * @param classificationName The name of classification, can contain group name by delimiter. (NotNull) * @return The list of all classification. (NotNull) */ public List<Classification> list(String classificationName) { assertArgumentNotNull("classificationName", classificationName); final String delimiter = GROUP_DELIMITER; final String pureName; final String groupName; if (classificationName.contains(delimiter)) { // e.g. sea.land or maihamadb-sea.land pureName = Srl.substringFirstFront(classificationName, delimiter); // e.g. sea or maihamadb-sea groupName = Srl.substringFirstRear(classificationName, delimiter); // e.g. land } else { // e.g. sea or maihamadb-sea pureName = classificationName; groupName = null; } final ClassificationMeta meta = findClassificationMeta(pureName, () -> { return "list('" + classificationName + "')"; }); if (groupName != null) { final List<Classification> groupOfList = meta.groupOf(groupName); if (groupOfList.isEmpty()) { // means not found throw new TemplateProcessingException("Not found the classification group: " + groupName + " of " + pureName); } return groupOfList; } else { return meta.listAll(); } } // ----------------------------------------------------- // listAll() // --------- /** * Get list of all classification. * @param classificationName The name of classification. (NotNull) * @return The list of all classification. (NotNull) */ public List<Classification> listAll(String classificationName) { assertArgumentNotNull("classificationName", classificationName); return findClassificationMeta(classificationName, () -> { return "listAll('" + classificationName + "')"; }).listAll(); } // ----------------------------------------------------- // alias() // ------- /** * Get classification alias. * @param cls The instance of classification to get code. (NotNull) * @return The alias of classification. (NotNull: if not classification, throws exception) */ public String alias(Object cls) { assertArgumentNotNull("cls", cls); assertCanBeClassification(cls); return findClassificationAlias((Classification) cls); } /** * Get classification alias or default value if the classification is null. * @param cls The instance of classification to get code. (NotNull) * @param defaultValue The default value for no classification. (NotNull, EmptyAllowed) * @return The alias of classification. (NotNull: if not classification, throws exception) */ public String alias(Object cls, String defaultValue) { assertArgumentNotNull("defaultValue", defaultValue); if (cls != null) { return alias(cls); } else { return defaultValue; } } /** * Get classification alias. * @param classificationName The name of classification. (NotNull) * @param elementName The name of classification element. (NotNull) * @return classification alias (NotNull: if not found, throws exception) */ public String alias(String classificationName, String elementName) { assertArgumentNotNull("classificationName", classificationName); assertArgumentNotNull("elementName", elementName); final ClassificationMeta meta = findClassificationMeta((String) classificationName, () -> { return "alias('" + classificationName + "', '" + elementName + "')"; }); final Classification cls = meta.nameOf(elementName); assertClassificationByNameExists(classificationName, elementName, cls); return findClassificationAlias(cls); } // ----------------------------------------------------- // code() // ------ /** * Get classification code. * @param cls The instance of classification to get code. (NotNull) * @return The code of classification. (NotNull: if not classification, throws exception) */ public String code(Object cls) { assertArgumentNotNull("cls", cls); assertCanBeClassification(cls); return ((Classification) cls).code(); } /** * Get classification code. * @param classificationName The name of classification. (NotNull) * @param elementName The name of classification element. (NotNull) * @return The found code of classification. (NotNull: if not found, throws exception) */ public String code(String classificationName, String elementName) { assertArgumentNotNull("classificationName", classificationName); assertArgumentNotNull("elementName", elementName); final ClassificationMeta meta = findClassificationMeta((String) classificationName, () -> { return "code('" + classificationName + "', '" + elementName + "')"; }); final Classification cls = meta.nameOf(elementName); assertClassificationByNameExists(classificationName, elementName, cls); return cls.code(); } // ----------------------------------------------------- // ...Of() // ------- /** * Get classification by code. * @param classificationName The name of classification. (NotNull) * @param code The code of classification to find. (NotNull) * @return The found instance of classification for the code. (NotNull: if not found, throws exception) */ public Classification codeOf(String classificationName, String code) { assertArgumentNotNull("elementName", classificationName); assertArgumentNotNull("code", code); return findClassificationMeta(classificationName, () -> { return "codeOf('" + classificationName + "', '" + code + "')"; }).codeOf(code); } /** * Get classification by name. * @param classificationName The name of classification. (NotNull) * @param name The name of classification to find. (NotNull) * @return The found instance of classification for the code. (NotNull: if not found, throws exception) */ public Classification nameOf(String classificationName, String name) { return findClassificationMeta((String) classificationName, () -> { return "nameOf('" + classificationName + "', '" + name + "')"; }).nameOf(name); } // =================================================================================== // Thymeleaf Resource // ================== protected Locale getUserLocale() { // not null return context.getLocale(); // from web context (synchronized with requestManager's user locale) } protected String getRequestTemplatePath() { // null allowed (basically not null, just in case) if (context instanceof WebEngineContext) { // basically true final TemplateData templateData = ((WebEngineContext) context).getTemplateData(); if (templateData != null) { // basically true return templateData.getTemplate(); // not null (by JavaDoc) } } return null; } // =================================================================================== // Classification // ============== protected ClassificationMeta findClassificationMeta(String classificationName, Supplier<Object> callerInfo) { return provideClassificationMeta(getListedClassificationProvider(), classificationName, callerInfo); } protected String findClassificationAlias(Classification cls) { return determineClassificationAliasKey().map(key -> { return (String) cls.subItemMap().get(key); }).orElse(cls.alias()); } protected OptionalThing<String> determineClassificationAliasKey() { return getListedClassificationProvider().determineAlias(getUserLocale()); } protected ListedClassificationProvider getListedClassificationProvider() { return getAssistantDirector().assistDbDirection().assistListedClassificationProvider(); } protected ClassificationMeta provideClassificationMeta(ListedClassificationProvider provider, String classificationName, Supplier<Object> callerInfo) { try { return provider.provide(classificationName); } catch (ProvidedClassificationNotFoundException e) { throwListedClassificationNotFoundException(classificationName, callerInfo, e); return null; // unreachable } } protected void throwListedClassificationNotFoundException(String classificationName, Supplier<Object> callerInfo, ProvidedClassificationNotFoundException cause) { final ExceptionMessageBuilder br = new ExceptionMessageBuilder(); br.addNotice("Not found the classification for the list."); br.addItem("Requested Template Path"); br.addElement(getRequestTemplatePath()); br.addItem("Target Expression"); br.addElement(callerInfo.get()); br.addItem("Classification Name"); br.addElement(classificationName); final String msg = br.buildExceptionMessage(); throw new TemplateProcessingException(msg, cause); } // //// =================================================================================== //// Component //// ========= protected FwAssistantDirector getAssistantDirector() { return getComponent(FwAssistantDirector.class); } protected <COMPONENT> COMPONENT getComponent(Class<COMPONENT> type) { return ContainerUtil.getComponent(type); } //// =================================================================================== //// Assert Helper //// ============= protected void assertCanBeClassification(Object cls) { if (!(cls instanceof Classification)) { throwNonClassificationObjectSpecifiedException(cls); } } protected void throwNonClassificationObjectSpecifiedException(Object cls) { final ExceptionMessageBuilder br = new ExceptionMessageBuilder(); br.addNotice("Non classification object specified."); br.addItem("Specified Object"); br.addElement(cls != null ? cls.getClass() : null); br.addElement(cls); final String msg = br.buildExceptionMessage(); throw new TemplateProcessingException(msg); } protected void assertClassificationByNameExists(String classificationName, String elementName, Classification cls) { if (cls == null) { throwClassificationByNameNotFoundException(classificationName, elementName); } } protected void throwClassificationByNameNotFoundException(String classificationName, String elementName) { final ExceptionMessageBuilder br = new ExceptionMessageBuilder(); br.addNotice("Non found the classification by the name."); br.addItem("Classification Name"); br.addElement(classificationName); br.addItem("Specified Name"); br.addElement(elementName); final String msg = br.buildExceptionMessage(); throw new TemplateProcessingException(msg); } protected void assertArgumentNotNull(String variableName, Object value) { if (variableName == null) { throw new IllegalArgumentException("The argument 'variableName' should not be null."); } if (value == null) { throw new IllegalArgumentException("The argument '" + variableName + "' should not be null."); } } }
[ "public", "class", "ClassificationExpressionObject", "{", "public", "static", "final", "String", "GROUP_DELIMITER", "=", "\"", ".", "\"", ";", "private", "final", "IExpressionContext", "context", ";", "public", "ClassificationExpressionObject", "(", "IExpressionContext", "context", ")", "{", "this", ".", "context", "=", "context", ";", "}", "/**\n * Get list of specified classification.\n * @param classificationName The name of classification, can contain group name by delimiter. (NotNull)\n * @return The list of all classification. (NotNull)\n */", "public", "List", "<", "Classification", ">", "list", "(", "String", "classificationName", ")", "{", "assertArgumentNotNull", "(", "\"", "classificationName", "\"", ",", "classificationName", ")", ";", "final", "String", "delimiter", "=", "GROUP_DELIMITER", ";", "final", "String", "pureName", ";", "final", "String", "groupName", ";", "if", "(", "classificationName", ".", "contains", "(", "delimiter", ")", ")", "{", "pureName", "=", "Srl", ".", "substringFirstFront", "(", "classificationName", ",", "delimiter", ")", ";", "groupName", "=", "Srl", ".", "substringFirstRear", "(", "classificationName", ",", "delimiter", ")", ";", "}", "else", "{", "pureName", "=", "classificationName", ";", "groupName", "=", "null", ";", "}", "final", "ClassificationMeta", "meta", "=", "findClassificationMeta", "(", "pureName", ",", "(", ")", "->", "{", "return", "\"", "list('", "\"", "+", "classificationName", "+", "\"", "')", "\"", ";", "}", ")", ";", "if", "(", "groupName", "!=", "null", ")", "{", "final", "List", "<", "Classification", ">", "groupOfList", "=", "meta", ".", "groupOf", "(", "groupName", ")", ";", "if", "(", "groupOfList", ".", "isEmpty", "(", ")", ")", "{", "throw", "new", "TemplateProcessingException", "(", "\"", "Not found the classification group: ", "\"", "+", "groupName", "+", "\"", " of ", "\"", "+", "pureName", ")", ";", "}", "return", "groupOfList", ";", "}", "else", "{", "return", "meta", ".", "listAll", "(", ")", ";", "}", "}", "/**\n * Get list of all classification.\n * @param classificationName The name of classification. (NotNull)\n * @return The list of all classification. (NotNull)\n */", "public", "List", "<", "Classification", ">", "listAll", "(", "String", "classificationName", ")", "{", "assertArgumentNotNull", "(", "\"", "classificationName", "\"", ",", "classificationName", ")", ";", "return", "findClassificationMeta", "(", "classificationName", ",", "(", ")", "->", "{", "return", "\"", "listAll('", "\"", "+", "classificationName", "+", "\"", "')", "\"", ";", "}", ")", ".", "listAll", "(", ")", ";", "}", "/**\n * Get classification alias.\n * @param cls The instance of classification to get code. (NotNull)\n * @return The alias of classification. (NotNull: if not classification, throws exception)\n */", "public", "String", "alias", "(", "Object", "cls", ")", "{", "assertArgumentNotNull", "(", "\"", "cls", "\"", ",", "cls", ")", ";", "assertCanBeClassification", "(", "cls", ")", ";", "return", "findClassificationAlias", "(", "(", "Classification", ")", "cls", ")", ";", "}", "/**\n * Get classification alias or default value if the classification is null.\n * @param cls The instance of classification to get code. (NotNull)\n * @param defaultValue The default value for no classification. (NotNull, EmptyAllowed)\n * @return The alias of classification. (NotNull: if not classification, throws exception)\n */", "public", "String", "alias", "(", "Object", "cls", ",", "String", "defaultValue", ")", "{", "assertArgumentNotNull", "(", "\"", "defaultValue", "\"", ",", "defaultValue", ")", ";", "if", "(", "cls", "!=", "null", ")", "{", "return", "alias", "(", "cls", ")", ";", "}", "else", "{", "return", "defaultValue", ";", "}", "}", "/**\n * Get classification alias.\n * @param classificationName The name of classification. (NotNull)\n * @param elementName The name of classification element. (NotNull)\n * @return classification alias (NotNull: if not found, throws exception)\n */", "public", "String", "alias", "(", "String", "classificationName", ",", "String", "elementName", ")", "{", "assertArgumentNotNull", "(", "\"", "classificationName", "\"", ",", "classificationName", ")", ";", "assertArgumentNotNull", "(", "\"", "elementName", "\"", ",", "elementName", ")", ";", "final", "ClassificationMeta", "meta", "=", "findClassificationMeta", "(", "(", "String", ")", "classificationName", ",", "(", ")", "->", "{", "return", "\"", "alias('", "\"", "+", "classificationName", "+", "\"", "', '", "\"", "+", "elementName", "+", "\"", "')", "\"", ";", "}", ")", ";", "final", "Classification", "cls", "=", "meta", ".", "nameOf", "(", "elementName", ")", ";", "assertClassificationByNameExists", "(", "classificationName", ",", "elementName", ",", "cls", ")", ";", "return", "findClassificationAlias", "(", "cls", ")", ";", "}", "/**\n * Get classification code.\n * @param cls The instance of classification to get code. (NotNull)\n * @return The code of classification. (NotNull: if not classification, throws exception)\n */", "public", "String", "code", "(", "Object", "cls", ")", "{", "assertArgumentNotNull", "(", "\"", "cls", "\"", ",", "cls", ")", ";", "assertCanBeClassification", "(", "cls", ")", ";", "return", "(", "(", "Classification", ")", "cls", ")", ".", "code", "(", ")", ";", "}", "/**\n * Get classification code.\n * @param classificationName The name of classification. (NotNull)\n * @param elementName The name of classification element. (NotNull)\n * @return The found code of classification. (NotNull: if not found, throws exception)\n */", "public", "String", "code", "(", "String", "classificationName", ",", "String", "elementName", ")", "{", "assertArgumentNotNull", "(", "\"", "classificationName", "\"", ",", "classificationName", ")", ";", "assertArgumentNotNull", "(", "\"", "elementName", "\"", ",", "elementName", ")", ";", "final", "ClassificationMeta", "meta", "=", "findClassificationMeta", "(", "(", "String", ")", "classificationName", ",", "(", ")", "->", "{", "return", "\"", "code('", "\"", "+", "classificationName", "+", "\"", "', '", "\"", "+", "elementName", "+", "\"", "')", "\"", ";", "}", ")", ";", "final", "Classification", "cls", "=", "meta", ".", "nameOf", "(", "elementName", ")", ";", "assertClassificationByNameExists", "(", "classificationName", ",", "elementName", ",", "cls", ")", ";", "return", "cls", ".", "code", "(", ")", ";", "}", "/**\n * Get classification by code.\n * @param classificationName The name of classification. (NotNull)\n * @param code The code of classification to find. (NotNull)\n * @return The found instance of classification for the code. (NotNull: if not found, throws exception)\n */", "public", "Classification", "codeOf", "(", "String", "classificationName", ",", "String", "code", ")", "{", "assertArgumentNotNull", "(", "\"", "elementName", "\"", ",", "classificationName", ")", ";", "assertArgumentNotNull", "(", "\"", "code", "\"", ",", "code", ")", ";", "return", "findClassificationMeta", "(", "classificationName", ",", "(", ")", "->", "{", "return", "\"", "codeOf('", "\"", "+", "classificationName", "+", "\"", "', '", "\"", "+", "code", "+", "\"", "')", "\"", ";", "}", ")", ".", "codeOf", "(", "code", ")", ";", "}", "/**\n * Get classification by name.\n * @param classificationName The name of classification. (NotNull)\n * @param name The name of classification to find. (NotNull)\n * @return The found instance of classification for the code. (NotNull: if not found, throws exception)\n */", "public", "Classification", "nameOf", "(", "String", "classificationName", ",", "String", "name", ")", "{", "return", "findClassificationMeta", "(", "(", "String", ")", "classificationName", ",", "(", ")", "->", "{", "return", "\"", "nameOf('", "\"", "+", "classificationName", "+", "\"", "', '", "\"", "+", "name", "+", "\"", "')", "\"", ";", "}", ")", ".", "nameOf", "(", "name", ")", ";", "}", "protected", "Locale", "getUserLocale", "(", ")", "{", "return", "context", ".", "getLocale", "(", ")", ";", "}", "protected", "String", "getRequestTemplatePath", "(", ")", "{", "if", "(", "context", "instanceof", "WebEngineContext", ")", "{", "final", "TemplateData", "templateData", "=", "(", "(", "WebEngineContext", ")", "context", ")", ".", "getTemplateData", "(", ")", ";", "if", "(", "templateData", "!=", "null", ")", "{", "return", "templateData", ".", "getTemplate", "(", ")", ";", "}", "}", "return", "null", ";", "}", "protected", "ClassificationMeta", "findClassificationMeta", "(", "String", "classificationName", ",", "Supplier", "<", "Object", ">", "callerInfo", ")", "{", "return", "provideClassificationMeta", "(", "getListedClassificationProvider", "(", ")", ",", "classificationName", ",", "callerInfo", ")", ";", "}", "protected", "String", "findClassificationAlias", "(", "Classification", "cls", ")", "{", "return", "determineClassificationAliasKey", "(", ")", ".", "map", "(", "key", "->", "{", "return", "(", "String", ")", "cls", ".", "subItemMap", "(", ")", ".", "get", "(", "key", ")", ";", "}", ")", ".", "orElse", "(", "cls", ".", "alias", "(", ")", ")", ";", "}", "protected", "OptionalThing", "<", "String", ">", "determineClassificationAliasKey", "(", ")", "{", "return", "getListedClassificationProvider", "(", ")", ".", "determineAlias", "(", "getUserLocale", "(", ")", ")", ";", "}", "protected", "ListedClassificationProvider", "getListedClassificationProvider", "(", ")", "{", "return", "getAssistantDirector", "(", ")", ".", "assistDbDirection", "(", ")", ".", "assistListedClassificationProvider", "(", ")", ";", "}", "protected", "ClassificationMeta", "provideClassificationMeta", "(", "ListedClassificationProvider", "provider", ",", "String", "classificationName", ",", "Supplier", "<", "Object", ">", "callerInfo", ")", "{", "try", "{", "return", "provider", ".", "provide", "(", "classificationName", ")", ";", "}", "catch", "(", "ProvidedClassificationNotFoundException", "e", ")", "{", "throwListedClassificationNotFoundException", "(", "classificationName", ",", "callerInfo", ",", "e", ")", ";", "return", "null", ";", "}", "}", "protected", "void", "throwListedClassificationNotFoundException", "(", "String", "classificationName", ",", "Supplier", "<", "Object", ">", "callerInfo", ",", "ProvidedClassificationNotFoundException", "cause", ")", "{", "final", "ExceptionMessageBuilder", "br", "=", "new", "ExceptionMessageBuilder", "(", ")", ";", "br", ".", "addNotice", "(", "\"", "Not found the classification for the list.", "\"", ")", ";", "br", ".", "addItem", "(", "\"", "Requested Template Path", "\"", ")", ";", "br", ".", "addElement", "(", "getRequestTemplatePath", "(", ")", ")", ";", "br", ".", "addItem", "(", "\"", "Target Expression", "\"", ")", ";", "br", ".", "addElement", "(", "callerInfo", ".", "get", "(", ")", ")", ";", "br", ".", "addItem", "(", "\"", "Classification Name", "\"", ")", ";", "br", ".", "addElement", "(", "classificationName", ")", ";", "final", "String", "msg", "=", "br", ".", "buildExceptionMessage", "(", ")", ";", "throw", "new", "TemplateProcessingException", "(", "msg", ",", "cause", ")", ";", "}", "protected", "FwAssistantDirector", "getAssistantDirector", "(", ")", "{", "return", "getComponent", "(", "FwAssistantDirector", ".", "class", ")", ";", "}", "protected", "<", "COMPONENT", ">", "COMPONENT", "getComponent", "(", "Class", "<", "COMPONENT", ">", "type", ")", "{", "return", "ContainerUtil", ".", "getComponent", "(", "type", ")", ";", "}", "protected", "void", "assertCanBeClassification", "(", "Object", "cls", ")", "{", "if", "(", "!", "(", "cls", "instanceof", "Classification", ")", ")", "{", "throwNonClassificationObjectSpecifiedException", "(", "cls", ")", ";", "}", "}", "protected", "void", "throwNonClassificationObjectSpecifiedException", "(", "Object", "cls", ")", "{", "final", "ExceptionMessageBuilder", "br", "=", "new", "ExceptionMessageBuilder", "(", ")", ";", "br", ".", "addNotice", "(", "\"", "Non classification object specified.", "\"", ")", ";", "br", ".", "addItem", "(", "\"", "Specified Object", "\"", ")", ";", "br", ".", "addElement", "(", "cls", "!=", "null", "?", "cls", ".", "getClass", "(", ")", ":", "null", ")", ";", "br", ".", "addElement", "(", "cls", ")", ";", "final", "String", "msg", "=", "br", ".", "buildExceptionMessage", "(", ")", ";", "throw", "new", "TemplateProcessingException", "(", "msg", ")", ";", "}", "protected", "void", "assertClassificationByNameExists", "(", "String", "classificationName", ",", "String", "elementName", ",", "Classification", "cls", ")", "{", "if", "(", "cls", "==", "null", ")", "{", "throwClassificationByNameNotFoundException", "(", "classificationName", ",", "elementName", ")", ";", "}", "}", "protected", "void", "throwClassificationByNameNotFoundException", "(", "String", "classificationName", ",", "String", "elementName", ")", "{", "final", "ExceptionMessageBuilder", "br", "=", "new", "ExceptionMessageBuilder", "(", ")", ";", "br", ".", "addNotice", "(", "\"", "Non found the classification by the name.", "\"", ")", ";", "br", ".", "addItem", "(", "\"", "Classification Name", "\"", ")", ";", "br", ".", "addElement", "(", "classificationName", ")", ";", "br", ".", "addItem", "(", "\"", "Specified Name", "\"", ")", ";", "br", ".", "addElement", "(", "elementName", ")", ";", "final", "String", "msg", "=", "br", ".", "buildExceptionMessage", "(", ")", ";", "throw", "new", "TemplateProcessingException", "(", "msg", ")", ";", "}", "protected", "void", "assertArgumentNotNull", "(", "String", "variableName", ",", "Object", "value", ")", "{", "if", "(", "variableName", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"", "The argument 'variableName' should not be null.", "\"", ")", ";", "}", "if", "(", "value", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"", "The argument '", "\"", "+", "variableName", "+", "\"", "' should not be null.", "\"", ")", ";", "}", "}", "}" ]
Utility methods for Classification objects.<br> <pre> Usage: &lt;select&gt; &lt;option th:each="cdef : ${#cls.listAll('MemberStatus')}" th:value="${cdef.code()}" th:text="${cdef.alias()}"&gt;&lt;/option&gt; &lt;/select&gt;
[ "Utility", "methods", "for", "Classification", "objects", ".", "<br", ">", "<pre", ">", "Usage", ":", "&lt", ";", "select&gt", ";", "&lt", ";", "option", "th", ":", "each", "=", "\"", "cdef", ":", "$", "{", "#cls", ".", "listAll", "(", "'", "MemberStatus", "'", ")", "}", "\"", "th", ":", "value", "=", "\"", "$", "{", "cdef", ".", "code", "()", "}", "\"", "th", ":", "text", "=", "\"", "$", "{", "cdef", ".", "alias", "()", "}", "\"", "&gt", ";", "&lt", ";", "/", "option&gt", ";", "&lt", ";", "/", "select&gt", ";" ]
[ "// ===================================================================================", "// Definition", "// ==========", "// ===================================================================================", "// Attribute", "// =========", "// ===================================================================================", "// Constructor", "// ===========", "// ===================================================================================", "// Expression", "// ==========", "// -----------------------------------------------------", "// list()", "// ------", "// e.g. sea.land or maihamadb-sea.land", "// e.g. sea or maihamadb-sea", "// e.g. land", "// e.g. sea or maihamadb-sea", "// means not found", "// -----------------------------------------------------", "// listAll()", "// ---------", "// -----------------------------------------------------", "// alias()", "// -------", "// -----------------------------------------------------", "// code()", "// ------", "// -----------------------------------------------------", "// ...Of()", "// -------", "// ===================================================================================", "// Thymeleaf Resource", "// ==================", "// not null", "// from web context (synchronized with requestManager's user locale)", "// null allowed (basically not null, just in case)", "// basically true", "// basically true", "// not null (by JavaDoc)", "// ===================================================================================", "// Classification", "// ==============", "// unreachable", "//", "//// ===================================================================================", "//// Component", "//// =========", "//// ===================================================================================", "//// Assert Helper", "//// =============" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
17
2,297
189
23d7ba52fd7c8e2f048bf5d8470d85ca7aaf70f1
Dahlgren/Serverify-A3
A3ServerTool/Properties/StaticLang.Designer.cs
[ "MIT" ]
C#
StaticLang
/// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project.
A strongly-typed resource class, for looking up localized strings, etc.
[ "A", "strongly", "-", "typed", "resource", "class", "for", "looking", "up", "localized", "strings", "etc", "." ]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] public class StaticLang { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal StaticLang() { } [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] public static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("A3ServerTool.Properties.StaticLang", typeof(StaticLang).Assembly); resourceMan = temp; } return resourceMan; } } [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] public static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } public static string AboutHamburgerMenuLozalizedTitle { get { return ResourceManager.GetString("AboutHamburgerMenuLozalizedTitle", resourceCulture); } } public static string AboutHamburgerMenuLozalizedTooltip { get { return ResourceManager.GetString("AboutHamburgerMenuLozalizedTooltip", resourceCulture); } } public static string ProfileDialogCreateButtonText { get { return ResourceManager.GetString("ProfileDialogCreateButtonText", resourceCulture); } } public static string ProfileDialogEditButtonText { get { return ResourceManager.GetString("ProfileDialogEditButtonText", resourceCulture); } } public static string ProfileDialogSaveButtonText { get { return ResourceManager.GetString("ProfileDialogSaveButtonText", resourceCulture); } } public static string ProfileDialogViewEditHeader { get { return ResourceManager.GetString("ProfileDialogViewEditHeader", resourceCulture); } } public static string ProfileDialogViewHeader { get { return ResourceManager.GetString("ProfileDialogViewHeader", resourceCulture); } } public static string ProfileDialogViewSaveHeader { get { return ResourceManager.GetString("ProfileDialogViewSaveHeader", resourceCulture); } } public static string ProfilesHamburgerMenuLocalizedTitle { get { return ResourceManager.GetString("ProfilesHamburgerMenuLocalizedTitle", resourceCulture); } } public static string ProfilesHamburgerMenuLocalizedTooltip { get { return ResourceManager.GetString("ProfilesHamburgerMenuLocalizedTooltip", resourceCulture); } } public static string ServerHamburgerMenuLocalizedTitle { get { return ResourceManager.GetString("ServerHamburgerMenuLocalizedTitle", resourceCulture); } } public static string ServerHamburgerMenuLocalizedTooltip { get { return ResourceManager.GetString("ServerHamburgerMenuLocalizedTooltip", resourceCulture); } } public static string SettingsHamburgerMenuLozalizedTitle { get { return ResourceManager.GetString("SettingsHamburgerMenuLozalizedTitle", resourceCulture); } } public static string SettingsHamburgerMenuLozalizedTooltip { get { return ResourceManager.GetString("SettingsHamburgerMenuLozalizedTooltip", resourceCulture); } } public static string SuccessfulSavedProfileText { get { return ResourceManager.GetString("SuccessfulSavedProfileText", resourceCulture); } } public static string SuccessTitle { get { return ResourceManager.GetString("SuccessTitle", resourceCulture); } } }
[ "[", "global", "::", "System", ".", "CodeDom", ".", "Compiler", ".", "GeneratedCodeAttribute", "(", "\"", "System.Resources.Tools.StronglyTypedResourceBuilder", "\"", ",", "\"", "16.0.0.0", "\"", ")", "]", "[", "global", "::", "System", ".", "Diagnostics", ".", "DebuggerNonUserCodeAttribute", "(", ")", "]", "[", "global", "::", "System", ".", "Runtime", ".", "CompilerServices", ".", "CompilerGeneratedAttribute", "(", ")", "]", "public", "class", "StaticLang", "{", "private", "static", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "resourceMan", ";", "private", "static", "global", "::", "System", ".", "Globalization", ".", "CultureInfo", "resourceCulture", ";", "[", "global", "::", "System", ".", "Diagnostics", ".", "CodeAnalysis", ".", "SuppressMessageAttribute", "(", "\"", "Microsoft.Performance", "\"", ",", "\"", "CA1811:AvoidUncalledPrivateCode", "\"", ")", "]", "internal", "StaticLang", "(", ")", "{", "}", "[", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableAttribute", "(", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableState", ".", "Advanced", ")", "]", "public", "static", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "ResourceManager", "{", "get", "{", "if", "(", "object", ".", "ReferenceEquals", "(", "resourceMan", ",", "null", ")", ")", "{", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "temp", "=", "new", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "(", "\"", "A3ServerTool.Properties.StaticLang", "\"", ",", "typeof", "(", "StaticLang", ")", ".", "Assembly", ")", ";", "resourceMan", "=", "temp", ";", "}", "return", "resourceMan", ";", "}", "}", "[", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableAttribute", "(", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableState", ".", "Advanced", ")", "]", "public", "static", "global", "::", "System", ".", "Globalization", ".", "CultureInfo", "Culture", "{", "get", "{", "return", "resourceCulture", ";", "}", "set", "{", "resourceCulture", "=", "value", ";", "}", "}", "public", "static", "string", "AboutHamburgerMenuLozalizedTitle", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "AboutHamburgerMenuLozalizedTitle", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "AboutHamburgerMenuLozalizedTooltip", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "AboutHamburgerMenuLozalizedTooltip", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "ProfileDialogCreateButtonText", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "ProfileDialogCreateButtonText", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "ProfileDialogEditButtonText", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "ProfileDialogEditButtonText", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "ProfileDialogSaveButtonText", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "ProfileDialogSaveButtonText", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "ProfileDialogViewEditHeader", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "ProfileDialogViewEditHeader", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "ProfileDialogViewHeader", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "ProfileDialogViewHeader", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "ProfileDialogViewSaveHeader", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "ProfileDialogViewSaveHeader", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "ProfilesHamburgerMenuLocalizedTitle", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "ProfilesHamburgerMenuLocalizedTitle", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "ProfilesHamburgerMenuLocalizedTooltip", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "ProfilesHamburgerMenuLocalizedTooltip", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "ServerHamburgerMenuLocalizedTitle", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "ServerHamburgerMenuLocalizedTitle", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "ServerHamburgerMenuLocalizedTooltip", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "ServerHamburgerMenuLocalizedTooltip", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "SettingsHamburgerMenuLozalizedTitle", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "SettingsHamburgerMenuLozalizedTitle", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "SettingsHamburgerMenuLozalizedTooltip", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "SettingsHamburgerMenuLozalizedTooltip", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "SuccessfulSavedProfileText", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "SuccessfulSavedProfileText", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "SuccessTitle", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "SuccessTitle", "\"", ",", "resourceCulture", ")", ";", "}", "}", "}" ]
A strongly-typed resource class, for looking up localized strings, etc.
[ "A", "strongly", "-", "typed", "resource", "class", "for", "looking", "up", "localized", "strings", "etc", "." ]
[ "/// <summary>", "/// Returns the cached ResourceManager instance used by this class.", "/// </summary>", "/// <summary>", "/// Overrides the current thread's CurrentUICulture property for all", "/// resource lookups using this strongly typed resource class.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to About.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Info about author and application itself..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Create.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Edit.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Save.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Edit Profile.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Create Profile.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Save Profile.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Profiles.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Server profiles..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Server.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to General game server tuning..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Settings.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Application settings..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Profile was saved..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Success.", "/// </summary>" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
17
788
84
e9a8cc81dc2c6eface6510be92836855e3f88264
HelloKitty/Testity
src/Testity.EngineServices/Collections/EngineObjectReferenceDictionary.cs
[ "MIT" ]
C#
EngineObjectReferenceDictionary
/// <summary> /// Dictionary/map that explictly requires a custom <see cref="IEqualityComparer{TEngineObjectType}"/>. This is for mapping <typeparamref name="TEngineObjectType"/>s to references of <typeparamref name="TActualEngineObjectType"/>. /// </summary> /// <typeparam name="TEngineObjectType">Engine object adapter type.</typeparam> /// <typeparam name="TActualEngineObjectType">Actual game engine's object type.</typeparam>
Dictionary/map that explictly requires a custom . This is for mapping s to references of .
[ "Dictionary", "/", "map", "that", "explictly", "requires", "a", "custom", ".", "This", "is", "for", "mapping", "s", "to", "references", "of", "." ]
[Serializable] public class EngineObjectReferenceDictionary<TEngineObjectType, TActualEngineObjectType> : Dictionary<TEngineObjectType, TActualEngineObjectType>, IReadOnlyMapLookup<TEngineObjectType, TActualEngineObjectType> where TEngineObjectType : class, IEngineObject where TActualEngineObjectType : class { public EngineObjectReferenceDictionary() : base() { } public EngineObjectReferenceDictionary(int initialSize) : base(initialSize) { } public EngineObjectReferenceDictionary(IEqualityComparer<TEngineObjectType> customEngineObjectEqualityComparer) : base(customEngineObjectEqualityComparer) { } public EngineObjectReferenceDictionary(int initialSize, IEqualityComparer<TEngineObjectType> customEngineObjectEqualityComparer) : base(initialSize, customEngineObjectEqualityComparer) { } public bool Register(TEngineObjectType keyToRegister, TActualEngineObjectType referenceToRegister) { if (keyToRegister == null) throw new ArgumentNullException(nameof(keyToRegister), "Key cannot be null."); if(referenceToRegister == null) throw new ArgumentNullException(nameof(referenceToRegister), "Value cannot be null."); if (!ContainsKey(keyToRegister)) Add(keyToRegister, referenceToRegister); return true; } public TActualEngineObjectType TryLookup(TEngineObjectType key) { if (ContainsKey(key)) return this[key]; else return null; } public UnregistrationResult<TActualEngineObjectType> TryUnregister(TEngineObjectType objectToUnregister) { if (ContainsKey(objectToUnregister)) { TActualEngineObjectType value = this[objectToUnregister]; if (!Remove(objectToUnregister)) throw new InvalidOperationException("Failed to remove " + nameof(objectToUnregister) + " from map in " + GetType()); return new UnregistrationResult<TActualEngineObjectType>(true, value); } else return new UnregistrationResult<TActualEngineObjectType>(false, null); } }
[ "[", "Serializable", "]", "public", "class", "EngineObjectReferenceDictionary", "<", "TEngineObjectType", ",", "TActualEngineObjectType", ">", ":", "Dictionary", "<", "TEngineObjectType", ",", "TActualEngineObjectType", ">", ",", "IReadOnlyMapLookup", "<", "TEngineObjectType", ",", "TActualEngineObjectType", ">", "where", "TEngineObjectType", ":", "class", ",", "IEngineObject", "where", "TActualEngineObjectType", ":", "class", "{", "public", "EngineObjectReferenceDictionary", "(", ")", ":", "base", "(", ")", "{", "}", "public", "EngineObjectReferenceDictionary", "(", "int", "initialSize", ")", ":", "base", "(", "initialSize", ")", "{", "}", "public", "EngineObjectReferenceDictionary", "(", "IEqualityComparer", "<", "TEngineObjectType", ">", "customEngineObjectEqualityComparer", ")", ":", "base", "(", "customEngineObjectEqualityComparer", ")", "{", "}", "public", "EngineObjectReferenceDictionary", "(", "int", "initialSize", ",", "IEqualityComparer", "<", "TEngineObjectType", ">", "customEngineObjectEqualityComparer", ")", ":", "base", "(", "initialSize", ",", "customEngineObjectEqualityComparer", ")", "{", "}", "public", "bool", "Register", "(", "TEngineObjectType", "keyToRegister", ",", "TActualEngineObjectType", "referenceToRegister", ")", "{", "if", "(", "keyToRegister", "==", "null", ")", "throw", "new", "ArgumentNullException", "(", "nameof", "(", "keyToRegister", ")", ",", "\"", "Key cannot be null.", "\"", ")", ";", "if", "(", "referenceToRegister", "==", "null", ")", "throw", "new", "ArgumentNullException", "(", "nameof", "(", "referenceToRegister", ")", ",", "\"", "Value cannot be null.", "\"", ")", ";", "if", "(", "!", "ContainsKey", "(", "keyToRegister", ")", ")", "Add", "(", "keyToRegister", ",", "referenceToRegister", ")", ";", "return", "true", ";", "}", "public", "TActualEngineObjectType", "TryLookup", "(", "TEngineObjectType", "key", ")", "{", "if", "(", "ContainsKey", "(", "key", ")", ")", "return", "this", "[", "key", "]", ";", "else", "return", "null", ";", "}", "public", "UnregistrationResult", "<", "TActualEngineObjectType", ">", "TryUnregister", "(", "TEngineObjectType", "objectToUnregister", ")", "{", "if", "(", "ContainsKey", "(", "objectToUnregister", ")", ")", "{", "TActualEngineObjectType", "value", "=", "this", "[", "objectToUnregister", "]", ";", "if", "(", "!", "Remove", "(", "objectToUnregister", ")", ")", "throw", "new", "InvalidOperationException", "(", "\"", "Failed to remove ", "\"", "+", "nameof", "(", "objectToUnregister", ")", "+", "\"", " from map in ", "\"", "+", "GetType", "(", ")", ")", ";", "return", "new", "UnregistrationResult", "<", "TActualEngineObjectType", ">", "(", "true", ",", "value", ")", ";", "}", "else", "return", "new", "UnregistrationResult", "<", "TActualEngineObjectType", ">", "(", "false", ",", "null", ")", ";", "}", "}" ]
Dictionary/map that explictly requires a custom .
[ "Dictionary", "/", "map", "that", "explictly", "requires", "a", "custom", "." ]
[ "/// <summary>", "/// Initializes a dictionary with the default <see cref=\"IEqualityComparer{TEngineObjectType}\"/>.", "/// </summary>", "/// <summary>", "/// Initializes a dictionary with the default <see cref=\"IEqualityComparer{TEngineObjectType}\"/>.", "/// <param name=\"initialSize\">Intial size of the dictionary.</param>", "/// </summary>", "/// <summary>", "/// Initializes a dictionary with the custom <see cref=\"IEqualityComparer{TEngineObjectType}\"/>.", "/// </summary>", "/// <param name=\"customEngineObjectEqualityComparer\">Custom reference equality comparer.</param>", "/// <summary>", "/// Initializes a dictionary with the custom <see cref=\"IEqualityComparer{TEngineObjectType}\"/> with an intialize size.", "/// </summary>", "/// <param name=\"customEngineObjectEqualityComparer\">Custom reference equality comparer.</param>", "/// <param name=\"initialSize\">Intial size of the dictionary.</param>", "/// <summary>", "/// Attempts to register a reference to <typeparamref name=\"TActualEngineObjectType\"/> with the key being <typeparamref name=\"TEngineObjectType\"/>.", "/// </summary>", "/// <param name=\"keyToRegister\">Key to store the reference under.</param>", "/// <param name=\"referenceToRegister\">Reference to store.</param>", "/// <returns>Indicates if the object is stored.</returns>", "/// <exception cref=\"ArgumentNullException\">Throws if either arg is null.</exception>", "/// <summary>", "/// Attempts to lookup an instance of <see cref=\"TValue\"/> using the specified <see cref=\"TKey\"/>.", "/// </summary>", "/// <param name=\"key\">Key value.</param>", "/// <returns>If found it returning the stored <see cref=\"TValue\"/> instance. Otherwise null.</returns>", "/// <exception cref=\"ArgumentNullException\">Will throw if key is null.</exception>", "/// <summary>", "/// Attempts to unregister the <typeparamref name=\"TEngineObjectType\"/> key. Returns the unregistered object if possible.", "/// </summary>", "/// <param name=\"objectToUnregister\">Key to unregister.</param>", "/// <returns>A result object that indicates failure or success. May contain the <typeparamref name=\"TActualEngineObjectType\"/> object.</returns>", "//shouldn't ever fail" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [ { "identifier": "typeparam", "docstring": "Engine object adapter type.", "docstring_tokens": [ "Engine", "object", "adapter", "type", "." ] }, { "identifier": "typeparam", "docstring": "Actual game engine's object type.", "docstring_tokens": [ "Actual", "game", "engine", "'", "s", "object", "type", "." ] } ] }
false
18
441
93
882fd491a028af356fe1990fa3bb654acd544d8c
SJonesy/UOMUD
com/planet_ink/coffee_mud/Abilities/Properties/Prop_LotsForSale.java
[ "Apache-2.0" ]
Java
Prop_LotsForSale
/* Copyright 2003-2017 Bo Zimmerman 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. */
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.
[ "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", "." ]
public class Prop_LotsForSale extends Prop_RoomForSale { @Override public String ID() { return "Prop_LotsForSale"; } @Override public String name() { return "Putting many rooms up for sale"; } protected String uniqueLotID = null; @Override public boolean allowsExpansionConstruction() { return true; } protected void fillCluster(Room R, List<Room> V) { V.add(R); for(int d=Directions.NUM_DIRECTIONS()-1;d>=0;d--) { final Room R2=R.getRoomInDir(d); if((R2!=null)&&(R2.roomID().length()>0)&&(!V.contains(R2))) { final Ability A=R2.fetchEffect(ID()); if((R2.getArea()==R.getArea())&&(A!=null)) fillCluster(R2,V); else { V.remove(R); // purpose here is to put the "front" door up front. V.add(0,R); } } } } @Override public List<Room> getConnectedPropertyRooms() { final List<Room> V=new ArrayList<Room>(); Room R=null; if(affected instanceof Room) R=(Room)affected; else R=CMLib.map().getRoom(landPropertyID()); if(R!=null) { fillCluster(R,V); String uniqueID="LOTS_PROPERTY_"+this; if(V.size()>0) uniqueID="LOTS_PROPERTY_"+CMLib.map().getExtendedRoomID(V.get(0)); for(final Iterator<Room> r=V.iterator();r.hasNext();) { Ability A=null; R=r.next(); if(R!=null) A=R.fetchEffect(ID()); if(A instanceof Prop_LotsForSale) ((Prop_LotsForSale)A).uniqueLotID=uniqueID; } } else uniqueLotID=""; return V; } protected boolean isRetractableLink(Map<Room,Boolean> recurseChkRooms, Room fromRoom, Room theRoom) { if(theRoom==null) return true; if((theRoom.roomID().length()>0) &&((CMLib.law().getLandTitle(theRoom)==null) ||(CMLib.law().getLandTitle(theRoom).getOwnerName().length()>0))) { if(recurseChkRooms != null) recurseChkRooms.put(theRoom, Boolean.valueOf(false)); return false; } for(int d=Directions.NUM_DIRECTIONS()-1;d>=0;d--) { final Room R=theRoom.rawDoors()[d]; if(R!=null) { if((recurseChkRooms != null) &&(recurseChkRooms.containsKey(R))) return recurseChkRooms.get(theRoom).booleanValue(); if((R!=fromRoom) &&(R.roomID().length()>0)) { if((CMLib.law().getLandTitle(R)==null)||(CMLib.law().getLandTitle(R).getOwnerName().length()>0)) { if(recurseChkRooms != null) recurseChkRooms.put(theRoom, Boolean.valueOf(false)); return false; } if((recurseChkRooms != null) &&(!isRetractableLink(recurseChkRooms,theRoom,R))) { recurseChkRooms.put(theRoom, Boolean.valueOf(false)); return false; } } } } if(recurseChkRooms != null) recurseChkRooms.put(theRoom, Boolean.valueOf(true)); return true; } @Override public String getUniqueLotID() { if(uniqueLotID==null) getConnectedPropertyRooms(); return uniqueLotID; } @Override public LandTitle generateNextRoomTitle() { final LandTitle newTitle=(LandTitle)this.copyOf(); newTitle.setOwnerName(""); newTitle.setBackTaxes(0); return newTitle; } protected boolean canGenerateAdjacentRooms(Room R) { return getOwnerName().length()>0; } protected boolean retractRooms(final Room R, List<Runnable> postWork) { boolean updateExits=false; boolean foundOne=false; boolean didAnything = false; final Map<Room,Boolean> checkedRetractRooms; if(super.gridLayout()) checkedRetractRooms = new Hashtable<Room,Boolean>(); else checkedRetractRooms = null; for(int d=0;d<Directions.NUM_DIRECTIONS();d++) { if(d==Directions.GATE) continue; final Room R2=R.rawDoors()[d]; if((R2!=null)&&((!R2.isSavable())||(R2.roomID().length()==0))) continue; Exit E=R.getRawExit(d); if(checkedRetractRooms != null) checkedRetractRooms.clear(); if((R2!=null)&&(R2.rawDoors()[Directions.getOpDirectionCode(d)]==R)) foundOne=true; else if((R2!=null) &&(isRetractableLink(checkedRetractRooms,R,R2))) { R.rawDoors()[d]=null; R.setRawExit(d,null); updateExits=true; postWork.add(new Runnable() { final Room room=R2; @Override public void run() { CMLib.map().obliterateRoom(room); } }); didAnything=true; } else if((E!=null)&&(E.hasALock())&&(E.isGeneric())) { E.setKeyName(""); E.setDoorsNLocks(E.hasADoor(),E.isOpen(),E.defaultsClosed(),false,false,false); updateExits=true; if(R2!=null) { E=R2.getRawExit(Directions.getOpDirectionCode(d)); if((E!=null)&&(E.hasALock())&&(E.isGeneric())) { E.setKeyName(""); E.setDoorsNLocks(E.hasADoor(),E.isOpen(),E.defaultsClosed(),false,false,false); postWork.add(new Runnable(){ final Room room=R2; @Override public void run() { CMLib.database().DBUpdateExits(room); R2.getArea().fillInAreaRoom(room); } }); didAnything=true; } } } } if(checkedRetractRooms != null) checkedRetractRooms.clear(); if(!foundOne) { CMLib.map().obliterateRoom(R); didAnything=true; } else if(updateExits) { CMLib.database().DBUpdateExits(R); R.getArea().fillInAreaRoom(R); didAnything=true; } return didAnything; } public boolean expandRooms(final Room R, final List<Runnable> postWork) { int numberOfPeers = -1;//getConnectedPropertyRooms().size(); final boolean doGrid=super.gridLayout(); long roomLimit = Long.MAX_VALUE; final Set<Room> updateExits=new HashSet<Room>(); Prop_ReqCapacity cap = null; boolean didAnything = false; for(int d=0;d<Directions.NUM_DIRECTIONS();d++) { if((d==Directions.UP)||(d==Directions.DOWN)||(d==Directions.GATE)) continue; final Room chkR=R.getRoomInDir(d); if((chkR==null)&&(numberOfPeers < 0)) { final List<Room> allRooms = getConnectedPropertyRooms(); if(allRooms.size()>0) { cap = (Prop_ReqCapacity)allRooms.get(0).fetchEffect("Prop_ReqCapacity"); if(cap != null) { roomLimit = cap.roomLimit; } } numberOfPeers = allRooms.size(); } if((chkR==null)&&(numberOfPeers < roomLimit)) { numberOfPeers++; final Room R2=CMClass.getLocale(CMClass.classID(R)); R2.setRoomID(R.getArea().getNewRoomID(R,d)); if(R2.roomID().length()==0) continue; R2.setArea(R.getArea()); LandTitle oldTitle=CMLib.law().getLandTitle(R); final LandTitle newTitle; if((oldTitle!=null)&&(CMLib.law().getLandTitle(R2)==null)) { newTitle = oldTitle.generateNextRoomTitle(); R2.addNonUninvokableEffect((Ability)newTitle); } else newTitle=null; R.rawDoors()[d]=R2; R.setRawExit(d,CMClass.getExit("Open")); R2.rawDoors()[Directions.getOpDirectionCode(d)]=R; R2.setRawExit(Directions.getOpDirectionCode(d),CMClass.getExit("Open")); updateExits.add(R); if(doGrid) { final PairVector<Room,int[]> rooms=CMLib.tracking().buildGridList(R2, this.getOwnerName(), 100); for(int dir=0;dir<Directions.NUM_DIRECTIONS();dir++) { if(dir==Directions.GATE) continue; Room R3=R2.getRoomInDir(dir); if(R3 == null) { R3=CMLib.tracking().getCalculatedAdjacentRoom(rooms, R3, dir); if(R3!=null) { R2.rawDoors()[dir]=R3; R3.rawDoors()[Directions.getOpDirectionCode(dir)]=R2; updateExits.add(R3); } } } } updateExits.add(R2); if(CMSecurity.isDebugging(CMSecurity.DbgFlag.PROPERTY)) Log.debugOut("Lots4Sale",R2.roomID()+" created and put up for sale."); if(cap != null) R2.addNonUninvokableEffect((Ability)cap.copyOf()); postWork.add(new Runnable() { final Room room = R2; final LandTitle title=newTitle; @Override public void run() { CMLib.database().DBCreateRoom(room); if(title!=null) CMLib.law().colorRoomForSale(room,title,true); room.getArea().fillInAreaRoom(room); } }); didAnything=true; } } if(updateExits.size()>0) { didAnything=true; R.getArea().fillInAreaRoom(R); postWork.add(new Runnable() { final Set<Room> updateExits2=new SHashSet<Room>(updateExits); @Override public void run() { for(Room xR : updateExits2) { CMLib.database().DBUpdateExits(xR); } } }); } return didAnything; } @Override public void updateLot(List<String> optPlayerList) { final Environmental EV=affected; if(!(EV instanceof Room)) return; Room R=(Room)EV; boolean didAnything=false; try { List<Runnable> postWork=new ArrayList<Runnable>(); synchronized(("SYNC"+R.roomID()).intern()) { R=CMLib.map().getRoom(R); lastItemNums=updateLotWithThisData(R,this,true,scheduleReset,optPlayerList,lastItemNums); if(getOwnerName().length()==0) { didAnything = retractRooms(R,postWork) || didAnything; } else if(canGenerateAdjacentRooms(R)) { didAnything = expandRooms(R,postWork) || didAnything; } } for(Runnable run : postWork) run.run(); scheduleReset=false; } finally { if(didAnything) getConnectedPropertyRooms(); // recalculates the unique id for this lot of rooms } } }
[ "public", "class", "Prop_LotsForSale", "extends", "Prop_RoomForSale", "{", "@", "Override", "public", "String", "ID", "(", ")", "{", "return", "\"", "Prop_LotsForSale", "\"", ";", "}", "@", "Override", "public", "String", "name", "(", ")", "{", "return", "\"", "Putting many rooms up for sale", "\"", ";", "}", "protected", "String", "uniqueLotID", "=", "null", ";", "@", "Override", "public", "boolean", "allowsExpansionConstruction", "(", ")", "{", "return", "true", ";", "}", "protected", "void", "fillCluster", "(", "Room", "R", ",", "List", "<", "Room", ">", "V", ")", "{", "V", ".", "add", "(", "R", ")", ";", "for", "(", "int", "d", "=", "Directions", ".", "NUM_DIRECTIONS", "(", ")", "-", "1", ";", "d", ">=", "0", ";", "d", "--", ")", "{", "final", "Room", "R2", "=", "R", ".", "getRoomInDir", "(", "d", ")", ";", "if", "(", "(", "R2", "!=", "null", ")", "&&", "(", "R2", ".", "roomID", "(", ")", ".", "length", "(", ")", ">", "0", ")", "&&", "(", "!", "V", ".", "contains", "(", "R2", ")", ")", ")", "{", "final", "Ability", "A", "=", "R2", ".", "fetchEffect", "(", "ID", "(", ")", ")", ";", "if", "(", "(", "R2", ".", "getArea", "(", ")", "==", "R", ".", "getArea", "(", ")", ")", "&&", "(", "A", "!=", "null", ")", ")", "fillCluster", "(", "R2", ",", "V", ")", ";", "else", "{", "V", ".", "remove", "(", "R", ")", ";", "V", ".", "add", "(", "0", ",", "R", ")", ";", "}", "}", "}", "}", "@", "Override", "public", "List", "<", "Room", ">", "getConnectedPropertyRooms", "(", ")", "{", "final", "List", "<", "Room", ">", "V", "=", "new", "ArrayList", "<", "Room", ">", "(", ")", ";", "Room", "R", "=", "null", ";", "if", "(", "affected", "instanceof", "Room", ")", "R", "=", "(", "Room", ")", "affected", ";", "else", "R", "=", "CMLib", ".", "map", "(", ")", ".", "getRoom", "(", "landPropertyID", "(", ")", ")", ";", "if", "(", "R", "!=", "null", ")", "{", "fillCluster", "(", "R", ",", "V", ")", ";", "String", "uniqueID", "=", "\"", "LOTS_PROPERTY_", "\"", "+", "this", ";", "if", "(", "V", ".", "size", "(", ")", ">", "0", ")", "uniqueID", "=", "\"", "LOTS_PROPERTY_", "\"", "+", "CMLib", ".", "map", "(", ")", ".", "getExtendedRoomID", "(", "V", ".", "get", "(", "0", ")", ")", ";", "for", "(", "final", "Iterator", "<", "Room", ">", "r", "=", "V", ".", "iterator", "(", ")", ";", "r", ".", "hasNext", "(", ")", ";", ")", "{", "Ability", "A", "=", "null", ";", "R", "=", "r", ".", "next", "(", ")", ";", "if", "(", "R", "!=", "null", ")", "A", "=", "R", ".", "fetchEffect", "(", "ID", "(", ")", ")", ";", "if", "(", "A", "instanceof", "Prop_LotsForSale", ")", "(", "(", "Prop_LotsForSale", ")", "A", ")", ".", "uniqueLotID", "=", "uniqueID", ";", "}", "}", "else", "uniqueLotID", "=", "\"", "\"", ";", "return", "V", ";", "}", "protected", "boolean", "isRetractableLink", "(", "Map", "<", "Room", ",", "Boolean", ">", "recurseChkRooms", ",", "Room", "fromRoom", ",", "Room", "theRoom", ")", "{", "if", "(", "theRoom", "==", "null", ")", "return", "true", ";", "if", "(", "(", "theRoom", ".", "roomID", "(", ")", ".", "length", "(", ")", ">", "0", ")", "&&", "(", "(", "CMLib", ".", "law", "(", ")", ".", "getLandTitle", "(", "theRoom", ")", "==", "null", ")", "||", "(", "CMLib", ".", "law", "(", ")", ".", "getLandTitle", "(", "theRoom", ")", ".", "getOwnerName", "(", ")", ".", "length", "(", ")", ">", "0", ")", ")", ")", "{", "if", "(", "recurseChkRooms", "!=", "null", ")", "recurseChkRooms", ".", "put", "(", "theRoom", ",", "Boolean", ".", "valueOf", "(", "false", ")", ")", ";", "return", "false", ";", "}", "for", "(", "int", "d", "=", "Directions", ".", "NUM_DIRECTIONS", "(", ")", "-", "1", ";", "d", ">=", "0", ";", "d", "--", ")", "{", "final", "Room", "R", "=", "theRoom", ".", "rawDoors", "(", ")", "[", "d", "]", ";", "if", "(", "R", "!=", "null", ")", "{", "if", "(", "(", "recurseChkRooms", "!=", "null", ")", "&&", "(", "recurseChkRooms", ".", "containsKey", "(", "R", ")", ")", ")", "return", "recurseChkRooms", ".", "get", "(", "theRoom", ")", ".", "booleanValue", "(", ")", ";", "if", "(", "(", "R", "!=", "fromRoom", ")", "&&", "(", "R", ".", "roomID", "(", ")", ".", "length", "(", ")", ">", "0", ")", ")", "{", "if", "(", "(", "CMLib", ".", "law", "(", ")", ".", "getLandTitle", "(", "R", ")", "==", "null", ")", "||", "(", "CMLib", ".", "law", "(", ")", ".", "getLandTitle", "(", "R", ")", ".", "getOwnerName", "(", ")", ".", "length", "(", ")", ">", "0", ")", ")", "{", "if", "(", "recurseChkRooms", "!=", "null", ")", "recurseChkRooms", ".", "put", "(", "theRoom", ",", "Boolean", ".", "valueOf", "(", "false", ")", ")", ";", "return", "false", ";", "}", "if", "(", "(", "recurseChkRooms", "!=", "null", ")", "&&", "(", "!", "isRetractableLink", "(", "recurseChkRooms", ",", "theRoom", ",", "R", ")", ")", ")", "{", "recurseChkRooms", ".", "put", "(", "theRoom", ",", "Boolean", ".", "valueOf", "(", "false", ")", ")", ";", "return", "false", ";", "}", "}", "}", "}", "if", "(", "recurseChkRooms", "!=", "null", ")", "recurseChkRooms", ".", "put", "(", "theRoom", ",", "Boolean", ".", "valueOf", "(", "true", ")", ")", ";", "return", "true", ";", "}", "@", "Override", "public", "String", "getUniqueLotID", "(", ")", "{", "if", "(", "uniqueLotID", "==", "null", ")", "getConnectedPropertyRooms", "(", ")", ";", "return", "uniqueLotID", ";", "}", "@", "Override", "public", "LandTitle", "generateNextRoomTitle", "(", ")", "{", "final", "LandTitle", "newTitle", "=", "(", "LandTitle", ")", "this", ".", "copyOf", "(", ")", ";", "newTitle", ".", "setOwnerName", "(", "\"", "\"", ")", ";", "newTitle", ".", "setBackTaxes", "(", "0", ")", ";", "return", "newTitle", ";", "}", "protected", "boolean", "canGenerateAdjacentRooms", "(", "Room", "R", ")", "{", "return", "getOwnerName", "(", ")", ".", "length", "(", ")", ">", "0", ";", "}", "protected", "boolean", "retractRooms", "(", "final", "Room", "R", ",", "List", "<", "Runnable", ">", "postWork", ")", "{", "boolean", "updateExits", "=", "false", ";", "boolean", "foundOne", "=", "false", ";", "boolean", "didAnything", "=", "false", ";", "final", "Map", "<", "Room", ",", "Boolean", ">", "checkedRetractRooms", ";", "if", "(", "super", ".", "gridLayout", "(", ")", ")", "checkedRetractRooms", "=", "new", "Hashtable", "<", "Room", ",", "Boolean", ">", "(", ")", ";", "else", "checkedRetractRooms", "=", "null", ";", "for", "(", "int", "d", "=", "0", ";", "d", "<", "Directions", ".", "NUM_DIRECTIONS", "(", ")", ";", "d", "++", ")", "{", "if", "(", "d", "==", "Directions", ".", "GATE", ")", "continue", ";", "final", "Room", "R2", "=", "R", ".", "rawDoors", "(", ")", "[", "d", "]", ";", "if", "(", "(", "R2", "!=", "null", ")", "&&", "(", "(", "!", "R2", ".", "isSavable", "(", ")", ")", "||", "(", "R2", ".", "roomID", "(", ")", ".", "length", "(", ")", "==", "0", ")", ")", ")", "continue", ";", "Exit", "E", "=", "R", ".", "getRawExit", "(", "d", ")", ";", "if", "(", "checkedRetractRooms", "!=", "null", ")", "checkedRetractRooms", ".", "clear", "(", ")", ";", "if", "(", "(", "R2", "!=", "null", ")", "&&", "(", "R2", ".", "rawDoors", "(", ")", "[", "Directions", ".", "getOpDirectionCode", "(", "d", ")", "]", "==", "R", ")", ")", "foundOne", "=", "true", ";", "else", "if", "(", "(", "R2", "!=", "null", ")", "&&", "(", "isRetractableLink", "(", "checkedRetractRooms", ",", "R", ",", "R2", ")", ")", ")", "{", "R", ".", "rawDoors", "(", ")", "[", "d", "]", "=", "null", ";", "R", ".", "setRawExit", "(", "d", ",", "null", ")", ";", "updateExits", "=", "true", ";", "postWork", ".", "add", "(", "new", "Runnable", "(", ")", "{", "final", "Room", "room", "=", "R2", ";", "@", "Override", "public", "void", "run", "(", ")", "{", "CMLib", ".", "map", "(", ")", ".", "obliterateRoom", "(", "room", ")", ";", "}", "}", ")", ";", "didAnything", "=", "true", ";", "}", "else", "if", "(", "(", "E", "!=", "null", ")", "&&", "(", "E", ".", "hasALock", "(", ")", ")", "&&", "(", "E", ".", "isGeneric", "(", ")", ")", ")", "{", "E", ".", "setKeyName", "(", "\"", "\"", ")", ";", "E", ".", "setDoorsNLocks", "(", "E", ".", "hasADoor", "(", ")", ",", "E", ".", "isOpen", "(", ")", ",", "E", ".", "defaultsClosed", "(", ")", ",", "false", ",", "false", ",", "false", ")", ";", "updateExits", "=", "true", ";", "if", "(", "R2", "!=", "null", ")", "{", "E", "=", "R2", ".", "getRawExit", "(", "Directions", ".", "getOpDirectionCode", "(", "d", ")", ")", ";", "if", "(", "(", "E", "!=", "null", ")", "&&", "(", "E", ".", "hasALock", "(", ")", ")", "&&", "(", "E", ".", "isGeneric", "(", ")", ")", ")", "{", "E", ".", "setKeyName", "(", "\"", "\"", ")", ";", "E", ".", "setDoorsNLocks", "(", "E", ".", "hasADoor", "(", ")", ",", "E", ".", "isOpen", "(", ")", ",", "E", ".", "defaultsClosed", "(", ")", ",", "false", ",", "false", ",", "false", ")", ";", "postWork", ".", "add", "(", "new", "Runnable", "(", ")", "{", "final", "Room", "room", "=", "R2", ";", "@", "Override", "public", "void", "run", "(", ")", "{", "CMLib", ".", "database", "(", ")", ".", "DBUpdateExits", "(", "room", ")", ";", "R2", ".", "getArea", "(", ")", ".", "fillInAreaRoom", "(", "room", ")", ";", "}", "}", ")", ";", "didAnything", "=", "true", ";", "}", "}", "}", "}", "if", "(", "checkedRetractRooms", "!=", "null", ")", "checkedRetractRooms", ".", "clear", "(", ")", ";", "if", "(", "!", "foundOne", ")", "{", "CMLib", ".", "map", "(", ")", ".", "obliterateRoom", "(", "R", ")", ";", "didAnything", "=", "true", ";", "}", "else", "if", "(", "updateExits", ")", "{", "CMLib", ".", "database", "(", ")", ".", "DBUpdateExits", "(", "R", ")", ";", "R", ".", "getArea", "(", ")", ".", "fillInAreaRoom", "(", "R", ")", ";", "didAnything", "=", "true", ";", "}", "return", "didAnything", ";", "}", "public", "boolean", "expandRooms", "(", "final", "Room", "R", ",", "final", "List", "<", "Runnable", ">", "postWork", ")", "{", "int", "numberOfPeers", "=", "-", "1", ";", "final", "boolean", "doGrid", "=", "super", ".", "gridLayout", "(", ")", ";", "long", "roomLimit", "=", "Long", ".", "MAX_VALUE", ";", "final", "Set", "<", "Room", ">", "updateExits", "=", "new", "HashSet", "<", "Room", ">", "(", ")", ";", "Prop_ReqCapacity", "cap", "=", "null", ";", "boolean", "didAnything", "=", "false", ";", "for", "(", "int", "d", "=", "0", ";", "d", "<", "Directions", ".", "NUM_DIRECTIONS", "(", ")", ";", "d", "++", ")", "{", "if", "(", "(", "d", "==", "Directions", ".", "UP", ")", "||", "(", "d", "==", "Directions", ".", "DOWN", ")", "||", "(", "d", "==", "Directions", ".", "GATE", ")", ")", "continue", ";", "final", "Room", "chkR", "=", "R", ".", "getRoomInDir", "(", "d", ")", ";", "if", "(", "(", "chkR", "==", "null", ")", "&&", "(", "numberOfPeers", "<", "0", ")", ")", "{", "final", "List", "<", "Room", ">", "allRooms", "=", "getConnectedPropertyRooms", "(", ")", ";", "if", "(", "allRooms", ".", "size", "(", ")", ">", "0", ")", "{", "cap", "=", "(", "Prop_ReqCapacity", ")", "allRooms", ".", "get", "(", "0", ")", ".", "fetchEffect", "(", "\"", "Prop_ReqCapacity", "\"", ")", ";", "if", "(", "cap", "!=", "null", ")", "{", "roomLimit", "=", "cap", ".", "roomLimit", ";", "}", "}", "numberOfPeers", "=", "allRooms", ".", "size", "(", ")", ";", "}", "if", "(", "(", "chkR", "==", "null", ")", "&&", "(", "numberOfPeers", "<", "roomLimit", ")", ")", "{", "numberOfPeers", "++", ";", "final", "Room", "R2", "=", "CMClass", ".", "getLocale", "(", "CMClass", ".", "classID", "(", "R", ")", ")", ";", "R2", ".", "setRoomID", "(", "R", ".", "getArea", "(", ")", ".", "getNewRoomID", "(", "R", ",", "d", ")", ")", ";", "if", "(", "R2", ".", "roomID", "(", ")", ".", "length", "(", ")", "==", "0", ")", "continue", ";", "R2", ".", "setArea", "(", "R", ".", "getArea", "(", ")", ")", ";", "LandTitle", "oldTitle", "=", "CMLib", ".", "law", "(", ")", ".", "getLandTitle", "(", "R", ")", ";", "final", "LandTitle", "newTitle", ";", "if", "(", "(", "oldTitle", "!=", "null", ")", "&&", "(", "CMLib", ".", "law", "(", ")", ".", "getLandTitle", "(", "R2", ")", "==", "null", ")", ")", "{", "newTitle", "=", "oldTitle", ".", "generateNextRoomTitle", "(", ")", ";", "R2", ".", "addNonUninvokableEffect", "(", "(", "Ability", ")", "newTitle", ")", ";", "}", "else", "newTitle", "=", "null", ";", "R", ".", "rawDoors", "(", ")", "[", "d", "]", "=", "R2", ";", "R", ".", "setRawExit", "(", "d", ",", "CMClass", ".", "getExit", "(", "\"", "Open", "\"", ")", ")", ";", "R2", ".", "rawDoors", "(", ")", "[", "Directions", ".", "getOpDirectionCode", "(", "d", ")", "]", "=", "R", ";", "R2", ".", "setRawExit", "(", "Directions", ".", "getOpDirectionCode", "(", "d", ")", ",", "CMClass", ".", "getExit", "(", "\"", "Open", "\"", ")", ")", ";", "updateExits", ".", "add", "(", "R", ")", ";", "if", "(", "doGrid", ")", "{", "final", "PairVector", "<", "Room", ",", "int", "[", "]", ">", "rooms", "=", "CMLib", ".", "tracking", "(", ")", ".", "buildGridList", "(", "R2", ",", "this", ".", "getOwnerName", "(", ")", ",", "100", ")", ";", "for", "(", "int", "dir", "=", "0", ";", "dir", "<", "Directions", ".", "NUM_DIRECTIONS", "(", ")", ";", "dir", "++", ")", "{", "if", "(", "dir", "==", "Directions", ".", "GATE", ")", "continue", ";", "Room", "R3", "=", "R2", ".", "getRoomInDir", "(", "dir", ")", ";", "if", "(", "R3", "==", "null", ")", "{", "R3", "=", "CMLib", ".", "tracking", "(", ")", ".", "getCalculatedAdjacentRoom", "(", "rooms", ",", "R3", ",", "dir", ")", ";", "if", "(", "R3", "!=", "null", ")", "{", "R2", ".", "rawDoors", "(", ")", "[", "dir", "]", "=", "R3", ";", "R3", ".", "rawDoors", "(", ")", "[", "Directions", ".", "getOpDirectionCode", "(", "dir", ")", "]", "=", "R2", ";", "updateExits", ".", "add", "(", "R3", ")", ";", "}", "}", "}", "}", "updateExits", ".", "add", "(", "R2", ")", ";", "if", "(", "CMSecurity", ".", "isDebugging", "(", "CMSecurity", ".", "DbgFlag", ".", "PROPERTY", ")", ")", "Log", ".", "debugOut", "(", "\"", "Lots4Sale", "\"", ",", "R2", ".", "roomID", "(", ")", "+", "\"", " created and put up for sale.", "\"", ")", ";", "if", "(", "cap", "!=", "null", ")", "R2", ".", "addNonUninvokableEffect", "(", "(", "Ability", ")", "cap", ".", "copyOf", "(", ")", ")", ";", "postWork", ".", "add", "(", "new", "Runnable", "(", ")", "{", "final", "Room", "room", "=", "R2", ";", "final", "LandTitle", "title", "=", "newTitle", ";", "@", "Override", "public", "void", "run", "(", ")", "{", "CMLib", ".", "database", "(", ")", ".", "DBCreateRoom", "(", "room", ")", ";", "if", "(", "title", "!=", "null", ")", "CMLib", ".", "law", "(", ")", ".", "colorRoomForSale", "(", "room", ",", "title", ",", "true", ")", ";", "room", ".", "getArea", "(", ")", ".", "fillInAreaRoom", "(", "room", ")", ";", "}", "}", ")", ";", "didAnything", "=", "true", ";", "}", "}", "if", "(", "updateExits", ".", "size", "(", ")", ">", "0", ")", "{", "didAnything", "=", "true", ";", "R", ".", "getArea", "(", ")", ".", "fillInAreaRoom", "(", "R", ")", ";", "postWork", ".", "add", "(", "new", "Runnable", "(", ")", "{", "final", "Set", "<", "Room", ">", "updateExits2", "=", "new", "SHashSet", "<", "Room", ">", "(", "updateExits", ")", ";", "@", "Override", "public", "void", "run", "(", ")", "{", "for", "(", "Room", "xR", ":", "updateExits2", ")", "{", "CMLib", ".", "database", "(", ")", ".", "DBUpdateExits", "(", "xR", ")", ";", "}", "}", "}", ")", ";", "}", "return", "didAnything", ";", "}", "@", "Override", "public", "void", "updateLot", "(", "List", "<", "String", ">", "optPlayerList", ")", "{", "final", "Environmental", "EV", "=", "affected", ";", "if", "(", "!", "(", "EV", "instanceof", "Room", ")", ")", "return", ";", "Room", "R", "=", "(", "Room", ")", "EV", ";", "boolean", "didAnything", "=", "false", ";", "try", "{", "List", "<", "Runnable", ">", "postWork", "=", "new", "ArrayList", "<", "Runnable", ">", "(", ")", ";", "synchronized", "(", "(", "\"", "SYNC", "\"", "+", "R", ".", "roomID", "(", ")", ")", ".", "intern", "(", ")", ")", "{", "R", "=", "CMLib", ".", "map", "(", ")", ".", "getRoom", "(", "R", ")", ";", "lastItemNums", "=", "updateLotWithThisData", "(", "R", ",", "this", ",", "true", ",", "scheduleReset", ",", "optPlayerList", ",", "lastItemNums", ")", ";", "if", "(", "getOwnerName", "(", ")", ".", "length", "(", ")", "==", "0", ")", "{", "didAnything", "=", "retractRooms", "(", "R", ",", "postWork", ")", "||", "didAnything", ";", "}", "else", "if", "(", "canGenerateAdjacentRooms", "(", "R", ")", ")", "{", "didAnything", "=", "expandRooms", "(", "R", ",", "postWork", ")", "||", "didAnything", ";", "}", "}", "for", "(", "Runnable", "run", ":", "postWork", ")", "run", ".", "run", "(", ")", ";", "scheduleReset", "=", "false", ";", "}", "finally", "{", "if", "(", "didAnything", ")", "getConnectedPropertyRooms", "(", ")", ";", "}", "}", "}" ]
Copyright 2003-2017 Bo Zimmerman Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
[ "Copyright", "2003", "-", "2017", "Bo", "Zimmerman", "Licensed", "under", "the", "Apache", "License", "Version", "2", ".", "0", "(", "the", "\"", "License", "\"", ")", ";", "you", "may", "not", "use", "this", "file", "except", "in", "compliance", "with", "the", "License", "." ]
[ "// purpose here is to put the \"front\" door up front.\r", "//getConnectedPropertyRooms().size();\r", "// recalculates the unique id for this lot of rooms\r" ]
[ { "param": "Prop_RoomForSale", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Prop_RoomForSale", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
26
2,761
133
8ebb8206a9b00038d09ae87d9ac0b2d0f37434cc
Refsheet/refsheet-ruby
lib/refsheet/api_error.rb
[ "Apache-2.0" ]
Ruby
Refsheet
#Refsheet.net API #The Refsheet.net API allows another application to view and manipulate data on behalf of a user. To get started, [generate an API Key from your account settings](https://refsheet.net/account/settings/api). ## Authentication The API requires two values, `api_key_id` and `api_key_secret` to be sent either as query parameters or via headers. |Field|URL Param|Header| |---|---|---| |API Key ID|`api_key_id`|`X-ApiKeyId`| |API Key Secret|`api_key_secret`|`X-ApiKeySecret`| ``` curl -H \"X-ApiKeyId: YOUR_KEY_ID\" \\ -H \"X-ApiKeySecret: YOUR_KEY_SECRET\" \\ https://refsheet.net/api/v1/users/abc123 ``` OpenAPI spec version: v1 Generated by: https://github.com/swagger-api/swagger-codegen.git 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.
Refsheet.net API The Refsheet.net API allows another application to view and manipulate data on behalf of a user. To get started, [generate an API Key from your account settings]. ## Authentication The API requires two values, `api_key_id` and `api_key_secret` to be sent either as query parameters or via headers. OpenAPI spec version: v1 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 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.
[ "Refsheet", ".", "net", "API", "The", "Refsheet", ".", "net", "API", "allows", "another", "application", "to", "view", "and", "manipulate", "data", "on", "behalf", "of", "a", "user", ".", "To", "get", "started", "[", "generate", "an", "API", "Key", "from", "your", "account", "settings", "]", ".", "##", "Authentication", "The", "API", "requires", "two", "values", "`", "api_key_id", "`", "and", "`", "api_key_secret", "`", "to", "be", "sent", "either", "as", "query", "parameters", "or", "via", "headers", ".", "OpenAPI", "spec", "version", ":", "v1", "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", "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", "." ]
module Refsheet class ApiError < StandardError attr_reader :code, :response_headers, :response_body # Usage examples: # ApiError.new # ApiError.new("message") # ApiError.new(:code => 500, :response_headers => {}, :response_body => "") # ApiError.new(:code => 404, :message => "Not Found") def initialize(arg = nil) if arg.is_a? Hash arg.each do |k, v| if k.to_s == 'message' super v else instance_variable_set "@#{k}", v end end else super arg end end end end
[ "module", "Refsheet", "class", "ApiError", "<", "StandardError", "attr_reader", ":code", ",", ":response_headers", ",", ":response_body", "def", "initialize", "(", "arg", "=", "nil", ")", "if", "arg", ".", "is_a?", "Hash", "arg", ".", "each", "do", "|", "k", ",", "v", "|", "if", "k", ".", "to_s", "==", "'message'", "super", "v", "else", "instance_variable_set", "\"@#{k}\"", ",", "v", "end", "end", "else", "super", "arg", "end", "end", "end", "end" ]
Refsheet.net API The Refsheet.net API allows another application to view and manipulate data on behalf of a user.
[ "Refsheet", ".", "net", "API", "The", "Refsheet", ".", "net", "API", "allows", "another", "application", "to", "view", "and", "manipulate", "data", "on", "behalf", "of", "a", "user", "." ]
[ "# Usage examples:", "# ApiError.new", "# ApiError.new(\"message\")", "# ApiError.new(:code => 500, :response_headers => {}, :response_body => \"\")", "# ApiError.new(:code => 404, :message => \"Not Found\")" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
18
165
309
04647e6a0845fca954bbf0fc1762ad44e318e741
alexonixon/docker_redmine
plugin/redmine_contacts/db/migrate/032_create_addresses.rb
[ "MIT" ]
Ruby
CreateAddresses
# This file is a part of Redmine CRM (redmine_contacts) plugin, # customer relationship management plugin for Redmine # # Copyright (C) 2011-2014 Kirill Bezrukov # http://www.redminecrm.com/ # # redmine_contacts is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # redmine_contacts is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with redmine_contacts. If not, see <http://www.gnu.org/licenses/>.
This file is a part of Redmine CRM (redmine_contacts) plugin, customer relationship management plugin for Redmine redmine_contacts is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. redmine_contacts is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with redmine_contacts. If not, see .
[ "This", "file", "is", "a", "part", "of", "Redmine", "CRM", "(", "redmine_contacts", ")", "plugin", "customer", "relationship", "management", "plugin", "for", "Redmine", "redmine_contacts", "is", "free", "software", ":", "you", "can", "redistribute", "it", "and", "/", "or", "modify", "it", "under", "the", "terms", "of", "the", "GNU", "General", "Public", "License", "as", "published", "by", "the", "Free", "Software", "Foundation", "either", "version", "3", "of", "the", "License", "or", "(", "at", "your", "option", ")", "any", "later", "version", ".", "redmine_contacts", "is", "distributed", "in", "the", "hope", "that", "it", "will", "be", "useful", "but", "WITHOUT", "ANY", "WARRANTY", ";", "without", "even", "the", "implied", "warranty", "of", "MERCHANTABILITY", "or", "FITNESS", "FOR", "A", "PARTICULAR", "PURPOSE", ".", "See", "the", "GNU", "General", "Public", "License", "for", "more", "details", ".", "You", "should", "have", "received", "a", "copy", "of", "the", "GNU", "General", "Public", "License", "along", "with", "redmine_contacts", ".", "If", "not", "see", "." ]
class CreateAddresses < ActiveRecord::Migration def up create_table :addresses do |t| t.string :street1 t.string :street2 t.string :city t.string :region t.string :postcode t.string :country_code, :limit => 2 t.text :full_address t.string :address_type, :limit => 16 t.references :addressable, :polymorphic => true t.timestamps end add_index :addresses, [ :addressable_id, :addressable_type ] Contact.all.each do |asset| Address.create(:street1 => asset.attributes["address"].gsub(/\n/, ' ').first(250), :full_address => asset.attributes["address"], :address_type => "business", :addressable => asset) unless asset.attributes["address"].blank? end remove_column(:contacts, :address) end def down add_column :contacts, :address, :text drop_table :addresses end end
[ "class", "CreateAddresses", "<", "ActiveRecord", "::", "Migration", "def", "up", "create_table", ":addresses", "do", "|", "t", "|", "t", ".", "string", ":street1", "t", ".", "string", ":street2", "t", ".", "string", ":city", "t", ".", "string", ":region", "t", ".", "string", ":postcode", "t", ".", "string", ":country_code", ",", ":limit", "=>", "2", "t", ".", "text", ":full_address", "t", ".", "string", ":address_type", ",", ":limit", "=>", "16", "t", ".", "references", ":addressable", ",", ":polymorphic", "=>", "true", "t", ".", "timestamps", "end", "add_index", ":addresses", ",", "[", ":addressable_id", ",", ":addressable_type", "]", "Contact", ".", "all", ".", "each", "do", "|", "asset", "|", "Address", ".", "create", "(", ":street1", "=>", "asset", ".", "attributes", "[", "\"address\"", "]", ".", "gsub", "(", "/", "\\n", "/", ",", "' '", ")", ".", "first", "(", "250", ")", ",", ":full_address", "=>", "asset", ".", "attributes", "[", "\"address\"", "]", ",", ":address_type", "=>", "\"business\"", ",", ":addressable", "=>", "asset", ")", "unless", "asset", ".", "attributes", "[", "\"address\"", "]", ".", "blank?", "end", "remove_column", "(", ":contacts", ",", ":address", ")", "end", "def", "down", "add_column", ":contacts", ",", ":address", ",", ":text", "drop_table", ":addresses", "end", "end" ]
This file is a part of Redmine CRM (redmine_contacts) plugin, customer relationship management plugin for Redmine
[ "This", "file", "is", "a", "part", "of", "Redmine", "CRM", "(", "redmine_contacts", ")", "plugin", "customer", "relationship", "management", "plugin", "for", "Redmine" ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
16
228
201
2fb387a59611e1bb8ec038828e120d7cdbd7ec00
uw-ictd/colte-maps
maps/app/models/way.rb
[ "MIT" ]
Ruby
Way
# == Schema Information # # Table name: current_ways # # id :bigint(8) not null, primary key # changeset_id :bigint(8) not null # timestamp :datetime not null # visible :boolean not null # version :bigint(8) not null # # Indexes # # current_ways_timestamp_idx (timestamp) # # Foreign Keys # # current_ways_changeset_id_fkey (changeset_id => changesets.id) #
Schema Information Table name: current_ways Indexes Foreign Keys
[ "Schema", "Information", "Table", "name", ":", "current_ways", "Indexes", "Foreign", "Keys" ]
class Way < ActiveRecord::Base require "xml/libxml" include ConsistencyValidations include NotRedactable include ObjectMetadata self.table_name = "current_ways" belongs_to :changeset has_many :old_ways, -> { order(:version) } has_many :way_nodes, -> { order(:sequence_id) } has_many :nodes, :through => :way_nodes has_many :way_tags has_many :containing_relation_members, :class_name => "RelationMember", :as => :member has_many :containing_relations, :class_name => "Relation", :through => :containing_relation_members, :source => :relation validates :id, :uniqueness => true, :presence => { :on => :update }, :numericality => { :on => :update, :integer_only => true } validates :version, :presence => true, :numericality => { :integer_only => true } validates :changeset_id, :presence => true, :numericality => { :integer_only => true } validates :timestamp, :presence => true validates :changeset, :associated => true validates :visible, :inclusion => [true, false] scope :visible, -> { where(:visible => true) } scope :invisible, -> { where(:visible => false) } # Read in xml as text and return it's Way object representation def self.from_xml(xml, create = false) p = XML::Parser.string(xml, :options => XML::Parser::Options::NOERROR) doc = p.parse doc.find("//osm/way").each do |pt| return Way.from_xml_node(pt, create) end raise OSM::APIBadXMLError.new("node", xml, "XML doesn't contain an osm/way element.") rescue LibXML::XML::Error, ArgumentError => ex raise OSM::APIBadXMLError.new("way", xml, ex.message) end def self.from_xml_node(pt, create = false) way = Way.new raise OSM::APIBadXMLError.new("way", pt, "Version is required when updating") unless create || !pt["version"].nil? way.version = pt["version"] raise OSM::APIBadXMLError.new("way", pt, "Changeset id is missing") if pt["changeset"].nil? way.changeset_id = pt["changeset"] unless create raise OSM::APIBadXMLError.new("way", pt, "ID is required when updating") if pt["id"].nil? way.id = pt["id"].to_i # .to_i will return 0 if there is no number that can be parsed. # We want to make sure that there is no id with zero anyway raise OSM::APIBadUserInput, "ID of way cannot be zero when updating." if way.id.zero? end # We don't care about the timestamp nor the visibility as these are either # set explicitly or implicit in the action. The visibility is set to true, # and manually set to false before the actual delete. way.visible = true # Start with no tags way.tags = {} # Add in any tags from the XML pt.find("tag").each do |tag| raise OSM::APIBadXMLError.new("way", pt, "tag is missing key") if tag["k"].nil? raise OSM::APIBadXMLError.new("way", pt, "tag is missing value") if tag["v"].nil? way.add_tag_keyval(tag["k"], tag["v"]) end pt.find("nd").each do |nd| way.add_nd_num(nd["ref"]) end way end # Find a way given it's ID, and in a single SQL call also grab its nodes and tags def to_xml doc = OSM::API.new.get_xml_doc doc.root << to_xml_node doc end def to_xml_node(visible_nodes = nil, changeset_cache = {}, user_display_name_cache = {}) el = XML::Node.new "way" el["id"] = id.to_s add_metadata_to_xml_node(el, self, changeset_cache, user_display_name_cache) # make sure nodes are output in sequence_id order ordered_nodes = [] way_nodes.each do |nd| if visible_nodes # if there is a list of visible nodes then use that to weed out deleted nodes ordered_nodes[nd.sequence_id] = nd.node_id.to_s if visible_nodes[nd.node_id] else # otherwise, manually go to the db to check things ordered_nodes[nd.sequence_id] = nd.node_id.to_s if nd.node && nd.node.visible? end end ordered_nodes.each do |nd_id| next unless nd_id && nd_id != "0" node_el = XML::Node.new "nd" node_el["ref"] = nd_id el << node_el end add_tags_to_xml_node(el, way_tags) el end def nds @nds ||= way_nodes.collect(&:node_id) end def tags @tags ||= Hash[way_tags.collect { |t| [t.k, t.v] }] end attr_writer :nds attr_writer :tags def add_nd_num(n) @nds ||= [] @nds << n.to_i end def add_tag_keyval(k, v) @tags ||= {} # duplicate tags are now forbidden, so we can't allow values # in the hash to be overwritten. raise OSM::APIDuplicateTagsError.new("way", id, k) if @tags.include? k @tags[k] = v end ## # the integer coords (i.e: unscaled) bounding box of the way, assuming # straight line segments. def bbox lons = nodes.collect(&:longitude) lats = nodes.collect(&:latitude) BoundingBox.new(lons.min, lats.min, lons.max, lats.max) end def update_from(new_way, user) Way.transaction do lock! check_consistency(self, new_way, user) raise OSM::APIPreconditionFailedError, "Cannot update way #{id}: data is invalid." unless new_way.preconditions_ok?(nds) self.changeset_id = new_way.changeset_id self.changeset = new_way.changeset self.tags = new_way.tags self.nds = new_way.nds self.visible = true save_with_history! end end def create_with_history(user) check_create_consistency(self, user) raise OSM::APIPreconditionFailedError, "Cannot create way: data is invalid." unless preconditions_ok? self.version = 0 self.visible = true save_with_history! end def preconditions_ok?(old_nodes = []) return false if nds.empty? raise OSM::APITooManyWayNodesError.new(id, nds.length, MAX_NUMBER_OF_WAY_NODES) if nds.length > MAX_NUMBER_OF_WAY_NODES # check only the new nodes, for efficiency - old nodes having been checked last time and can't # be deleted when they're in-use. new_nds = (nds - old_nodes).sort.uniq unless new_nds.empty? # NOTE: nodes are locked here to ensure they can't be deleted before # the current transaction commits. db_nds = Node.where(:id => new_nds, :visible => true).lock("for share") if db_nds.length < new_nds.length missing = new_nds - db_nds.collect(&:id) raise OSM::APIPreconditionFailedError, "Way #{id} requires the nodes with id in (#{missing.join(',')}), which either do not exist, or are not visible." end end true end def delete_with_history!(new_way, user) raise OSM::APIAlreadyDeletedError.new("way", new_way.id) unless visible # need to start the transaction here, so that the database can # provide repeatable reads for the used-by checks. this means it # shouldn't be possible to get race conditions. Way.transaction do lock! check_consistency(self, new_way, user) rels = Relation.joins(:relation_members).where(:visible => true, :current_relation_members => { :member_type => "Way", :member_id => id }).order(:id) raise OSM::APIPreconditionFailedError, "Way #{id} is still used by relations #{rels.collect(&:id).join(',')}." unless rels.empty? self.changeset_id = new_way.changeset_id self.changeset = new_way.changeset self.tags = [] self.nds = [] self.visible = false save_with_history! end end ## # if any referenced nodes are placeholder IDs (i.e: are negative) then # this calling this method will fix them using the map from placeholders # to IDs +id_map+. def fix_placeholders!(id_map, placeholder_id = nil) nds.map! do |node_id| if node_id < 0 new_id = id_map[:node][node_id] raise OSM::APIBadUserInput, "Placeholder node not found for reference #{node_id} in way #{id.nil? ? placeholder_id : id}" if new_id.nil? new_id else node_id end end end private def save_with_history! t = Time.now.getutc self.version += 1 self.timestamp = t # update the bounding box, note that this has to be done both before # and after the save, so that nodes from both versions are included in the # bbox. we use a copy of the changeset so that it isn't reloaded # later in the save. cs = changeset cs.update_bbox!(bbox) unless nodes.empty? Way.transaction do # clone the object before saving it so that the original is # still marked as dirty if we retry the transaction clone.save! tags = self.tags WayTag.where(:way_id => id).delete_all tags.each do |k, v| tag = WayTag.new tag.way_id = id tag.k = k tag.v = v tag.save! end nds = self.nds WayNode.where(:way_id => id).delete_all sequence = 1 nds.each do |n| nd = WayNode.new nd.id = [id, sequence] nd.node_id = n nd.save! sequence += 1 end old_way = OldWay.from_way(self) old_way.timestamp = t old_way.save_with_dependencies! # reload the way so that the nodes array points to the correct # new set of nodes. reload # update and commit the bounding box, now that way nodes # have been updated and we're in a transaction. cs.update_bbox!(bbox) unless nodes.empty? # tell the changeset we updated one element only cs.add_changes! 1 cs.save! end end end
[ "class", "Way", "<", "ActiveRecord", "::", "Base", "require", "\"xml/libxml\"", "include", "ConsistencyValidations", "include", "NotRedactable", "include", "ObjectMetadata", "self", ".", "table_name", "=", "\"current_ways\"", "belongs_to", ":changeset", "has_many", ":old_ways", ",", "->", "{", "order", "(", ":version", ")", "}", "has_many", ":way_nodes", ",", "->", "{", "order", "(", ":sequence_id", ")", "}", "has_many", ":nodes", ",", ":through", "=>", ":way_nodes", "has_many", ":way_tags", "has_many", ":containing_relation_members", ",", ":class_name", "=>", "\"RelationMember\"", ",", ":as", "=>", ":member", "has_many", ":containing_relations", ",", ":class_name", "=>", "\"Relation\"", ",", ":through", "=>", ":containing_relation_members", ",", ":source", "=>", ":relation", "validates", ":id", ",", ":uniqueness", "=>", "true", ",", ":presence", "=>", "{", ":on", "=>", ":update", "}", ",", ":numericality", "=>", "{", ":on", "=>", ":update", ",", ":integer_only", "=>", "true", "}", "validates", ":version", ",", ":presence", "=>", "true", ",", ":numericality", "=>", "{", ":integer_only", "=>", "true", "}", "validates", ":changeset_id", ",", ":presence", "=>", "true", ",", ":numericality", "=>", "{", ":integer_only", "=>", "true", "}", "validates", ":timestamp", ",", ":presence", "=>", "true", "validates", ":changeset", ",", ":associated", "=>", "true", "validates", ":visible", ",", ":inclusion", "=>", "[", "true", ",", "false", "]", "scope", ":visible", ",", "->", "{", "where", "(", ":visible", "=>", "true", ")", "}", "scope", ":invisible", ",", "->", "{", "where", "(", ":visible", "=>", "false", ")", "}", "def", "self", ".", "from_xml", "(", "xml", ",", "create", "=", "false", ")", "p", "=", "XML", "::", "Parser", ".", "string", "(", "xml", ",", ":options", "=>", "XML", "::", "Parser", "::", "Options", "::", "NOERROR", ")", "doc", "=", "p", ".", "parse", "doc", ".", "find", "(", "\"//osm/way\"", ")", ".", "each", "do", "|", "pt", "|", "return", "Way", ".", "from_xml_node", "(", "pt", ",", "create", ")", "end", "raise", "OSM", "::", "APIBadXMLError", ".", "new", "(", "\"node\"", ",", "xml", ",", "\"XML doesn't contain an osm/way element.\"", ")", "rescue", "LibXML", "::", "XML", "::", "Error", ",", "ArgumentError", "=>", "ex", "raise", "OSM", "::", "APIBadXMLError", ".", "new", "(", "\"way\"", ",", "xml", ",", "ex", ".", "message", ")", "end", "def", "self", ".", "from_xml_node", "(", "pt", ",", "create", "=", "false", ")", "way", "=", "Way", ".", "new", "raise", "OSM", "::", "APIBadXMLError", ".", "new", "(", "\"way\"", ",", "pt", ",", "\"Version is required when updating\"", ")", "unless", "create", "||", "!", "pt", "[", "\"version\"", "]", ".", "nil?", "way", ".", "version", "=", "pt", "[", "\"version\"", "]", "raise", "OSM", "::", "APIBadXMLError", ".", "new", "(", "\"way\"", ",", "pt", ",", "\"Changeset id is missing\"", ")", "if", "pt", "[", "\"changeset\"", "]", ".", "nil?", "way", ".", "changeset_id", "=", "pt", "[", "\"changeset\"", "]", "unless", "create", "raise", "OSM", "::", "APIBadXMLError", ".", "new", "(", "\"way\"", ",", "pt", ",", "\"ID is required when updating\"", ")", "if", "pt", "[", "\"id\"", "]", ".", "nil?", "way", ".", "id", "=", "pt", "[", "\"id\"", "]", ".", "to_i", "raise", "OSM", "::", "APIBadUserInput", ",", "\"ID of way cannot be zero when updating.\"", "if", "way", ".", "id", ".", "zero?", "end", "way", ".", "visible", "=", "true", "way", ".", "tags", "=", "{", "}", "pt", ".", "find", "(", "\"tag\"", ")", ".", "each", "do", "|", "tag", "|", "raise", "OSM", "::", "APIBadXMLError", ".", "new", "(", "\"way\"", ",", "pt", ",", "\"tag is missing key\"", ")", "if", "tag", "[", "\"k\"", "]", ".", "nil?", "raise", "OSM", "::", "APIBadXMLError", ".", "new", "(", "\"way\"", ",", "pt", ",", "\"tag is missing value\"", ")", "if", "tag", "[", "\"v\"", "]", ".", "nil?", "way", ".", "add_tag_keyval", "(", "tag", "[", "\"k\"", "]", ",", "tag", "[", "\"v\"", "]", ")", "end", "pt", ".", "find", "(", "\"nd\"", ")", ".", "each", "do", "|", "nd", "|", "way", ".", "add_nd_num", "(", "nd", "[", "\"ref\"", "]", ")", "end", "way", "end", "def", "to_xml", "doc", "=", "OSM", "::", "API", ".", "new", ".", "get_xml_doc", "doc", ".", "root", "<<", "to_xml_node", "doc", "end", "def", "to_xml_node", "(", "visible_nodes", "=", "nil", ",", "changeset_cache", "=", "{", "}", ",", "user_display_name_cache", "=", "{", "}", ")", "el", "=", "XML", "::", "Node", ".", "new", "\"way\"", "el", "[", "\"id\"", "]", "=", "id", ".", "to_s", "add_metadata_to_xml_node", "(", "el", ",", "self", ",", "changeset_cache", ",", "user_display_name_cache", ")", "ordered_nodes", "=", "[", "]", "way_nodes", ".", "each", "do", "|", "nd", "|", "if", "visible_nodes", "ordered_nodes", "[", "nd", ".", "sequence_id", "]", "=", "nd", ".", "node_id", ".", "to_s", "if", "visible_nodes", "[", "nd", ".", "node_id", "]", "else", "ordered_nodes", "[", "nd", ".", "sequence_id", "]", "=", "nd", ".", "node_id", ".", "to_s", "if", "nd", ".", "node", "&&", "nd", ".", "node", ".", "visible?", "end", "end", "ordered_nodes", ".", "each", "do", "|", "nd_id", "|", "next", "unless", "nd_id", "&&", "nd_id", "!=", "\"0\"", "node_el", "=", "XML", "::", "Node", ".", "new", "\"nd\"", "node_el", "[", "\"ref\"", "]", "=", "nd_id", "el", "<<", "node_el", "end", "add_tags_to_xml_node", "(", "el", ",", "way_tags", ")", "el", "end", "def", "nds", "@nds", "||=", "way_nodes", ".", "collect", "(", "&", ":node_id", ")", "end", "def", "tags", "@tags", "||=", "Hash", "[", "way_tags", ".", "collect", "{", "|", "t", "|", "[", "t", ".", "k", ",", "t", ".", "v", "]", "}", "]", "end", "attr_writer", ":nds", "attr_writer", ":tags", "def", "add_nd_num", "(", "n", ")", "@nds", "||=", "[", "]", "@nds", "<<", "n", ".", "to_i", "end", "def", "add_tag_keyval", "(", "k", ",", "v", ")", "@tags", "||=", "{", "}", "raise", "OSM", "::", "APIDuplicateTagsError", ".", "new", "(", "\"way\"", ",", "id", ",", "k", ")", "if", "@tags", ".", "include?", "k", "@tags", "[", "k", "]", "=", "v", "end", "def", "bbox", "lons", "=", "nodes", ".", "collect", "(", "&", ":longitude", ")", "lats", "=", "nodes", ".", "collect", "(", "&", ":latitude", ")", "BoundingBox", ".", "new", "(", "lons", ".", "min", ",", "lats", ".", "min", ",", "lons", ".", "max", ",", "lats", ".", "max", ")", "end", "def", "update_from", "(", "new_way", ",", "user", ")", "Way", ".", "transaction", "do", "lock!", "check_consistency", "(", "self", ",", "new_way", ",", "user", ")", "raise", "OSM", "::", "APIPreconditionFailedError", ",", "\"Cannot update way #{id}: data is invalid.\"", "unless", "new_way", ".", "preconditions_ok?", "(", "nds", ")", "self", ".", "changeset_id", "=", "new_way", ".", "changeset_id", "self", ".", "changeset", "=", "new_way", ".", "changeset", "self", ".", "tags", "=", "new_way", ".", "tags", "self", ".", "nds", "=", "new_way", ".", "nds", "self", ".", "visible", "=", "true", "save_with_history!", "end", "end", "def", "create_with_history", "(", "user", ")", "check_create_consistency", "(", "self", ",", "user", ")", "raise", "OSM", "::", "APIPreconditionFailedError", ",", "\"Cannot create way: data is invalid.\"", "unless", "preconditions_ok?", "self", ".", "version", "=", "0", "self", ".", "visible", "=", "true", "save_with_history!", "end", "def", "preconditions_ok?", "(", "old_nodes", "=", "[", "]", ")", "return", "false", "if", "nds", ".", "empty?", "raise", "OSM", "::", "APITooManyWayNodesError", ".", "new", "(", "id", ",", "nds", ".", "length", ",", "MAX_NUMBER_OF_WAY_NODES", ")", "if", "nds", ".", "length", ">", "MAX_NUMBER_OF_WAY_NODES", "new_nds", "=", "(", "nds", "-", "old_nodes", ")", ".", "sort", ".", "uniq", "unless", "new_nds", ".", "empty?", "db_nds", "=", "Node", ".", "where", "(", ":id", "=>", "new_nds", ",", ":visible", "=>", "true", ")", ".", "lock", "(", "\"for share\"", ")", "if", "db_nds", ".", "length", "<", "new_nds", ".", "length", "missing", "=", "new_nds", "-", "db_nds", ".", "collect", "(", "&", ":id", ")", "raise", "OSM", "::", "APIPreconditionFailedError", ",", "\"Way #{id} requires the nodes with id in (#{missing.join(',')}), which either do not exist, or are not visible.\"", "end", "end", "true", "end", "def", "delete_with_history!", "(", "new_way", ",", "user", ")", "raise", "OSM", "::", "APIAlreadyDeletedError", ".", "new", "(", "\"way\"", ",", "new_way", ".", "id", ")", "unless", "visible", "Way", ".", "transaction", "do", "lock!", "check_consistency", "(", "self", ",", "new_way", ",", "user", ")", "rels", "=", "Relation", ".", "joins", "(", ":relation_members", ")", ".", "where", "(", ":visible", "=>", "true", ",", ":current_relation_members", "=>", "{", ":member_type", "=>", "\"Way\"", ",", ":member_id", "=>", "id", "}", ")", ".", "order", "(", ":id", ")", "raise", "OSM", "::", "APIPreconditionFailedError", ",", "\"Way #{id} is still used by relations #{rels.collect(&:id).join(',')}.\"", "unless", "rels", ".", "empty?", "self", ".", "changeset_id", "=", "new_way", ".", "changeset_id", "self", ".", "changeset", "=", "new_way", ".", "changeset", "self", ".", "tags", "=", "[", "]", "self", ".", "nds", "=", "[", "]", "self", ".", "visible", "=", "false", "save_with_history!", "end", "end", "def", "fix_placeholders!", "(", "id_map", ",", "placeholder_id", "=", "nil", ")", "nds", ".", "map!", "do", "|", "node_id", "|", "if", "node_id", "<", "0", "new_id", "=", "id_map", "[", ":node", "]", "[", "node_id", "]", "raise", "OSM", "::", "APIBadUserInput", ",", "\"Placeholder node not found for reference #{node_id} in way #{id.nil? ? placeholder_id : id}\"", "if", "new_id", ".", "nil?", "new_id", "else", "node_id", "end", "end", "end", "private", "def", "save_with_history!", "t", "=", "Time", ".", "now", ".", "getutc", "self", ".", "version", "+=", "1", "self", ".", "timestamp", "=", "t", "cs", "=", "changeset", "cs", ".", "update_bbox!", "(", "bbox", ")", "unless", "nodes", ".", "empty?", "Way", ".", "transaction", "do", "clone", ".", "save!", "tags", "=", "self", ".", "tags", "WayTag", ".", "where", "(", ":way_id", "=>", "id", ")", ".", "delete_all", "tags", ".", "each", "do", "|", "k", ",", "v", "|", "tag", "=", "WayTag", ".", "new", "tag", ".", "way_id", "=", "id", "tag", ".", "k", "=", "k", "tag", ".", "v", "=", "v", "tag", ".", "save!", "end", "nds", "=", "self", ".", "nds", "WayNode", ".", "where", "(", ":way_id", "=>", "id", ")", ".", "delete_all", "sequence", "=", "1", "nds", ".", "each", "do", "|", "n", "|", "nd", "=", "WayNode", ".", "new", "nd", ".", "id", "=", "[", "id", ",", "sequence", "]", "nd", ".", "node_id", "=", "n", "nd", ".", "save!", "sequence", "+=", "1", "end", "old_way", "=", "OldWay", ".", "from_way", "(", "self", ")", "old_way", ".", "timestamp", "=", "t", "old_way", ".", "save_with_dependencies!", "reload", "cs", ".", "update_bbox!", "(", "bbox", ")", "unless", "nodes", ".", "empty?", "cs", ".", "add_changes!", "1", "cs", ".", "save!", "end", "end", "end" ]
Schema Information Table name: current_ways
[ "Schema", "Information", "Table", "name", ":", "current_ways" ]
[ "# Read in xml as text and return it's Way object representation", "# .to_i will return 0 if there is no number that can be parsed.", "# We want to make sure that there is no id with zero anyway", "# We don't care about the timestamp nor the visibility as these are either", "# set explicitly or implicit in the action. The visibility is set to true,", "# and manually set to false before the actual delete.", "# Start with no tags", "# Add in any tags from the XML", "# Find a way given it's ID, and in a single SQL call also grab its nodes and tags", "# make sure nodes are output in sequence_id order", "# if there is a list of visible nodes then use that to weed out deleted nodes", "# otherwise, manually go to the db to check things", "# duplicate tags are now forbidden, so we can't allow values", "# in the hash to be overwritten.", "##", "# the integer coords (i.e: unscaled) bounding box of the way, assuming", "# straight line segments.", "# check only the new nodes, for efficiency - old nodes having been checked last time and can't", "# be deleted when they're in-use.", "# NOTE: nodes are locked here to ensure they can't be deleted before", "# the current transaction commits.", "# need to start the transaction here, so that the database can", "# provide repeatable reads for the used-by checks. this means it", "# shouldn't be possible to get race conditions.", "##", "# if any referenced nodes are placeholder IDs (i.e: are negative) then", "# this calling this method will fix them using the map from placeholders", "# to IDs +id_map+.", "# update the bounding box, note that this has to be done both before", "# and after the save, so that nodes from both versions are included in the", "# bbox. we use a copy of the changeset so that it isn't reloaded", "# later in the save.", "# clone the object before saving it so that the original is", "# still marked as dirty if we retry the transaction", "# reload the way so that the nodes array points to the correct", "# new set of nodes.", "# update and commit the bounding box, now that way nodes", "# have been updated and we're in a transaction.", "# tell the changeset we updated one element only" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
17
2,552
122
ae96193d0a14ec1db062fd128dcbc925cf057b8b
Distrotech/jruby
lib/ruby/truffle/mri/thread.rb
[ "Ruby", "Apache-2.0" ]
Ruby
Queue
# # This class provides a way to synchronize communication between threads. # # Example: # # require 'thread' # # queue = Queue.new # # producer = Thread.new do # 5.times do |i| # sleep rand(i) # simulate expense # queue << i # puts "#{i} produced" # end # end # # consumer = Thread.new do # 5.times do |i| # value = queue.pop # sleep rand(i/2) # simulate expense # puts "consumed #{value}" # end # end # # consumer.join #
This class provides a way to synchronize communication between threads. Example. require 'thread' producer = Thread.new do 5.times do |i| sleep rand(i) # simulate expense queue << i puts "#{i} produced" end end consumer = Thread.new do 5.times do |i| value = queue.pop sleep rand(i/2) # simulate expense puts "consumed #{value}" end end
[ "This", "class", "provides", "a", "way", "to", "synchronize", "communication", "between", "threads", ".", "Example", ".", "require", "'", "thread", "'", "producer", "=", "Thread", ".", "new", "do", "5", ".", "times", "do", "|i|", "sleep", "rand", "(", "i", ")", "#", "simulate", "expense", "queue", "<<", "i", "puts", "\"", "#", "{", "i", "}", "produced", "\"", "end", "end", "consumer", "=", "Thread", ".", "new", "do", "5", ".", "times", "do", "|i|", "value", "=", "queue", ".", "pop", "sleep", "rand", "(", "i", "/", "2", ")", "#", "simulate", "expense", "puts", "\"", "consumed", "#", "{", "value", "}", "\"", "end", "end" ]
class Queue # # Creates a new queue. # def initialize @que = [] @que.taint # enable tainted communication @num_waiting = 0 self.taint @mutex = Mutex.new @cond = ConditionVariable.new end # # Pushes +obj+ to the queue. # def push(obj) Thread.handle_interrupt(StandardError => :on_blocking) do @mutex.synchronize do @que.push obj @cond.signal end self end end # # Alias of push # alias << push # # Alias of push # alias enq push # # Retrieves data from the queue. If the queue is empty, the calling thread is # suspended until data is pushed onto the queue. If +non_block+ is true, the # thread isn't suspended, and an exception is raised. # def pop(non_block=false) Thread.handle_interrupt(StandardError => :on_blocking) do @mutex.synchronize do while true if @que.empty? if non_block raise ThreadError, "queue empty" else begin @num_waiting += 1 @cond.wait @mutex ensure @num_waiting -= 1 end end else return @que.shift end end end end end # # Alias of pop # alias shift pop # # Alias of pop # alias deq pop # # Returns +true+ if the queue is empty. # def empty? @que.empty? end # # Removes all objects from the queue. # def clear @que.clear self end # # Returns the length of the queue. # def length @que.length end # # Alias of length. # alias size length # # Returns the number of threads waiting on the queue. # def num_waiting @num_waiting end end
[ "class", "Queue", "def", "initialize", "@que", "=", "[", "]", "@que", ".", "taint", "@num_waiting", "=", "0", "self", ".", "taint", "@mutex", "=", "Mutex", ".", "new", "@cond", "=", "ConditionVariable", ".", "new", "end", "def", "push", "(", "obj", ")", "Thread", ".", "handle_interrupt", "(", "StandardError", "=>", ":on_blocking", ")", "do", "@mutex", ".", "synchronize", "do", "@que", ".", "push", "obj", "@cond", ".", "signal", "end", "self", "end", "end", "alias", "<<", "push", "alias", "enq", "push", "def", "pop", "(", "non_block", "=", "false", ")", "Thread", ".", "handle_interrupt", "(", "StandardError", "=>", ":on_blocking", ")", "do", "@mutex", ".", "synchronize", "do", "while", "true", "if", "@que", ".", "empty?", "if", "non_block", "raise", "ThreadError", ",", "\"queue empty\"", "else", "begin", "@num_waiting", "+=", "1", "@cond", ".", "wait", "@mutex", "ensure", "@num_waiting", "-=", "1", "end", "end", "else", "return", "@que", ".", "shift", "end", "end", "end", "end", "end", "alias", "shift", "pop", "alias", "deq", "pop", "def", "empty?", "@que", ".", "empty?", "end", "def", "clear", "@que", ".", "clear", "self", "end", "def", "length", "@que", ".", "length", "end", "alias", "size", "length", "def", "num_waiting", "@num_waiting", "end", "end" ]
This class provides a way to synchronize communication between threads.
[ "This", "class", "provides", "a", "way", "to", "synchronize", "communication", "between", "threads", "." ]
[ "#", "# Creates a new queue.", "#", "# enable tainted communication", "#", "# Pushes +obj+ to the queue.", "#", "#", "# Alias of push", "#", "#", "# Alias of push", "#", "#", "# Retrieves data from the queue. If the queue is empty, the calling thread is", "# suspended until data is pushed onto the queue. If +non_block+ is true, the", "# thread isn't suspended, and an exception is raised.", "#", "#", "# Alias of pop", "#", "#", "# Alias of pop", "#", "#", "# Returns +true+ if the queue is empty.", "#", "#", "# Removes all objects from the queue.", "#", "#", "# Returns the length of the queue.", "#", "#", "# Alias of length.", "#", "#", "# Returns the number of threads waiting on the queue.", "#" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
20
490
143
865cef9d9e284b729b13c88766fdc612da5138f3
JLLeitschuh/brigade
src/main/java/com/kmwllc/brigade/utils/BrigadeRunner.java
[ "Apache-2.0" ]
Java
BrigadeRunner
/** * Represents a Brigade "job" to be run on the Brigade server. It includes all the config * objects which govern execution of the pipeline. * <p> * Calling exec() will begin execution of the pipeline. At this point, all the configuration objects * are "frozen". Changes made to them after this point will not be reflected in the pipeline execution. * Created by matt on 3/22/17. */
Represents a Brigade "job" to be run on the Brigade server. It includes all the config objects which govern execution of the pipeline. Calling exec() will begin execution of the pipeline. At this point, all the configuration objects are "frozen". Changes made to them after this point will not be reflected in the pipeline execution. Created by matt on 3/22/17.
[ "Represents", "a", "Brigade", "\"", "job", "\"", "to", "be", "run", "on", "the", "Brigade", "server", ".", "It", "includes", "all", "the", "config", "objects", "which", "govern", "execution", "of", "the", "pipeline", ".", "Calling", "exec", "()", "will", "begin", "execution", "of", "the", "pipeline", ".", "At", "this", "point", "all", "the", "configuration", "objects", "are", "\"", "frozen", "\"", ".", "Changes", "made", "to", "them", "after", "this", "point", "will", "not", "be", "reflected", "in", "the", "pipeline", "execution", ".", "Created", "by", "matt", "on", "3", "/", "22", "/", "17", "." ]
public class BrigadeRunner { private final BrigadeProperties brigadeProperties; private final ConnectorConfig connectorConfig; private final WorkflowConfig<StageConfig> workflowConfig; /** * Convenience invocation of BrigadeRunner which builds from given configurations. This is how * BrigadeRunner is invoked when Brigade is run from the command line. * <p> * Note that it is not clear whether we are building the configurations from a file or stream and so * the following logic is performed for each of propertiesFile, connectorFile, workflowFile:<ul> * <li>If there is a file in the filesystem at the path given, build the config object from the file</li> * <li>If not, attempt to build from a stream of a classpath resource at the given path</li> * <li>An exception is thrown otherwise</li> * </ul> * @param propertiesFile Path to properties * @param connectorFile Path to connector config * @param workflowFile Path to workflow config * @return BrigadeRunner instance ready to manipulate programmatically or exec * @throws IOException If could not locate one of the paths to config object * @throws ConfigException If an error occurs while instantiating a config object */ public static BrigadeRunner init(String propertiesFile, String connectorFile, String workflowFile) throws IOException, ConfigException { BrigadeProperties bp = null; ConnectorConfig cc = null; WorkflowConfig<StageConfig> wc = null; if (isFile(propertiesFile)) { bp = BrigadeProperties.fromFile(propertiesFile); } else { bp = BrigadeProperties.fromStream(getStream(propertiesFile)); } // bootstrap existing properties if (isFile(propertiesFile)) { bp = BrigadeProperties.fromFile(propertiesFile, bp); } else { bp = BrigadeProperties.fromStream(getStream(propertiesFile), bp); } if (isFile(connectorFile)) { cc = ConnectorConfig.fromFile(connectorFile, bp); } else { cc = ConnectorConfig.fromStream(getStream(connectorFile), bp); } if (isFile(workflowFile)) { wc = WorkflowConfig.fromFile(workflowFile, bp); } else { wc = WorkflowConfig.fromStream(getStream(workflowFile), bp); } return new BrigadeRunner(bp, cc, wc); } public BrigadeRunner(BrigadeProperties brigadeProperties, ConnectorConfig connectorConfig, WorkflowConfig<StageConfig> workflowConfig) { this.brigadeProperties = brigadeProperties; this.connectorConfig = connectorConfig; this.workflowConfig = workflowConfig; } private static boolean isFile(String fileName) { File f = new File(fileName); return f.exists(); } private static InputStream getStream(String fileName) { InputStream in = BrigadeRunner.class.getClassLoader().getResourceAsStream(fileName); return in; } /** * Begin executing the pipeline based upon configuration objects. Once this is called, the configuration * is "frozen" (ie. config settings cannot be changed programmatically) * * @throws Exception If an exception occurred while running the pipeline */ public void exec() throws Exception { // init the brigade config! BrigadeConfig config = new BrigadeConfig(); config.addConnectorConfig(connectorConfig); config.addWorkflowConfig(workflowConfig); config.setProps(brigadeProperties); // Start up the Brigade Server Brigade brigadeServer = Brigade.getInstance(); brigadeServer.setConfig(config); try { brigadeServer.start(); if (brigadeServer.isRunning()) { try { brigadeServer.startConnector(connectorConfig.getConnectorName()); } catch (InterruptedException e) { e.printStackTrace(); throw e; } // TODO: this should do a flush! and then shutdown.. try { brigadeServer.waitForConnector(connectorConfig.getConnectorName()); } catch (InterruptedException e) { e.printStackTrace(); throw e; } } } catch (Exception e) { e.printStackTrace(); brigadeServer.shutdown(false); throw e; } brigadeServer.shutdown(false); // System.exit(0); } }
[ "public", "class", "BrigadeRunner", "{", "private", "final", "BrigadeProperties", "brigadeProperties", ";", "private", "final", "ConnectorConfig", "connectorConfig", ";", "private", "final", "WorkflowConfig", "<", "StageConfig", ">", "workflowConfig", ";", "/**\n * Convenience invocation of BrigadeRunner which builds from given configurations. This is how\n * BrigadeRunner is invoked when Brigade is run from the command line.\n * <p>\n * Note that it is not clear whether we are building the configurations from a file or stream and so\n * the following logic is performed for each of propertiesFile, connectorFile, workflowFile:<ul>\n * <li>If there is a file in the filesystem at the path given, build the config object from the file</li>\n * <li>If not, attempt to build from a stream of a classpath resource at the given path</li>\n * <li>An exception is thrown otherwise</li>\n * </ul>\n * @param propertiesFile Path to properties\n * @param connectorFile Path to connector config\n * @param workflowFile Path to workflow config\n * @return BrigadeRunner instance ready to manipulate programmatically or exec\n * @throws IOException If could not locate one of the paths to config object\n * @throws ConfigException If an error occurs while instantiating a config object\n */", "public", "static", "BrigadeRunner", "init", "(", "String", "propertiesFile", ",", "String", "connectorFile", ",", "String", "workflowFile", ")", "throws", "IOException", ",", "ConfigException", "{", "BrigadeProperties", "bp", "=", "null", ";", "ConnectorConfig", "cc", "=", "null", ";", "WorkflowConfig", "<", "StageConfig", ">", "wc", "=", "null", ";", "if", "(", "isFile", "(", "propertiesFile", ")", ")", "{", "bp", "=", "BrigadeProperties", ".", "fromFile", "(", "propertiesFile", ")", ";", "}", "else", "{", "bp", "=", "BrigadeProperties", ".", "fromStream", "(", "getStream", "(", "propertiesFile", ")", ")", ";", "}", "if", "(", "isFile", "(", "propertiesFile", ")", ")", "{", "bp", "=", "BrigadeProperties", ".", "fromFile", "(", "propertiesFile", ",", "bp", ")", ";", "}", "else", "{", "bp", "=", "BrigadeProperties", ".", "fromStream", "(", "getStream", "(", "propertiesFile", ")", ",", "bp", ")", ";", "}", "if", "(", "isFile", "(", "connectorFile", ")", ")", "{", "cc", "=", "ConnectorConfig", ".", "fromFile", "(", "connectorFile", ",", "bp", ")", ";", "}", "else", "{", "cc", "=", "ConnectorConfig", ".", "fromStream", "(", "getStream", "(", "connectorFile", ")", ",", "bp", ")", ";", "}", "if", "(", "isFile", "(", "workflowFile", ")", ")", "{", "wc", "=", "WorkflowConfig", ".", "fromFile", "(", "workflowFile", ",", "bp", ")", ";", "}", "else", "{", "wc", "=", "WorkflowConfig", ".", "fromStream", "(", "getStream", "(", "workflowFile", ")", ",", "bp", ")", ";", "}", "return", "new", "BrigadeRunner", "(", "bp", ",", "cc", ",", "wc", ")", ";", "}", "public", "BrigadeRunner", "(", "BrigadeProperties", "brigadeProperties", ",", "ConnectorConfig", "connectorConfig", ",", "WorkflowConfig", "<", "StageConfig", ">", "workflowConfig", ")", "{", "this", ".", "brigadeProperties", "=", "brigadeProperties", ";", "this", ".", "connectorConfig", "=", "connectorConfig", ";", "this", ".", "workflowConfig", "=", "workflowConfig", ";", "}", "private", "static", "boolean", "isFile", "(", "String", "fileName", ")", "{", "File", "f", "=", "new", "File", "(", "fileName", ")", ";", "return", "f", ".", "exists", "(", ")", ";", "}", "private", "static", "InputStream", "getStream", "(", "String", "fileName", ")", "{", "InputStream", "in", "=", "BrigadeRunner", ".", "class", ".", "getClassLoader", "(", ")", ".", "getResourceAsStream", "(", "fileName", ")", ";", "return", "in", ";", "}", "/**\n * Begin executing the pipeline based upon configuration objects. Once this is called, the configuration\n * is \"frozen\" (ie. config settings cannot be changed programmatically)\n *\n * @throws Exception If an exception occurred while running the pipeline\n */", "public", "void", "exec", "(", ")", "throws", "Exception", "{", "BrigadeConfig", "config", "=", "new", "BrigadeConfig", "(", ")", ";", "config", ".", "addConnectorConfig", "(", "connectorConfig", ")", ";", "config", ".", "addWorkflowConfig", "(", "workflowConfig", ")", ";", "config", ".", "setProps", "(", "brigadeProperties", ")", ";", "Brigade", "brigadeServer", "=", "Brigade", ".", "getInstance", "(", ")", ";", "brigadeServer", ".", "setConfig", "(", "config", ")", ";", "try", "{", "brigadeServer", ".", "start", "(", ")", ";", "if", "(", "brigadeServer", ".", "isRunning", "(", ")", ")", "{", "try", "{", "brigadeServer", ".", "startConnector", "(", "connectorConfig", ".", "getConnectorName", "(", ")", ")", ";", "}", "catch", "(", "InterruptedException", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "throw", "e", ";", "}", "try", "{", "brigadeServer", ".", "waitForConnector", "(", "connectorConfig", ".", "getConnectorName", "(", ")", ")", ";", "}", "catch", "(", "InterruptedException", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "throw", "e", ";", "}", "}", "}", "catch", "(", "Exception", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "brigadeServer", ".", "shutdown", "(", "false", ")", ";", "throw", "e", ";", "}", "brigadeServer", ".", "shutdown", "(", "false", ")", ";", "}", "}" ]
Represents a Brigade "job" to be run on the Brigade server.
[ "Represents", "a", "Brigade", "\"", "job", "\"", "to", "be", "run", "on", "the", "Brigade", "server", "." ]
[ "// bootstrap existing properties", "// init the brigade config!", "// Start up the Brigade Server", "// TODO: this should do a flush! and then shutdown..", "// System.exit(0);" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
16
890
95
de3876f5fc17844a556a82c19f26db2a7d498719
hejj16/Machine-Learning-Algorithms
KMeans.py
[ "MIT" ]
Python
KMeans
This class implements KMeans. Args: k(int): Amount of classes. random_seed(int): Optional. Random seed for initialization. Attributes: KMeans.k(int): Amount of classes. KMeans.random_seed: Optional. Random seed for initialization. KMeans.means: Central value of each class. KMeans.dimension: Amount of dimensions of each data. Methods: KMeans.fit: Fit model to the data. KMeans.fit_predict: Fit model to the data, and return the class labels of data. KMeans.predict: Use the trained model to predict the class labels of data.
This class implements KMeans.
[ "This", "class", "implements", "KMeans", "." ]
class KMeans: """ This class implements KMeans. Args: k(int): Amount of classes. random_seed(int): Optional. Random seed for initialization. Attributes: KMeans.k(int): Amount of classes. KMeans.random_seed: Optional. Random seed for initialization. KMeans.means: Central value of each class. KMeans.dimension: Amount of dimensions of each data. Methods: KMeans.fit: Fit model to the data. KMeans.fit_predict: Fit model to the data, and return the class labels of data. KMeans.predict: Use the trained model to predict the class labels of data. """ def __init__(self, k, random_seed=None): """ Constructor method """ self.k = k self.random_seed = random_seed self.means = None self.dimension = None def fit(self, x, max_iteration=100, terminate_condition=0.0): """ Fit model to the data. Args: x: Array-like. Contains training data. max_iteration: Maximum times of iteration. terminate_condition(float): A fraction. Terminate if this value of fraction of data converge. Default 0. """ self.fit_predict(x, max_iteration, terminate_condition) def fit_predict(self, x, max_iteration=100, terminate_condition=0.0): """ Fit model to the data, and return the class labels of data. Args: x: Array-like. Contains training data. max_iteration: Maximum times of iteration. terminate_condition(float): A fraction. Terminate if this value of fraction of data converge. Default 0. Raises: ValueError("Amount of data can not be less than k") Return: Array of size[amount of data,], contains labels of data. """ x = np.array(x) if x.ndim == 0: x = np.reshape(x, [1, 1]) if x.ndim == 1: x = np.reshape(x, [x.shape[0], 1]) self.dimension = x.shape[1] if self.k > x.shape[0]: raise ValueError("Amount of data can not be less than k") if self.random_seed is not None: np.random.seed(self.random_seed) self.means = x[np.random.choice(x.shape[0], self.k, replace=False)] labels = np.zeros(x.shape[0]).astype(np.int) for i in range(max_iteration): new_labels = self.__predict(x) if np.sum(new_labels != labels) > terminate_condition / x.shape[0]: labels = new_labels else: break for j in range(self.k): # Re-calculate center of each class. self.means[j] = np.average(x[labels == j], axis=0) return labels def predict(self, x): """ Use the trained model to predict the class labels of data. Args: x: Array-like. Contains data to be predicted. Raises: ValueError("Dimension not match."): data in x have different dimension with training data. Return: Array of size[amount of data,], contains labels of data. """ x = np.array(x) if x.ndim == 0: x = np.reshape(x, [1, 1]) if x.ndim == 1: x = np.reshape(x, [x.shape[0], 1]) if self.dimension == 1 else np.reshape(x, [1, self.dimension]) if x.shape[1] != self.dimension: raise ValueError("Dimension not match.") return self.__predict(x) def __predict(self, x): """ Predict the labels for input data, by calculating square Euclidean distance. Args: x: Array-like. Contains data to be predicted. Return: Array of size[amount of data,], contains labels of data. """ labels = np.zeros(x.shape[0]).astype(np.int) distance = np.full(x.shape[0], np.inf) for i in range(self.k): current_distance = np.sum((x - self.means[i]) ** 2, axis=1) mask = distance > current_distance labels[mask] = i distance[mask] = current_distance[mask] return labels
[ "class", "KMeans", ":", "def", "__init__", "(", "self", ",", "k", ",", "random_seed", "=", "None", ")", ":", "\"\"\"\r\n Constructor method\r\n\r\n \"\"\"", "self", ".", "k", "=", "k", "self", ".", "random_seed", "=", "random_seed", "self", ".", "means", "=", "None", "self", ".", "dimension", "=", "None", "def", "fit", "(", "self", ",", "x", ",", "max_iteration", "=", "100", ",", "terminate_condition", "=", "0.0", ")", ":", "\"\"\"\r\n Fit model to the data.\r\n\r\n Args:\r\n x: Array-like. Contains training data.\r\n max_iteration: Maximum times of iteration.\r\n terminate_condition(float): A fraction. Terminate if this value of fraction of data converge. Default 0.\r\n\r\n \"\"\"", "self", ".", "fit_predict", "(", "x", ",", "max_iteration", ",", "terminate_condition", ")", "def", "fit_predict", "(", "self", ",", "x", ",", "max_iteration", "=", "100", ",", "terminate_condition", "=", "0.0", ")", ":", "\"\"\"\r\n Fit model to the data, and return the class labels of data.\r\n\r\n Args:\r\n x: Array-like. Contains training data.\r\n max_iteration: Maximum times of iteration.\r\n terminate_condition(float): A fraction. Terminate if this value of fraction of data converge. Default 0.\r\n\r\n Raises:\r\n ValueError(\"Amount of data can not be less than k\")\r\n\r\n Return:\r\n Array of size[amount of data,], contains labels of data.\r\n\r\n \"\"\"", "x", "=", "np", ".", "array", "(", "x", ")", "if", "x", ".", "ndim", "==", "0", ":", "x", "=", "np", ".", "reshape", "(", "x", ",", "[", "1", ",", "1", "]", ")", "if", "x", ".", "ndim", "==", "1", ":", "x", "=", "np", ".", "reshape", "(", "x", ",", "[", "x", ".", "shape", "[", "0", "]", ",", "1", "]", ")", "self", ".", "dimension", "=", "x", ".", "shape", "[", "1", "]", "if", "self", ".", "k", ">", "x", ".", "shape", "[", "0", "]", ":", "raise", "ValueError", "(", "\"Amount of data can not be less than k\"", ")", "if", "self", ".", "random_seed", "is", "not", "None", ":", "np", ".", "random", ".", "seed", "(", "self", ".", "random_seed", ")", "self", ".", "means", "=", "x", "[", "np", ".", "random", ".", "choice", "(", "x", ".", "shape", "[", "0", "]", ",", "self", ".", "k", ",", "replace", "=", "False", ")", "]", "labels", "=", "np", ".", "zeros", "(", "x", ".", "shape", "[", "0", "]", ")", ".", "astype", "(", "np", ".", "int", ")", "for", "i", "in", "range", "(", "max_iteration", ")", ":", "new_labels", "=", "self", ".", "__predict", "(", "x", ")", "if", "np", ".", "sum", "(", "new_labels", "!=", "labels", ")", ">", "terminate_condition", "/", "x", ".", "shape", "[", "0", "]", ":", "labels", "=", "new_labels", "else", ":", "break", "for", "j", "in", "range", "(", "self", ".", "k", ")", ":", "self", ".", "means", "[", "j", "]", "=", "np", ".", "average", "(", "x", "[", "labels", "==", "j", "]", ",", "axis", "=", "0", ")", "return", "labels", "def", "predict", "(", "self", ",", "x", ")", ":", "\"\"\"\r\n Use the trained model to predict the class labels of data.\r\n\r\n Args:\r\n x: Array-like. Contains data to be predicted.\r\n\r\n Raises:\r\n ValueError(\"Dimension not match.\"): data in x have different dimension with training data.\r\n\r\n Return:\r\n Array of size[amount of data,], contains labels of data.\r\n\r\n \"\"\"", "x", "=", "np", ".", "array", "(", "x", ")", "if", "x", ".", "ndim", "==", "0", ":", "x", "=", "np", ".", "reshape", "(", "x", ",", "[", "1", ",", "1", "]", ")", "if", "x", ".", "ndim", "==", "1", ":", "x", "=", "np", ".", "reshape", "(", "x", ",", "[", "x", ".", "shape", "[", "0", "]", ",", "1", "]", ")", "if", "self", ".", "dimension", "==", "1", "else", "np", ".", "reshape", "(", "x", ",", "[", "1", ",", "self", ".", "dimension", "]", ")", "if", "x", ".", "shape", "[", "1", "]", "!=", "self", ".", "dimension", ":", "raise", "ValueError", "(", "\"Dimension not match.\"", ")", "return", "self", ".", "__predict", "(", "x", ")", "def", "__predict", "(", "self", ",", "x", ")", ":", "\"\"\"\r\n Predict the labels for input data, by calculating square Euclidean distance.\r\n\r\n Args:\r\n x: Array-like. Contains data to be predicted.\r\n\r\n Return:\r\n Array of size[amount of data,], contains labels of data.\r\n \r\n \"\"\"", "labels", "=", "np", ".", "zeros", "(", "x", ".", "shape", "[", "0", "]", ")", ".", "astype", "(", "np", ".", "int", ")", "distance", "=", "np", ".", "full", "(", "x", ".", "shape", "[", "0", "]", ",", "np", ".", "inf", ")", "for", "i", "in", "range", "(", "self", ".", "k", ")", ":", "current_distance", "=", "np", ".", "sum", "(", "(", "x", "-", "self", ".", "means", "[", "i", "]", ")", "**", "2", ",", "axis", "=", "1", ")", "mask", "=", "distance", ">", "current_distance", "labels", "[", "mask", "]", "=", "i", "distance", "[", "mask", "]", "=", "current_distance", "[", "mask", "]", "return", "labels" ]
This class implements KMeans.
[ "This", "class", "implements", "KMeans", "." ]
[ "\"\"\"\r\n This class implements KMeans.\r\n\r\n Args:\r\n k(int): Amount of classes.\r\n random_seed(int): Optional. Random seed for initialization.\r\n\r\n Attributes:\r\n KMeans.k(int): Amount of classes.\r\n KMeans.random_seed: Optional. Random seed for initialization.\r\n KMeans.means: Central value of each class.\r\n KMeans.dimension: Amount of dimensions of each data.\r\n\r\n Methods:\r\n KMeans.fit: Fit model to the data.\r\n KMeans.fit_predict: Fit model to the data, and return the class labels of data.\r\n KMeans.predict: Use the trained model to predict the class labels of data.\r\n\r\n \"\"\"", "\"\"\"\r\n Constructor method\r\n\r\n \"\"\"", "\"\"\"\r\n Fit model to the data.\r\n\r\n Args:\r\n x: Array-like. Contains training data.\r\n max_iteration: Maximum times of iteration.\r\n terminate_condition(float): A fraction. Terminate if this value of fraction of data converge. Default 0.\r\n\r\n \"\"\"", "\"\"\"\r\n Fit model to the data, and return the class labels of data.\r\n\r\n Args:\r\n x: Array-like. Contains training data.\r\n max_iteration: Maximum times of iteration.\r\n terminate_condition(float): A fraction. Terminate if this value of fraction of data converge. Default 0.\r\n\r\n Raises:\r\n ValueError(\"Amount of data can not be less than k\")\r\n\r\n Return:\r\n Array of size[amount of data,], contains labels of data.\r\n\r\n \"\"\"", "# Re-calculate center of each class.\r", "\"\"\"\r\n Use the trained model to predict the class labels of data.\r\n\r\n Args:\r\n x: Array-like. Contains data to be predicted.\r\n\r\n Raises:\r\n ValueError(\"Dimension not match.\"): data in x have different dimension with training data.\r\n\r\n Return:\r\n Array of size[amount of data,], contains labels of data.\r\n\r\n \"\"\"", "\"\"\"\r\n Predict the labels for input data, by calculating square Euclidean distance.\r\n\r\n Args:\r\n x: Array-like. Contains data to be predicted.\r\n\r\n Return:\r\n Array of size[amount of data,], contains labels of data.\r\n \r\n \"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [ { "identifier": "k", "type": null, "docstring": "Amount of classes.", "docstring_tokens": [ "Amount", "of", "classes", "." ], "default": null, "is_optional": false }, { "identifier": "random_seed", "type": null, "docstring": "Optional. Random seed for initialization.", "docstring_tokens": [ "Optional", ".", "Random", "seed", "for", "initialization", "." ], "default": null, "is_optional": false }, { "identifier": "KMeans.k", "type": null, "docstring": "Amount of classes.", "docstring_tokens": [ "Amount", "of", "classes", "." ], "default": null, "is_optional": false }, { "identifier": "KMeans.random_seed", "type": null, "docstring": "Optional. Random seed for initialization.", "docstring_tokens": [ "Optional", ".", "Random", "seed", "for", "initialization", "." ], "default": null, "is_optional": null }, { "identifier": "KMeans.means", "type": null, "docstring": "Central value of each class.", "docstring_tokens": [ "Central", "value", "of", "each", "class", "." ], "default": null, "is_optional": null }, { "identifier": "KMeans.dimension", "type": null, "docstring": "Amount of dimensions of each data.", "docstring_tokens": [ "Amount", "of", "dimensions", "of", "each", "data", "." ], "default": null, "is_optional": null } ], "others": [] }
false
16
939
133
e384c22d794747fa62aea18f6568e02e5f8150ce
Axiologic/apars
cardinal/libs/zxing.js
[ "MIT" ]
JavaScript
HybridBinarizer
/** * This class implements a local thresholding algorithm, which while slower than the * GlobalHistogramBinarizer, is fairly efficient for what it does. It is designed for * high frequency images of barcodes with black data on white backgrounds. For this application, * it does a much better job than a global blackpoint with severe shadows and gradients. * However it tends to produce artifacts on lower frequency images and is therefore not * a good general purpose binarizer for uses outside ZXing. * * This class extends GlobalHistogramBinarizer, using the older histogram approach for 1D readers, * and the newer local approach for 2D readers. 1D decoding using a per-row histogram is already * inherently local, and only fails for horizontal gradients. We can revisit that problem later, * but for now it was not a win to use local blocks for 1D. * * This Binarizer is the default for the unit tests and the recommended class for library users. * * @author [email protected] (Daniel Switkin) */
This class implements a local thresholding algorithm, which while slower than the GlobalHistogramBinarizer, is fairly efficient for what it does. It is designed for high frequency images of barcodes with black data on white backgrounds. For this application, it does a much better job than a global blackpoint with severe shadows and gradients. However it tends to produce artifacts on lower frequency images and is therefore not a good general purpose binarizer for uses outside ZXing. This class extends GlobalHistogramBinarizer, using the older histogram approach for 1D readers, and the newer local approach for 2D readers. 1D decoding using a per-row histogram is already inherently local, and only fails for horizontal gradients. We can revisit that problem later, but for now it was not a win to use local blocks for 1D. This Binarizer is the default for the unit tests and the recommended class for library users.
[ "This", "class", "implements", "a", "local", "thresholding", "algorithm", "which", "while", "slower", "than", "the", "GlobalHistogramBinarizer", "is", "fairly", "efficient", "for", "what", "it", "does", ".", "It", "is", "designed", "for", "high", "frequency", "images", "of", "barcodes", "with", "black", "data", "on", "white", "backgrounds", ".", "For", "this", "application", "it", "does", "a", "much", "better", "job", "than", "a", "global", "blackpoint", "with", "severe", "shadows", "and", "gradients", ".", "However", "it", "tends", "to", "produce", "artifacts", "on", "lower", "frequency", "images", "and", "is", "therefore", "not", "a", "good", "general", "purpose", "binarizer", "for", "uses", "outside", "ZXing", ".", "This", "class", "extends", "GlobalHistogramBinarizer", "using", "the", "older", "histogram", "approach", "for", "1D", "readers", "and", "the", "newer", "local", "approach", "for", "2D", "readers", ".", "1D", "decoding", "using", "a", "per", "-", "row", "histogram", "is", "already", "inherently", "local", "and", "only", "fails", "for", "horizontal", "gradients", ".", "We", "can", "revisit", "that", "problem", "later", "but", "for", "now", "it", "was", "not", "a", "win", "to", "use", "local", "blocks", "for", "1D", ".", "This", "Binarizer", "is", "the", "default", "for", "the", "unit", "tests", "and", "the", "recommended", "class", "for", "library", "users", "." ]
class HybridBinarizer extends GlobalHistogramBinarizer { constructor(source) { super(source); this.matrix = null; } /** * Calculates the final BitMatrix once for all requests. This could be called once from the * constructor instead, but there are some advantages to doing it lazily, such as making * profiling easier, and not doing heavy lifting when callers don't expect it. */ /*@Override*/ getBlackMatrix() { if (this.matrix !== null) { return this.matrix; } const source = this.getLuminanceSource(); const width = source.getWidth(); const height = source.getHeight(); if (width >= HybridBinarizer.MINIMUM_DIMENSION && height >= HybridBinarizer.MINIMUM_DIMENSION) { const luminances = source.getMatrix(); let subWidth = width >> HybridBinarizer.BLOCK_SIZE_POWER; if ((width & HybridBinarizer.BLOCK_SIZE_MASK) !== 0) { subWidth++; } let subHeight = height >> HybridBinarizer.BLOCK_SIZE_POWER; if ((height & HybridBinarizer.BLOCK_SIZE_MASK) !== 0) { subHeight++; } const blackPoints = HybridBinarizer.calculateBlackPoints(luminances, subWidth, subHeight, width, height); const newMatrix = new BitMatrix(width, height); HybridBinarizer.calculateThresholdForBlock(luminances, subWidth, subHeight, width, height, blackPoints, newMatrix); this.matrix = newMatrix; } else { // If the image is too small, fall back to the global histogram approach. this.matrix = super.getBlackMatrix(); } return this.matrix; } /*@Override*/ createBinarizer(source) { return new HybridBinarizer(source); } /** * For each block in the image, calculate the average black point using a 5x5 grid * of the blocks around it. Also handles the corner cases (fractional blocks are computed based * on the last pixels in the row/column which are also used in the previous block). */ static calculateThresholdForBlock(luminances, subWidth /*int*/, subHeight /*int*/, width /*int*/, height /*int*/, blackPoints, matrix) { const maxYOffset = height - HybridBinarizer.BLOCK_SIZE; const maxXOffset = width - HybridBinarizer.BLOCK_SIZE; for (let y = 0; y < subHeight; y++) { let yoffset = y << HybridBinarizer.BLOCK_SIZE_POWER; if (yoffset > maxYOffset) { yoffset = maxYOffset; } const top = HybridBinarizer.cap(y, 2, subHeight - 3); for (let x = 0; x < subWidth; x++) { let xoffset = x << HybridBinarizer.BLOCK_SIZE_POWER; if (xoffset > maxXOffset) { xoffset = maxXOffset; } const left = HybridBinarizer.cap(x, 2, subWidth - 3); let sum = 0; for (let z = -2; z <= 2; z++) { const blackRow = blackPoints[top + z]; sum += blackRow[left - 2] + blackRow[left - 1] + blackRow[left] + blackRow[left + 1] + blackRow[left + 2]; } const average = sum / 25; HybridBinarizer.thresholdBlock(luminances, xoffset, yoffset, average, width, matrix); } } } static cap(value /*int*/, min /*int*/, max /*int*/) { return value < min ? min : value > max ? max : value; } /** * Applies a single threshold to a block of pixels. */ static thresholdBlock(luminances, xoffset /*int*/, yoffset /*int*/, threshold /*int*/, stride /*int*/, matrix) { for (let y = 0, offset = yoffset * stride + xoffset; y < HybridBinarizer.BLOCK_SIZE; y++, offset += stride) { for (let x = 0; x < HybridBinarizer.BLOCK_SIZE; x++) { // Comparison needs to be <= so that black == 0 pixels are black even if the threshold is 0. if ((luminances[offset + x] & 0xFF) <= threshold) { matrix.set(xoffset + x, yoffset + y); } } } } /** * Calculates a single black point for each block of pixels and saves it away. * See the following thread for a discussion of this algorithm: * http://groups.google.com/group/zxing/browse_thread/thread/d06efa2c35a7ddc0 */ static calculateBlackPoints(luminances, subWidth /*int*/, subHeight /*int*/, width /*int*/, height /*int*/) { const maxYOffset = height - HybridBinarizer.BLOCK_SIZE; const maxXOffset = width - HybridBinarizer.BLOCK_SIZE; // tslint:disable-next-line:whitespace const blackPoints = new Array(subHeight); // subWidth for (let y = 0; y < subHeight; y++) { blackPoints[y] = new Int32Array(subWidth); let yoffset = y << HybridBinarizer.BLOCK_SIZE_POWER; if (yoffset > maxYOffset) { yoffset = maxYOffset; } for (let x = 0; x < subWidth; x++) { let xoffset = x << HybridBinarizer.BLOCK_SIZE_POWER; if (xoffset > maxXOffset) { xoffset = maxXOffset; } let sum = 0; let min = 0xFF; let max = 0; for (let yy = 0, offset = yoffset * width + xoffset; yy < HybridBinarizer.BLOCK_SIZE; yy++, offset += width) { for (let xx = 0; xx < HybridBinarizer.BLOCK_SIZE; xx++) { const pixel = luminances[offset + xx] & 0xFF; sum += pixel; // still looking for good contrast if (pixel < min) { min = pixel; } if (pixel > max) { max = pixel; } } // short-circuit min/max tests once dynamic range is met if (max - min > HybridBinarizer.MIN_DYNAMIC_RANGE) { // finish the rest of the rows quickly for (yy++, offset += width; yy < HybridBinarizer.BLOCK_SIZE; yy++, offset += width) { for (let xx = 0; xx < HybridBinarizer.BLOCK_SIZE; xx++) { sum += luminances[offset + xx] & 0xFF; } } } } // The default estimate is the average of the values in the block. let average = sum >> (HybridBinarizer.BLOCK_SIZE_POWER * 2); if (max - min <= HybridBinarizer.MIN_DYNAMIC_RANGE) { // If variation within the block is low, assume this is a block with only light or only // dark pixels. In that case we do not want to use the average, as it would divide this // low contrast area into black and white pixels, essentially creating data out of noise. // // The default assumption is that the block is light/background. Since no estimate for // the level of dark pixels exists locally, use half the min for the block. average = min / 2; if (y > 0 && x > 0) { // Correct the "white background" assumption for blocks that have neighbors by comparing // the pixels in this block to the previously calculated black points. This is based on // the fact that dark barcode symbology is always surrounded by some amount of light // background for which reasonable black point estimates were made. The bp estimated at // the boundaries is used for the interior. // The (min < bp) is arbitrary but works better than other heuristics that were tried. const averageNeighborBlackPoint = (blackPoints[y - 1][x] + (2 * blackPoints[y][x - 1]) + blackPoints[y - 1][x - 1]) / 4; if (min < averageNeighborBlackPoint) { average = averageNeighborBlackPoint; } } } blackPoints[y][x] = average; } } return blackPoints; } }
[ "class", "HybridBinarizer", "extends", "GlobalHistogramBinarizer", "{", "constructor", "(", "source", ")", "{", "super", "(", "source", ")", ";", "this", ".", "matrix", "=", "null", ";", "}", "getBlackMatrix", "(", ")", "{", "if", "(", "this", ".", "matrix", "!==", "null", ")", "{", "return", "this", ".", "matrix", ";", "}", "const", "source", "=", "this", ".", "getLuminanceSource", "(", ")", ";", "const", "width", "=", "source", ".", "getWidth", "(", ")", ";", "const", "height", "=", "source", ".", "getHeight", "(", ")", ";", "if", "(", "width", ">=", "HybridBinarizer", ".", "MINIMUM_DIMENSION", "&&", "height", ">=", "HybridBinarizer", ".", "MINIMUM_DIMENSION", ")", "{", "const", "luminances", "=", "source", ".", "getMatrix", "(", ")", ";", "let", "subWidth", "=", "width", ">>", "HybridBinarizer", ".", "BLOCK_SIZE_POWER", ";", "if", "(", "(", "width", "&", "HybridBinarizer", ".", "BLOCK_SIZE_MASK", ")", "!==", "0", ")", "{", "subWidth", "++", ";", "}", "let", "subHeight", "=", "height", ">>", "HybridBinarizer", ".", "BLOCK_SIZE_POWER", ";", "if", "(", "(", "height", "&", "HybridBinarizer", ".", "BLOCK_SIZE_MASK", ")", "!==", "0", ")", "{", "subHeight", "++", ";", "}", "const", "blackPoints", "=", "HybridBinarizer", ".", "calculateBlackPoints", "(", "luminances", ",", "subWidth", ",", "subHeight", ",", "width", ",", "height", ")", ";", "const", "newMatrix", "=", "new", "BitMatrix", "(", "width", ",", "height", ")", ";", "HybridBinarizer", ".", "calculateThresholdForBlock", "(", "luminances", ",", "subWidth", ",", "subHeight", ",", "width", ",", "height", ",", "blackPoints", ",", "newMatrix", ")", ";", "this", ".", "matrix", "=", "newMatrix", ";", "}", "else", "{", "this", ".", "matrix", "=", "super", ".", "getBlackMatrix", "(", ")", ";", "}", "return", "this", ".", "matrix", ";", "}", "createBinarizer", "(", "source", ")", "{", "return", "new", "HybridBinarizer", "(", "source", ")", ";", "}", "static", "calculateThresholdForBlock", "(", "luminances", ",", "subWidth", ",", "subHeight", ",", "width", ",", "height", ",", "blackPoints", ",", "matrix", ")", "{", "const", "maxYOffset", "=", "height", "-", "HybridBinarizer", ".", "BLOCK_SIZE", ";", "const", "maxXOffset", "=", "width", "-", "HybridBinarizer", ".", "BLOCK_SIZE", ";", "for", "(", "let", "y", "=", "0", ";", "y", "<", "subHeight", ";", "y", "++", ")", "{", "let", "yoffset", "=", "y", "<<", "HybridBinarizer", ".", "BLOCK_SIZE_POWER", ";", "if", "(", "yoffset", ">", "maxYOffset", ")", "{", "yoffset", "=", "maxYOffset", ";", "}", "const", "top", "=", "HybridBinarizer", ".", "cap", "(", "y", ",", "2", ",", "subHeight", "-", "3", ")", ";", "for", "(", "let", "x", "=", "0", ";", "x", "<", "subWidth", ";", "x", "++", ")", "{", "let", "xoffset", "=", "x", "<<", "HybridBinarizer", ".", "BLOCK_SIZE_POWER", ";", "if", "(", "xoffset", ">", "maxXOffset", ")", "{", "xoffset", "=", "maxXOffset", ";", "}", "const", "left", "=", "HybridBinarizer", ".", "cap", "(", "x", ",", "2", ",", "subWidth", "-", "3", ")", ";", "let", "sum", "=", "0", ";", "for", "(", "let", "z", "=", "-", "2", ";", "z", "<=", "2", ";", "z", "++", ")", "{", "const", "blackRow", "=", "blackPoints", "[", "top", "+", "z", "]", ";", "sum", "+=", "blackRow", "[", "left", "-", "2", "]", "+", "blackRow", "[", "left", "-", "1", "]", "+", "blackRow", "[", "left", "]", "+", "blackRow", "[", "left", "+", "1", "]", "+", "blackRow", "[", "left", "+", "2", "]", ";", "}", "const", "average", "=", "sum", "/", "25", ";", "HybridBinarizer", ".", "thresholdBlock", "(", "luminances", ",", "xoffset", ",", "yoffset", ",", "average", ",", "width", ",", "matrix", ")", ";", "}", "}", "}", "static", "cap", "(", "value", ",", "min", ",", "max", ")", "{", "return", "value", "<", "min", "?", "min", ":", "value", ">", "max", "?", "max", ":", "value", ";", "}", "static", "thresholdBlock", "(", "luminances", ",", "xoffset", ",", "yoffset", ",", "threshold", ",", "stride", ",", "matrix", ")", "{", "for", "(", "let", "y", "=", "0", ",", "offset", "=", "yoffset", "*", "stride", "+", "xoffset", ";", "y", "<", "HybridBinarizer", ".", "BLOCK_SIZE", ";", "y", "++", ",", "offset", "+=", "stride", ")", "{", "for", "(", "let", "x", "=", "0", ";", "x", "<", "HybridBinarizer", ".", "BLOCK_SIZE", ";", "x", "++", ")", "{", "if", "(", "(", "luminances", "[", "offset", "+", "x", "]", "&", "0xFF", ")", "<=", "threshold", ")", "{", "matrix", ".", "set", "(", "xoffset", "+", "x", ",", "yoffset", "+", "y", ")", ";", "}", "}", "}", "}", "static", "calculateBlackPoints", "(", "luminances", ",", "subWidth", ",", "subHeight", ",", "width", ",", "height", ")", "{", "const", "maxYOffset", "=", "height", "-", "HybridBinarizer", ".", "BLOCK_SIZE", ";", "const", "maxXOffset", "=", "width", "-", "HybridBinarizer", ".", "BLOCK_SIZE", ";", "const", "blackPoints", "=", "new", "Array", "(", "subHeight", ")", ";", "for", "(", "let", "y", "=", "0", ";", "y", "<", "subHeight", ";", "y", "++", ")", "{", "blackPoints", "[", "y", "]", "=", "new", "Int32Array", "(", "subWidth", ")", ";", "let", "yoffset", "=", "y", "<<", "HybridBinarizer", ".", "BLOCK_SIZE_POWER", ";", "if", "(", "yoffset", ">", "maxYOffset", ")", "{", "yoffset", "=", "maxYOffset", ";", "}", "for", "(", "let", "x", "=", "0", ";", "x", "<", "subWidth", ";", "x", "++", ")", "{", "let", "xoffset", "=", "x", "<<", "HybridBinarizer", ".", "BLOCK_SIZE_POWER", ";", "if", "(", "xoffset", ">", "maxXOffset", ")", "{", "xoffset", "=", "maxXOffset", ";", "}", "let", "sum", "=", "0", ";", "let", "min", "=", "0xFF", ";", "let", "max", "=", "0", ";", "for", "(", "let", "yy", "=", "0", ",", "offset", "=", "yoffset", "*", "width", "+", "xoffset", ";", "yy", "<", "HybridBinarizer", ".", "BLOCK_SIZE", ";", "yy", "++", ",", "offset", "+=", "width", ")", "{", "for", "(", "let", "xx", "=", "0", ";", "xx", "<", "HybridBinarizer", ".", "BLOCK_SIZE", ";", "xx", "++", ")", "{", "const", "pixel", "=", "luminances", "[", "offset", "+", "xx", "]", "&", "0xFF", ";", "sum", "+=", "pixel", ";", "if", "(", "pixel", "<", "min", ")", "{", "min", "=", "pixel", ";", "}", "if", "(", "pixel", ">", "max", ")", "{", "max", "=", "pixel", ";", "}", "}", "if", "(", "max", "-", "min", ">", "HybridBinarizer", ".", "MIN_DYNAMIC_RANGE", ")", "{", "for", "(", "yy", "++", ",", "offset", "+=", "width", ";", "yy", "<", "HybridBinarizer", ".", "BLOCK_SIZE", ";", "yy", "++", ",", "offset", "+=", "width", ")", "{", "for", "(", "let", "xx", "=", "0", ";", "xx", "<", "HybridBinarizer", ".", "BLOCK_SIZE", ";", "xx", "++", ")", "{", "sum", "+=", "luminances", "[", "offset", "+", "xx", "]", "&", "0xFF", ";", "}", "}", "}", "}", "let", "average", "=", "sum", ">>", "(", "HybridBinarizer", ".", "BLOCK_SIZE_POWER", "*", "2", ")", ";", "if", "(", "max", "-", "min", "<=", "HybridBinarizer", ".", "MIN_DYNAMIC_RANGE", ")", "{", "average", "=", "min", "/", "2", ";", "if", "(", "y", ">", "0", "&&", "x", ">", "0", ")", "{", "const", "averageNeighborBlackPoint", "=", "(", "blackPoints", "[", "y", "-", "1", "]", "[", "x", "]", "+", "(", "2", "*", "blackPoints", "[", "y", "]", "[", "x", "-", "1", "]", ")", "+", "blackPoints", "[", "y", "-", "1", "]", "[", "x", "-", "1", "]", ")", "/", "4", ";", "if", "(", "min", "<", "averageNeighborBlackPoint", ")", "{", "average", "=", "averageNeighborBlackPoint", ";", "}", "}", "}", "blackPoints", "[", "y", "]", "[", "x", "]", "=", "average", ";", "}", "}", "return", "blackPoints", ";", "}", "}" ]
This class implements a local thresholding algorithm, which while slower than the GlobalHistogramBinarizer, is fairly efficient for what it does.
[ "This", "class", "implements", "a", "local", "thresholding", "algorithm", "which", "while", "slower", "than", "the", "GlobalHistogramBinarizer", "is", "fairly", "efficient", "for", "what", "it", "does", "." ]
[ "/**\n * Calculates the final BitMatrix once for all requests. This could be called once from the\n * constructor instead, but there are some advantages to doing it lazily, such as making\n * profiling easier, and not doing heavy lifting when callers don't expect it.\n */", "/*@Override*/", "// If the image is too small, fall back to the global histogram approach.", "/*@Override*/", "/**\n * For each block in the image, calculate the average black point using a 5x5 grid\n * of the blocks around it. Also handles the corner cases (fractional blocks are computed based\n * on the last pixels in the row/column which are also used in the previous block).\n */", "/*int*/", "/*int*/", "/*int*/", "/*int*/", "/*int*/", "/*int*/", "/*int*/", "/**\n * Applies a single threshold to a block of pixels.\n */", "/*int*/", "/*int*/", "/*int*/", "/*int*/", "// Comparison needs to be <= so that black == 0 pixels are black even if the threshold is 0.", "/**\n * Calculates a single black point for each block of pixels and saves it away.\n * See the following thread for a discussion of this algorithm:\n * http://groups.google.com/group/zxing/browse_thread/thread/d06efa2c35a7ddc0\n */", "/*int*/", "/*int*/", "/*int*/", "/*int*/", "// tslint:disable-next-line:whitespace", "// subWidth", "// still looking for good contrast", "// short-circuit min/max tests once dynamic range is met", "// finish the rest of the rows quickly", "// The default estimate is the average of the values in the block.", "// If variation within the block is low, assume this is a block with only light or only", "// dark pixels. In that case we do not want to use the average, as it would divide this", "// low contrast area into black and white pixels, essentially creating data out of noise.", "//", "// The default assumption is that the block is light/background. Since no estimate for", "// the level of dark pixels exists locally, use half the min for the block.", "// Correct the \"white background\" assumption for blocks that have neighbors by comparing", "// the pixels in this block to the previously calculated black points. This is based on", "// the fact that dark barcode symbology is always surrounded by some amount of light", "// background for which reasonable black point estimates were made. The bp estimated at", "// the boundaries is used for the interior.", "// The (min < bp) is arbitrary but works better than other heuristics that were tried." ]
[ { "param": "GlobalHistogramBinarizer", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "GlobalHistogramBinarizer", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
23
1,870
240
d8b77f43d26e0e73be2779c00a0ed8f67b65585a
ghstahl/P7.RestHook
src/SD.Tools.Algorithmia/Commands/CommandQueue.cs
[ "MIT" ]
C#
CommandQueue
/// <summary> /// Class which is used as a command queue to store commands to execute. Supports undo/redo. /// </summary> /// <remarks>This command queue uses the policy that the current command pointer points to the command which has been executed the last time. It can only be /// null if it hasn't executed any commands or if the queue is empty. /// This policy is different from the policy where the current command pointer points to the command which is about to be executed: as the execution of a command /// can spawn commands, it first has to move to the command executed, and then execute it, otherwise there is a state where the current command pointer is actually /// the command which was executed last (as the new command to enqueue is spawned during execution of the command), because the move to the new command happens after /// the command has been executed in full. /// </remarks>
Class which is used as a command queue to store commands to execute. Supports undo/redo.
[ "Class", "which", "is", "used", "as", "a", "command", "queue", "to", "store", "commands", "to", "execute", ".", "Supports", "undo", "/", "redo", "." ]
public class CommandQueue : IEnumerable<CommandBase> { #region Class Member Declarations private readonly LinkedBucketList<CommandBase> _commands; private ListBucket<CommandBase> _currentCommandBucket; #endregion public CommandQueue() { _commands = new LinkedBucketList<CommandBase>(); } public bool EnqueueCommand(CommandBase toEnqueue) { ArgumentVerifier.CantBeNull(toEnqueue, "toEnqueue"); if(CommandQueueManagerSingleton.GetInstance().IsInUndoablePeriod) { return false; } if(this.UndoInProgress) { if(CommandQueueManager.ThrowExceptionOnDoDuringUndo) { throw new DoDuringUndoException(); } return false; } if(_currentCommandBucket == null) { _commands.Clear(); } else { _commands.RemoveAfter(_currentCommandBucket); } _commands.InsertAfter(new ListBucket<CommandBase>(toEnqueue), _currentCommandBucket); return true; } public void RedoCurrentCommand() { PerformDoRedoCommand(true); } public void DoCurrentCommand() { PerformDoRedoCommand(false); } private void PerformDoRedoCommand(bool performRedo) { if(this.CanDo) { MoveNext(); CommandBase commandToExecute = _currentCommandBucket.Contents; if(commandToExecute.BeforeDoAction != null) { commandToExecute.BeforeDoAction(); } if(performRedo) { commandToExecute.Redo(); } else { commandToExecute.Do(); } if(commandToExecute.AfterDoAction != null) { commandToExecute.AfterDoAction(); } } } public void UndoPreviousCommand() { if(this.CanUndo) { CommandBase commandToExecute = _currentCommandBucket.Contents; if(commandToExecute.BeforeUndoAction != null) { commandToExecute.BeforeUndoAction(); } commandToExecute.Undo(); if(commandToExecute.AfterUndoAction != null) { commandToExecute.AfterUndoAction(); } MovePrevious(); } } public void DequeueLastExecutedCommand() { if(this.CanUndo) { ListBucket<CommandBase> toRemove = _currentCommandBucket; MovePrevious(); _commands.Remove(toRemove); } } public void Clear() { _commands.Clear(); _currentCommandBucket = null; } private void MovePrevious() { if(_currentCommandBucket == null) { return; } _currentCommandBucket = _currentCommandBucket.Previous; } private void MoveNext() { _currentCommandBucket = _currentCommandBucket == null ? _commands.Head : _currentCommandBucket.Next; } #region IEnumerable<CommandBase> Members public IEnumerator<CommandBase> GetEnumerator() { return _commands.GetEnumerator(); } #endregion #region IEnumerable Members IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } #endregion #region Class Property Declarations internal bool UndoInProgress { get; set;} public bool CanUndo { get { return _currentCommandBucket != null; } } public bool CanDo { get { return (((_currentCommandBucket != null) && (_currentCommandBucket.Next!=null)) || ((_currentCommandBucket==null) && (_commands.Count>0))); } } public CommandBase ActiveCommand { get { return _currentCommandBucket == null ? null : _currentCommandBucket.Contents; } } public int Count { get { return _commands == null ? 0 : _commands.Count; } } #endregion }
[ "public", "class", "CommandQueue", ":", "IEnumerable", "<", "CommandBase", ">", "{", "region", " Class Member Declarations", "private", "readonly", "LinkedBucketList", "<", "CommandBase", ">", "_commands", ";", "private", "ListBucket", "<", "CommandBase", ">", "_currentCommandBucket", ";", "endregion", "public", "CommandQueue", "(", ")", "{", "_commands", "=", "new", "LinkedBucketList", "<", "CommandBase", ">", "(", ")", ";", "}", "public", "bool", "EnqueueCommand", "(", "CommandBase", "toEnqueue", ")", "{", "ArgumentVerifier", ".", "CantBeNull", "(", "toEnqueue", ",", "\"", "toEnqueue", "\"", ")", ";", "if", "(", "CommandQueueManagerSingleton", ".", "GetInstance", "(", ")", ".", "IsInUndoablePeriod", ")", "{", "return", "false", ";", "}", "if", "(", "this", ".", "UndoInProgress", ")", "{", "if", "(", "CommandQueueManager", ".", "ThrowExceptionOnDoDuringUndo", ")", "{", "throw", "new", "DoDuringUndoException", "(", ")", ";", "}", "return", "false", ";", "}", "if", "(", "_currentCommandBucket", "==", "null", ")", "{", "_commands", ".", "Clear", "(", ")", ";", "}", "else", "{", "_commands", ".", "RemoveAfter", "(", "_currentCommandBucket", ")", ";", "}", "_commands", ".", "InsertAfter", "(", "new", "ListBucket", "<", "CommandBase", ">", "(", "toEnqueue", ")", ",", "_currentCommandBucket", ")", ";", "return", "true", ";", "}", "public", "void", "RedoCurrentCommand", "(", ")", "{", "PerformDoRedoCommand", "(", "true", ")", ";", "}", "public", "void", "DoCurrentCommand", "(", ")", "{", "PerformDoRedoCommand", "(", "false", ")", ";", "}", "private", "void", "PerformDoRedoCommand", "(", "bool", "performRedo", ")", "{", "if", "(", "this", ".", "CanDo", ")", "{", "MoveNext", "(", ")", ";", "CommandBase", "commandToExecute", "=", "_currentCommandBucket", ".", "Contents", ";", "if", "(", "commandToExecute", ".", "BeforeDoAction", "!=", "null", ")", "{", "commandToExecute", ".", "BeforeDoAction", "(", ")", ";", "}", "if", "(", "performRedo", ")", "{", "commandToExecute", ".", "Redo", "(", ")", ";", "}", "else", "{", "commandToExecute", ".", "Do", "(", ")", ";", "}", "if", "(", "commandToExecute", ".", "AfterDoAction", "!=", "null", ")", "{", "commandToExecute", ".", "AfterDoAction", "(", ")", ";", "}", "}", "}", "public", "void", "UndoPreviousCommand", "(", ")", "{", "if", "(", "this", ".", "CanUndo", ")", "{", "CommandBase", "commandToExecute", "=", "_currentCommandBucket", ".", "Contents", ";", "if", "(", "commandToExecute", ".", "BeforeUndoAction", "!=", "null", ")", "{", "commandToExecute", ".", "BeforeUndoAction", "(", ")", ";", "}", "commandToExecute", ".", "Undo", "(", ")", ";", "if", "(", "commandToExecute", ".", "AfterUndoAction", "!=", "null", ")", "{", "commandToExecute", ".", "AfterUndoAction", "(", ")", ";", "}", "MovePrevious", "(", ")", ";", "}", "}", "public", "void", "DequeueLastExecutedCommand", "(", ")", "{", "if", "(", "this", ".", "CanUndo", ")", "{", "ListBucket", "<", "CommandBase", ">", "toRemove", "=", "_currentCommandBucket", ";", "MovePrevious", "(", ")", ";", "_commands", ".", "Remove", "(", "toRemove", ")", ";", "}", "}", "public", "void", "Clear", "(", ")", "{", "_commands", ".", "Clear", "(", ")", ";", "_currentCommandBucket", "=", "null", ";", "}", "private", "void", "MovePrevious", "(", ")", "{", "if", "(", "_currentCommandBucket", "==", "null", ")", "{", "return", ";", "}", "_currentCommandBucket", "=", "_currentCommandBucket", ".", "Previous", ";", "}", "private", "void", "MoveNext", "(", ")", "{", "_currentCommandBucket", "=", "_currentCommandBucket", "==", "null", "?", "_commands", ".", "Head", ":", "_currentCommandBucket", ".", "Next", ";", "}", "region", " IEnumerable<CommandBase> Members", "public", "IEnumerator", "<", "CommandBase", ">", "GetEnumerator", "(", ")", "{", "return", "_commands", ".", "GetEnumerator", "(", ")", ";", "}", "endregion", "region", " IEnumerable Members", "IEnumerator", "IEnumerable", ".", "GetEnumerator", "(", ")", "{", "return", "this", ".", "GetEnumerator", "(", ")", ";", "}", "endregion", "region", " Class Property Declarations", "internal", "bool", "UndoInProgress", "{", "get", ";", "set", ";", "}", "public", "bool", "CanUndo", "{", "get", "{", "return", "_currentCommandBucket", "!=", "null", ";", "}", "}", "public", "bool", "CanDo", "{", "get", "{", "return", "(", "(", "(", "_currentCommandBucket", "!=", "null", ")", "&&", "(", "_currentCommandBucket", ".", "Next", "!=", "null", ")", ")", "||", "(", "(", "_currentCommandBucket", "==", "null", ")", "&&", "(", "_commands", ".", "Count", ">", "0", ")", ")", ")", ";", "}", "}", "public", "CommandBase", "ActiveCommand", "{", "get", "{", "return", "_currentCommandBucket", "==", "null", "?", "null", ":", "_currentCommandBucket", ".", "Contents", ";", "}", "}", "public", "int", "Count", "{", "get", "{", "return", "_commands", "==", "null", "?", "0", ":", "_commands", ".", "Count", ";", "}", "}", "endregion", "}" ]
Class which is used as a command queue to store commands to execute.
[ "Class", "which", "is", "used", "as", "a", "command", "queue", "to", "store", "commands", "to", "execute", "." ]
[ "/// <summary>", "/// Initializes a new instance of the <see cref=\"CommandQueue\"/> class.", "/// </summary>", "/// <summary>", "/// Enqueues the command specified and makes it the current command.", "/// </summary>", "/// <param name=\"toEnqueue\">To enqueue.</param>", "/// <returns>true if enqueue action succeeded, false otherwise</returns>", "// ignore, all commands are already there in this mode and this command therefore already is either there or is not important", "// can't add new commands to a queue of a command which executed an undoFunc. This happens through bugs in the using code so we have to ", "// thrown an exception to illustrate that there's a problem with the code using this library.", "// ignore", "// clear queue from the active index", "// clear the complete queue from any commands which might have been undone, as the new command makes them unreachable. ", "/// <summary>", "/// Calls the current command's Redo() method, if there's a command left to execute. It first makes the next command the current command and then executes it.", "/// </summary>", "/// <summary>", "/// Calls the current command's Do() method, if there's a command left to execute. It first makes the next command the current command and then executes it.", "/// </summary>", "/// <summary>", "/// Performs the do / redo action on the current command.", "/// </summary>", "/// <param name=\"performRedo\">if set to <see langword=\"true\"/> perform a redo, otherwise perform a do.</param>", "/// <summary>", "/// Calls the last executed command's Undo method, if there's was a command last executed. It then makes the previous command the current command.", "/// </summary>", "/// <summary>", "/// Dequeues the last executed command. This is done in periods which aren't undoable.", "/// </summary>", "/// <summary>", "/// Clears this instance.", "/// </summary>", "/// <summary>", "/// Moves the previous.", "/// </summary>", "/// <summary>", "/// Moves the current command to the next command in the queue.", "/// </summary>", "/// <summary>", "/// Returns an enumerator that iterates through the collection.", "/// </summary>", "/// <returns>", "/// A <see cref=\"T:System.Collections.Generic.IEnumerator`1\"/> that can be used to iterate through the collection.", "/// </returns>", "/// <summary>", "/// Returns an enumerator that iterates through a collection.", "/// </summary>", "/// <returns>", "/// An <see cref=\"T:System.Collections.IEnumerator\"/> object that can be used to iterate through the collection.", "/// </returns>", "/// <summary>", "/// Gets or sets a value indicating whether an undo action is in progress. If an undo action is in progress, no commands can be added to this queue, as ", "/// those commands will never be undoable nor processable in a normal way: undo actions should restore state with direct actions. Adding commands to a queue", "/// which is in an undo action will cause an exception. ", "/// </summary>", "/// <summary>", "/// Gets a value indicating whether this command queue can undo the last executed command (so there are commands left to undo) (true), or false if no more", "/// commands can be undone in this queue.", "/// </summary>", "/// <summary>", "/// Gets a value indicating whether this command queue can do a current command (so there's a command left to execute) (true) or false if no more commands", "/// can be executed in this queue.", "/// </summary>", "/// <summary>", "/// Gets the active command in this queue.", "/// </summary>", "/// <summary>", "/// Gets the number of commands in this queue", "/// </summary>" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [ { "identifier": "remarks", "docstring": "This command queue uses the policy that the current command pointer points to the command which has been executed the last time. It can only be\nnull if it hasn't executed any commands or if the queue is empty.\nThis policy is different from the policy where the current command pointer points to the command which is about to be executed: as the execution of a command\ncan spawn commands, it first has to move to the command executed, and then execute it, otherwise there is a state where the current command pointer is actually\nthe command which was executed last (as the new command to enqueue is spawned during execution of the command), because the move to the new command happens after\nthe command has been executed in full.", "docstring_tokens": [ "This", "command", "queue", "uses", "the", "policy", "that", "the", "current", "command", "pointer", "points", "to", "the", "command", "which", "has", "been", "executed", "the", "last", "time", ".", "It", "can", "only", "be", "null", "if", "it", "hasn", "'", "t", "executed", "any", "commands", "or", "if", "the", "queue", "is", "empty", ".", "This", "policy", "is", "different", "from", "the", "policy", "where", "the", "current", "command", "pointer", "points", "to", "the", "command", "which", "is", "about", "to", "be", "executed", ":", "as", "the", "execution", "of", "a", "command", "can", "spawn", "commands", "it", "first", "has", "to", "move", "to", "the", "command", "executed", "and", "then", "execute", "it", "otherwise", "there", "is", "a", "state", "where", "the", "current", "command", "pointer", "is", "actually", "the", "command", "which", "was", "executed", "last", "(", "as", "the", "new", "command", "to", "enqueue", "is", "spawned", "during", "execution", "of", "the", "command", ")", "because", "the", "move", "to", "the", "new", "command", "happens", "after", "the", "command", "has", "been", "executed", "in", "full", "." ] } ] }
false
15
895
186
a77223a50d3d8a9547dca51f2af7c2cd326598b6
PopovKS/dataobjects-net
Orm/Xtensive.Orm/Orm/Structure.cs
[ "MIT" ]
C#
Structure
/// <summary> /// Abstract base class for any persistent structure. /// Persistent structures are types having <see cref="ValueType"/> behavior - /// they have no keys, and thus can be stored only as parts of entities. /// </summary> /// <remarks> /// <para> /// Like <see cref="Entity"/>, structures support inheritance and consist of one or more persistent /// fields (properties) of scalar, <see cref="Structure"/>, or <see cref="Entity"/> type. /// </para> /// <para> /// However unlike entity, structure is not identified by <see cref="Key"/> /// and has value type behavior: it can be stored only inside some entity. /// </para> /// </remarks> /// <example>In the following example Address fields (City, Street and Building) will be included in Person table. /// <code> /// public class Person : Entity /// { /// [Field, Key] /// public int Id { get; set; } /// /// public string Name { get; set; } /// /// public Address Address { get; set; } /// } /// /// public class Address : Structure /// { /// [Field] /// public City City { get; set; } /// /// [Field] /// public string Street { get; set; } /// /// [Field] /// public string Building { get; set; } /// } /// </code> /// </example>
Abstract base class for any persistent structure. Persistent structures are types having behavior they have no keys, and thus can be stored only as parts of entities.
[ "Abstract", "base", "class", "for", "any", "persistent", "structure", ".", "Persistent", "structures", "are", "types", "having", "behavior", "they", "have", "no", "keys", "and", "thus", "can", "be", "stored", "only", "as", "parts", "of", "entities", "." ]
[SystemType] public abstract class Structure : Persistent, IEquatable<Structure>, IFieldValueAdapter { private readonly Tuple tuple; private readonly TypeInfo typeInfo; private Persistent owner; private Entity entity; public override TypeInfo TypeInfo { [DebuggerStepThrough] get { return typeInfo; } } public Persistent Owner { get { return owner; } private set { entity = null; owner = value; } } public FieldInfo Field { get; private set; } public Entity Entity { get { if (Owner == null) return null; return entity ?? (entity = (Owner as Entity) ?? ((Structure) Owner).Entity); } } public bool IsBoundToEntity { get { return (Owner!=null) && ((Owner is Entity) || ((Structure) Owner).IsBoundToEntity); } } protected internal override sealed Tuple Tuple { [DebuggerStepThrough] get { return tuple; } } protected internal override sealed bool CanBeValidated { get { return IsBoundToEntity; } } public override sealed event PropertyChangedEventHandler PropertyChanged { add { Session.EntityEvents.AddSubscriber(GetOwnerEntityKey(Owner), Field, EntityEventBroker.PropertyChangedEventKey, value); } remove { Session.EntityEvents.RemoveSubscriber(GetOwnerEntityKey(Owner), Field, EntityEventBroker.PropertyChangedEventKey, value); } } #region System-level event-like members & GetSubscription members internal override sealed void SystemBeforeInitialize(bool materialize) { if (Session.IsSystemLogicOnly) return; var subscriptionInfo = GetSubscription(EntityEventBroker.InitializingPersistentEventKey); if (subscriptionInfo.Second!=null) ((Action<Key, FieldInfo>) subscriptionInfo.Second) .Invoke(subscriptionInfo.First, Field); } internal sealed override void SystemInitialize(bool materialize) { if (Session.IsSystemLogicOnly) return; var subscriptionInfo = GetSubscription(EntityEventBroker.InitializePersistentEventKey); if (subscriptionInfo.Second!=null) ((Action<Key, FieldInfo>) subscriptionInfo.Second) .Invoke(subscriptionInfo.First, Field); OnInitialize(); if (!materialize && CanBeValidated) Session.ValidationContext.RegisterForValidation(Entity); } internal override sealed void SystemInitializationError(Exception error) { if (Session.IsSystemLogicOnly) return; var subscriptionInfo = GetSubscription(EntityEventBroker.InitializationErrorPersistentEventKey); if (subscriptionInfo.Second!=null) ((Action<Key>) subscriptionInfo.Second) .Invoke(subscriptionInfo.First); OnInitializationError(error); } internal override sealed void SystemBeforeGetValue(FieldInfo field) { if (!Session.IsSystemLogicOnly) { var subscriptionInfo = GetSubscription(EntityEventBroker.GettingFieldEventKey); if (subscriptionInfo.Second!=null) ((Action<Key, FieldInfo, FieldInfo>) subscriptionInfo.Second) .Invoke(subscriptionInfo.First, Field, field); OnGettingFieldValue(field); } if (Owner == null) return; var ownerField = Owner.TypeInfo.StructureFieldMapping[new Pair<FieldInfo>(Field, field)]; Owner.SystemBeforeGetValue(ownerField); } internal override sealed void SystemGetValue(FieldInfo field, object value) { if (!Session.IsSystemLogicOnly) { var subscriptionInfo = GetSubscription(EntityEventBroker.GetFieldEventKey); if (subscriptionInfo.Second != null) ((Action<Key, FieldInfo, FieldInfo, object>) subscriptionInfo.Second) .Invoke(subscriptionInfo.First, Field, field, value); OnGetFieldValue(Field, value); } if (Owner == null) return; var ownerField = Owner.TypeInfo.StructureFieldMapping[new Pair<FieldInfo>(Field, field)]; Owner.SystemGetValue(ownerField, value); } internal override sealed void SystemGetValueCompleted(FieldInfo field, object value, Exception exception) { if (Owner == null) return; var ownerField = Owner.TypeInfo.StructureFieldMapping[new Pair<FieldInfo>(Field, field)]; Owner.SystemGetValueCompleted(ownerField, value, exception); } internal override sealed void SystemSetValueAttempt(FieldInfo field, object value) { if (!Session.IsSystemLogicOnly) { var subscriptionInfo = GetSubscription(EntityEventBroker.SettingFieldAttemptEventKey); if (subscriptionInfo.Second != null) ((Action<Key, FieldInfo, FieldInfo, object>)subscriptionInfo.Second) .Invoke(subscriptionInfo.First, Field, field, value); OnSettingFieldValue(field, value); } if (Owner == null) return; var ownerField = Owner.TypeInfo.StructureFieldMapping[new Pair<FieldInfo>(Field, field)]; Owner.SystemSetValueAttempt(ownerField, value); } internal override sealed void SystemBeforeSetValue(FieldInfo field, object value) { if (!Session.IsSystemLogicOnly) { var subscriptionInfo = GetSubscription(EntityEventBroker.SettingFieldEventKey); if (subscriptionInfo.Second != null) ((Action<Key, FieldInfo, FieldInfo, object>) subscriptionInfo.Second) .Invoke(subscriptionInfo.First, Field, field, value); OnSettingFieldValue(field, value); } if (Owner == null) return; var ownerField = Owner.TypeInfo.StructureFieldMapping[new Pair<FieldInfo>(Field, field)]; Owner.SystemBeforeSetValue(ownerField, value); } internal override sealed void SystemBeforeTupleChange() { if (Owner != null) Owner.SystemBeforeTupleChange(); } internal override void SystemTupleChange() { if (Owner != null) Owner.SystemTupleChange(); } internal override sealed void SystemSetValue(FieldInfo field, object oldValue, object newValue) { if (!Session.IsSystemLogicOnly) { using (Session.Operations.EnableSystemOperationRegistration()) { if (CanBeValidated) Session.ValidationContext.RegisterForValidation(Entity, field); var subscriptionInfo = GetSubscription(EntityEventBroker.SetFieldEventKey); if (subscriptionInfo.Second!=null) ((Action<Key, FieldInfo, FieldInfo, object, object>) subscriptionInfo.Second) .Invoke(subscriptionInfo.First, Field, field, oldValue, newValue); NotifyFieldChanged(field); OnSetFieldValue(field, oldValue, newValue); } } if (Owner == null) return; var ownerField = Owner.TypeInfo.StructureFieldMapping[new Pair<FieldInfo>(Field, field)]; Owner.SystemSetValue(ownerField, oldValue, newValue); } internal override sealed void SystemSetValueCompleted(FieldInfo field, object oldValue, object newValue, Exception exception) { if (Owner == null) return; var ownerField = Owner.TypeInfo.StructureFieldMapping[new Pair<FieldInfo>(Field, field)]; Owner.SystemSetValueCompleted(ownerField, oldValue, newValue, exception); } protected override sealed Pair<Key, Delegate> GetSubscription(object eventKey) { var entityKey = GetOwnerEntityKey(Owner); if (entityKey!=null) return new Pair<Key, Delegate>(entityKey, Session.EntityEvents.GetSubscriber(entityKey, Field, eventKey)); return new Pair<Key, Delegate>(null, null); } #endregion #region Equals & GetHashCode public static bool operator==(Structure left, Structure right) { if (!ReferenceEquals(left, null)) return left.Equals(right); return ReferenceEquals(right, null); } public static bool operator !=(Structure left, Structure rigth) { return !(left==rigth); } public override bool Equals(object obj) => obj is Structure other && Equals(other); public bool Equals(Structure other) { if (other==null) return false; if (ReferenceEquals(this, other)) return true; var thisIsBound = IsBoundToEntity; var otherIsBound = other.IsBoundToEntity; if (thisIsBound || otherIsBound) return InnerEquals(other, thisIsBound, otherIsBound); return Equals(Tuple, other.Tuple); } private bool InnerEquals(Structure other, bool thisIsBound, bool otherIsBound) { if (thisIsBound) { EnsureIsFetched(Field); if (Entity.IsRemoved && !Session.Configuration.Supports(SessionOptions.ReadRemovedObjects)) throw new InvalidOperationException(Strings.ExEntityIsRemoved); } if (otherIsBound) { other.EnsureIsFetched(other.Field); if (other.Entity.IsRemoved && !Session.Configuration.Supports(SessionOptions.ReadRemovedObjects)) throw new InvalidOperationException(Strings.ExEntityIsRemoved); } return Equals(Tuple, other.Tuple); } public override int GetHashCode() { return Tuple.GetHashCode(); } #endregion #region Private / internal methods internal override sealed void EnsureIsFetched(FieldInfo field) { if (Owner!=null) Owner.EnsureIsFetched(field); } internal override sealed ValidationResult GetValidationResult() { return Session.ValidationContext.ValidateOnceAndGetErrors(Entity).FirstOrDefault(r => r.Field.Equals(Field)); } internal override sealed ValidationResult GetValidationResult(string fieldName) { return Session.ValidationContext.ValidateOnceAndGetErrors(Entity).FirstOrDefault(f => f.Field!=null && f.Field.Name==fieldName); } private static Key GetOwnerEntityKey(Persistent owner) { var asFieldValueAdapter = owner as IFieldValueAdapter; if (asFieldValueAdapter != null) return GetOwnerEntityKey(asFieldValueAdapter.Owner); return owner != null ? ((Entity) owner).Key : null; } #endregion protected Structure() { typeInfo = GetTypeInfo(); tuple = typeInfo.TuplePrototype.Clone(); SystemBeforeInitialize(false); } protected Structure(Session session) : base(session) { typeInfo = GetTypeInfo(); tuple = typeInfo.TuplePrototype.Clone(); SystemBeforeInitialize(false); } protected Structure(Tuple data) { try { typeInfo = GetTypeInfo(); tuple = data; SystemBeforeInitialize(false); } catch (Exception error) { InitializationError(GetType(), error); throw; } } protected Structure(Session session, Tuple data) : base(session) { try { typeInfo = GetTypeInfo(); tuple = data; SystemBeforeInitialize(false); InitializeOnMaterialize(); } catch (Exception error) { InitializationError(GetType(), error); throw; } } protected Structure(Persistent owner, FieldInfo field) : base(owner.Session) { try { typeInfo = GetTypeInfo(); Owner = owner; Field = field; if (owner==null || field==null) tuple = typeInfo.TuplePrototype.Clone(); else tuple = field.ExtractValue( new ReferencedTuple(() => Owner.Tuple)); SystemBeforeInitialize(true); InitializeOnMaterialize(); } catch (Exception error) { InitializationErrorOnMaterialize(error); throw; } } protected Structure(SerializationInfo info, StreamingContext context) { DeserializationContext.Demand().SetObjectData(this, info, context); } }
[ "[", "SystemType", "]", "public", "abstract", "class", "Structure", ":", "Persistent", ",", "IEquatable", "<", "Structure", ">", ",", "IFieldValueAdapter", "{", "private", "readonly", "Tuple", "tuple", ";", "private", "readonly", "TypeInfo", "typeInfo", ";", "private", "Persistent", "owner", ";", "private", "Entity", "entity", ";", "public", "override", "TypeInfo", "TypeInfo", "{", "[", "DebuggerStepThrough", "]", "get", "{", "return", "typeInfo", ";", "}", "}", "public", "Persistent", "Owner", "{", "get", "{", "return", "owner", ";", "}", "private", "set", "{", "entity", "=", "null", ";", "owner", "=", "value", ";", "}", "}", "public", "FieldInfo", "Field", "{", "get", ";", "private", "set", ";", "}", "public", "Entity", "Entity", "{", "get", "{", "if", "(", "Owner", "==", "null", ")", "return", "null", ";", "return", "entity", "??", "(", "entity", "=", "(", "Owner", "as", "Entity", ")", "??", "(", "(", "Structure", ")", "Owner", ")", ".", "Entity", ")", ";", "}", "}", "public", "bool", "IsBoundToEntity", "{", "get", "{", "return", "(", "Owner", "!=", "null", ")", "&&", "(", "(", "Owner", "is", "Entity", ")", "||", "(", "(", "Structure", ")", "Owner", ")", ".", "IsBoundToEntity", ")", ";", "}", "}", "protected", "internal", "override", "sealed", "Tuple", "Tuple", "{", "[", "DebuggerStepThrough", "]", "get", "{", "return", "tuple", ";", "}", "}", "protected", "internal", "override", "sealed", "bool", "CanBeValidated", "{", "get", "{", "return", "IsBoundToEntity", ";", "}", "}", "public", "override", "sealed", "event", "PropertyChangedEventHandler", "PropertyChanged", "{", "add", "{", "Session", ".", "EntityEvents", ".", "AddSubscriber", "(", "GetOwnerEntityKey", "(", "Owner", ")", ",", "Field", ",", "EntityEventBroker", ".", "PropertyChangedEventKey", ",", "value", ")", ";", "}", "remove", "{", "Session", ".", "EntityEvents", ".", "RemoveSubscriber", "(", "GetOwnerEntityKey", "(", "Owner", ")", ",", "Field", ",", "EntityEventBroker", ".", "PropertyChangedEventKey", ",", "value", ")", ";", "}", "}", "region", " System-level event-like members & GetSubscription members", "internal", "override", "sealed", "void", "SystemBeforeInitialize", "(", "bool", "materialize", ")", "{", "if", "(", "Session", ".", "IsSystemLogicOnly", ")", "return", ";", "var", "subscriptionInfo", "=", "GetSubscription", "(", "EntityEventBroker", ".", "InitializingPersistentEventKey", ")", ";", "if", "(", "subscriptionInfo", ".", "Second", "!=", "null", ")", "(", "(", "Action", "<", "Key", ",", "FieldInfo", ">", ")", "subscriptionInfo", ".", "Second", ")", ".", "Invoke", "(", "subscriptionInfo", ".", "First", ",", "Field", ")", ";", "}", "internal", "sealed", "override", "void", "SystemInitialize", "(", "bool", "materialize", ")", "{", "if", "(", "Session", ".", "IsSystemLogicOnly", ")", "return", ";", "var", "subscriptionInfo", "=", "GetSubscription", "(", "EntityEventBroker", ".", "InitializePersistentEventKey", ")", ";", "if", "(", "subscriptionInfo", ".", "Second", "!=", "null", ")", "(", "(", "Action", "<", "Key", ",", "FieldInfo", ">", ")", "subscriptionInfo", ".", "Second", ")", ".", "Invoke", "(", "subscriptionInfo", ".", "First", ",", "Field", ")", ";", "OnInitialize", "(", ")", ";", "if", "(", "!", "materialize", "&&", "CanBeValidated", ")", "Session", ".", "ValidationContext", ".", "RegisterForValidation", "(", "Entity", ")", ";", "}", "internal", "override", "sealed", "void", "SystemInitializationError", "(", "Exception", "error", ")", "{", "if", "(", "Session", ".", "IsSystemLogicOnly", ")", "return", ";", "var", "subscriptionInfo", "=", "GetSubscription", "(", "EntityEventBroker", ".", "InitializationErrorPersistentEventKey", ")", ";", "if", "(", "subscriptionInfo", ".", "Second", "!=", "null", ")", "(", "(", "Action", "<", "Key", ">", ")", "subscriptionInfo", ".", "Second", ")", ".", "Invoke", "(", "subscriptionInfo", ".", "First", ")", ";", "OnInitializationError", "(", "error", ")", ";", "}", "internal", "override", "sealed", "void", "SystemBeforeGetValue", "(", "FieldInfo", "field", ")", "{", "if", "(", "!", "Session", ".", "IsSystemLogicOnly", ")", "{", "var", "subscriptionInfo", "=", "GetSubscription", "(", "EntityEventBroker", ".", "GettingFieldEventKey", ")", ";", "if", "(", "subscriptionInfo", ".", "Second", "!=", "null", ")", "(", "(", "Action", "<", "Key", ",", "FieldInfo", ",", "FieldInfo", ">", ")", "subscriptionInfo", ".", "Second", ")", ".", "Invoke", "(", "subscriptionInfo", ".", "First", ",", "Field", ",", "field", ")", ";", "OnGettingFieldValue", "(", "field", ")", ";", "}", "if", "(", "Owner", "==", "null", ")", "return", ";", "var", "ownerField", "=", "Owner", ".", "TypeInfo", ".", "StructureFieldMapping", "[", "new", "Pair", "<", "FieldInfo", ">", "(", "Field", ",", "field", ")", "]", ";", "Owner", ".", "SystemBeforeGetValue", "(", "ownerField", ")", ";", "}", "internal", "override", "sealed", "void", "SystemGetValue", "(", "FieldInfo", "field", ",", "object", "value", ")", "{", "if", "(", "!", "Session", ".", "IsSystemLogicOnly", ")", "{", "var", "subscriptionInfo", "=", "GetSubscription", "(", "EntityEventBroker", ".", "GetFieldEventKey", ")", ";", "if", "(", "subscriptionInfo", ".", "Second", "!=", "null", ")", "(", "(", "Action", "<", "Key", ",", "FieldInfo", ",", "FieldInfo", ",", "object", ">", ")", "subscriptionInfo", ".", "Second", ")", ".", "Invoke", "(", "subscriptionInfo", ".", "First", ",", "Field", ",", "field", ",", "value", ")", ";", "OnGetFieldValue", "(", "Field", ",", "value", ")", ";", "}", "if", "(", "Owner", "==", "null", ")", "return", ";", "var", "ownerField", "=", "Owner", ".", "TypeInfo", ".", "StructureFieldMapping", "[", "new", "Pair", "<", "FieldInfo", ">", "(", "Field", ",", "field", ")", "]", ";", "Owner", ".", "SystemGetValue", "(", "ownerField", ",", "value", ")", ";", "}", "internal", "override", "sealed", "void", "SystemGetValueCompleted", "(", "FieldInfo", "field", ",", "object", "value", ",", "Exception", "exception", ")", "{", "if", "(", "Owner", "==", "null", ")", "return", ";", "var", "ownerField", "=", "Owner", ".", "TypeInfo", ".", "StructureFieldMapping", "[", "new", "Pair", "<", "FieldInfo", ">", "(", "Field", ",", "field", ")", "]", ";", "Owner", ".", "SystemGetValueCompleted", "(", "ownerField", ",", "value", ",", "exception", ")", ";", "}", "internal", "override", "sealed", "void", "SystemSetValueAttempt", "(", "FieldInfo", "field", ",", "object", "value", ")", "{", "if", "(", "!", "Session", ".", "IsSystemLogicOnly", ")", "{", "var", "subscriptionInfo", "=", "GetSubscription", "(", "EntityEventBroker", ".", "SettingFieldAttemptEventKey", ")", ";", "if", "(", "subscriptionInfo", ".", "Second", "!=", "null", ")", "(", "(", "Action", "<", "Key", ",", "FieldInfo", ",", "FieldInfo", ",", "object", ">", ")", "subscriptionInfo", ".", "Second", ")", ".", "Invoke", "(", "subscriptionInfo", ".", "First", ",", "Field", ",", "field", ",", "value", ")", ";", "OnSettingFieldValue", "(", "field", ",", "value", ")", ";", "}", "if", "(", "Owner", "==", "null", ")", "return", ";", "var", "ownerField", "=", "Owner", ".", "TypeInfo", ".", "StructureFieldMapping", "[", "new", "Pair", "<", "FieldInfo", ">", "(", "Field", ",", "field", ")", "]", ";", "Owner", ".", "SystemSetValueAttempt", "(", "ownerField", ",", "value", ")", ";", "}", "internal", "override", "sealed", "void", "SystemBeforeSetValue", "(", "FieldInfo", "field", ",", "object", "value", ")", "{", "if", "(", "!", "Session", ".", "IsSystemLogicOnly", ")", "{", "var", "subscriptionInfo", "=", "GetSubscription", "(", "EntityEventBroker", ".", "SettingFieldEventKey", ")", ";", "if", "(", "subscriptionInfo", ".", "Second", "!=", "null", ")", "(", "(", "Action", "<", "Key", ",", "FieldInfo", ",", "FieldInfo", ",", "object", ">", ")", "subscriptionInfo", ".", "Second", ")", ".", "Invoke", "(", "subscriptionInfo", ".", "First", ",", "Field", ",", "field", ",", "value", ")", ";", "OnSettingFieldValue", "(", "field", ",", "value", ")", ";", "}", "if", "(", "Owner", "==", "null", ")", "return", ";", "var", "ownerField", "=", "Owner", ".", "TypeInfo", ".", "StructureFieldMapping", "[", "new", "Pair", "<", "FieldInfo", ">", "(", "Field", ",", "field", ")", "]", ";", "Owner", ".", "SystemBeforeSetValue", "(", "ownerField", ",", "value", ")", ";", "}", "internal", "override", "sealed", "void", "SystemBeforeTupleChange", "(", ")", "{", "if", "(", "Owner", "!=", "null", ")", "Owner", ".", "SystemBeforeTupleChange", "(", ")", ";", "}", "internal", "override", "void", "SystemTupleChange", "(", ")", "{", "if", "(", "Owner", "!=", "null", ")", "Owner", ".", "SystemTupleChange", "(", ")", ";", "}", "internal", "override", "sealed", "void", "SystemSetValue", "(", "FieldInfo", "field", ",", "object", "oldValue", ",", "object", "newValue", ")", "{", "if", "(", "!", "Session", ".", "IsSystemLogicOnly", ")", "{", "using", "(", "Session", ".", "Operations", ".", "EnableSystemOperationRegistration", "(", ")", ")", "{", "if", "(", "CanBeValidated", ")", "Session", ".", "ValidationContext", ".", "RegisterForValidation", "(", "Entity", ",", "field", ")", ";", "var", "subscriptionInfo", "=", "GetSubscription", "(", "EntityEventBroker", ".", "SetFieldEventKey", ")", ";", "if", "(", "subscriptionInfo", ".", "Second", "!=", "null", ")", "(", "(", "Action", "<", "Key", ",", "FieldInfo", ",", "FieldInfo", ",", "object", ",", "object", ">", ")", "subscriptionInfo", ".", "Second", ")", ".", "Invoke", "(", "subscriptionInfo", ".", "First", ",", "Field", ",", "field", ",", "oldValue", ",", "newValue", ")", ";", "NotifyFieldChanged", "(", "field", ")", ";", "OnSetFieldValue", "(", "field", ",", "oldValue", ",", "newValue", ")", ";", "}", "}", "if", "(", "Owner", "==", "null", ")", "return", ";", "var", "ownerField", "=", "Owner", ".", "TypeInfo", ".", "StructureFieldMapping", "[", "new", "Pair", "<", "FieldInfo", ">", "(", "Field", ",", "field", ")", "]", ";", "Owner", ".", "SystemSetValue", "(", "ownerField", ",", "oldValue", ",", "newValue", ")", ";", "}", "internal", "override", "sealed", "void", "SystemSetValueCompleted", "(", "FieldInfo", "field", ",", "object", "oldValue", ",", "object", "newValue", ",", "Exception", "exception", ")", "{", "if", "(", "Owner", "==", "null", ")", "return", ";", "var", "ownerField", "=", "Owner", ".", "TypeInfo", ".", "StructureFieldMapping", "[", "new", "Pair", "<", "FieldInfo", ">", "(", "Field", ",", "field", ")", "]", ";", "Owner", ".", "SystemSetValueCompleted", "(", "ownerField", ",", "oldValue", ",", "newValue", ",", "exception", ")", ";", "}", "protected", "override", "sealed", "Pair", "<", "Key", ",", "Delegate", ">", "GetSubscription", "(", "object", "eventKey", ")", "{", "var", "entityKey", "=", "GetOwnerEntityKey", "(", "Owner", ")", ";", "if", "(", "entityKey", "!=", "null", ")", "return", "new", "Pair", "<", "Key", ",", "Delegate", ">", "(", "entityKey", ",", "Session", ".", "EntityEvents", ".", "GetSubscriber", "(", "entityKey", ",", "Field", ",", "eventKey", ")", ")", ";", "return", "new", "Pair", "<", "Key", ",", "Delegate", ">", "(", "null", ",", "null", ")", ";", "}", "endregion", "region", " Equals & GetHashCode", "public", "static", "bool", "operator", "==", "(", "Structure", "left", ",", "Structure", "right", ")", "{", "if", "(", "!", "ReferenceEquals", "(", "left", ",", "null", ")", ")", "return", "left", ".", "Equals", "(", "right", ")", ";", "return", "ReferenceEquals", "(", "right", ",", "null", ")", ";", "}", "public", "static", "bool", "operator", "!=", "(", "Structure", "left", ",", "Structure", "rigth", ")", "{", "return", "!", "(", "left", "==", "rigth", ")", ";", "}", "public", "override", "bool", "Equals", "(", "object", "obj", ")", "=>", "obj", "is", "Structure", "other", "&&", "Equals", "(", "other", ")", ";", "public", "bool", "Equals", "(", "Structure", "other", ")", "{", "if", "(", "other", "==", "null", ")", "return", "false", ";", "if", "(", "ReferenceEquals", "(", "this", ",", "other", ")", ")", "return", "true", ";", "var", "thisIsBound", "=", "IsBoundToEntity", ";", "var", "otherIsBound", "=", "other", ".", "IsBoundToEntity", ";", "if", "(", "thisIsBound", "||", "otherIsBound", ")", "return", "InnerEquals", "(", "other", ",", "thisIsBound", ",", "otherIsBound", ")", ";", "return", "Equals", "(", "Tuple", ",", "other", ".", "Tuple", ")", ";", "}", "private", "bool", "InnerEquals", "(", "Structure", "other", ",", "bool", "thisIsBound", ",", "bool", "otherIsBound", ")", "{", "if", "(", "thisIsBound", ")", "{", "EnsureIsFetched", "(", "Field", ")", ";", "if", "(", "Entity", ".", "IsRemoved", "&&", "!", "Session", ".", "Configuration", ".", "Supports", "(", "SessionOptions", ".", "ReadRemovedObjects", ")", ")", "throw", "new", "InvalidOperationException", "(", "Strings", ".", "ExEntityIsRemoved", ")", ";", "}", "if", "(", "otherIsBound", ")", "{", "other", ".", "EnsureIsFetched", "(", "other", ".", "Field", ")", ";", "if", "(", "other", ".", "Entity", ".", "IsRemoved", "&&", "!", "Session", ".", "Configuration", ".", "Supports", "(", "SessionOptions", ".", "ReadRemovedObjects", ")", ")", "throw", "new", "InvalidOperationException", "(", "Strings", ".", "ExEntityIsRemoved", ")", ";", "}", "return", "Equals", "(", "Tuple", ",", "other", ".", "Tuple", ")", ";", "}", "public", "override", "int", "GetHashCode", "(", ")", "{", "return", "Tuple", ".", "GetHashCode", "(", ")", ";", "}", "endregion", "region", " Private / internal methods", "internal", "override", "sealed", "void", "EnsureIsFetched", "(", "FieldInfo", "field", ")", "{", "if", "(", "Owner", "!=", "null", ")", "Owner", ".", "EnsureIsFetched", "(", "field", ")", ";", "}", "internal", "override", "sealed", "ValidationResult", "GetValidationResult", "(", ")", "{", "return", "Session", ".", "ValidationContext", ".", "ValidateOnceAndGetErrors", "(", "Entity", ")", ".", "FirstOrDefault", "(", "r", "=>", "r", ".", "Field", ".", "Equals", "(", "Field", ")", ")", ";", "}", "internal", "override", "sealed", "ValidationResult", "GetValidationResult", "(", "string", "fieldName", ")", "{", "return", "Session", ".", "ValidationContext", ".", "ValidateOnceAndGetErrors", "(", "Entity", ")", ".", "FirstOrDefault", "(", "f", "=>", "f", ".", "Field", "!=", "null", "&&", "f", ".", "Field", ".", "Name", "==", "fieldName", ")", ";", "}", "private", "static", "Key", "GetOwnerEntityKey", "(", "Persistent", "owner", ")", "{", "var", "asFieldValueAdapter", "=", "owner", "as", "IFieldValueAdapter", ";", "if", "(", "asFieldValueAdapter", "!=", "null", ")", "return", "GetOwnerEntityKey", "(", "asFieldValueAdapter", ".", "Owner", ")", ";", "return", "owner", "!=", "null", "?", "(", "(", "Entity", ")", "owner", ")", ".", "Key", ":", "null", ";", "}", "endregion", "protected", "Structure", "(", ")", "{", "typeInfo", "=", "GetTypeInfo", "(", ")", ";", "tuple", "=", "typeInfo", ".", "TuplePrototype", ".", "Clone", "(", ")", ";", "SystemBeforeInitialize", "(", "false", ")", ";", "}", "protected", "Structure", "(", "Session", "session", ")", ":", "base", "(", "session", ")", "{", "typeInfo", "=", "GetTypeInfo", "(", ")", ";", "tuple", "=", "typeInfo", ".", "TuplePrototype", ".", "Clone", "(", ")", ";", "SystemBeforeInitialize", "(", "false", ")", ";", "}", "protected", "Structure", "(", "Tuple", "data", ")", "{", "try", "{", "typeInfo", "=", "GetTypeInfo", "(", ")", ";", "tuple", "=", "data", ";", "SystemBeforeInitialize", "(", "false", ")", ";", "}", "catch", "(", "Exception", "error", ")", "{", "InitializationError", "(", "GetType", "(", ")", ",", "error", ")", ";", "throw", ";", "}", "}", "protected", "Structure", "(", "Session", "session", ",", "Tuple", "data", ")", ":", "base", "(", "session", ")", "{", "try", "{", "typeInfo", "=", "GetTypeInfo", "(", ")", ";", "tuple", "=", "data", ";", "SystemBeforeInitialize", "(", "false", ")", ";", "InitializeOnMaterialize", "(", ")", ";", "}", "catch", "(", "Exception", "error", ")", "{", "InitializationError", "(", "GetType", "(", ")", ",", "error", ")", ";", "throw", ";", "}", "}", "protected", "Structure", "(", "Persistent", "owner", ",", "FieldInfo", "field", ")", ":", "base", "(", "owner", ".", "Session", ")", "{", "try", "{", "typeInfo", "=", "GetTypeInfo", "(", ")", ";", "Owner", "=", "owner", ";", "Field", "=", "field", ";", "if", "(", "owner", "==", "null", "||", "field", "==", "null", ")", "tuple", "=", "typeInfo", ".", "TuplePrototype", ".", "Clone", "(", ")", ";", "else", "tuple", "=", "field", ".", "ExtractValue", "(", "new", "ReferencedTuple", "(", "(", ")", "=>", "Owner", ".", "Tuple", ")", ")", ";", "SystemBeforeInitialize", "(", "true", ")", ";", "InitializeOnMaterialize", "(", ")", ";", "}", "catch", "(", "Exception", "error", ")", "{", "InitializationErrorOnMaterialize", "(", "error", ")", ";", "throw", ";", "}", "}", "protected", "Structure", "(", "SerializationInfo", "info", ",", "StreamingContext", "context", ")", "{", "DeserializationContext", ".", "Demand", "(", ")", ".", "SetObjectData", "(", "this", ",", "info", ",", "context", ")", ";", "}", "}" ]
Abstract base class for any persistent structure.
[ "Abstract", "base", "class", "for", "any", "persistent", "structure", "." ]
[ "/// <inheritdoc/>", "/// <inheritdoc/>", "/// <inheritdoc/>", "/// <summary>", "/// Gets the entity.", "/// </summary>", "/// <summary>", "/// Gets a value indicating whether this <see cref=\"Structure\"/> instance is bound to entity.", "/// </summary>", "/// <inheritdoc/>", "/// <inheritdoc/> ", "/// <inheritdoc/>", "/// <inheritdoc/>", "/// <inheritdoc/>", "/// <inheritdoc/>", "/// <inheritdoc/>", "// Constructors", "/// <summary>", "/// Initializes a new instance of this class.", "/// </summary>", "/// <summary>", "/// Initializes a new instance of this class.", "/// </summary>", "/// <param name=\"session\">The session.</param>", "/// <summary>", "/// Initializes a new instance of this class.", "/// </summary>", "/// <param name=\"data\">Underlying <see cref=\"Tuple\"/> value.</param>", "// GetType() call is correct here: no code will be executed further,", "// if base constructor will fail, but since descendant's constructor is aspected,", "// we must \"simulate\" its own call of InitializationError method.", "/// <summary>", "/// Initializes a new instance of this class.", "/// </summary>", "/// <param name=\"session\">The session.</param>", "/// <param name=\"data\">Underlying <see cref=\"Tuple\"/> value.</param>", "// GetType() call is correct here: no code will be executed further,", "// if base constructor will fail, but since descendant's constructor is aspected,", "// we must \"simulate\" its own call of InitializationError method.", "/// <summary>", "/// Initializes a new instance of this class.", "/// Used internally to initialize the structure on materialization.", "/// </summary>", "/// <param name=\"owner\">The owner of this instance.</param>", "/// <param name=\"field\">The owner field that describes this instance.</param>", "/// <summary>", "/// Initializes a new instance of the <see cref=\"Structure\"/> class.", "/// </summary>", "/// <param name=\"info\">The info.</param>", "/// <param name=\"context\">The context.</param>" ]
[ { "param": "Persistent", "type": null }, { "param": "IFieldValueAdapter", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Persistent", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "IFieldValueAdapter", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [ { "identifier": "remarks", "docstring": "Like , structures support inheritance and consist of one or more persistent\nfields (properties) of scalar, , or type.\n\nHowever unlike entity, structure is not identified by\nand has value type behavior: it can be stored only inside some entity.", "docstring_tokens": [ "Like", "structures", "support", "inheritance", "and", "consist", "of", "one", "or", "more", "persistent", "fields", "(", "properties", ")", "of", "scalar", "or", "type", ".", "However", "unlike", "entity", "structure", "is", "not", "identified", "by", "and", "has", "value", "type", "behavior", ":", "it", "can", "be", "stored", "only", "inside", "some", "entity", "." ] }, { "identifier": "example", "docstring": "In the following example Address fields (City, Street and Building) will be included in Person table.\n\npublic class Person : Entity\n{\n[Field, Key]\npublic int Id { get; set; }\n\npublic string Name { get; set; }\n\npublic Address Address { get; set; }\n}\n\npublic class Address : Structure\n{\n[Field]\npublic City City { get; set; }\n\n[Field]\npublic string Street { get; set; }\n\n[Field]\npublic string Building { get; set; }\n}", "docstring_tokens": [ "In", "the", "following", "example", "Address", "fields", "(", "City", "Street", "and", "Building", ")", "will", "be", "included", "in", "Person", "table", ".", "public", "class", "Person", ":", "Entity", "{", "[", "Field", "Key", "]", "public", "int", "Id", "{", "get", ";", "set", ";", "}", "public", "string", "Name", "{", "get", ";", "set", ";", "}", "public", "Address", "Address", "{", "get", ";", "set", ";", "}", "}", "public", "class", "Address", ":", "Structure", "{", "[", "Field", "]", "public", "City", "City", "{", "get", ";", "set", ";", "}", "[", "Field", "]", "public", "string", "Street", "{", "get", ";", "set", ";", "}", "[", "Field", "]", "public", "string", "Building", "{", "get", ";", "set", ";", "}", "}" ] } ] }
false
18
2,416
303
ea02419af9f17b99785a3246436da1b10c38871c
atomminer/atomminer-core
src/mining/work/work.js
[ "BSD-3-Clause" ]
JavaScript
Work
/** * Generate and cache mining work(s) from Stratum job. Measure time between new jobs from the pool * and amount of works it has to generate on average to make an intelligent decision about * how many works do we need to cache on next update for max efficiency. * * Example: pool send new job every 24 seconds on average; 1 active miner is connected that can hash * the whole work in ~6 seconds. It is far more beneficial to generate 4 works items when new job received * and feed new work from cache (i.e instantly) vs generating work every time miner is idle. * I.e return work from cache when miner needs it and the slowly schedule self to refill cache * * Self-adjusting cache size is more efficient when: * 1. miners are "randomly" switching between pools, which is always * 2. miners can connect/disconnect at random time * * @class Work * @param {Transport} pool pool instance */
Generate and cache mining work(s) from Stratum job. Measure time between new jobs from the pool and amount of works it has to generate on average to make an intelligent decision about how many works do we need to cache on next update for max efficiency. pool send new job every 24 seconds on average; 1 active miner is connected that can hash the whole work in ~6 seconds. It is far more beneficial to generate 4 works items when new job received and feed new work from cache vs generating work every time miner is idle. I.e return work from cache when miner needs it and the slowly schedule self to refill cache Self-adjusting cache size is more efficient when: 1. miners are "randomly" switching between pools, which is always 2. miners can connect/disconnect at random time @class Work @param {Transport} pool pool instance
[ "Generate", "and", "cache", "mining", "work", "(", "s", ")", "from", "Stratum", "job", ".", "Measure", "time", "between", "new", "jobs", "from", "the", "pool", "and", "amount", "of", "works", "it", "has", "to", "generate", "on", "average", "to", "make", "an", "intelligent", "decision", "about", "how", "many", "works", "do", "we", "need", "to", "cache", "on", "next", "update", "for", "max", "efficiency", ".", "pool", "send", "new", "job", "every", "24", "seconds", "on", "average", ";", "1", "active", "miner", "is", "connected", "that", "can", "hash", "the", "whole", "work", "in", "~6", "seconds", ".", "It", "is", "far", "more", "beneficial", "to", "generate", "4", "works", "items", "when", "new", "job", "received", "and", "feed", "new", "work", "from", "cache", "vs", "generating", "work", "every", "time", "miner", "is", "idle", ".", "I", ".", "e", "return", "work", "from", "cache", "when", "miner", "needs", "it", "and", "the", "slowly", "schedule", "self", "to", "refill", "cache", "Self", "-", "adjusting", "cache", "size", "is", "more", "efficient", "when", ":", "1", ".", "miners", "are", "\"", "randomly", "\"", "switching", "between", "pools", "which", "is", "always", "2", ".", "miners", "can", "connect", "/", "disconnect", "at", "random", "time", "@class", "Work", "@param", "{", "Transport", "}", "pool", "pool", "instance" ]
class Work { constructor(pool) { if(!pool) throw new Error('Pool is null'); this._pool = pool; this._cache = []; this._jobID = null; this._rpc2 = false; // RPC 1.x fields this._diff = 0; this._prevhash = null; this._coinbase1 = null; this._coinbase2 = null; this._leafs = []; this._version = null; this._bits = 0; this._time = 0; this._xnonceSize = 0; // ? this._xnonce = 0; this._xnonce2Size = 0; //? this._xnonce2 = 0; this._merkle = null; this._multiplier = 1; this._height = 1; // todo: RPC 2.0 fields this._blob = null; // internal counters this._lastUpdate = 0; this._avglifespan = 0; // average job lifespan. this._cacheDrained = 0; // drain event counter happened during current job. this._worksCreated = 0; // amount of works created during current job. this._worksConsumed = 0; // amount of works consumed during current job. this._cacheSize = 1; // by default, hold 1 work active and refill when it is consumed. // debug this._printWorkStats = false; // print debug stats this._printTarget = false; // print new target this._printScheduleWork = false; // print when work is being scheduled this.update(); } /** Invoked after pool received new job */ update() { if(!this._pool) return; if(!this._pool._job) return; const tm = +new Date(); const rpc2 = this._pool.jsonRPC2; const rpc1 = ~rpc2; const jobID = rpc2 ? this._pool._job.job_id : this._pool._job[0]; this._multiplier = Multipliers[this._pool.config.algo] || 1; // there's absolutely no reason to (re)calculate target for every block if(this._diff != this._pool._diff) { this._diff = this._pool._diff; this._target = diff.diffToTarget(this._pool._diff / this._multiplier); this._target64 = diff.diffToTarget64(this._pool._diff / this._multiplier); if(this._printTarget) console.debug(`Target for ${this._pool._diff}: ${this._target}`); } // same job. this.get() will take care of cache when required. however target could change between jobs if(jobID === this._jobID) return; if(rpc1) { if(!Array.isArray(this._pool._job)) return console.error('Work::update Invalid job. Array expected'); if(this._pool._job.length < 8) return console.error('Work::update Invalid job length'); this._diff = this._pool.diff; this._prevhash = this._pool._job[1]; this._coinbase1 = this._pool._job[2]; this._coinbase2 = this._pool._job[3]; this._leafs = Array.isArray(this._pool._job[4]) ? this._pool._job[4] : []; this._version = this._pool._job[5]; this._bits = this._pool._job[6]; this._time = this._pool._job[7]; this._xnonceSize = this._pool._extraNonce.length; // ? this._xnonce = this._pool._extraNonce; this._xnonce2Size = 4; // assuming extranonce 2 is 32bit value this._xnonce2 = 0; this._height = decodeBlockHeight(this._coinbase1); this._pool._coinDiff = diff.bitsToDiff(this._bits); } else { if(!this._pool._job.blob) return console.error('Work::update Invalid job. Missing blob'); throw new Error('not implemented'); } // save it for last, in case something went wrong this._jobID = jobID; // analyze production-demand ratio and adjust this._cacheSize if required if(this._lastUpdate) { const dt = tm - this._lastUpdate; this._avglifespan = this._avglifespan ? ((dt + this._avglifespan) >> 1) : dt; // debug info if(this._printWorkStats) { console.debug(`----------------- Updating new job counters -----------------`); console.debug(`Pool : ${this._pool.poolname()}`); console.debug(`Lifespan: ${(this._avglifespan/1000).toFixed(3)}s`); console.debug(`Cache : ${this._cacheSize}`); console.debug(`Consumed: ${this._worksConsumed}`); console.debug(`Produced: ${this._worksCreated}`); console.debug(`Drained : ${this._cacheDrained}`); } // clearly, cache is too small if(this._cacheDrained) this._cacheSize += this._cacheDrained; else { if(this._worksConsumed < (this._worksCreated - this._cacheSize - 1)) { if(this._cacheSize > this._worksConsumed) this._cacheSize = this._cacheSize >> 1; else this._cacheSize --; } } } if(this._cacheSize <= 0) this._cacheSize = 1; // fill new cache with the required amount of works before we proceed further this._cache = []; while(this._cache.length < this._cacheSize) this._generate(); this._lastUpdate = tm; this._cacheDrained = 0; this._worksCreated = 0; this._worksConsumed = 0; } /** Get new mining work */ get() { if(!(this._pool && this._pool._job)) return null; // if works are consumed faster than generated. Example: // we had single miner and cache refill was fast enough to provide enough works. Second miner connected // and requires an extra work on every job. Next this.update() should generate 2 jobs right away to prevent downtime if(!this._cache.length) { this._cacheDrained ++; this._generate(); } // we're about to remove 1 cached work. schedule cache refill setImmediate(() => { if(this._printScheduleWork) console.log(`Work: scheduled refill for job ${this._jobID}`); this._generate(); }); this._worksConsumed ++; return this._cache.pop(); } _generate() { var work = ''; if(this._rpc2) { throw new Error('not implemented'); } else { this._xnonce2 = (this._xnonce2 + 1) >>> 0; var coinbase = this._coinbase1; coinbase += this._xnonce; coinbase += hex.hex32(this._xnonce2); // again, assuming that _xnonce2 is 32bit coinbase += this._coinbase2; const tree = Merkle.tree(coinbase, this._leafs, RootFn[this._pool.config.algo]); work += this._version; work += this._prevhash; work += Buffer.from(tree, 'hex').swap32().toString('hex'); work += this._time; work += this._bits; //work += '00000000'; // <-- 32bit nonce should be here work = Buffer.from(work, 'hex').swap32().toString('hex'); work = { id: uuid(), poolid: this._pool.id, jobid: this._jobID, height: this._height, header: work, nonce2: hex.hex32(this._xnonce2), time: this._time, // just in case if we will want to implement time rolling multiplier: this._multiplier, // algo diff multiplier target: this._target, target64: this._target64, }; } this._cache.push(work); this._worksCreated ++; } }
[ "class", "Work", "{", "constructor", "(", "pool", ")", "{", "if", "(", "!", "pool", ")", "throw", "new", "Error", "(", "'Pool is null'", ")", ";", "this", ".", "_pool", "=", "pool", ";", "this", ".", "_cache", "=", "[", "]", ";", "this", ".", "_jobID", "=", "null", ";", "this", ".", "_rpc2", "=", "false", ";", "this", ".", "_diff", "=", "0", ";", "this", ".", "_prevhash", "=", "null", ";", "this", ".", "_coinbase1", "=", "null", ";", "this", ".", "_coinbase2", "=", "null", ";", "this", ".", "_leafs", "=", "[", "]", ";", "this", ".", "_version", "=", "null", ";", "this", ".", "_bits", "=", "0", ";", "this", ".", "_time", "=", "0", ";", "this", ".", "_xnonceSize", "=", "0", ";", "this", ".", "_xnonce", "=", "0", ";", "this", ".", "_xnonce2Size", "=", "0", ";", "this", ".", "_xnonce2", "=", "0", ";", "this", ".", "_merkle", "=", "null", ";", "this", ".", "_multiplier", "=", "1", ";", "this", ".", "_height", "=", "1", ";", "this", ".", "_blob", "=", "null", ";", "this", ".", "_lastUpdate", "=", "0", ";", "this", ".", "_avglifespan", "=", "0", ";", "this", ".", "_cacheDrained", "=", "0", ";", "this", ".", "_worksCreated", "=", "0", ";", "this", ".", "_worksConsumed", "=", "0", ";", "this", ".", "_cacheSize", "=", "1", ";", "this", ".", "_printWorkStats", "=", "false", ";", "this", ".", "_printTarget", "=", "false", ";", "this", ".", "_printScheduleWork", "=", "false", ";", "this", ".", "update", "(", ")", ";", "}", "update", "(", ")", "{", "if", "(", "!", "this", ".", "_pool", ")", "return", ";", "if", "(", "!", "this", ".", "_pool", ".", "_job", ")", "return", ";", "const", "tm", "=", "+", "new", "Date", "(", ")", ";", "const", "rpc2", "=", "this", ".", "_pool", ".", "jsonRPC2", ";", "const", "rpc1", "=", "~", "rpc2", ";", "const", "jobID", "=", "rpc2", "?", "this", ".", "_pool", ".", "_job", ".", "job_id", ":", "this", ".", "_pool", ".", "_job", "[", "0", "]", ";", "this", ".", "_multiplier", "=", "Multipliers", "[", "this", ".", "_pool", ".", "config", ".", "algo", "]", "||", "1", ";", "if", "(", "this", ".", "_diff", "!=", "this", ".", "_pool", ".", "_diff", ")", "{", "this", ".", "_diff", "=", "this", ".", "_pool", ".", "_diff", ";", "this", ".", "_target", "=", "diff", ".", "diffToTarget", "(", "this", ".", "_pool", ".", "_diff", "/", "this", ".", "_multiplier", ")", ";", "this", ".", "_target64", "=", "diff", ".", "diffToTarget64", "(", "this", ".", "_pool", ".", "_diff", "/", "this", ".", "_multiplier", ")", ";", "if", "(", "this", ".", "_printTarget", ")", "console", ".", "debug", "(", "`", "${", "this", ".", "_pool", ".", "_diff", "}", "${", "this", ".", "_target", "}", "`", ")", ";", "}", "if", "(", "jobID", "===", "this", ".", "_jobID", ")", "return", ";", "if", "(", "rpc1", ")", "{", "if", "(", "!", "Array", ".", "isArray", "(", "this", ".", "_pool", ".", "_job", ")", ")", "return", "console", ".", "error", "(", "'Work::update Invalid job. Array expected'", ")", ";", "if", "(", "this", ".", "_pool", ".", "_job", ".", "length", "<", "8", ")", "return", "console", ".", "error", "(", "'Work::update Invalid job length'", ")", ";", "this", ".", "_diff", "=", "this", ".", "_pool", ".", "diff", ";", "this", ".", "_prevhash", "=", "this", ".", "_pool", ".", "_job", "[", "1", "]", ";", "this", ".", "_coinbase1", "=", "this", ".", "_pool", ".", "_job", "[", "2", "]", ";", "this", ".", "_coinbase2", "=", "this", ".", "_pool", ".", "_job", "[", "3", "]", ";", "this", ".", "_leafs", "=", "Array", ".", "isArray", "(", "this", ".", "_pool", ".", "_job", "[", "4", "]", ")", "?", "this", ".", "_pool", ".", "_job", "[", "4", "]", ":", "[", "]", ";", "this", ".", "_version", "=", "this", ".", "_pool", ".", "_job", "[", "5", "]", ";", "this", ".", "_bits", "=", "this", ".", "_pool", ".", "_job", "[", "6", "]", ";", "this", ".", "_time", "=", "this", ".", "_pool", ".", "_job", "[", "7", "]", ";", "this", ".", "_xnonceSize", "=", "this", ".", "_pool", ".", "_extraNonce", ".", "length", ";", "this", ".", "_xnonce", "=", "this", ".", "_pool", ".", "_extraNonce", ";", "this", ".", "_xnonce2Size", "=", "4", ";", "this", ".", "_xnonce2", "=", "0", ";", "this", ".", "_height", "=", "decodeBlockHeight", "(", "this", ".", "_coinbase1", ")", ";", "this", ".", "_pool", ".", "_coinDiff", "=", "diff", ".", "bitsToDiff", "(", "this", ".", "_bits", ")", ";", "}", "else", "{", "if", "(", "!", "this", ".", "_pool", ".", "_job", ".", "blob", ")", "return", "console", ".", "error", "(", "'Work::update Invalid job. Missing blob'", ")", ";", "throw", "new", "Error", "(", "'not implemented'", ")", ";", "}", "this", ".", "_jobID", "=", "jobID", ";", "if", "(", "this", ".", "_lastUpdate", ")", "{", "const", "dt", "=", "tm", "-", "this", ".", "_lastUpdate", ";", "this", ".", "_avglifespan", "=", "this", ".", "_avglifespan", "?", "(", "(", "dt", "+", "this", ".", "_avglifespan", ")", ">>", "1", ")", ":", "dt", ";", "if", "(", "this", ".", "_printWorkStats", ")", "{", "console", ".", "debug", "(", "`", "`", ")", ";", "console", ".", "debug", "(", "`", "${", "this", ".", "_pool", ".", "poolname", "(", ")", "}", "`", ")", ";", "console", ".", "debug", "(", "`", "${", "(", "this", ".", "_avglifespan", "/", "1000", ")", ".", "toFixed", "(", "3", ")", "}", "`", ")", ";", "console", ".", "debug", "(", "`", "${", "this", ".", "_cacheSize", "}", "`", ")", ";", "console", ".", "debug", "(", "`", "${", "this", ".", "_worksConsumed", "}", "`", ")", ";", "console", ".", "debug", "(", "`", "${", "this", ".", "_worksCreated", "}", "`", ")", ";", "console", ".", "debug", "(", "`", "${", "this", ".", "_cacheDrained", "}", "`", ")", ";", "}", "if", "(", "this", ".", "_cacheDrained", ")", "this", ".", "_cacheSize", "+=", "this", ".", "_cacheDrained", ";", "else", "{", "if", "(", "this", ".", "_worksConsumed", "<", "(", "this", ".", "_worksCreated", "-", "this", ".", "_cacheSize", "-", "1", ")", ")", "{", "if", "(", "this", ".", "_cacheSize", ">", "this", ".", "_worksConsumed", ")", "this", ".", "_cacheSize", "=", "this", ".", "_cacheSize", ">>", "1", ";", "else", "this", ".", "_cacheSize", "--", ";", "}", "}", "}", "if", "(", "this", ".", "_cacheSize", "<=", "0", ")", "this", ".", "_cacheSize", "=", "1", ";", "this", ".", "_cache", "=", "[", "]", ";", "while", "(", "this", ".", "_cache", ".", "length", "<", "this", ".", "_cacheSize", ")", "this", ".", "_generate", "(", ")", ";", "this", ".", "_lastUpdate", "=", "tm", ";", "this", ".", "_cacheDrained", "=", "0", ";", "this", ".", "_worksCreated", "=", "0", ";", "this", ".", "_worksConsumed", "=", "0", ";", "}", "get", "(", ")", "{", "if", "(", "!", "(", "this", ".", "_pool", "&&", "this", ".", "_pool", ".", "_job", ")", ")", "return", "null", ";", "if", "(", "!", "this", ".", "_cache", ".", "length", ")", "{", "this", ".", "_cacheDrained", "++", ";", "this", ".", "_generate", "(", ")", ";", "}", "setImmediate", "(", "(", ")", "=>", "{", "if", "(", "this", ".", "_printScheduleWork", ")", "console", ".", "log", "(", "`", "${", "this", ".", "_jobID", "}", "`", ")", ";", "this", ".", "_generate", "(", ")", ";", "}", ")", ";", "this", ".", "_worksConsumed", "++", ";", "return", "this", ".", "_cache", ".", "pop", "(", ")", ";", "}", "_generate", "(", ")", "{", "var", "work", "=", "''", ";", "if", "(", "this", ".", "_rpc2", ")", "{", "throw", "new", "Error", "(", "'not implemented'", ")", ";", "}", "else", "{", "this", ".", "_xnonce2", "=", "(", "this", ".", "_xnonce2", "+", "1", ")", ">>>", "0", ";", "var", "coinbase", "=", "this", ".", "_coinbase1", ";", "coinbase", "+=", "this", ".", "_xnonce", ";", "coinbase", "+=", "hex", ".", "hex32", "(", "this", ".", "_xnonce2", ")", ";", "coinbase", "+=", "this", ".", "_coinbase2", ";", "const", "tree", "=", "Merkle", ".", "tree", "(", "coinbase", ",", "this", ".", "_leafs", ",", "RootFn", "[", "this", ".", "_pool", ".", "config", ".", "algo", "]", ")", ";", "work", "+=", "this", ".", "_version", ";", "work", "+=", "this", ".", "_prevhash", ";", "work", "+=", "Buffer", ".", "from", "(", "tree", ",", "'hex'", ")", ".", "swap32", "(", ")", ".", "toString", "(", "'hex'", ")", ";", "work", "+=", "this", ".", "_time", ";", "work", "+=", "this", ".", "_bits", ";", "work", "=", "Buffer", ".", "from", "(", "work", ",", "'hex'", ")", ".", "swap32", "(", ")", ".", "toString", "(", "'hex'", ")", ";", "work", "=", "{", "id", ":", "uuid", "(", ")", ",", "poolid", ":", "this", ".", "_pool", ".", "id", ",", "jobid", ":", "this", ".", "_jobID", ",", "height", ":", "this", ".", "_height", ",", "header", ":", "work", ",", "nonce2", ":", "hex", ".", "hex32", "(", "this", ".", "_xnonce2", ")", ",", "time", ":", "this", ".", "_time", ",", "multiplier", ":", "this", ".", "_multiplier", ",", "target", ":", "this", ".", "_target", ",", "target64", ":", "this", ".", "_target64", ",", "}", ";", "}", "this", ".", "_cache", ".", "push", "(", "work", ")", ";", "this", ".", "_worksCreated", "++", ";", "}", "}" ]
Generate and cache mining work(s) from Stratum job.
[ "Generate", "and", "cache", "mining", "work", "(", "s", ")", "from", "Stratum", "job", "." ]
[ "// RPC 1.x fields", "// ?", "//?", "// todo: RPC 2.0 fields", "// internal counters", "// average job lifespan.", "// drain event counter happened during current job.", "// amount of works created during current job.", "// amount of works consumed during current job.", "// by default, hold 1 work active and refill when it is consumed.", "// debug", "// print debug stats", "// print new target ", "// print when work is being scheduled", "/** Invoked after pool received new job */", "// there's absolutely no reason to (re)calculate target for every block", "// same job. this.get() will take care of cache when required. however target could change between jobs", "// ?", "// assuming extranonce 2 is 32bit value", "// save it for last, in case something went wrong", "// analyze production-demand ratio and adjust this._cacheSize if required", "// debug info", "// clearly, cache is too small", "// fill new cache with the required amount of works before we proceed further", "/** Get new mining work */", "// if works are consumed faster than generated. Example:", "// we had single miner and cache refill was fast enough to provide enough works. Second miner connected", "// and requires an extra work on every job. Next this.update() should generate 2 jobs right away to prevent downtime", "// we're about to remove 1 cached work. schedule cache refill", "// again, assuming that _xnonce2 is 32bit", "//work += '00000000'; // <-- 32bit nonce should be here", "// just in case if we will want to implement time rolling", "// algo diff multiplier" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
19
1,920
212
eac455a0295b522574abb178612387b5861ea7d0
flrnbc/arxiv_script
src/article.py
[ "MIT" ]
Python
Article
Class for articles. All attributes are self-explanatory except for - authors_short: short version of the authors' names which is printed before a download Formate (as created via retrieve.py): 2 authors: A and B. 3 authors: A, B and C. > 3 authors: A et al. - authors_contracted: essentially remove 'and' as well as all space in authors_short; used for file name and bibtex key. - ax_id: short for arxiv identifier. - main_subject: main arxiv subject.
Class for articles. All attributes are self-explanatory except for authors_short: short version of the authors' names which is printed before a download Formate (as created via retrieve.py): 2 authors: A and B. 3 authors: A, B and C. > 3 authors: A et al. authors_contracted: essentially remove 'and' as well as all space in authors_short; used for file name and bibtex key. ax_id: short for arxiv identifier. main_subject: main arxiv subject.
[ "Class", "for", "articles", ".", "All", "attributes", "are", "self", "-", "explanatory", "except", "for", "authors_short", ":", "short", "version", "of", "the", "authors", "'", "names", "which", "is", "printed", "before", "a", "download", "Formate", "(", "as", "created", "via", "retrieve", ".", "py", ")", ":", "2", "authors", ":", "A", "and", "B", ".", "3", "authors", ":", "A", "B", "and", "C", ".", ">", "3", "authors", ":", "A", "et", "al", ".", "authors_contracted", ":", "essentially", "remove", "'", "and", "'", "as", "well", "as", "all", "space", "in", "authors_short", ";", "used", "for", "file", "name", "and", "bibtex", "key", ".", "ax_id", ":", "short", "for", "arxiv", "identifier", ".", "main_subject", ":", "main", "arxiv", "subject", "." ]
class Article: """Class for articles. All attributes are self-explanatory except for - authors_short: short version of the authors' names which is printed before a download Formate (as created via retrieve.py): 2 authors: A and B. 3 authors: A, B and C. > 3 authors: A et al. - authors_contracted: essentially remove 'and' as well as all space in authors_short; used for file name and bibtex key. - ax_id: short for arxiv identifier. - main_subject: main arxiv subject. """ # pylint: disable=too-many-instance-attributes # Eight attributes are ok here. def __init__( self, title, authors, authors_short, authors_contracted, abstract, ax_id, year, main_subject, ): self.title = title self.authors = authors self.authors_short = authors_short self.authors_contracted = authors_contracted self.abstract = abstract self.ax_id = ax_id self.year = year self.main_subject = main_subject def __str__(self): return ( f"\nTitle:\n{self.title} \n\nAuthors:\n{self.authors}" f"\n\nAbstract:\n{self.abstract}" f"\n\narXiv identifier:\n{self.ax_id}" f"\n\nYear: \n{self.year}" f"\n\nMain subject: \n{self.main_subject}\n" ) def download(self, save_dir): """Download article to save_dir.""" # create convenient file name title_split = self.title.split() # more intelligent "cut-off" for title? contracted_title = "_".join(title_split[:15]) + "-" + self.year file_name = self.authors_contracted + "-" + contracted_title file_path = "{}/{}.pdf".format(save_dir, file_name) # request url of pdf pdf_url = "https://arxiv.org/pdf/{}.pdf".format(self.ax_id) r_pdf = requests.get(pdf_url) # download file with delay t_count = 3 while t_count: print( "Download in {} second(s)".format(t_count) + "(press Ctrl + c to cancel).", end="\r", ) time.sleep(1) t_count -= 1 open(file_path, "wb").write(r_pdf.content) return file_path def bib_key(self): """Create a convenient bibtex entry. For authors: `Contract' the short authors' name, i.e. remove white space and capitalize 'et al' (if present). For title: Remove commas as well as all common propositions and articles (i.e. 'on', 'in', 'a', 'the', ...); then take the first three words. """ # key for authors authors_key = self.authors_contracted # key for title # remove most common propositions and articles to_remove = ["a", "and", "in", "of", "on", "or", "the", "for"] title_key = delete_prepositions(self.title, to_remove, case_sensitive=False) # print(title_key) # remove characters which are not allowed/unnecessary in bibtex key remove_chars = re.compile(r'[\\{},~#%:"]') title_key = re.sub(remove_chars, "", title_key) title_key_split = title_key.split() title_key = "".join(t.capitalize() for t in title_key_split[:3]) # TODO: add arxiv identifier only to make key unique; better way? return authors_key + "-" + title_key + "-" + self.ax_id def bib(self): """Create a bibtex entry for the given article using bib_key and bib_tile. """ article_key = self.bib_key() url = "https://arxiv.org/abs/{}".format(self.ax_id) title = bib_title(self.title) bib_entry = ( "@article{{{0},\n\tAuthor = {{{1}}},\n\tTitle = {{{2}}}," "\n\tYear = {{{3}}}," "\n\tNote = {{\\href{{{4}}}{{arXiv:{5}}}}}\n}}" ).format(article_key, self.authors, title, self.year, url, self.ax_id) return bib_entry
[ "class", "Article", ":", "def", "__init__", "(", "self", ",", "title", ",", "authors", ",", "authors_short", ",", "authors_contracted", ",", "abstract", ",", "ax_id", ",", "year", ",", "main_subject", ",", ")", ":", "self", ".", "title", "=", "title", "self", ".", "authors", "=", "authors", "self", ".", "authors_short", "=", "authors_short", "self", ".", "authors_contracted", "=", "authors_contracted", "self", ".", "abstract", "=", "abstract", "self", ".", "ax_id", "=", "ax_id", "self", ".", "year", "=", "year", "self", ".", "main_subject", "=", "main_subject", "def", "__str__", "(", "self", ")", ":", "return", "(", "f\"\\nTitle:\\n{self.title} \\n\\nAuthors:\\n{self.authors}\"", "f\"\\n\\nAbstract:\\n{self.abstract}\"", "f\"\\n\\narXiv identifier:\\n{self.ax_id}\"", "f\"\\n\\nYear: \\n{self.year}\"", "f\"\\n\\nMain subject: \\n{self.main_subject}\\n\"", ")", "def", "download", "(", "self", ",", "save_dir", ")", ":", "\"\"\"Download article to save_dir.\"\"\"", "title_split", "=", "self", ".", "title", ".", "split", "(", ")", "contracted_title", "=", "\"_\"", ".", "join", "(", "title_split", "[", ":", "15", "]", ")", "+", "\"-\"", "+", "self", ".", "year", "file_name", "=", "self", ".", "authors_contracted", "+", "\"-\"", "+", "contracted_title", "file_path", "=", "\"{}/{}.pdf\"", ".", "format", "(", "save_dir", ",", "file_name", ")", "pdf_url", "=", "\"https://arxiv.org/pdf/{}.pdf\"", ".", "format", "(", "self", ".", "ax_id", ")", "r_pdf", "=", "requests", ".", "get", "(", "pdf_url", ")", "t_count", "=", "3", "while", "t_count", ":", "print", "(", "\"Download in {} second(s)\"", ".", "format", "(", "t_count", ")", "+", "\"(press Ctrl + c to cancel).\"", ",", "end", "=", "\"\\r\"", ",", ")", "time", ".", "sleep", "(", "1", ")", "t_count", "-=", "1", "open", "(", "file_path", ",", "\"wb\"", ")", ".", "write", "(", "r_pdf", ".", "content", ")", "return", "file_path", "def", "bib_key", "(", "self", ")", ":", "\"\"\"Create a convenient bibtex entry.\n For authors: `Contract' the short authors' name, i.e. remove\n white space and capitalize 'et al' (if present).\n For title: Remove commas as well as all common propositions and\n articles (i.e. 'on', 'in', 'a', 'the', ...); then take the first\n three words.\n \"\"\"", "authors_key", "=", "self", ".", "authors_contracted", "to_remove", "=", "[", "\"a\"", ",", "\"and\"", ",", "\"in\"", ",", "\"of\"", ",", "\"on\"", ",", "\"or\"", ",", "\"the\"", ",", "\"for\"", "]", "title_key", "=", "delete_prepositions", "(", "self", ".", "title", ",", "to_remove", ",", "case_sensitive", "=", "False", ")", "remove_chars", "=", "re", ".", "compile", "(", "r'[\\\\{},~#%:\"]'", ")", "title_key", "=", "re", ".", "sub", "(", "remove_chars", ",", "\"\"", ",", "title_key", ")", "title_key_split", "=", "title_key", ".", "split", "(", ")", "title_key", "=", "\"\"", ".", "join", "(", "t", ".", "capitalize", "(", ")", "for", "t", "in", "title_key_split", "[", ":", "3", "]", ")", "return", "authors_key", "+", "\"-\"", "+", "title_key", "+", "\"-\"", "+", "self", ".", "ax_id", "def", "bib", "(", "self", ")", ":", "\"\"\"Create a bibtex entry for the given article using\n bib_key and bib_tile.\n \"\"\"", "article_key", "=", "self", ".", "bib_key", "(", ")", "url", "=", "\"https://arxiv.org/abs/{}\"", ".", "format", "(", "self", ".", "ax_id", ")", "title", "=", "bib_title", "(", "self", ".", "title", ")", "bib_entry", "=", "(", "\"@article{{{0},\\n\\tAuthor = {{{1}}},\\n\\tTitle = {{{2}}},\"", "\"\\n\\tYear = {{{3}}},\"", "\"\\n\\tNote = {{\\\\href{{{4}}}{{arXiv:{5}}}}}\\n}}\"", ")", ".", "format", "(", "article_key", ",", "self", ".", "authors", ",", "title", ",", "self", ".", "year", ",", "url", ",", "self", ".", "ax_id", ")", "return", "bib_entry" ]
Class for articles.
[ "Class", "for", "articles", "." ]
[ "\"\"\"Class for articles. All attributes are self-explanatory except for\n - authors_short: short version of the authors' names which is printed\n before a download Formate (as created via retrieve.py):\n 2 authors: A and B.\n 3 authors: A, B and C.\n > 3 authors: A et al.\n - authors_contracted: essentially remove 'and' as well as all space in\n authors_short; used for file name and bibtex key.\n - ax_id: short for arxiv identifier.\n - main_subject: main arxiv subject.\n \"\"\"", "# pylint: disable=too-many-instance-attributes", "# Eight attributes are ok here.", "\"\"\"Download article to save_dir.\"\"\"", "# create convenient file name", "# more intelligent \"cut-off\" for title?", "# request url of pdf", "# download file with delay", "\"\"\"Create a convenient bibtex entry.\n For authors: `Contract' the short authors' name, i.e. remove\n white space and capitalize 'et al' (if present).\n For title: Remove commas as well as all common propositions and\n articles (i.e. 'on', 'in', 'a', 'the', ...); then take the first\n three words.\n \"\"\"", "# key for authors", "# key for title", "# remove most common propositions and articles", "# print(title_key)", "# remove characters which are not allowed/unnecessary in bibtex key", "# TODO: add arxiv identifier only to make key unique; better way?", "\"\"\"Create a bibtex entry for the given article using\n bib_key and bib_tile.\n \"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
14
988
127
3716caef2c39b12375f4165a5f346e395cfae3c9
TheEpicBlock/Flywheel
src/main/java/com/jozufozu/flywheel/core/shader/spec/ProgramSpec.java
[ "MIT" ]
Java
ProgramSpec
/** * An object describing a shader program that can be loaded by flywheel. * * <p> * These are defined through json. All ProgramSpecs in <code>assets/modid/flywheel/programs</code> are parsed and * processed. One ProgramSpec typically specifies one "material" that can be used in game to render things. * </p> * <p> * All shader source files in <code>assets/modid/flywheel/shaders</code> are completely loaded and parsed into * {@link SourceFile SourceFiles}, but not compiled until one of them is * referenced by a ProgramSpec. * </p> */
An object describing a shader program that can be loaded by flywheel. These are defined through json. All ProgramSpecs in assets/modid/flywheel/programs are parsed and processed. One ProgramSpec typically specifies one "material" that can be used in game to render things. All shader source files in assets/modid/flywheel/shaders are completely loaded and parsed into SourceFile SourceFiles, but not compiled until one of them is referenced by a ProgramSpec.
[ "An", "object", "describing", "a", "shader", "program", "that", "can", "be", "loaded", "by", "flywheel", ".", "These", "are", "defined", "through", "json", ".", "All", "ProgramSpecs", "in", "assets", "/", "modid", "/", "flywheel", "/", "programs", "are", "parsed", "and", "processed", ".", "One", "ProgramSpec", "typically", "specifies", "one", "\"", "material", "\"", "that", "can", "be", "used", "in", "game", "to", "render", "things", ".", "All", "shader", "source", "files", "in", "assets", "/", "modid", "/", "flywheel", "/", "shaders", "are", "completely", "loaded", "and", "parsed", "into", "SourceFile", "SourceFiles", "but", "not", "compiled", "until", "one", "of", "them", "is", "referenced", "by", "a", "ProgramSpec", "." ]
public class ProgramSpec { // TODO: Block model style inheritance? public static final Codec<ProgramSpec> CODEC = RecordCodecBuilder.create(instance -> instance.group( ResourceLocation.CODEC.fieldOf("source") .forGetter(ProgramSpec::getSourceLoc), ProgramState.CODEC.listOf() .optionalFieldOf("states", Collections.emptyList()) .forGetter(ProgramSpec::getStates)) .apply(instance, ProgramSpec::new)); public ResourceLocation name; public final FileResolution source; public final List<ProgramState> states; public ProgramSpec(ResourceLocation source, List<ProgramState> states) { this.source = Resolver.INSTANCE.findShader(source); this.states = states; } public void setName(ResourceLocation name) { this.name = name; } public ResourceLocation getSourceLoc() { return source.getFileLoc(); } public FileResolution getSource() { return source; } public List<ProgramState> getStates() { return states; } }
[ "public", "class", "ProgramSpec", "{", "public", "static", "final", "Codec", "<", "ProgramSpec", ">", "CODEC", "=", "RecordCodecBuilder", ".", "create", "(", "instance", "->", "instance", ".", "group", "(", "ResourceLocation", ".", "CODEC", ".", "fieldOf", "(", "\"", "source", "\"", ")", ".", "forGetter", "(", "ProgramSpec", "::", "getSourceLoc", ")", ",", "ProgramState", ".", "CODEC", ".", "listOf", "(", ")", ".", "optionalFieldOf", "(", "\"", "states", "\"", ",", "Collections", ".", "emptyList", "(", ")", ")", ".", "forGetter", "(", "ProgramSpec", "::", "getStates", ")", ")", ".", "apply", "(", "instance", ",", "ProgramSpec", "::", "new", ")", ")", ";", "public", "ResourceLocation", "name", ";", "public", "final", "FileResolution", "source", ";", "public", "final", "List", "<", "ProgramState", ">", "states", ";", "public", "ProgramSpec", "(", "ResourceLocation", "source", ",", "List", "<", "ProgramState", ">", "states", ")", "{", "this", ".", "source", "=", "Resolver", ".", "INSTANCE", ".", "findShader", "(", "source", ")", ";", "this", ".", "states", "=", "states", ";", "}", "public", "void", "setName", "(", "ResourceLocation", "name", ")", "{", "this", ".", "name", "=", "name", ";", "}", "public", "ResourceLocation", "getSourceLoc", "(", ")", "{", "return", "source", ".", "getFileLoc", "(", ")", ";", "}", "public", "FileResolution", "getSource", "(", ")", "{", "return", "source", ";", "}", "public", "List", "<", "ProgramState", ">", "getStates", "(", ")", "{", "return", "states", ";", "}", "}" ]
An object describing a shader program that can be loaded by flywheel.
[ "An", "object", "describing", "a", "shader", "program", "that", "can", "be", "loaded", "by", "flywheel", "." ]
[ "// TODO: Block model style inheritance?" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
16
207
142
1e8f0e1088a3778963d4ab025198a7b0b05b9196
zzgchina888/msdn-code-gallery-microsoft
Official Windows Platform Sample/Bluetooth app to device sample/[C#]-Bluetooth app to device sample/C#/sdkBluetoothA2DWP8CS/Resources/AppResources.Designer.cs
[ "MIT" ]
C#
AppResources
/// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project.
A strongly-typed resource class, for looking up localized strings, etc.
[ "A", "strongly", "-", "typed", "resource", "class", "for", "looking", "up", "localized", "strings", "etc", "." ]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] public class AppResources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal AppResources() { } [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] public static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("sdkBluetoothA2DWP8CS.Resources.AppResources", typeof(AppResources).Assembly); resourceMan = temp; } return resourceMan; } } [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] public static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } public static string ApplicationTitle { get { return ResourceManager.GetString("ApplicationTitle", resourceCulture); } } public static string ConnectButtonCaption { get { return ResourceManager.GetString("ConnectButtonCaption", resourceCulture); } } public static string FindButtonCaption { get { return ResourceManager.GetString("FindButtonCaption", resourceCulture); } } public static string InstructionsText { get { return ResourceManager.GetString("InstructionsText", resourceCulture); } } public static string Msg_BluetoothOff { get { return ResourceManager.GetString("Msg_BluetoothOff", resourceCulture); } } public static string Msg_ConnectedTo { get { return ResourceManager.GetString("Msg_ConnectedTo", resourceCulture); } } public static string Msg_EmulatorMode { get { return ResourceManager.GetString("Msg_EmulatorMode", resourceCulture); } } public static string Msg_MissingCaps { get { return ResourceManager.GetString("Msg_MissingCaps", resourceCulture); } } public static string Msg_NoPairedDevices { get { return ResourceManager.GetString("Msg_NoPairedDevices", resourceCulture); } } public static string PageTitle { get { return ResourceManager.GetString("PageTitle", resourceCulture); } } public static string ServiceFieldPrompt { get { return ResourceManager.GetString("ServiceFieldPrompt", resourceCulture); } } }
[ "[", "global", "::", "System", ".", "CodeDom", ".", "Compiler", ".", "GeneratedCodeAttribute", "(", "\"", "System.Resources.Tools.StronglyTypedResourceBuilder", "\"", ",", "\"", "4.0.0.0", "\"", ")", "]", "[", "global", "::", "System", ".", "Diagnostics", ".", "DebuggerNonUserCodeAttribute", "(", ")", "]", "[", "global", "::", "System", ".", "Runtime", ".", "CompilerServices", ".", "CompilerGeneratedAttribute", "(", ")", "]", "public", "class", "AppResources", "{", "private", "static", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "resourceMan", ";", "private", "static", "global", "::", "System", ".", "Globalization", ".", "CultureInfo", "resourceCulture", ";", "[", "global", "::", "System", ".", "Diagnostics", ".", "CodeAnalysis", ".", "SuppressMessageAttribute", "(", "\"", "Microsoft.Performance", "\"", ",", "\"", "CA1811:AvoidUncalledPrivateCode", "\"", ")", "]", "internal", "AppResources", "(", ")", "{", "}", "[", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableAttribute", "(", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableState", ".", "Advanced", ")", "]", "public", "static", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "ResourceManager", "{", "get", "{", "if", "(", "object", ".", "ReferenceEquals", "(", "resourceMan", ",", "null", ")", ")", "{", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "temp", "=", "new", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "(", "\"", "sdkBluetoothA2DWP8CS.Resources.AppResources", "\"", ",", "typeof", "(", "AppResources", ")", ".", "Assembly", ")", ";", "resourceMan", "=", "temp", ";", "}", "return", "resourceMan", ";", "}", "}", "[", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableAttribute", "(", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableState", ".", "Advanced", ")", "]", "public", "static", "global", "::", "System", ".", "Globalization", ".", "CultureInfo", "Culture", "{", "get", "{", "return", "resourceCulture", ";", "}", "set", "{", "resourceCulture", "=", "value", ";", "}", "}", "public", "static", "string", "ApplicationTitle", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "ApplicationTitle", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "ConnectButtonCaption", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "ConnectButtonCaption", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "FindButtonCaption", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "FindButtonCaption", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "InstructionsText", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "InstructionsText", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "Msg_BluetoothOff", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Msg_BluetoothOff", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "Msg_ConnectedTo", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Msg_ConnectedTo", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "Msg_EmulatorMode", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Msg_EmulatorMode", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "Msg_MissingCaps", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Msg_MissingCaps", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "Msg_NoPairedDevices", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Msg_NoPairedDevices", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "PageTitle", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "PageTitle", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "ServiceFieldPrompt", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "ServiceFieldPrompt", "\"", ",", "resourceCulture", ")", ";", "}", "}", "}" ]
A strongly-typed resource class, for looking up localized strings, etc.
[ "A", "strongly", "-", "typed", "resource", "class", "for", "looking", "up", "localized", "strings", "etc", "." ]
[ "/// <summary>", "/// Returns the cached ResourceManager instance used by this class.", "/// </summary>", "/// <summary>", "/// Overrides the current thread's CurrentUICulture property for all", "/// resource lookups using this strongly typed resource class.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to BLUETOOTH A2D SAMPLE.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Connect to selected.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Find paired devices.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to This sample shows you how to find all paired devices, enumerate the device PeerInformation, attempt a connection to a device, and handle errors that occur. ", "///To begin, tap &quot;Find paired devices&quot;..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Bluetooth is turned off. To see the current Bluetooth settings tap &apos;ok&apos;..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Connected to {0}!.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to You cannot run this sample in the emulator because Bluetooth is not enabled. To see the sample working, run it on a Windows Phone 8 device..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to To run this app, you must have ID_CAP_PROXIMITY enabled in WMAppManifest.xaml.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to No paired devices found.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to page name.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Service name to use:.", "/// </summary>" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
17
575
84
18fa8e0d0cbefc4ed154d31b11c1e926e1731939
nemec/clipr.Converters
src/clipr.Converters/IPEndpointConverter.cs
[ "MIT" ]
C#
IPEndPointConverter
/// <summary> /// TypeConverter that takes a String and turns it into an IPEndPoint /// object. The IPEndPoint class represents both an IP address and a port /// number, therefore the supported format is 'ipaddr:port'. This converter /// supports both IPv4 and IPv6. An IPv6 address MUST be enclosed /// in [brackets] to eliminate ambiguity between port and IPv6 component. /// </summary>
TypeConverter that takes a String and turns it into an IPEndPoint object. The IPEndPoint class represents both an IP address and a port number, therefore the supported format is 'ipaddr:port'. This converter supports both IPv4 and IPv6. An IPv6 address MUST be enclosed in [brackets] to eliminate ambiguity between port and IPv6 component.
[ "TypeConverter", "that", "takes", "a", "String", "and", "turns", "it", "into", "an", "IPEndPoint", "object", ".", "The", "IPEndPoint", "class", "represents", "both", "an", "IP", "address", "and", "a", "port", "number", "therefore", "the", "supported", "format", "is", "'", "ipaddr", ":", "port", "'", ".", "This", "converter", "supports", "both", "IPv4", "and", "IPv6", ".", "An", "IPv6", "address", "MUST", "be", "enclosed", "in", "[", "brackets", "]", "to", "eliminate", "ambiguity", "between", "port", "and", "IPv6", "component", "." ]
public class IPEndPointConverter : TypeConverter { private readonly int? _defaultPort; public IPEndPointConverter() { } public IPEndPointConverter(int defaultPort) { _defaultPort = defaultPort; } private bool TryParse(string value, out IPEndPoint result) { if (String.IsNullOrEmpty(value)) { result = null; return false; } var braceOpenIdx = value.IndexOf('['); var braceCloseIdx = 0; if(braceOpenIdx >= 0) { braceCloseIdx = value.IndexOf(']', braceOpenIdx + 1); if (braceCloseIdx < 0) { result = null; return false; } } var idx = value.LastIndexOf(':', value.Length-1, value.Length - (braceCloseIdx + 1)); if (idx < 0 && !_defaultPort.HasValue) { result = null; return false; } string addrstr; string portstr = null; if (idx > 0) { addrstr = value.Substring(0, idx); portstr = value.Substring(idx + 1); } else { addrstr = value; } if (!IPAddress.TryParse(addrstr, out IPAddress addr)) { result = null; return false; } int port; if (portstr == null) { port = _defaultPort.Value; } else if (!int.TryParse(portstr, out port)) { result = null; return false; } result = new IPEndPoint(addr, port); return true; } public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { return sourceType == typeof(string); } public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { return destinationType == typeof(IPEndPoint); } public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { var str = value as string; if(str == null) { throw new FormatException("Unable to convert null or non-string value to IPEndpoint"); } if(TryParse(str, out IPEndPoint result)) { return result; } throw new FormatException(String.Format( "Unable to convert '{0}' to an IPEndpoint. Must be in format 'ipaddr:port'", value)); } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if(destinationType != typeof(IPEndPoint)) { throw new FormatException("Unable to use IPEndPointConverter to convert to any type other than IPEndPoint"); } return ConvertFrom(context, culture, value); } public override bool IsValid(ITypeDescriptorContext context, object value) { var str = value as string; if (str == null) return false; return TryParse(str, out _); } }
[ "public", "class", "IPEndPointConverter", ":", "TypeConverter", "{", "private", "readonly", "int", "?", "_defaultPort", ";", "public", "IPEndPointConverter", "(", ")", "{", "}", "public", "IPEndPointConverter", "(", "int", "defaultPort", ")", "{", "_defaultPort", "=", "defaultPort", ";", "}", "private", "bool", "TryParse", "(", "string", "value", ",", "out", "IPEndPoint", "result", ")", "{", "if", "(", "String", ".", "IsNullOrEmpty", "(", "value", ")", ")", "{", "result", "=", "null", ";", "return", "false", ";", "}", "var", "braceOpenIdx", "=", "value", ".", "IndexOf", "(", "'", "[", "'", ")", ";", "var", "braceCloseIdx", "=", "0", ";", "if", "(", "braceOpenIdx", ">=", "0", ")", "{", "braceCloseIdx", "=", "value", ".", "IndexOf", "(", "'", "]", "'", ",", "braceOpenIdx", "+", "1", ")", ";", "if", "(", "braceCloseIdx", "<", "0", ")", "{", "result", "=", "null", ";", "return", "false", ";", "}", "}", "var", "idx", "=", "value", ".", "LastIndexOf", "(", "'", ":", "'", ",", "value", ".", "Length", "-", "1", ",", "value", ".", "Length", "-", "(", "braceCloseIdx", "+", "1", ")", ")", ";", "if", "(", "idx", "<", "0", "&&", "!", "_defaultPort", ".", "HasValue", ")", "{", "result", "=", "null", ";", "return", "false", ";", "}", "string", "addrstr", ";", "string", "portstr", "=", "null", ";", "if", "(", "idx", ">", "0", ")", "{", "addrstr", "=", "value", ".", "Substring", "(", "0", ",", "idx", ")", ";", "portstr", "=", "value", ".", "Substring", "(", "idx", "+", "1", ")", ";", "}", "else", "{", "addrstr", "=", "value", ";", "}", "if", "(", "!", "IPAddress", ".", "TryParse", "(", "addrstr", ",", "out", "IPAddress", "addr", ")", ")", "{", "result", "=", "null", ";", "return", "false", ";", "}", "int", "port", ";", "if", "(", "portstr", "==", "null", ")", "{", "port", "=", "_defaultPort", ".", "Value", ";", "}", "else", "if", "(", "!", "int", ".", "TryParse", "(", "portstr", ",", "out", "port", ")", ")", "{", "result", "=", "null", ";", "return", "false", ";", "}", "result", "=", "new", "IPEndPoint", "(", "addr", ",", "port", ")", ";", "return", "true", ";", "}", "public", "override", "bool", "CanConvertFrom", "(", "ITypeDescriptorContext", "context", ",", "Type", "sourceType", ")", "{", "return", "sourceType", "==", "typeof", "(", "string", ")", ";", "}", "public", "override", "bool", "CanConvertTo", "(", "ITypeDescriptorContext", "context", ",", "Type", "destinationType", ")", "{", "return", "destinationType", "==", "typeof", "(", "IPEndPoint", ")", ";", "}", "public", "override", "object", "ConvertFrom", "(", "ITypeDescriptorContext", "context", ",", "CultureInfo", "culture", ",", "object", "value", ")", "{", "var", "str", "=", "value", "as", "string", ";", "if", "(", "str", "==", "null", ")", "{", "throw", "new", "FormatException", "(", "\"", "Unable to convert null or non-string value to IPEndpoint", "\"", ")", ";", "}", "if", "(", "TryParse", "(", "str", ",", "out", "IPEndPoint", "result", ")", ")", "{", "return", "result", ";", "}", "throw", "new", "FormatException", "(", "String", ".", "Format", "(", "\"", "Unable to convert '{0}' to an IPEndpoint. Must be in format 'ipaddr:port'", "\"", ",", "value", ")", ")", ";", "}", "public", "override", "object", "ConvertTo", "(", "ITypeDescriptorContext", "context", ",", "CultureInfo", "culture", ",", "object", "value", ",", "Type", "destinationType", ")", "{", "if", "(", "destinationType", "!=", "typeof", "(", "IPEndPoint", ")", ")", "{", "throw", "new", "FormatException", "(", "\"", "Unable to use IPEndPointConverter to convert to any type other than IPEndPoint", "\"", ")", ";", "}", "return", "ConvertFrom", "(", "context", ",", "culture", ",", "value", ")", ";", "}", "public", "override", "bool", "IsValid", "(", "ITypeDescriptorContext", "context", ",", "object", "value", ")", "{", "var", "str", "=", "value", "as", "string", ";", "if", "(", "str", "==", "null", ")", "return", "false", ";", "return", "TryParse", "(", "str", ",", "out", "_", ")", ";", "}", "}" ]
TypeConverter that takes a String and turns it into an IPEndPoint object.
[ "TypeConverter", "that", "takes", "a", "String", "and", "turns", "it", "into", "an", "IPEndPoint", "object", "." ]
[ "/// <summary>", "/// Create a new IPEndPointConverter with a default port. Typically", "/// only parameterless TypeConverter constructors are supported by", "/// the converter machinery, so one must create a derived class that", "/// calls this constructor with a default port.", "/// </summary>", "/// <param name=\"defaultPort\"></param>", "// IPv6 addresses contain colons too", "// No closing brace - invalid IP" ]
[ { "param": "TypeConverter", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "TypeConverter", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
14
650
89
ff946ebc3be44ebc7c3a46c24e15375f97f840a4
dongkcs/mindspore
mindspore/explainer/benchmark/_attribution/faithfulness.py
[ "Apache-2.0" ]
Python
_BaseReplacement
Base class of generator for generating different replacement for perturbations. Args: kwargs: Optional args for generating replacement. Derived class need to add necessary arg names and default value to '_necessary_args'. If the argument has no default value, the value should be set to 'EMPTY' to mark the required args. Initializing an object will check the given kwargs w.r.t '_necessary_args'. Raise: ValueError: Raise when provided kwargs not contain necessary arg names with 'EMPTY' mark.
Base class of generator for generating different replacement for perturbations.
[ "Base", "class", "of", "generator", "for", "generating", "different", "replacement", "for", "perturbations", "." ]
class _BaseReplacement: """ Base class of generator for generating different replacement for perturbations. Args: kwargs: Optional args for generating replacement. Derived class need to add necessary arg names and default value to '_necessary_args'. If the argument has no default value, the value should be set to 'EMPTY' to mark the required args. Initializing an object will check the given kwargs w.r.t '_necessary_args'. Raise: ValueError: Raise when provided kwargs not contain necessary arg names with 'EMPTY' mark. """ _necessary_args = {} def __init__(self, **kwargs): self._replace_args = self._necessary_args.copy() for key, value in self._replace_args.items(): if key in kwargs.keys(): self._replace_args[key] = kwargs[key] elif key not in kwargs.keys() and value == 'EMPTY': raise ValueError(f"Missing keyword arg {key} for {self.__class__.__name__}.") __call__: Callable """ Generate replacement for perturbations. Derived class should overwrite this function to generate different replacement for perturbing. Args: inputs (_Array): Array to be perturb. Returns: - replacement (_Array): Array to provide alternative pixels for every position in the given inputs. The returned array should have same shape as inputs. """
[ "class", "_BaseReplacement", ":", "_necessary_args", "=", "{", "}", "def", "__init__", "(", "self", ",", "**", "kwargs", ")", ":", "self", ".", "_replace_args", "=", "self", ".", "_necessary_args", ".", "copy", "(", ")", "for", "key", ",", "value", "in", "self", ".", "_replace_args", ".", "items", "(", ")", ":", "if", "key", "in", "kwargs", ".", "keys", "(", ")", ":", "self", ".", "_replace_args", "[", "key", "]", "=", "kwargs", "[", "key", "]", "elif", "key", "not", "in", "kwargs", ".", "keys", "(", ")", "and", "value", "==", "'EMPTY'", ":", "raise", "ValueError", "(", "f\"Missing keyword arg {key} for {self.__class__.__name__}.\"", ")", "__call__", ":", "Callable", "\"\"\"\n Generate replacement for perturbations. Derived class should overwrite this\n function to generate different replacement for perturbing.\n\n Args:\n inputs (_Array): Array to be perturb.\n\n Returns:\n - replacement (_Array): Array to provide alternative pixels for every\n position in the given\n inputs. The returned array should have same shape as inputs.\n \"\"\"" ]
Base class of generator for generating different replacement for perturbations.
[ "Base", "class", "of", "generator", "for", "generating", "different", "replacement", "for", "perturbations", "." ]
[ "\"\"\"\n Base class of generator for generating different replacement for perturbations.\n\n Args:\n kwargs: Optional args for generating replacement. Derived class need to\n add necessary arg names and default value to '_necessary_args'.\n If the argument has no default value, the value should be set to\n 'EMPTY' to mark the required args. Initializing an object will\n check the given kwargs w.r.t '_necessary_args'.\n\n Raise:\n ValueError: Raise when provided kwargs not contain necessary arg names with 'EMPTY' mark.\n \"\"\"", "\"\"\"\n Generate replacement for perturbations. Derived class should overwrite this\n function to generate different replacement for perturbing.\n\n Args:\n inputs (_Array): Array to be perturb.\n\n Returns:\n - replacement (_Array): Array to provide alternative pixels for every\n position in the given\n inputs. The returned array should have same shape as inputs.\n \"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [ { "identifier": "kwargs", "type": null, "docstring": "Optional args for generating replacement. Derived class need to\nadd necessary arg names and default value to '_necessary_args'.\nIf the argument has no default value, the value should be set to\n'EMPTY' to mark the required args. Initializing an object will\ncheck the given kwargs w.r.t '_necessary_args'.", "docstring_tokens": [ "Optional", "args", "for", "generating", "replacement", ".", "Derived", "class", "need", "to", "add", "necessary", "arg", "names", "and", "default", "value", "to", "'", "_necessary_args", "'", ".", "If", "the", "argument", "has", "no", "default", "value", "the", "value", "should", "be", "set", "to", "'", "EMPTY", "'", "to", "mark", "the", "required", "args", ".", "Initializing", "an", "object", "will", "check", "the", "given", "kwargs", "w", ".", "r", ".", "t", "'", "_necessary_args", "'", "." ], "default": null, "is_optional": null } ], "others": [] }
false
17
295
110
330df2c06a2e190f0c194b9a91cfe875f7963f20
xxbidiao/oxkiller
oxkiller/Utility/QuestionIndex.cs
[ "MIT" ]
C#
QuestionIndex
/// <summary> /// Index of the question text. /// The index use 5 bit for each character, starting from lowest bit. /// Index - Character Mapping: /// 0 - Nothing (Question is not enough long) /// 1 - A /// 2 - B /// ... /// 26 - Z /// 27-30 (Reserved) /// 31 - Terminal (Do not use - for logic in this class) /// </summary>
Index of the question text. The index use 5 bit for each character, starting from lowest bit.
[ "Index", "of", "the", "question", "text", ".", "The", "index", "use", "5", "bit", "for", "each", "character", "starting", "from", "lowest", "bit", "." ]
public class QuestionIndex { static long[] locationMoverLookup = { 34359738368L, 1073741824L, 33554432L, 1048576L, 32768L, 1024L, 32L, 1L }; const int maxLength = 8; static char charNextToZ { get { return (char)('Z' + 1); } } public static long getPreciseIndex(string initials) { string cleanInitials = initials.ToUpper(); long result = 0; int length = maxLength; if (initials.Length < length) length = initials.Length; for(int i = 0; i < length; i++) { long currentCharInitial = 1 + cleanInitials[i] - 'A'; if (currentCharInitial < 0) currentCharInitial = 0; if (currentCharInitial > 26) currentCharInitial = 0; if (cleanInitials[i] == charNextToZ) currentCharInitial = 31; result += currentCharInitial * locationMoverLookup[i]; } return result; } public static Tuple<long,long> getPossibleIndex(string initials) { long minimum = getPreciseIndex(initials); long maximum = getPreciseIndex(initials +charNextToZ); return new Tuple<long,long>(minimum,maximum); } }
[ "public", "class", "QuestionIndex", "{", "static", "long", "[", "]", "locationMoverLookup", "=", "{", "34359738368L", ",", "1073741824L", ",", "33554432L", ",", "1048576L", ",", "32768L", ",", "1024L", ",", "32L", ",", "1L", "}", ";", "const", "int", "maxLength", "=", "8", ";", "static", "char", "charNextToZ", "{", "get", "{", "return", "(", "char", ")", "(", "'", "Z", "'", "+", "1", ")", ";", "}", "}", "public", "static", "long", "getPreciseIndex", "(", "string", "initials", ")", "{", "string", "cleanInitials", "=", "initials", ".", "ToUpper", "(", ")", ";", "long", "result", "=", "0", ";", "int", "length", "=", "maxLength", ";", "if", "(", "initials", ".", "Length", "<", "length", ")", "length", "=", "initials", ".", "Length", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "length", ";", "i", "++", ")", "{", "long", "currentCharInitial", "=", "1", "+", "cleanInitials", "[", "i", "]", "-", "'", "A", "'", ";", "if", "(", "currentCharInitial", "<", "0", ")", "currentCharInitial", "=", "0", ";", "if", "(", "currentCharInitial", ">", "26", ")", "currentCharInitial", "=", "0", ";", "if", "(", "cleanInitials", "[", "i", "]", "==", "charNextToZ", ")", "currentCharInitial", "=", "31", ";", "result", "+=", "currentCharInitial", "*", "locationMoverLookup", "[", "i", "]", ";", "}", "return", "result", ";", "}", "public", "static", "Tuple", "<", "long", ",", "long", ">", "getPossibleIndex", "(", "string", "initials", ")", "{", "long", "minimum", "=", "getPreciseIndex", "(", "initials", ")", ";", "long", "maximum", "=", "getPreciseIndex", "(", "initials", "+", "charNextToZ", ")", ";", "return", "new", "Tuple", "<", "long", ",", "long", ">", "(", "minimum", ",", "maximum", ")", ";", "}", "}" ]
Index of the question text.
[ "Index", "of", "the", "question", "text", "." ]
[ "/// <summary>", "/// Get the precise index of the given string.", "/// the string will be filled with spaces if not enough long.", "/// </summary>", "/// <param name=\"initials\">Initial string.</param>", "/// <returns></returns>", "//TODO: currently only for spaces - not yet dealing with bad input", "/// <summary>", "/// Get all possible index with given initial.", "/// </summary>", "/// <param name=\"initials\">initial string.</param>", "/// <returns>Minimum and maximum possible index of given initial.</returns>" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
15
347
97
5f6256fac4446944f316816fcddcc3689633db11
sandhaka/csp
SchoolCalendar/CspTest.cs
[ "Apache-2.0" ]
C#
CspTest
/// <summary> /// School calendar problem combine 6 professors to fill 1 week teachings over 3 classes /// That's a special case because we need to track the hours spent for each teacher, /// we also have to try to assign them uniformly in the week and in the classes. /// Just a few constraints: /// - Teacher can't have two different classes in the same time /// - Teacher can't have more then one teaching hour at a time /// </summary>
School calendar problem combine 6 professors to fill 1 week teachings over 3 classes That's a special case because we need to track the hours spent for each teacher, we also have to try to assign them uniformly in the week and in the classes. Just a few constraints: Teacher can't have two different classes in the same time Teacher can't have more then one teaching hour at a time
[ "School", "calendar", "problem", "combine", "6", "professors", "to", "fill", "1", "week", "teachings", "over", "3", "classes", "That", "'", "s", "a", "special", "case", "because", "we", "need", "to", "track", "the", "hours", "spent", "for", "each", "teacher", "we", "also", "have", "to", "try", "to", "assign", "them", "uniformly", "in", "the", "week", "and", "in", "the", "classes", ".", "Just", "a", "few", "constraints", ":", "Teacher", "can", "'", "t", "have", "two", "different", "classes", "in", "the", "same", "time", "Teacher", "can", "'", "t", "have", "more", "then", "one", "teaching", "hour", "at", "a", "time" ]
public class CspTest { private readonly ITestOutputHelper _testOutputHelper; private readonly Csp<Teacher> _schoolCalendarCsp; public CspTest(ITestOutputHelper testOutputHelper) { _testOutputHelper = testOutputHelper; var testData = SchoolCalendarTestFactory.CreateTestData(); var domains = testData.Select(v => new KeyValuePair<string, IEnumerable<Teacher>>(v.Key, v.Value.domains)); var relations = testData.Select(v => new KeyValuePair<string, IEnumerable<string>>(v.Key, v.Value.relations)); _schoolCalendarCsp = CspFactory.Create( new Dictionary<string, IEnumerable<Teacher>>(domains), new Dictionary<string, IEnumerable<string>>(relations), new Func<string, Teacher, string, Teacher, bool>[] { NextPreviousHoursConstraint.Eval, SimultaneouslyHoursConstraint.Eval } ); } [Fact] public void ShouldCreateSchoolCalendarCsp() { Assert.False(_schoolCalendarCsp.Resolved); } [Fact] public void ShouldPropagateConsistencyWithAc3() { } [Fact] public void ShouldResolveWithBackTrackingSearch() { var solved = _schoolCalendarCsp .UseBackTrackingSearchResolver( SelectUnassignedVariableStrategyTypes<Teacher>.FirstUnassignedVariable, DomainValuesOrderingStrategyTypes<Teacher>.DomainCustomOrder) .Resolve(() => { PrintPlan(); _testOutputHelper.WriteLine(Environment.NewLine); _testOutputHelper.WriteLine("==== Model: ===="); _testOutputHelper.WriteLine($"{_schoolCalendarCsp.ShowModelAsJson()}"); _testOutputHelper.WriteLine("================"); }); Assert.True(solved); Assert.True(_schoolCalendarCsp.Resolved); } [Fact] public void ShouldResolveWithBackTrackingSearchAndForwardCheckingInferenceStrategy() { var solved = _schoolCalendarCsp .UseBackTrackingSearchResolver( SelectUnassignedVariableStrategyTypes<Teacher>.FirstUnassignedVariable, DomainValuesOrderingStrategyTypes<Teacher>.DomainCustomOrder, InferenceStrategyTypes<Teacher>.ForwardChecking) .Resolve(() => { PrintPlan(); _testOutputHelper.WriteLine(Environment.NewLine); _testOutputHelper.WriteLine("==== Model: ===="); _testOutputHelper.WriteLine($"{_schoolCalendarCsp.ShowModelAsJson()}"); _testOutputHelper.WriteLine("================"); }); Assert.True(solved); Assert.True(_schoolCalendarCsp.Resolved); } [Fact] public void ShouldResolveWithBackTrackingSearchAndMinimumRemainingStrategy() { var solved = _schoolCalendarCsp .UseBackTrackingSearchResolver( SelectUnassignedVariableStrategyTypes<Teacher>.MinimumRemainingValues, DomainValuesOrderingStrategyTypes<Teacher>.DomainCustomOrder) .Resolve(() => { PrintPlan(); _testOutputHelper.WriteLine(Environment.NewLine); _testOutputHelper.WriteLine("==== Model: ===="); _testOutputHelper.WriteLine($"{_schoolCalendarCsp.ShowModelAsJson()}"); _testOutputHelper.WriteLine("================"); }); Assert.True(solved); Assert.True(_schoolCalendarCsp.Resolved); } private void PrintPlan() { var current = _schoolCalendarCsp.Status; using var ms = new MemoryStream(); using var writer = new StreamWriter(ms); foreach (var c in SchoolCalendarTestFactory.Classes) { var @class = current.Where(v => DomainUtils.DecodeClass(v.Key).Equals(c)).ToList(); var table = new ConsoleTable("MON", "TUE", "WEN", "THU", "FRI") { Options = { EnableCount = false, OutputTo = writer } }; for (var h = 1; h <= SchoolCalendarTestFactory.NumOfDayHours; h++) { var hour = h.ToString(); var th1 = @class.Single(v => DomainUtils.DecodeDay(v.Key).Equals("1") && DomainUtils.DecodeHour(v.Key).Equals(hour)).Value; var th2 = @class.Single(v => DomainUtils.DecodeDay(v.Key).Equals("2") && DomainUtils.DecodeHour(v.Key).Equals(hour)).Value; var th3 = @class.Single(v => DomainUtils.DecodeDay(v.Key).Equals("3") && DomainUtils.DecodeHour(v.Key).Equals(hour)).Value; var th4 = @class.Single(v => DomainUtils.DecodeDay(v.Key).Equals("4") && DomainUtils.DecodeHour(v.Key).Equals(hour)).Value; var th5 = @class.Single(v => DomainUtils.DecodeDay(v.Key).Equals("5") && DomainUtils.DecodeHour(v.Key).Equals(hour)).Value; table.AddRow(th1.Name, th2.Name, th3.Name, th4.Name, th5.Name); } writer.WriteLine($"--- CLASS {c} ---"); table.Write(); writer.WriteLine(); writer.Flush(); ms.Seek(0, SeekOrigin.Begin); _testOutputHelper.WriteLine(Encoding.UTF8.GetString(ms.ToArray())); } } }
[ "public", "class", "CspTest", "{", "private", "readonly", "ITestOutputHelper", "_testOutputHelper", ";", "private", "readonly", "Csp", "<", "Teacher", ">", "_schoolCalendarCsp", ";", "public", "CspTest", "(", "ITestOutputHelper", "testOutputHelper", ")", "{", "_testOutputHelper", "=", "testOutputHelper", ";", "var", "testData", "=", "SchoolCalendarTestFactory", ".", "CreateTestData", "(", ")", ";", "var", "domains", "=", "testData", ".", "Select", "(", "v", "=>", "new", "KeyValuePair", "<", "string", ",", "IEnumerable", "<", "Teacher", ">", ">", "(", "v", ".", "Key", ",", "v", ".", "Value", ".", "domains", ")", ")", ";", "var", "relations", "=", "testData", ".", "Select", "(", "v", "=>", "new", "KeyValuePair", "<", "string", ",", "IEnumerable", "<", "string", ">", ">", "(", "v", ".", "Key", ",", "v", ".", "Value", ".", "relations", ")", ")", ";", "_schoolCalendarCsp", "=", "CspFactory", ".", "Create", "(", "new", "Dictionary", "<", "string", ",", "IEnumerable", "<", "Teacher", ">", ">", "(", "domains", ")", ",", "new", "Dictionary", "<", "string", ",", "IEnumerable", "<", "string", ">", ">", "(", "relations", ")", ",", "new", "Func", "<", "string", ",", "Teacher", ",", "string", ",", "Teacher", ",", "bool", ">", "[", "]", "{", "NextPreviousHoursConstraint", ".", "Eval", ",", "SimultaneouslyHoursConstraint", ".", "Eval", "}", ")", ";", "}", "[", "Fact", "]", "public", "void", "ShouldCreateSchoolCalendarCsp", "(", ")", "{", "Assert", ".", "False", "(", "_schoolCalendarCsp", ".", "Resolved", ")", ";", "}", "[", "Fact", "]", "public", "void", "ShouldPropagateConsistencyWithAc3", "(", ")", "{", "}", "[", "Fact", "]", "public", "void", "ShouldResolveWithBackTrackingSearch", "(", ")", "{", "var", "solved", "=", "_schoolCalendarCsp", ".", "UseBackTrackingSearchResolver", "(", "SelectUnassignedVariableStrategyTypes", "<", "Teacher", ">", ".", "FirstUnassignedVariable", ",", "DomainValuesOrderingStrategyTypes", "<", "Teacher", ">", ".", "DomainCustomOrder", ")", ".", "Resolve", "(", "(", ")", "=>", "{", "PrintPlan", "(", ")", ";", "_testOutputHelper", ".", "WriteLine", "(", "Environment", ".", "NewLine", ")", ";", "_testOutputHelper", ".", "WriteLine", "(", "\"", "==== Model: ====", "\"", ")", ";", "_testOutputHelper", ".", "WriteLine", "(", "$\"", "{", "_schoolCalendarCsp", ".", "ShowModelAsJson", "(", ")", "}", "\"", ")", ";", "_testOutputHelper", ".", "WriteLine", "(", "\"", "================", "\"", ")", ";", "}", ")", ";", "Assert", ".", "True", "(", "solved", ")", ";", "Assert", ".", "True", "(", "_schoolCalendarCsp", ".", "Resolved", ")", ";", "}", "[", "Fact", "]", "public", "void", "ShouldResolveWithBackTrackingSearchAndForwardCheckingInferenceStrategy", "(", ")", "{", "var", "solved", "=", "_schoolCalendarCsp", ".", "UseBackTrackingSearchResolver", "(", "SelectUnassignedVariableStrategyTypes", "<", "Teacher", ">", ".", "FirstUnassignedVariable", ",", "DomainValuesOrderingStrategyTypes", "<", "Teacher", ">", ".", "DomainCustomOrder", ",", "InferenceStrategyTypes", "<", "Teacher", ">", ".", "ForwardChecking", ")", ".", "Resolve", "(", "(", ")", "=>", "{", "PrintPlan", "(", ")", ";", "_testOutputHelper", ".", "WriteLine", "(", "Environment", ".", "NewLine", ")", ";", "_testOutputHelper", ".", "WriteLine", "(", "\"", "==== Model: ====", "\"", ")", ";", "_testOutputHelper", ".", "WriteLine", "(", "$\"", "{", "_schoolCalendarCsp", ".", "ShowModelAsJson", "(", ")", "}", "\"", ")", ";", "_testOutputHelper", ".", "WriteLine", "(", "\"", "================", "\"", ")", ";", "}", ")", ";", "Assert", ".", "True", "(", "solved", ")", ";", "Assert", ".", "True", "(", "_schoolCalendarCsp", ".", "Resolved", ")", ";", "}", "[", "Fact", "]", "public", "void", "ShouldResolveWithBackTrackingSearchAndMinimumRemainingStrategy", "(", ")", "{", "var", "solved", "=", "_schoolCalendarCsp", ".", "UseBackTrackingSearchResolver", "(", "SelectUnassignedVariableStrategyTypes", "<", "Teacher", ">", ".", "MinimumRemainingValues", ",", "DomainValuesOrderingStrategyTypes", "<", "Teacher", ">", ".", "DomainCustomOrder", ")", ".", "Resolve", "(", "(", ")", "=>", "{", "PrintPlan", "(", ")", ";", "_testOutputHelper", ".", "WriteLine", "(", "Environment", ".", "NewLine", ")", ";", "_testOutputHelper", ".", "WriteLine", "(", "\"", "==== Model: ====", "\"", ")", ";", "_testOutputHelper", ".", "WriteLine", "(", "$\"", "{", "_schoolCalendarCsp", ".", "ShowModelAsJson", "(", ")", "}", "\"", ")", ";", "_testOutputHelper", ".", "WriteLine", "(", "\"", "================", "\"", ")", ";", "}", ")", ";", "Assert", ".", "True", "(", "solved", ")", ";", "Assert", ".", "True", "(", "_schoolCalendarCsp", ".", "Resolved", ")", ";", "}", "private", "void", "PrintPlan", "(", ")", "{", "var", "current", "=", "_schoolCalendarCsp", ".", "Status", ";", "using", "var", "ms", "=", "new", "MemoryStream", "(", ")", ";", "using", "var", "writer", "=", "new", "StreamWriter", "(", "ms", ")", ";", "foreach", "(", "var", "c", "in", "SchoolCalendarTestFactory", ".", "Classes", ")", "{", "var", "@class", "=", "current", ".", "Where", "(", "v", "=>", "DomainUtils", ".", "DecodeClass", "(", "v", ".", "Key", ")", ".", "Equals", "(", "c", ")", ")", ".", "ToList", "(", ")", ";", "var", "table", "=", "new", "ConsoleTable", "(", "\"", "MON", "\"", ",", "\"", "TUE", "\"", ",", "\"", "WEN", "\"", ",", "\"", "THU", "\"", ",", "\"", "FRI", "\"", ")", "{", "Options", "=", "{", "EnableCount", "=", "false", ",", "OutputTo", "=", "writer", "}", "}", ";", "for", "(", "var", "h", "=", "1", ";", "h", "<=", "SchoolCalendarTestFactory", ".", "NumOfDayHours", ";", "h", "++", ")", "{", "var", "hour", "=", "h", ".", "ToString", "(", ")", ";", "var", "th1", "=", "@class", ".", "Single", "(", "v", "=>", "DomainUtils", ".", "DecodeDay", "(", "v", ".", "Key", ")", ".", "Equals", "(", "\"", "1", "\"", ")", "&&", "DomainUtils", ".", "DecodeHour", "(", "v", ".", "Key", ")", ".", "Equals", "(", "hour", ")", ")", ".", "Value", ";", "var", "th2", "=", "@class", ".", "Single", "(", "v", "=>", "DomainUtils", ".", "DecodeDay", "(", "v", ".", "Key", ")", ".", "Equals", "(", "\"", "2", "\"", ")", "&&", "DomainUtils", ".", "DecodeHour", "(", "v", ".", "Key", ")", ".", "Equals", "(", "hour", ")", ")", ".", "Value", ";", "var", "th3", "=", "@class", ".", "Single", "(", "v", "=>", "DomainUtils", ".", "DecodeDay", "(", "v", ".", "Key", ")", ".", "Equals", "(", "\"", "3", "\"", ")", "&&", "DomainUtils", ".", "DecodeHour", "(", "v", ".", "Key", ")", ".", "Equals", "(", "hour", ")", ")", ".", "Value", ";", "var", "th4", "=", "@class", ".", "Single", "(", "v", "=>", "DomainUtils", ".", "DecodeDay", "(", "v", ".", "Key", ")", ".", "Equals", "(", "\"", "4", "\"", ")", "&&", "DomainUtils", ".", "DecodeHour", "(", "v", ".", "Key", ")", ".", "Equals", "(", "hour", ")", ")", ".", "Value", ";", "var", "th5", "=", "@class", ".", "Single", "(", "v", "=>", "DomainUtils", ".", "DecodeDay", "(", "v", ".", "Key", ")", ".", "Equals", "(", "\"", "5", "\"", ")", "&&", "DomainUtils", ".", "DecodeHour", "(", "v", ".", "Key", ")", ".", "Equals", "(", "hour", ")", ")", ".", "Value", ";", "table", ".", "AddRow", "(", "th1", ".", "Name", ",", "th2", ".", "Name", ",", "th3", ".", "Name", ",", "th4", ".", "Name", ",", "th5", ".", "Name", ")", ";", "}", "writer", ".", "WriteLine", "(", "$\"", "--- CLASS ", "{", "c", "}", " ---", "\"", ")", ";", "table", ".", "Write", "(", ")", ";", "writer", ".", "WriteLine", "(", ")", ";", "writer", ".", "Flush", "(", ")", ";", "ms", ".", "Seek", "(", "0", ",", "SeekOrigin", ".", "Begin", ")", ";", "_testOutputHelper", ".", "WriteLine", "(", "Encoding", ".", "UTF8", ".", "GetString", "(", "ms", ".", "ToArray", "(", ")", ")", ")", ";", "}", "}", "}" ]
School calendar problem combine 6 professors to fill 1 week teachings over 3 classes That's a special case because we need to track the hours spent for each teacher, we also have to try to assign them uniformly in the week and in the classes.
[ "School", "calendar", "problem", "combine", "6", "professors", "to", "fill", "1", "week", "teachings", "over", "3", "classes", "That", "'", "s", "a", "special", "case", "because", "we", "need", "to", "track", "the", "hours", "spent", "for", "each", "teacher", "we", "also", "have", "to", "try", "to", "assign", "them", "uniformly", "in", "the", "week", "and", "in", "the", "classes", "." ]
[ "// Can't use arc propagation due to limit amount of the teacher hours.", "// We need a strategy with an effective assignment like backtracking search", "// Use Backtracking Search (Depth-First) to assign legal values,", "// using custom order to sort by teachers hours left", "// Use Backtracking Search (Depth-First) to assign legal values", "// Use Backtracking Search (Depth-First) to assign legal values" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
24
1,092
98
214331284557c322e56fc5bbb11bcdb78c12532b
virjar/vscrawler
vscrawler-core/src/main/java/com/virjar/vscrawler/core/selector/string/function/awk/jrt/PartitioningReader.java
[ "Apache-2.0" ]
Java
PartitioningReader
/** * A reader which consumes one record at a time from * an underlying input reader. * <p> * <h3>Greedy Regex Matching</h3> * The current implementation matches setRecordSeparator against * contents of an input buffer (the underlying input * stream filling the input buffer). Records are * split against the matched regular expression * input, treating the regular expression as a * record separator. * </p> * <p> * By default, greedy regular expression matching * for setRecordSeparator is turned off. It is assumed * the user will employ a non-ambiguous regex for setRecordSeparator. * For example, ab*c is a non-ambiguous regex, * but ab?c?b is an ambiguous regex because * it can match ab or abc, and the reader may * accept either one, depending on input buffer boundaries. * The implemented way to employ greedy regex matching * is to consume subsequent input until the match * does not occur at the end of the input buffer, * or no input is available. However, this behavior * is not desirable in all cases (i.e., interactive * input against some sort of ambiguous newline * regex). To enable greedy setRecordSeparator regex consumption, * use <code>-Djawk.forceGreedyRS=true</code>. * </p> */
A reader which consumes one record at a time from an underlying input reader. Greedy Regex Matching The current implementation matches setRecordSeparator against contents of an input buffer (the underlying input stream filling the input buffer). Records are split against the matched regular expression input, treating the regular expression as a record separator. By default, greedy regular expression matching for setRecordSeparator is turned off. It is assumed the user will employ a non-ambiguous regex for setRecordSeparator. For example, ab*c is a non-ambiguous regex, but ab?c?b is an ambiguous regex because it can match ab or abc, and the reader may accept either one, depending on input buffer boundaries. The implemented way to employ greedy regex matching is to consume subsequent input until the match does not occur at the end of the input buffer, or no input is available. However, this behavior is not desirable in all cases . To enable greedy setRecordSeparator regex consumption, use -Djawk.forceGreedyRS=true.
[ "A", "reader", "which", "consumes", "one", "record", "at", "a", "time", "from", "an", "underlying", "input", "reader", ".", "Greedy", "Regex", "Matching", "The", "current", "implementation", "matches", "setRecordSeparator", "against", "contents", "of", "an", "input", "buffer", "(", "the", "underlying", "input", "stream", "filling", "the", "input", "buffer", ")", ".", "Records", "are", "split", "against", "the", "matched", "regular", "expression", "input", "treating", "the", "regular", "expression", "as", "a", "record", "separator", ".", "By", "default", "greedy", "regular", "expression", "matching", "for", "setRecordSeparator", "is", "turned", "off", ".", "It", "is", "assumed", "the", "user", "will", "employ", "a", "non", "-", "ambiguous", "regex", "for", "setRecordSeparator", ".", "For", "example", "ab", "*", "c", "is", "a", "non", "-", "ambiguous", "regex", "but", "ab?c?b", "is", "an", "ambiguous", "regex", "because", "it", "can", "match", "ab", "or", "abc", "and", "the", "reader", "may", "accept", "either", "one", "depending", "on", "input", "buffer", "boundaries", ".", "The", "implemented", "way", "to", "employ", "greedy", "regex", "matching", "is", "to", "consume", "subsequent", "input", "until", "the", "match", "does", "not", "occur", "at", "the", "end", "of", "the", "input", "buffer", "or", "no", "input", "is", "available", ".", "However", "this", "behavior", "is", "not", "desirable", "in", "all", "cases", ".", "To", "enable", "greedy", "setRecordSeparator", "regex", "consumption", "use", "-", "Djawk", ".", "forceGreedyRS", "=", "true", "." ]
public class PartitioningReader extends FilterReader { private static final boolean FORCE_GREEDY_RS; static { String grs = System.getProperty("jawk.forceGreedyRS", "0").trim(); FORCE_GREEDY_RS = grs.equals("1") || grs.equalsIgnoreCase("yes") || grs.equalsIgnoreCase("true"); } private Pattern rs; private Matcher matcher; private boolean fromFileNameList; /** * Construct the partitioning reader. * * @param reader The reader containing the input data stream. * @param recordSeparator The record separator, as a regular expression. */ public PartitioningReader(Reader reader, String recordSeparator) { this(reader, recordSeparator, false); } /** * Construct the partitioning reader. * * @param r The reader containing the input data stream. * @param recordSeparator The record separator, as a regular expression. * @param fromFileNameList Whether the underlying input reader * is a file from the filename list (the parameters passed * into AWK after the script argument). */ public PartitioningReader(Reader r, String recordSeparator, boolean fromFileNameList) { super(r); this.fromFileNameList = fromFileNameList; setRecordSeparator(recordSeparator); } private String priorRecordSeparator = null; private boolean consumeAll = false; /** * Assign a new record separator for this partitioning reader. * * @param recordSeparator The new record separator, as a regular expression. */ public final void setRecordSeparator(String recordSeparator) { //assert !recordSeparator.equals("") : "recordSeparator cannot be BLANK"; if (!recordSeparator.equals(priorRecordSeparator)) { if (recordSeparator.equals("")) { consumeAll = true; rs = Pattern.compile("\\z", Pattern.DOTALL | Pattern.MULTILINE); } else { consumeAll = false; rs = Pattern.compile(recordSeparator, Pattern.DOTALL | Pattern.MULTILINE); } priorRecordSeparator = recordSeparator; } } /** * @return true whether the underlying input reader is from a * filename list argument; false otherwise */ public boolean fromFilenameList() { return fromFileNameList; } private StringBuffer remaining = new StringBuffer(); private char[] readBuffer = new char[4096]; @Override public int read(char[] b, int start, int len) throws IOException { int retVal = super.read(b, start, len); if (retVal >= 0) { remaining.append(b, start, retVal); } return retVal; } public boolean willBlock() { if (matcher == null) { matcher = rs.matcher(remaining); } else { matcher.reset(remaining); } return (consumeAll || eof || remaining.length() == 0 || !matcher.find()); } private boolean eof = false; /** * Consume one record from the reader. * It uses the record separator regular * expression to mark start/end of records. * * @return the next record, null if no more records exist * * @throws IOException upon an IO error */ public String readRecord() throws IOException { if (matcher == null) { matcher = rs.matcher(remaining); } else { matcher.reset(remaining); } while (consumeAll || eof || remaining.length() == 0 || !matcher.find()) { int len = read(readBuffer, 0, readBuffer.length); if (eof || (len < 0)) { eof = true; String retVal = remaining.toString(); remaining.setLength(0); if (retVal.length() == 0) { return null; } else { return retVal; } } else if (len == 0) { throw new RuntimeException("len == 0 ?!"); } matcher = rs.matcher(remaining); } matcher.reset(); // if force greedy regex consumption: if (FORCE_GREEDY_RS) { // attempt to move last match away from the end of the input // so that buffer bounderies landing in the middle of // regexp matches that *could* match the regexp if more chars // were read // (one char at a time!) while (matcher.find() && matcher.end() == remaining.length() && matcher.requireEnd()) { if (read(readBuffer, 0, 1) >= 0) { matcher = rs.matcher(remaining); } else { break; } } } // we have a record separator! String[] splitString = rs.split(remaining, 2); String retVal = splitString[0]; remaining.setLength(0); // append to remaining only if the split // resulted in multiple parts if (splitString.length > 1) { remaining.append(splitString[1]); } return retVal; } }
[ "public", "class", "PartitioningReader", "extends", "FilterReader", "{", "private", "static", "final", "boolean", "FORCE_GREEDY_RS", ";", "static", "{", "String", "grs", "=", "System", ".", "getProperty", "(", "\"", "jawk.forceGreedyRS", "\"", ",", "\"", "0", "\"", ")", ".", "trim", "(", ")", ";", "FORCE_GREEDY_RS", "=", "grs", ".", "equals", "(", "\"", "1", "\"", ")", "||", "grs", ".", "equalsIgnoreCase", "(", "\"", "yes", "\"", ")", "||", "grs", ".", "equalsIgnoreCase", "(", "\"", "true", "\"", ")", ";", "}", "private", "Pattern", "rs", ";", "private", "Matcher", "matcher", ";", "private", "boolean", "fromFileNameList", ";", "/**\n\t * Construct the partitioning reader.\n\t *\n\t * @param reader The reader containing the input data stream.\n\t * @param recordSeparator The record separator, as a regular expression.\n\t */", "public", "PartitioningReader", "(", "Reader", "reader", ",", "String", "recordSeparator", ")", "{", "this", "(", "reader", ",", "recordSeparator", ",", "false", ")", ";", "}", "/**\n\t * Construct the partitioning reader.\n\t *\n\t * @param r The reader containing the input data stream.\n\t * @param recordSeparator The record separator, as a regular expression.\n\t * @param fromFileNameList Whether the underlying input reader\n\t * is a file from the filename list (the parameters passed\n\t * into AWK after the script argument).\n\t */", "public", "PartitioningReader", "(", "Reader", "r", ",", "String", "recordSeparator", ",", "boolean", "fromFileNameList", ")", "{", "super", "(", "r", ")", ";", "this", ".", "fromFileNameList", "=", "fromFileNameList", ";", "setRecordSeparator", "(", "recordSeparator", ")", ";", "}", "private", "String", "priorRecordSeparator", "=", "null", ";", "private", "boolean", "consumeAll", "=", "false", ";", "/**\n\t * Assign a new record separator for this partitioning reader.\n\t *\n\t * @param recordSeparator The new record separator, as a regular expression.\n\t */", "public", "final", "void", "setRecordSeparator", "(", "String", "recordSeparator", ")", "{", "if", "(", "!", "recordSeparator", ".", "equals", "(", "priorRecordSeparator", ")", ")", "{", "if", "(", "recordSeparator", ".", "equals", "(", "\"", "\"", ")", ")", "{", "consumeAll", "=", "true", ";", "rs", "=", "Pattern", ".", "compile", "(", "\"", "\\\\", "z", "\"", ",", "Pattern", ".", "DOTALL", "|", "Pattern", ".", "MULTILINE", ")", ";", "}", "else", "{", "consumeAll", "=", "false", ";", "rs", "=", "Pattern", ".", "compile", "(", "recordSeparator", ",", "Pattern", ".", "DOTALL", "|", "Pattern", ".", "MULTILINE", ")", ";", "}", "priorRecordSeparator", "=", "recordSeparator", ";", "}", "}", "/**\n\t * @return true whether the underlying input reader is from a\n\t *\tfilename list argument; false otherwise\n\t */", "public", "boolean", "fromFilenameList", "(", ")", "{", "return", "fromFileNameList", ";", "}", "private", "StringBuffer", "remaining", "=", "new", "StringBuffer", "(", ")", ";", "private", "char", "[", "]", "readBuffer", "=", "new", "char", "[", "4096", "]", ";", "@", "Override", "public", "int", "read", "(", "char", "[", "]", "b", ",", "int", "start", ",", "int", "len", ")", "throws", "IOException", "{", "int", "retVal", "=", "super", ".", "read", "(", "b", ",", "start", ",", "len", ")", ";", "if", "(", "retVal", ">=", "0", ")", "{", "remaining", ".", "append", "(", "b", ",", "start", ",", "retVal", ")", ";", "}", "return", "retVal", ";", "}", "public", "boolean", "willBlock", "(", ")", "{", "if", "(", "matcher", "==", "null", ")", "{", "matcher", "=", "rs", ".", "matcher", "(", "remaining", ")", ";", "}", "else", "{", "matcher", ".", "reset", "(", "remaining", ")", ";", "}", "return", "(", "consumeAll", "||", "eof", "||", "remaining", ".", "length", "(", ")", "==", "0", "||", "!", "matcher", ".", "find", "(", ")", ")", ";", "}", "private", "boolean", "eof", "=", "false", ";", "/**\n\t * Consume one record from the reader.\n\t * It uses the record separator regular\n\t * expression to mark start/end of records.\n\t *\n\t * @return the next record, null if no more records exist\n\t *\n\t * @throws IOException upon an IO error\n\t */", "public", "String", "readRecord", "(", ")", "throws", "IOException", "{", "if", "(", "matcher", "==", "null", ")", "{", "matcher", "=", "rs", ".", "matcher", "(", "remaining", ")", ";", "}", "else", "{", "matcher", ".", "reset", "(", "remaining", ")", ";", "}", "while", "(", "consumeAll", "||", "eof", "||", "remaining", ".", "length", "(", ")", "==", "0", "||", "!", "matcher", ".", "find", "(", ")", ")", "{", "int", "len", "=", "read", "(", "readBuffer", ",", "0", ",", "readBuffer", ".", "length", ")", ";", "if", "(", "eof", "||", "(", "len", "<", "0", ")", ")", "{", "eof", "=", "true", ";", "String", "retVal", "=", "remaining", ".", "toString", "(", ")", ";", "remaining", ".", "setLength", "(", "0", ")", ";", "if", "(", "retVal", ".", "length", "(", ")", "==", "0", ")", "{", "return", "null", ";", "}", "else", "{", "return", "retVal", ";", "}", "}", "else", "if", "(", "len", "==", "0", ")", "{", "throw", "new", "RuntimeException", "(", "\"", "len == 0 ?!", "\"", ")", ";", "}", "matcher", "=", "rs", ".", "matcher", "(", "remaining", ")", ";", "}", "matcher", ".", "reset", "(", ")", ";", "if", "(", "FORCE_GREEDY_RS", ")", "{", "while", "(", "matcher", ".", "find", "(", ")", "&&", "matcher", ".", "end", "(", ")", "==", "remaining", ".", "length", "(", ")", "&&", "matcher", ".", "requireEnd", "(", ")", ")", "{", "if", "(", "read", "(", "readBuffer", ",", "0", ",", "1", ")", ">=", "0", ")", "{", "matcher", "=", "rs", ".", "matcher", "(", "remaining", ")", ";", "}", "else", "{", "break", ";", "}", "}", "}", "String", "[", "]", "splitString", "=", "rs", ".", "split", "(", "remaining", ",", "2", ")", ";", "String", "retVal", "=", "splitString", "[", "0", "]", ";", "remaining", ".", "setLength", "(", "0", ")", ";", "if", "(", "splitString", ".", "length", ">", "1", ")", "{", "remaining", ".", "append", "(", "splitString", "[", "1", "]", ")", ";", "}", "return", "retVal", ";", "}", "}" ]
A reader which consumes one record at a time from an underlying input reader.
[ "A", "reader", "which", "consumes", "one", "record", "at", "a", "time", "from", "an", "underlying", "input", "reader", "." ]
[ "//assert !recordSeparator.equals(\"\") : \"recordSeparator cannot be BLANK\";", "// if force greedy regex consumption:", "// attempt to move last match away from the end of the input", "// so that buffer bounderies landing in the middle of", "// regexp matches that *could* match the regexp if more chars", "// were read", "// (one char at a time!)", "// we have a record separator!", "// append to remaining only if the split", "// resulted in multiple parts" ]
[ { "param": "FilterReader", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "FilterReader", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
15
1,105
283
77004fbafea7ed620c40552899a599cce87f88a2
DrCopyPaste/RecNForget
RecNForget.Controls/TimeSpanTextBox.xaml.cs
[ "Apache-2.0" ]
C#
TimeSpanTextBox
/// <summary> /// Interaction logic for TimeSpanTextBox.xaml /// /// Display can always be set directly via TextValueTimeSpan /// When the control (TimeSpanTextBox) is enabled a change in ExternallyBoundTextValueTimeSpan also triggers a value change of TextValueTimeSpan and vice versa (if that value is valid) /// /// /// This does explicitly NOT expose an actual timespan value /// When enabled this textbox updates the bound value from "TextValueTimeSpan" according to current valid text contents /// When disabled this does not update the underlying bound value (can be used for countdown timer mode in which u dont want to update the underlyling setting every second) /// </summary>
Display can always be set directly via TextValueTimeSpan When the control (TimeSpanTextBox) is enabled a change in ExternallyBoundTextValueTimeSpan also triggers a value change of TextValueTimeSpan and vice versa (if that value is valid) This does explicitly NOT expose an actual timespan value When enabled this textbox updates the bound value from "TextValueTimeSpan" according to current valid text contents When disabled this does not update the underlying bound value (can be used for countdown timer mode in which u dont want to update the underlyling setting every second)
[ "Display", "can", "always", "be", "set", "directly", "via", "TextValueTimeSpan", "When", "the", "control", "(", "TimeSpanTextBox", ")", "is", "enabled", "a", "change", "in", "ExternallyBoundTextValueTimeSpan", "also", "triggers", "a", "value", "change", "of", "TextValueTimeSpan", "and", "vice", "versa", "(", "if", "that", "value", "is", "valid", ")", "This", "does", "explicitly", "NOT", "expose", "an", "actual", "timespan", "value", "When", "enabled", "this", "textbox", "updates", "the", "bound", "value", "from", "\"", "TextValueTimeSpan", "\"", "according", "to", "current", "valid", "text", "contents", "When", "disabled", "this", "does", "not", "update", "the", "underlying", "bound", "value", "(", "can", "be", "used", "for", "countdown", "timer", "mode", "in", "which", "u", "dont", "want", "to", "update", "the", "underlyling", "setting", "every", "second", ")" ]
public partial class TimeSpanTextBox : UserControl, INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } public string TimerBoundTextValueTimeSpan { get { return (string)GetValue(TimerBoundTextValueTimeSpanProperty); } set { SetValue(TimerBoundTextValueTimeSpanProperty, value); } } public static readonly DependencyProperty TimerBoundTextValueTimeSpanProperty = DependencyProperty.Register("TimerBoundTextValueTimeSpan", typeof(string), typeof(TimeSpanTextBox), new PropertyMetadata(string.Empty)); public string SettingTextValueTimeSpan { get { return (string)GetValue(SettingTextValueTimeSpanProperty); } set { SetValue(SettingTextValueTimeSpanProperty, value); OnPropertyChanged(); } } public static readonly DependencyProperty SettingTextValueTimeSpanProperty = DependencyProperty.Register("SettingTextValueTimeSpan", typeof(string), typeof(TimeSpanTextBox), new PropertyMetadata("0:00:00:00")); public TimeSpanTextBox() { DataContext = this; InitializeComponent(); this.IsEnabledChanged += TimeSpanTextBox_IsEnabledChanged; ShowEditableTextBoxConditionally(); if (DesignerProperties.GetIsInDesignMode(this)) { } else { this.Resources = null; } } private void TimeSpanTextBox_IsEnabledChanged(object sender, DependencyPropertyChangedEventArgs e) { ShowEditableTextBoxConditionally(); } private void ShowEditableTextBoxConditionally() { SettingTextValueTimeSpanBoxTextBox.Visibility = IsEnabled ? Visibility.Visible : Visibility.Collapsed; TimerBoundTextValueTimeSpanTextBox.Visibility = IsEnabled ? Visibility.Collapsed : Visibility.Visible; } void TimeSpanTextBox_TextChanged(object sender, TextChangedEventArgs e) { var newValue = (sender as TextBox).Text; var tbEntry = sender as TextBox; Regex rgx = new Regex("[^0-9]"); var workingValue = rgx.Replace(newValue, ""); workingValue = workingValue.TrimStart('0'); workingValue = workingValue.Length < 7 ? workingValue.PadLeft(7, '0') : workingValue; workingValue = workingValue.Insert(workingValue.Length - 2, ":"); workingValue = workingValue.Insert(workingValue.Length - 5, ":"); workingValue = workingValue.Insert(workingValue.Length - 8, ":"); tbEntry.Text = workingValue; tbEntry.CaretIndex = tbEntry.Text.Length; var parseSuccessful = TimeSpan.TryParseExact(workingValue, Formats.TimeSpanFormat, CultureInfo.InvariantCulture, out TimeSpan outputTimeSpan); ValidationErrorMark.Visibility = parseSuccessful ? Visibility.Hidden : Visibility.Visible; if (parseSuccessful) { BindingExpression binding = SettingTextValueTimeSpanBoxTextBox.GetBindingExpression(TextBox.TextProperty); binding.UpdateSource(); } } }
[ "public", "partial", "class", "TimeSpanTextBox", ":", "UserControl", ",", "INotifyPropertyChanged", "{", "public", "event", "PropertyChangedEventHandler", "PropertyChanged", ";", "private", "void", "OnPropertyChanged", "(", "[", "CallerMemberName", "]", "string", "propertyName", "=", "null", ")", "{", "PropertyChanged", "?", ".", "Invoke", "(", "this", ",", "new", "PropertyChangedEventArgs", "(", "propertyName", ")", ")", ";", "}", "public", "string", "TimerBoundTextValueTimeSpan", "{", "get", "{", "return", "(", "string", ")", "GetValue", "(", "TimerBoundTextValueTimeSpanProperty", ")", ";", "}", "set", "{", "SetValue", "(", "TimerBoundTextValueTimeSpanProperty", ",", "value", ")", ";", "}", "}", "public", "static", "readonly", "DependencyProperty", "TimerBoundTextValueTimeSpanProperty", "=", "DependencyProperty", ".", "Register", "(", "\"", "TimerBoundTextValueTimeSpan", "\"", ",", "typeof", "(", "string", ")", ",", "typeof", "(", "TimeSpanTextBox", ")", ",", "new", "PropertyMetadata", "(", "string", ".", "Empty", ")", ")", ";", "public", "string", "SettingTextValueTimeSpan", "{", "get", "{", "return", "(", "string", ")", "GetValue", "(", "SettingTextValueTimeSpanProperty", ")", ";", "}", "set", "{", "SetValue", "(", "SettingTextValueTimeSpanProperty", ",", "value", ")", ";", "OnPropertyChanged", "(", ")", ";", "}", "}", "public", "static", "readonly", "DependencyProperty", "SettingTextValueTimeSpanProperty", "=", "DependencyProperty", ".", "Register", "(", "\"", "SettingTextValueTimeSpan", "\"", ",", "typeof", "(", "string", ")", ",", "typeof", "(", "TimeSpanTextBox", ")", ",", "new", "PropertyMetadata", "(", "\"", "0:00:00:00", "\"", ")", ")", ";", "public", "TimeSpanTextBox", "(", ")", "{", "DataContext", "=", "this", ";", "InitializeComponent", "(", ")", ";", "this", ".", "IsEnabledChanged", "+=", "TimeSpanTextBox_IsEnabledChanged", ";", "ShowEditableTextBoxConditionally", "(", ")", ";", "if", "(", "DesignerProperties", ".", "GetIsInDesignMode", "(", "this", ")", ")", "{", "}", "else", "{", "this", ".", "Resources", "=", "null", ";", "}", "}", "private", "void", "TimeSpanTextBox_IsEnabledChanged", "(", "object", "sender", ",", "DependencyPropertyChangedEventArgs", "e", ")", "{", "ShowEditableTextBoxConditionally", "(", ")", ";", "}", "private", "void", "ShowEditableTextBoxConditionally", "(", ")", "{", "SettingTextValueTimeSpanBoxTextBox", ".", "Visibility", "=", "IsEnabled", "?", "Visibility", ".", "Visible", ":", "Visibility", ".", "Collapsed", ";", "TimerBoundTextValueTimeSpanTextBox", ".", "Visibility", "=", "IsEnabled", "?", "Visibility", ".", "Collapsed", ":", "Visibility", ".", "Visible", ";", "}", "void", "TimeSpanTextBox_TextChanged", "(", "object", "sender", ",", "TextChangedEventArgs", "e", ")", "{", "var", "newValue", "=", "(", "sender", "as", "TextBox", ")", ".", "Text", ";", "var", "tbEntry", "=", "sender", "as", "TextBox", ";", "Regex", "rgx", "=", "new", "Regex", "(", "\"", "[^0-9]", "\"", ")", ";", "var", "workingValue", "=", "rgx", ".", "Replace", "(", "newValue", ",", "\"", "\"", ")", ";", "workingValue", "=", "workingValue", ".", "TrimStart", "(", "'", "0", "'", ")", ";", "workingValue", "=", "workingValue", ".", "Length", "<", "7", "?", "workingValue", ".", "PadLeft", "(", "7", ",", "'", "0", "'", ")", ":", "workingValue", ";", "workingValue", "=", "workingValue", ".", "Insert", "(", "workingValue", ".", "Length", "-", "2", ",", "\"", ":", "\"", ")", ";", "workingValue", "=", "workingValue", ".", "Insert", "(", "workingValue", ".", "Length", "-", "5", ",", "\"", ":", "\"", ")", ";", "workingValue", "=", "workingValue", ".", "Insert", "(", "workingValue", ".", "Length", "-", "8", ",", "\"", ":", "\"", ")", ";", "tbEntry", ".", "Text", "=", "workingValue", ";", "tbEntry", ".", "CaretIndex", "=", "tbEntry", ".", "Text", ".", "Length", ";", "var", "parseSuccessful", "=", "TimeSpan", ".", "TryParseExact", "(", "workingValue", ",", "Formats", ".", "TimeSpanFormat", ",", "CultureInfo", ".", "InvariantCulture", ",", "out", "TimeSpan", "outputTimeSpan", ")", ";", "ValidationErrorMark", ".", "Visibility", "=", "parseSuccessful", "?", "Visibility", ".", "Hidden", ":", "Visibility", ".", "Visible", ";", "if", "(", "parseSuccessful", ")", "{", "BindingExpression", "binding", "=", "SettingTextValueTimeSpanBoxTextBox", ".", "GetBindingExpression", "(", "TextBox", ".", "TextProperty", ")", ";", "binding", ".", "UpdateSource", "(", ")", ";", "}", "}", "}" ]
Interaction logic for TimeSpanTextBox.xaml
[ "Interaction", "logic", "for", "TimeSpanTextBox", ".", "xaml" ]
[ "/// <summary>", "/// This binds to the setting value corresponding to the actually saved time", "/// </summary>", "// ToDo: Evil Hack to have the cake (see actual design in design mode) and eat it too (have different styles at runtime)", "// if enabled show editable timespanbox SettingTextValueTimeSpanBoxTextBox which binds to SettingTextValueTimeSpan", "// otherwise show disabled timespanbox TimerBoundTextValueTimeSpan which binds to SettingTextValueTimeSpan", "// remove all chars but 0-9", "// remove all leading zeroes", "// pad with zeroes from the left to have at least 7 digits total (more than 7 digits means more digits for days...", "// format with : from right 3 times afer every second digit", "// maybe only write back setting value when focus is lost?", "// only update underlying bound value if the entered value was valid" ]
[ { "param": "UserControl", "type": null }, { "param": "INotifyPropertyChanged", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "UserControl", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "INotifyPropertyChanged", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
14
614
146
4194ba85dc1bd48a4ba92320e3d1c6312686034c
jskeet/google-api-dotnet-client
Src/Generated/Google.Apis.DLP.v2/Google.Apis.DLP.v2.cs
[ "Apache-2.0" ]
C#
DeleteRequest
/// <summary> /// Deletes a long-running DlpJob. This method indicates that the client is no longer interested in the /// DlpJob result. The job will be cancelled if possible. See /// https://cloud.google.com/dlp/docs/inspecting-storage and /// https://cloud.google.com/dlp/docs/compute-risk-analysis to learn more. /// </summary>
Deletes a long-running DlpJob. This method indicates that the client is no longer interested in the DlpJob result. The job will be cancelled if possible.
[ "Deletes", "a", "long", "-", "running", "DlpJob", ".", "This", "method", "indicates", "that", "the", "client", "is", "no", "longer", "interested", "in", "the", "DlpJob", "result", ".", "The", "job", "will", "be", "cancelled", "if", "possible", "." ]
public class DeleteRequest : DLPBaseServiceRequest<Google.Apis.DLP.v2.Data.GoogleProtobufEmpty> { public DeleteRequest(Google.Apis.Services.IClientService service, string name) : base(service) { Name = name; InitParameters(); } [Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)] public virtual string Name { get; private set; } public override string MethodName => "delete"; public override string HttpMethod => "DELETE"; public override string RestPath => "v2/{+name}"; protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("name", new Google.Apis.Discovery.Parameter { Name = "name", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^projects/[^/]+/locations/[^/]+/dlpJobs/[^/]+$", }); } }
[ "public", "class", "DeleteRequest", ":", "DLPBaseServiceRequest", "<", "Google", ".", "Apis", ".", "DLP", ".", "v2", ".", "Data", ".", "GoogleProtobufEmpty", ">", "{", "public", "DeleteRequest", "(", "Google", ".", "Apis", ".", "Services", ".", "IClientService", "service", ",", "string", "name", ")", ":", "base", "(", "service", ")", "{", "Name", "=", "name", ";", "InitParameters", "(", ")", ";", "}", "[", "Google", ".", "Apis", ".", "Util", ".", "RequestParameterAttribute", "(", "\"", "name", "\"", ",", "Google", ".", "Apis", ".", "Util", ".", "RequestParameterType", ".", "Path", ")", "]", "public", "virtual", "string", "Name", "{", "get", ";", "private", "set", ";", "}", "public", "override", "string", "MethodName", "=>", "\"", "delete", "\"", ";", "public", "override", "string", "HttpMethod", "=>", "\"", "DELETE", "\"", ";", "public", "override", "string", "RestPath", "=>", "\"", "v2/{+name}", "\"", ";", "protected", "override", "void", "InitParameters", "(", ")", "{", "base", ".", "InitParameters", "(", ")", ";", "RequestParameters", ".", "Add", "(", "\"", "name", "\"", ",", "new", "Google", ".", "Apis", ".", "Discovery", ".", "Parameter", "{", "Name", "=", "\"", "name", "\"", ",", "IsRequired", "=", "true", ",", "ParameterType", "=", "\"", "path", "\"", ",", "DefaultValue", "=", "null", ",", "Pattern", "=", "@\"^projects/[^/]+/locations/[^/]+/dlpJobs/[^/]+$\"", ",", "}", ")", ";", "}", "}" ]
Deletes a long-running DlpJob.
[ "Deletes", "a", "long", "-", "running", "DlpJob", "." ]
[ "/// <summary>Constructs a new Delete request.</summary>", "/// <summary>Required. The name of the DlpJob resource to be deleted.</summary>", "/// <summary>Gets the method name.</summary>", "/// <summary>Gets the HTTP method.</summary>", "/// <summary>Gets the REST path.</summary>", "/// <summary>Initializes Delete parameter list.</summary>" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
13
207
78
f0ec4cc042098cf3e1772099dcb8da1f7af5682b
ajarms/RelativityScriptRunner
Milyli.ScriptRunner.Core/Repositories/BaseReadWriteRepository.cs
[ "MIT" ]
C#
BaseReadWriteRepository
/// <summary> /// Base repository class to inherit when read and write functionality will be needed for the entity. /// </summary> /// <typeparam name="TDataContext">The data context that is used to represent the data source.</typeparam> /// <typeparam name="TModel">Type of model the repository is responsible for.</typeparam> /// <typeparam name="TKey">Type of the primary key of the model.</typeparam>
Base repository class to inherit when read and write functionality will be needed for the entity.
[ "Base", "repository", "class", "to", "inherit", "when", "read", "and", "write", "functionality", "will", "be", "needed", "for", "the", "entity", "." ]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1005:AvoidExcessiveParametersOnGenericTypes", Justification = "Necessary to specify context for child classes")] public abstract class BaseReadWriteRepository<TDataContext, TModel, TKey> : BaseReadRepository<TDataContext, TModel, TKey>, IReadWriteRepository<TModel, TKey> where TModel : class, IModel<TKey> where TKey : struct where TDataContext : IDataContext { protected BaseReadWriteRepository(TDataContext dataContext) : base(dataContext) { } public TKey Create(TModel model) { var id = this.DataContext.InsertWithIdentity(model); return (id is TKey) ? (TKey)id : (TKey)Convert.ChangeType(id, typeof(TKey), CultureInfo.InvariantCulture); } public void CreateMany(ICollection<TModel> models) { var dataContextAsConnection = this.DataContext as DataConnection; if (dataContextAsConnection != null) { var bulkCopyOptions = new BulkCopyOptions { BulkCopyType = BulkCopyType.MultipleRows }; dataContextAsConnection.BulkCopy(bulkCopyOptions, models); } else { foreach (var model in models) { this.DataContext.Insert(model); } } } public bool Delete(TKey key) { return ParseSingletonRowCount(this.DataContext.GetTable<TModel>().Delete(i => i.Id.Equals(key))); } public int DeleteMany(ICollection<TKey> keys) { return this.DataContext .GetTable<TModel>() .Delete(i => keys.Contains(i.Id)); } public bool Update(TModel model) { return ParseSingletonRowCount(this.DataContext.Update(model)); } private static bool ParseSingletonRowCount(int rowCount) { switch (rowCount) { case 0: return false; case 1: return true; default: throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "Invalid number of rows ({0}) for a singleton operation", rowCount), nameof(rowCount)); } } }
[ "[", "System", ".", "Diagnostics", ".", "CodeAnalysis", ".", "SuppressMessage", "(", "\"", "Microsoft.Design", "\"", ",", "\"", "CA1005:AvoidExcessiveParametersOnGenericTypes", "\"", ",", "Justification", "=", "\"", "Necessary to specify context for child classes", "\"", ")", "]", "public", "abstract", "class", "BaseReadWriteRepository", "<", "TDataContext", ",", "TModel", ",", "TKey", ">", ":", "BaseReadRepository", "<", "TDataContext", ",", "TModel", ",", "TKey", ">", ",", "IReadWriteRepository", "<", "TModel", ",", "TKey", ">", "where", "TModel", ":", "class", ",", "IModel", "<", "TKey", ">", "where", "TKey", ":", "struct", "where", "TDataContext", ":", "IDataContext", "{", "protected", "BaseReadWriteRepository", "(", "TDataContext", "dataContext", ")", ":", "base", "(", "dataContext", ")", "{", "}", "public", "TKey", "Create", "(", "TModel", "model", ")", "{", "var", "id", "=", "this", ".", "DataContext", ".", "InsertWithIdentity", "(", "model", ")", ";", "return", "(", "id", "is", "TKey", ")", "?", "(", "TKey", ")", "id", ":", "(", "TKey", ")", "Convert", ".", "ChangeType", "(", "id", ",", "typeof", "(", "TKey", ")", ",", "CultureInfo", ".", "InvariantCulture", ")", ";", "}", "public", "void", "CreateMany", "(", "ICollection", "<", "TModel", ">", "models", ")", "{", "var", "dataContextAsConnection", "=", "this", ".", "DataContext", "as", "DataConnection", ";", "if", "(", "dataContextAsConnection", "!=", "null", ")", "{", "var", "bulkCopyOptions", "=", "new", "BulkCopyOptions", "{", "BulkCopyType", "=", "BulkCopyType", ".", "MultipleRows", "}", ";", "dataContextAsConnection", ".", "BulkCopy", "(", "bulkCopyOptions", ",", "models", ")", ";", "}", "else", "{", "foreach", "(", "var", "model", "in", "models", ")", "{", "this", ".", "DataContext", ".", "Insert", "(", "model", ")", ";", "}", "}", "}", "public", "bool", "Delete", "(", "TKey", "key", ")", "{", "return", "ParseSingletonRowCount", "(", "this", ".", "DataContext", ".", "GetTable", "<", "TModel", ">", "(", ")", ".", "Delete", "(", "i", "=>", "i", ".", "Id", ".", "Equals", "(", "key", ")", ")", ")", ";", "}", "public", "int", "DeleteMany", "(", "ICollection", "<", "TKey", ">", "keys", ")", "{", "return", "this", ".", "DataContext", ".", "GetTable", "<", "TModel", ">", "(", ")", ".", "Delete", "(", "i", "=>", "keys", ".", "Contains", "(", "i", ".", "Id", ")", ")", ";", "}", "public", "bool", "Update", "(", "TModel", "model", ")", "{", "return", "ParseSingletonRowCount", "(", "this", ".", "DataContext", ".", "Update", "(", "model", ")", ")", ";", "}", "private", "static", "bool", "ParseSingletonRowCount", "(", "int", "rowCount", ")", "{", "switch", "(", "rowCount", ")", "{", "case", "0", ":", "return", "false", ";", "case", "1", ":", "return", "true", ";", "default", ":", "throw", "new", "ArgumentException", "(", "string", ".", "Format", "(", "CultureInfo", ".", "InvariantCulture", ",", "\"", "Invalid number of rows ({0}) for a singleton operation", "\"", ",", "rowCount", ")", ",", "nameof", "(", "rowCount", ")", ")", ";", "}", "}", "}" ]
Base repository class to inherit when read and write functionality will be needed for the entity.
[ "Base", "repository", "class", "to", "inherit", "when", "read", "and", "write", "functionality", "will", "be", "needed", "for", "the", "entity", "." ]
[ "/// <summary>", "/// Initializes a new instance of the <see cref=\"BaseReadWriteRepository{TDataContext, TModel, TKey}\"/> class.", "/// </summary>", "/// <param name=\"dataContext\"><see cref=\"IDataContext\"/> dependency.</param>", "/// <summary>", "/// Creates a new instance of the model in the repository.", "/// </summary>", "/// <param name=\"model\">The model to create.</param>", "/// <returns>The identity of the new instance.</returns>", "// TODO: How does InsertWithIdentity work with GUIDs?", "/// <inheritdoc/>", "// all non-mocked implementations inherit from this, so worth checking", "// generate large INSERT statement", "/// <inheritdoc/>", "/// <inheritdoc/>", "/// <inheritdoc/>" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [ { "identifier": "typeparam", "docstring": "The data context that is used to represent the data source.", "docstring_tokens": [ "The", "data", "context", "that", "is", "used", "to", "represent", "the", "data", "source", "." ] }, { "identifier": "typeparam", "docstring": "Type of model the repository is responsible for.", "docstring_tokens": [ "Type", "of", "model", "the", "repository", "is", "responsible", "for", "." ] }, { "identifier": "typeparam", "docstring": "Type of the primary key of the model.", "docstring_tokens": [ "Type", "of", "the", "primary", "key", "of", "the", "model", "." ] } ] }
false
16
444
86
36acdb0edd80706bbe099149e99b3edd7520b292
pravin-d/dipdup-py
src/dipdup/config.py
[ "MIT" ]
Python
HTTPConfig
Advanced configuration of HTTP client :param cache: Whether to cache responses :param retry_count: Number of retries before giving up :param retry_sleep: Sleep time between retries :param retry_multiplier: Multiplier for sleep time between retries :param ratelimit_rate: Number of requests per `ratelimit_period` :param ratelimit_period: Time period for rate limiting :param connection_limit: Number of simultaneous connections :param connection_timeout: Connection timeout :param batch_size: Number of items fetched in a single request
Advanced configuration of HTTP client
[ "Advanced", "configuration", "of", "HTTP", "client" ]
class HTTPConfig: """Advanced configuration of HTTP client :param cache: Whether to cache responses :param retry_count: Number of retries before giving up :param retry_sleep: Sleep time between retries :param retry_multiplier: Multiplier for sleep time between retries :param ratelimit_rate: Number of requests per `ratelimit_period` :param ratelimit_period: Time period for rate limiting :param connection_limit: Number of simultaneous connections :param connection_timeout: Connection timeout :param batch_size: Number of items fetched in a single request """ cache: Optional[bool] = None retry_count: Optional[int] = None retry_sleep: Optional[float] = None retry_multiplier: Optional[float] = None ratelimit_rate: Optional[int] = None ratelimit_period: Optional[int] = None connection_limit: Optional[int] = None # default 100 connection_timeout: Optional[int] = None # default 60 batch_size: Optional[int] = None def merge(self, other: Optional['HTTPConfig']) -> 'HTTPConfig': config = copy(self) if other: for k, v in other.__dict__.items(): if v is not None: setattr(config, k, v) return config
[ "class", "HTTPConfig", ":", "cache", ":", "Optional", "[", "bool", "]", "=", "None", "retry_count", ":", "Optional", "[", "int", "]", "=", "None", "retry_sleep", ":", "Optional", "[", "float", "]", "=", "None", "retry_multiplier", ":", "Optional", "[", "float", "]", "=", "None", "ratelimit_rate", ":", "Optional", "[", "int", "]", "=", "None", "ratelimit_period", ":", "Optional", "[", "int", "]", "=", "None", "connection_limit", ":", "Optional", "[", "int", "]", "=", "None", "connection_timeout", ":", "Optional", "[", "int", "]", "=", "None", "batch_size", ":", "Optional", "[", "int", "]", "=", "None", "def", "merge", "(", "self", ",", "other", ":", "Optional", "[", "'HTTPConfig'", "]", ")", "->", "'HTTPConfig'", ":", "config", "=", "copy", "(", "self", ")", "if", "other", ":", "for", "k", ",", "v", "in", "other", ".", "__dict__", ".", "items", "(", ")", ":", "if", "v", "is", "not", "None", ":", "setattr", "(", "config", ",", "k", ",", "v", ")", "return", "config" ]
Advanced configuration of HTTP client
[ "Advanced", "configuration", "of", "HTTP", "client" ]
[ "\"\"\"Advanced configuration of HTTP client\n \n :param cache: Whether to cache responses\n :param retry_count: Number of retries before giving up\n :param retry_sleep: Sleep time between retries\n :param retry_multiplier: Multiplier for sleep time between retries\n :param ratelimit_rate: Number of requests per `ratelimit_period`\n :param ratelimit_period: Time period for rate limiting\n :param connection_limit: Number of simultaneous connections\n :param connection_timeout: Connection timeout\n :param batch_size: Number of items fetched in a single request \n \"\"\"", "# default 100", "# default 60" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [ { "identifier": "cache", "type": null, "docstring": "Whether to cache responses", "docstring_tokens": [ "Whether", "to", "cache", "responses" ], "default": null, "is_optional": null }, { "identifier": "retry_count", "type": null, "docstring": "Number of retries before giving up", "docstring_tokens": [ "Number", "of", "retries", "before", "giving", "up" ], "default": null, "is_optional": null }, { "identifier": "retry_sleep", "type": null, "docstring": "Sleep time between retries", "docstring_tokens": [ "Sleep", "time", "between", "retries" ], "default": null, "is_optional": null }, { "identifier": "retry_multiplier", "type": null, "docstring": "Multiplier for sleep time between retries", "docstring_tokens": [ "Multiplier", "for", "sleep", "time", "between", "retries" ], "default": null, "is_optional": null }, { "identifier": "ratelimit_rate", "type": null, "docstring": "Number of requests per `ratelimit_period`", "docstring_tokens": [ "Number", "of", "requests", "per", "`", "ratelimit_period", "`" ], "default": null, "is_optional": null }, { "identifier": "ratelimit_period", "type": null, "docstring": "Time period for rate limiting", "docstring_tokens": [ "Time", "period", "for", "rate", "limiting" ], "default": null, "is_optional": null }, { "identifier": "connection_limit", "type": null, "docstring": "Number of simultaneous connections", "docstring_tokens": [ "Number", "of", "simultaneous", "connections" ], "default": null, "is_optional": null }, { "identifier": "connection_timeout", "type": null, "docstring": null, "docstring_tokens": [ "None" ], "default": null, "is_optional": null }, { "identifier": "batch_size", "type": null, "docstring": "Number of items fetched in a single request", "docstring_tokens": [ "Number", "of", "items", "fetched", "in", "a", "single", "request" ], "default": null, "is_optional": null } ], "others": [] }
false
14
293
122
6af6611be8311f32eb52556e30317ef3285ca2e2
FHFTechTeam/expertfinder
Source/Microsoft.Teams.Apps.ExpertFinder/Resources/Strings.Designer.cs
[ "MIT" ]
C#
Strings
/// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project.
A strongly-typed resource class, for looking up localized strings, etc.
[ "A", "strongly", "-", "typed", "resource", "class", "for", "looking", "up", "localized", "strings", "etc", "." ]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Strings { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Strings() { } [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Microsoft.Teams.Apps.ExpertFinder.Resources.Strings", typeof(Strings).Assembly); resourceMan = temp; } return resourceMan; } } [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } internal static string AboutMePlaceHolderText { get { return ResourceManager.GetString("AboutMePlaceHolderText", resourceCulture); } } internal static string AboutMeTitle { get { return ResourceManager.GetString("AboutMeTitle", resourceCulture); } } internal static string ChatTitle { get { return ResourceManager.GetString("ChatTitle", resourceCulture); } } internal static string DefaultCardContentME { get { return ResourceManager.GetString("DefaultCardContentME", resourceCulture); } } internal static string DetailsTitle { get { return ResourceManager.GetString("DetailsTitle", resourceCulture); } } internal static string EditProfileTitle { get { return ResourceManager.GetString("EditProfileTitle", resourceCulture); } } internal static string EmptyProfileCardContent { get { return ResourceManager.GetString("EmptyProfileCardContent", resourceCulture); } } internal static string ErrorMessage { get { return ResourceManager.GetString("ErrorMessage", resourceCulture); } } internal static string FailedToUpdateProfile { get { return ResourceManager.GetString("FailedToUpdateProfile", resourceCulture); } } internal static string ForbiddenErrorMessage { get { return ResourceManager.GetString("ForbiddenErrorMessage", resourceCulture); } } internal static string FullNameTitle { get { return ResourceManager.GetString("FullNameTitle", resourceCulture); } } internal static string GeneralErrorMessage { get { return ResourceManager.GetString("GeneralErrorMessage", resourceCulture); } } internal static string GotoProfileTitle { get { return ResourceManager.GetString("GotoProfileTitle", resourceCulture); } } internal static string HelpMessage { get { return ResourceManager.GetString("HelpMessage", resourceCulture); } } internal static string InitialSearchResultMessageBodyText { get { return ResourceManager.GetString("InitialSearchResultMessageBodyText", resourceCulture); } } internal static string InitialSearchResultMessageHeaderText { get { return ResourceManager.GetString("InitialSearchResultMessageHeaderText", resourceCulture); } } internal static string InterestsPlaceHolderText { get { return ResourceManager.GetString("InterestsPlaceHolderText", resourceCulture); } } internal static string InterestTitle { get { return ResourceManager.GetString("InterestTitle", resourceCulture); } } internal static string InvalidTenant { get { return ResourceManager.GetString("InvalidTenant", resourceCulture); } } internal static string LoginSuccessText { get { return ResourceManager.GetString("LoginSuccessText", resourceCulture); } } internal static string MaxUserProfilesError { get { return ResourceManager.GetString("MaxUserProfilesError", resourceCulture); } } internal static string MyProfileTitle { get { return ResourceManager.GetString("MyProfileTitle", resourceCulture); } } internal static string MyProfileWelcomeCardContent { get { return ResourceManager.GetString("MyProfileWelcomeCardContent", resourceCulture); } } internal static string NoneText { get { return ResourceManager.GetString("NoneText", resourceCulture); } } internal static string NotLoginText { get { return ResourceManager.GetString("NotLoginText", resourceCulture); } } internal static string RefreshLinkText { get { return ResourceManager.GetString("RefreshLinkText", resourceCulture); } } internal static string SchoolsPlaceHolderText { get { return ResourceManager.GetString("SchoolsPlaceHolderText", resourceCulture); } } internal static string SchoolsTitle { get { return ResourceManager.GetString("SchoolsTitle", resourceCulture); } } internal static string SearchCardContent { get { return ResourceManager.GetString("SearchCardContent", resourceCulture); } } internal static string SearchResultNoItemsText { get { return ResourceManager.GetString("SearchResultNoItemsText", resourceCulture); } } internal static string SearchTaskModuleTitle { get { return ResourceManager.GetString("SearchTaskModuleTitle", resourceCulture); } } internal static string SearchTextBoxPlaceholder { get { return ResourceManager.GetString("SearchTextBoxPlaceholder", resourceCulture); } } internal static string SearchTitle { get { return ResourceManager.GetString("SearchTitle", resourceCulture); } } internal static string SearchWelcomeCardContent { get { return ResourceManager.GetString("SearchWelcomeCardContent", resourceCulture); } } internal static string SignInBtnText { get { return ResourceManager.GetString("SignInBtnText", resourceCulture); } } internal static string SigninCardText { get { return ResourceManager.GetString("SigninCardText", resourceCulture); } } internal static string SignOutText { get { return ResourceManager.GetString("SignOutText", resourceCulture); } } internal static string SkillsPlaceHolderText { get { return ResourceManager.GetString("SkillsPlaceHolderText", resourceCulture); } } internal static string SkillsTitle { get { return ResourceManager.GetString("SkillsTitle", resourceCulture); } } internal static string UnauthorizedErrorMessage { get { return ResourceManager.GetString("UnauthorizedErrorMessage", resourceCulture); } } internal static string UpdateTitle { get { return ResourceManager.GetString("UpdateTitle", resourceCulture); } } internal static string ValidationTaskModuleMessage { get { return ResourceManager.GetString("ValidationTaskModuleMessage", resourceCulture); } } internal static string ViewButtonText { get { return ResourceManager.GetString("ViewButtonText", resourceCulture); } } internal static string WelcomeCardContent { get { return ResourceManager.GetString("WelcomeCardContent", resourceCulture); } } internal static string WelocmeText { get { return ResourceManager.GetString("WelocmeText", resourceCulture); } } }
[ "[", "global", "::", "System", ".", "CodeDom", ".", "Compiler", ".", "GeneratedCodeAttribute", "(", "\"", "System.Resources.Tools.StronglyTypedResourceBuilder", "\"", ",", "\"", "16.0.0.0", "\"", ")", "]", "[", "global", "::", "System", ".", "Diagnostics", ".", "DebuggerNonUserCodeAttribute", "(", ")", "]", "[", "global", "::", "System", ".", "Runtime", ".", "CompilerServices", ".", "CompilerGeneratedAttribute", "(", ")", "]", "internal", "class", "Strings", "{", "private", "static", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "resourceMan", ";", "private", "static", "global", "::", "System", ".", "Globalization", ".", "CultureInfo", "resourceCulture", ";", "[", "global", "::", "System", ".", "Diagnostics", ".", "CodeAnalysis", ".", "SuppressMessageAttribute", "(", "\"", "Microsoft.Performance", "\"", ",", "\"", "CA1811:AvoidUncalledPrivateCode", "\"", ")", "]", "internal", "Strings", "(", ")", "{", "}", "[", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableAttribute", "(", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableState", ".", "Advanced", ")", "]", "internal", "static", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "ResourceManager", "{", "get", "{", "if", "(", "object", ".", "ReferenceEquals", "(", "resourceMan", ",", "null", ")", ")", "{", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "temp", "=", "new", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "(", "\"", "Microsoft.Teams.Apps.ExpertFinder.Resources.Strings", "\"", ",", "typeof", "(", "Strings", ")", ".", "Assembly", ")", ";", "resourceMan", "=", "temp", ";", "}", "return", "resourceMan", ";", "}", "}", "[", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableAttribute", "(", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableState", ".", "Advanced", ")", "]", "internal", "static", "global", "::", "System", ".", "Globalization", ".", "CultureInfo", "Culture", "{", "get", "{", "return", "resourceCulture", ";", "}", "set", "{", "resourceCulture", "=", "value", ";", "}", "}", "internal", "static", "string", "AboutMePlaceHolderText", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "AboutMePlaceHolderText", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "AboutMeTitle", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "AboutMeTitle", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "ChatTitle", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "ChatTitle", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "DefaultCardContentME", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "DefaultCardContentME", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "DetailsTitle", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "DetailsTitle", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "EditProfileTitle", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "EditProfileTitle", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "EmptyProfileCardContent", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "EmptyProfileCardContent", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "ErrorMessage", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "ErrorMessage", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "FailedToUpdateProfile", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "FailedToUpdateProfile", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "ForbiddenErrorMessage", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "ForbiddenErrorMessage", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "FullNameTitle", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "FullNameTitle", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "GeneralErrorMessage", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "GeneralErrorMessage", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "GotoProfileTitle", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "GotoProfileTitle", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "HelpMessage", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "HelpMessage", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "InitialSearchResultMessageBodyText", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "InitialSearchResultMessageBodyText", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "InitialSearchResultMessageHeaderText", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "InitialSearchResultMessageHeaderText", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "InterestsPlaceHolderText", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "InterestsPlaceHolderText", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "InterestTitle", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "InterestTitle", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "InvalidTenant", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "InvalidTenant", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "LoginSuccessText", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "LoginSuccessText", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "MaxUserProfilesError", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "MaxUserProfilesError", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "MyProfileTitle", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "MyProfileTitle", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "MyProfileWelcomeCardContent", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "MyProfileWelcomeCardContent", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "NoneText", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "NoneText", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "NotLoginText", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "NotLoginText", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "RefreshLinkText", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "RefreshLinkText", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "SchoolsPlaceHolderText", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "SchoolsPlaceHolderText", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "SchoolsTitle", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "SchoolsTitle", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "SearchCardContent", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "SearchCardContent", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "SearchResultNoItemsText", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "SearchResultNoItemsText", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "SearchTaskModuleTitle", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "SearchTaskModuleTitle", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "SearchTextBoxPlaceholder", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "SearchTextBoxPlaceholder", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "SearchTitle", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "SearchTitle", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "SearchWelcomeCardContent", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "SearchWelcomeCardContent", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "SignInBtnText", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "SignInBtnText", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "SigninCardText", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "SigninCardText", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "SignOutText", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "SignOutText", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "SkillsPlaceHolderText", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "SkillsPlaceHolderText", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "SkillsTitle", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "SkillsTitle", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "UnauthorizedErrorMessage", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "UnauthorizedErrorMessage", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "UpdateTitle", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "UpdateTitle", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "ValidationTaskModuleMessage", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "ValidationTaskModuleMessage", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "ViewButtonText", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "ViewButtonText", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "WelcomeCardContent", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "WelcomeCardContent", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "WelocmeText", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "WelocmeText", "\"", ",", "resourceCulture", ")", ";", "}", "}", "}" ]
A strongly-typed resource class, for looking up localized strings, etc.
[ "A", "strongly", "-", "typed", "resource", "class", "for", "looking", "up", "localized", "strings", "etc", "." ]
[ "/// <summary>", "/// Returns the cached ResourceManager instance used by this class.", "/// </summary>", "/// <summary>", "/// Overrides the current thread's CurrentUICulture property for all", "/// resource lookups using this strongly typed resource class.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Enter information (300 characters max).", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to About me.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Start a chat.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Type a keyword to find people with that information in their profile..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to View more.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Edit profile.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Please update your profile so your friends know what you do..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Something went wrong. Try again in a few minutes..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Something went wrong and I couldn’t update your profile. Try again in a few minutes..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Sorry, seems like you don&apos;t have permission to access this page..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Name.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Oops! An unexpected error seems to have occured. Why not try refreshing your page? Or you can contact your administrator if the problem persists..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Go to profile.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to I can only support below commands..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Hint: Type a skill (like “data visualization”), interest (“hiking”), or the name of a school to find people with that information in their profile..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Here are list of things one can do:.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Enter information (100 characters max).", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Interests.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Unauthorized tenant detected..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Login is successful!.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to You can select max 5 user profiles..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to My profile.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to See how your profile looks to others. Update your profile with skills, interests, and schools..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to None.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to To search for experts, you’ll need to sign in..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Refresh.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Enter information (200 characters max).", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Schools.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Click **Search** to filter for individuals by skills, interests, and other attributes in their profiles..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to No results found. Try different keyword..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Search for experts.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Type a term to search for.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Search.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Filter for individuals by skills, interests, and other attributes in their profiles..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Sign in.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to To search for experts, you’ll need to sign in..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to You have been signed out..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Enter info (100 characters max).", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Skills.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Sorry, an error occurred while trying to access this service..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Update.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Use semicolons between each item in the fields below..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to View.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to I can help you find people in your organization with specific expertise and skills. If it’s in their profile, I can find it! Here’s what you can do:.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Welcome!.", "/// </summary>" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
17
1,486
84
0ade0996ebc71ade33b45ad61aade75066e48fc8
brian-jordan/CellSimulator
src/RunPackage/StatePlot.java
[ "MIT" ]
Java
StatePlot
/** * This is an example of well designed code, because it exemplifies modularity in the front-end of the program. This * class encapsulates the plotting of cell state counts in the program window. It is closed off from other parts of the * program except for an addData method that allows for points to be dynamically plotted after each step. This also * exemplifies flexible code, because it works for any type of simulation as long as the names of the states, colors of * the states' cells, and data are passed in. */
This is an example of well designed code, because it exemplifies modularity in the front-end of the program. This class encapsulates the plotting of cell state counts in the program window. It is closed off from other parts of the program except for an addData method that allows for points to be dynamically plotted after each step. This also exemplifies flexible code, because it works for any type of simulation as long as the names of the states, colors of the states' cells, and data are passed in.
[ "This", "is", "an", "example", "of", "well", "designed", "code", "because", "it", "exemplifies", "modularity", "in", "the", "front", "-", "end", "of", "the", "program", ".", "This", "class", "encapsulates", "the", "plotting", "of", "cell", "state", "counts", "in", "the", "program", "window", ".", "It", "is", "closed", "off", "from", "other", "parts", "of", "the", "program", "except", "for", "an", "addData", "method", "that", "allows", "for", "points", "to", "be", "dynamically", "plotted", "after", "each", "step", ".", "This", "also", "exemplifies", "flexible", "code", "because", "it", "works", "for", "any", "type", "of", "simulation", "as", "long", "as", "the", "names", "of", "the", "states", "colors", "of", "the", "states", "'", "cells", "and", "data", "are", "passed", "in", "." ]
public class StatePlot extends Pane { public static final String PLOT_TITLE_STRING = "PlotTitle"; public static final String XAXIS_STRING = "XAxisLabel"; public static final String YAXIS_STRING = "YAxisLabel"; public static final String AXIS_DESIGN = "axis"; public static final String CHART_STYLE = "chart"; private XYChart.Series[] mySeriesArray; /** * Creates an instance of the StatePlot class and adds a formatted plot to it corresponding to a specific simulation * @param mySim - specific simulation to plot the states of * @param displayedStrings - resource bundle containing strings displayed in the interface */ public StatePlot(Simulation mySim, ResourceBundle displayedStrings){ super(); NumberAxis[] axis = makeAxis(displayedStrings); LineChart<Number, Number> plotOfStates = new LineChart<>(axis[0], axis[1]); plotOfStates.setTitle(displayedStrings.getString(PLOT_TITLE_STRING)); String myColors = getColors(mySim); plotOfStates.getStyleClass().add(CHART_STYLE); plotOfStates.setStyle(myColors); mySeriesArray = createStatesPlots(mySim, plotOfStates); this.getChildren().add(plotOfStates); } private NumberAxis[] makeAxis(ResourceBundle displayedStrings){ NumberAxis[] axis = new NumberAxis[2]; var xAxis = new NumberAxis(); var yAxis = new NumberAxis(); xAxis.getStyleClass().add(AXIS_DESIGN); yAxis.getStyleClass().add(AXIS_DESIGN); xAxis.setLabel(displayedStrings.getString(XAXIS_STRING)); yAxis.setLabel(displayedStrings.getString(YAXIS_STRING)); axis[0] = xAxis; axis[1] = yAxis; return axis; } private XYChart.Series[] createStatesPlots(Simulation mySim, LineChart<Number, Number> chart){ XYChart.Series[] sa = new XYChart.Series[mySim.getStateNames().size()]; int iter = 0; for (String state: mySim.getStateNames()){ sa[iter] = new XYChart.Series(); sa[iter].setName(state); chart.getData().add(sa[iter]); iter++; } return sa; } /** * Adds cell state counts to the plot in relation to the step number * @param step - number of times cell states have been updated * @param mySim - specific simulation to plot the states of */ public void addData(int step, Simulation mySim){ int iter = 0; for (String s: mySim.getStateNames()){ mySeriesArray[iter].getData().add(new XYChart.Data(step, mySim.getMap().get(s))); iter++; } } private String getColors(Simulation mySim){ String colorString = ""; for (int i = 0; i < mySim.getStateColors().length; i++){ colorString = colorString + "CHART_COLOR_" + (i + 1) + ": #" + mySim.getStateColors()[i].toString().substring(2, mySim.getStateColors()[i].toString().length() - 2) + " ;"; } return colorString; } }
[ "public", "class", "StatePlot", "extends", "Pane", "{", "public", "static", "final", "String", "PLOT_TITLE_STRING", "=", "\"", "PlotTitle", "\"", ";", "public", "static", "final", "String", "XAXIS_STRING", "=", "\"", "XAxisLabel", "\"", ";", "public", "static", "final", "String", "YAXIS_STRING", "=", "\"", "YAxisLabel", "\"", ";", "public", "static", "final", "String", "AXIS_DESIGN", "=", "\"", "axis", "\"", ";", "public", "static", "final", "String", "CHART_STYLE", "=", "\"", "chart", "\"", ";", "private", "XYChart", ".", "Series", "[", "]", "mySeriesArray", ";", "/**\n * Creates an instance of the StatePlot class and adds a formatted plot to it corresponding to a specific simulation\n * @param mySim - specific simulation to plot the states of\n * @param displayedStrings - resource bundle containing strings displayed in the interface\n */", "public", "StatePlot", "(", "Simulation", "mySim", ",", "ResourceBundle", "displayedStrings", ")", "{", "super", "(", ")", ";", "NumberAxis", "[", "]", "axis", "=", "makeAxis", "(", "displayedStrings", ")", ";", "LineChart", "<", "Number", ",", "Number", ">", "plotOfStates", "=", "new", "LineChart", "<", ">", "(", "axis", "[", "0", "]", ",", "axis", "[", "1", "]", ")", ";", "plotOfStates", ".", "setTitle", "(", "displayedStrings", ".", "getString", "(", "PLOT_TITLE_STRING", ")", ")", ";", "String", "myColors", "=", "getColors", "(", "mySim", ")", ";", "plotOfStates", ".", "getStyleClass", "(", ")", ".", "add", "(", "CHART_STYLE", ")", ";", "plotOfStates", ".", "setStyle", "(", "myColors", ")", ";", "mySeriesArray", "=", "createStatesPlots", "(", "mySim", ",", "plotOfStates", ")", ";", "this", ".", "getChildren", "(", ")", ".", "add", "(", "plotOfStates", ")", ";", "}", "private", "NumberAxis", "[", "]", "makeAxis", "(", "ResourceBundle", "displayedStrings", ")", "{", "NumberAxis", "[", "]", "axis", "=", "new", "NumberAxis", "[", "2", "]", ";", "var", "xAxis", "=", "new", "NumberAxis", "(", ")", ";", "var", "yAxis", "=", "new", "NumberAxis", "(", ")", ";", "xAxis", ".", "getStyleClass", "(", ")", ".", "add", "(", "AXIS_DESIGN", ")", ";", "yAxis", ".", "getStyleClass", "(", ")", ".", "add", "(", "AXIS_DESIGN", ")", ";", "xAxis", ".", "setLabel", "(", "displayedStrings", ".", "getString", "(", "XAXIS_STRING", ")", ")", ";", "yAxis", ".", "setLabel", "(", "displayedStrings", ".", "getString", "(", "YAXIS_STRING", ")", ")", ";", "axis", "[", "0", "]", "=", "xAxis", ";", "axis", "[", "1", "]", "=", "yAxis", ";", "return", "axis", ";", "}", "private", "XYChart", ".", "Series", "[", "]", "createStatesPlots", "(", "Simulation", "mySim", ",", "LineChart", "<", "Number", ",", "Number", ">", "chart", ")", "{", "XYChart", ".", "Series", "[", "]", "sa", "=", "new", "XYChart", ".", "Series", "[", "mySim", ".", "getStateNames", "(", ")", ".", "size", "(", ")", "]", ";", "int", "iter", "=", "0", ";", "for", "(", "String", "state", ":", "mySim", ".", "getStateNames", "(", ")", ")", "{", "sa", "[", "iter", "]", "=", "new", "XYChart", ".", "Series", "(", ")", ";", "sa", "[", "iter", "]", ".", "setName", "(", "state", ")", ";", "chart", ".", "getData", "(", ")", ".", "add", "(", "sa", "[", "iter", "]", ")", ";", "iter", "++", ";", "}", "return", "sa", ";", "}", "/**\n * Adds cell state counts to the plot in relation to the step number\n * @param step - number of times cell states have been updated\n * @param mySim - specific simulation to plot the states of\n */", "public", "void", "addData", "(", "int", "step", ",", "Simulation", "mySim", ")", "{", "int", "iter", "=", "0", ";", "for", "(", "String", "s", ":", "mySim", ".", "getStateNames", "(", ")", ")", "{", "mySeriesArray", "[", "iter", "]", ".", "getData", "(", ")", ".", "add", "(", "new", "XYChart", ".", "Data", "(", "step", ",", "mySim", ".", "getMap", "(", ")", ".", "get", "(", "s", ")", ")", ")", ";", "iter", "++", ";", "}", "}", "private", "String", "getColors", "(", "Simulation", "mySim", ")", "{", "String", "colorString", "=", "\"", "\"", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "mySim", ".", "getStateColors", "(", ")", ".", "length", ";", "i", "++", ")", "{", "colorString", "=", "colorString", "+", "\"", "CHART_COLOR_", "\"", "+", "(", "i", "+", "1", ")", "+", "\"", ": #", "\"", "+", "mySim", ".", "getStateColors", "(", ")", "[", "i", "]", ".", "toString", "(", ")", ".", "substring", "(", "2", ",", "mySim", ".", "getStateColors", "(", ")", "[", "i", "]", ".", "toString", "(", ")", ".", "length", "(", ")", "-", "2", ")", "+", "\"", " ;", "\"", ";", "}", "return", "colorString", ";", "}", "}" ]
This is an example of well designed code, because it exemplifies modularity in the front-end of the program.
[ "This", "is", "an", "example", "of", "well", "designed", "code", "because", "it", "exemplifies", "modularity", "in", "the", "front", "-", "end", "of", "the", "program", "." ]
[]
[ { "param": "Pane", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Pane", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
19
689
117
0fdf45b461b7b5cdb3c63f16c9dad12107864b63
fidesmo/fidesmo-android-tutorial
src/main/java/com/fidesmo/tutorials/hellofidesmo/MainActivity.java
[ "Apache-2.0" ]
Java
MainActivity
/** * Unique Activity in the HelloFidesmo example app, written for the Fidesmo Android tutorial * It attempts to open the NFC interface (if disabled, shows a dialog to the user) * Once a card is detected, it sends a SELECT command towards the cardlet written in the tutorial * - if successful, it displays the string returned by the card * - if unsuccessful, it assumes the cardlet is not installed on the card and triggers * the service delivery process using the Fidesmo App */
Unique Activity in the HelloFidesmo example app, written for the Fidesmo Android tutorial It attempts to open the NFC interface (if disabled, shows a dialog to the user) Once a card is detected, it sends a SELECT command towards the cardlet written in the tutorial - if successful, it displays the string returned by the card - if unsuccessful, it assumes the cardlet is not installed on the card and triggers the service delivery process using the Fidesmo App
[ "Unique", "Activity", "in", "the", "HelloFidesmo", "example", "app", "written", "for", "the", "Fidesmo", "Android", "tutorial", "It", "attempts", "to", "open", "the", "NFC", "interface", "(", "if", "disabled", "shows", "a", "dialog", "to", "the", "user", ")", "Once", "a", "card", "is", "detected", "it", "sends", "a", "SELECT", "command", "towards", "the", "cardlet", "written", "in", "the", "tutorial", "-", "if", "successful", "it", "displays", "the", "string", "returned", "by", "the", "card", "-", "if", "unsuccessful", "it", "assumes", "the", "cardlet", "is", "not", "installed", "on", "the", "card", "and", "triggers", "the", "service", "delivery", "process", "using", "the", "Fidesmo", "App" ]
@EActivity(R.layout.activity_main) public class MainActivity extends AppCompatActivity implements OnDiscoveredTagListener { // APPLICATION_ID is the value assigned to your application by Fidesmo final private static String APPLICATION_ID = "XXXXXXXX"; final private static String APP_VERSION = "01"; final private static String SERVICE_ID = "HelloFidesmo"; // Constants used to initiate cardlet delivery through the Fidesmo App private final static String FIDESMO_APP = "com.fidesmo.sec.android"; private final static String SERVICE_URI = "https://apps.fidesmo.com/"; // Code to identify the call when starting Intent for Result static private final int SERVICE_DELIVERY_REQUEST_CODE = 724; // URLs for Google Play app and to install apps via browser private final static String MARKET_URI = "market://details?id="; private final static String MARKET_VIA_BROWSER_URI = "http://play.google.com/store/apps/details?id="; private static final String TAG = "MainActivity"; // The TagDispatcher is responsible for managing the NFC for the activity private TagDispatcher tagDispatcher; // UI elements @ViewById TextView mainText; @ViewById Button installButton; //Two methods for setting the UI (on UI thread, because, threading...) @UiThread void setMainMessage(int resource) { setMainMessage(getString(resource)); } @UiThread void setMainMessage(String text) { String oldString = mainText.getText().toString(); mainText.setText(oldString + "\n" + text); } @Override protected void onResume() { super.onResume(); // The first argument is the activity for which the NFC is managed // The second argument is the OnDiscoveredTagListener which is also implemented by this activity // This means that tagDiscovered will be called whenever a new tag appears tagDispatcher = TagDispatcher.get(this, this); // Start listening on the NFC interface when the app gains focus. tagDispatcher.enableExclusiveNfc(); } // Stop listening on the NFC interface if the app loses focus @Override public void onPause() { super.onPause(); tagDispatcher.disableExclusiveNfc(); } /** * This method is called when a contactless device is detected at the NFC interface * @param intent the PendingIntent declared in onResume */ @Override protected void onNewIntent(Intent intent) { tagDispatcher.interceptIntent(intent); } @Override public void tagDiscovered(Tag tag) { setMainMessage(R.string.reading_card); try { IsoCard isoCard = AndroidCard.get(tag); communicateWithCard(isoCard); } catch(IOException e) { e.printStackTrace(); } } /** * Sends a SELECT APDU to the HelloFidesmo cardlet on the card and parses the response * - If the response's status bytes are '90 00' (=APDU successfully executed, Apdu.OK_APDU), it displays the response payload * - If not, it assumes that HelloFidesmo cardlet was not installed and shows a button * so the user can launch the installation process * @param isoCard card detected at the NFC interface, supporting ISO 14443/4 standard */ private void communicateWithCard(IsoCard isoCard) { try { isoCard.connect(); //This is where you use your appId to select your app on the card (the one assigned to you when signing up to the Dev Portal) byte[] response = isoCard.transceive(Apdu.select(APPLICATION_ID, APP_VERSION)); // Analyze the response. Its last two bytes are the status bytes - '90 00'/Apdu.OK_APDU means 'success' if (Apdu.hasStatus(response, Apdu.OK_APDU)) { setMainMessage(getString(R.string.select_ok)); // print the message byte[] payload = Apdu.responseData(response); String printableResponse = new String(); for (int i=0; i<payload.length; i++) printableResponse += (char)payload[i]; setMainMessage(printableResponse); } else { setMainMessage(getString(R.string.select_not_ok)); // enable the button so the user can install the cardlet setMainMessage(R.string.cardlet_not_installed); showInstallButton(true); } isoCard.close(); } catch (IOException e) { Log.e(TAG, "Error reading card", e); } } @UiThread void showInstallButton(boolean visibility) { if (visibility){ installButton.setVisibility(View.VISIBLE); } else { installButton.setVisibility(View.GONE); } } /** * Calls the Fidesmo App in order to install the HelloFidesmo cardlet into the Fidesmo Card * First, it checks whether the Fidesmo App is installed; if not, it opens Google Play */ @Click void installButtonClicked() { if (appInstalledOrNot(FIDESMO_APP)) { try { // create Intent to the Action exposed by the Fidesmo App Intent intent = new Intent("android.intent.action.VIEW", Uri.parse(SERVICE_URI + APPLICATION_ID + "/services/" + SERVICE_ID)); startActivityForResult(intent, SERVICE_DELIVERY_REQUEST_CODE); } catch (IllegalArgumentException e) { Log.e(TAG, "Error when parsing URI"); } } else { notifyMustInstall(); } } // method called when the Fidesmo App activity has finished // Will redraw the screen if it finished successfully @OnActivityResult(SERVICE_DELIVERY_REQUEST_CODE) void onResult(int resultCode) { if (resultCode == RESULT_OK) { Log.i(TAG, "Cardlet installation returned SUCCESS"); setMainMessage(R.string.put_card); installButton.setVisibility(View.GONE); } else { Log.i(TAG, "Cardlet installation returned FAILURE"); Toast.makeText(getApplicationContext(), getString(R.string.failure), Toast.LENGTH_LONG).show(); } } /** * Use the package manager to detect if an application is installed on the phone * @param uri an URI identifying the application's package * @return 'true' is the app is installed */ private boolean appInstalledOrNot(String uri) { PackageManager pm = getPackageManager(); boolean app_installed = false; try { pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES); app_installed = true; } catch (PackageManager.NameNotFoundException e) { Log.i(TAG, "Fidesmo App not installed in phone"); app_installed = false; } return app_installed; } /** * Show a Toast message to the user informing that Fidesmo App must be installed and launch the Google Play app-store */ private void notifyMustInstall() { Toast.makeText(getApplicationContext(), R.string.install_app_message, Toast.LENGTH_LONG).show(); // if the Google Play app is not installed, call the browser try { startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(MARKET_URI + FIDESMO_APP))); } catch (android.content.ActivityNotFoundException exception) { startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(MARKET_VIA_BROWSER_URI + FIDESMO_APP))); } } }
[ "@", "EActivity", "(", "R", ".", "layout", ".", "activity_main", ")", "public", "class", "MainActivity", "extends", "AppCompatActivity", "implements", "OnDiscoveredTagListener", "{", "final", "private", "static", "String", "APPLICATION_ID", "=", "\"", "XXXXXXXX", "\"", ";", "final", "private", "static", "String", "APP_VERSION", "=", "\"", "01", "\"", ";", "final", "private", "static", "String", "SERVICE_ID", "=", "\"", "HelloFidesmo", "\"", ";", "private", "final", "static", "String", "FIDESMO_APP", "=", "\"", "com.fidesmo.sec.android", "\"", ";", "private", "final", "static", "String", "SERVICE_URI", "=", "\"", "https://apps.fidesmo.com/", "\"", ";", "static", "private", "final", "int", "SERVICE_DELIVERY_REQUEST_CODE", "=", "724", ";", "private", "final", "static", "String", "MARKET_URI", "=", "\"", "market://details?id=", "\"", ";", "private", "final", "static", "String", "MARKET_VIA_BROWSER_URI", "=", "\"", "http://play.google.com/store/apps/details?id=", "\"", ";", "private", "static", "final", "String", "TAG", "=", "\"", "MainActivity", "\"", ";", "private", "TagDispatcher", "tagDispatcher", ";", "@", "ViewById", "TextView", "mainText", ";", "@", "ViewById", "Button", "installButton", ";", "@", "UiThread", "void", "setMainMessage", "(", "int", "resource", ")", "{", "setMainMessage", "(", "getString", "(", "resource", ")", ")", ";", "}", "@", "UiThread", "void", "setMainMessage", "(", "String", "text", ")", "{", "String", "oldString", "=", "mainText", ".", "getText", "(", ")", ".", "toString", "(", ")", ";", "mainText", ".", "setText", "(", "oldString", "+", "\"", "\\n", "\"", "+", "text", ")", ";", "}", "@", "Override", "protected", "void", "onResume", "(", ")", "{", "super", ".", "onResume", "(", ")", ";", "tagDispatcher", "=", "TagDispatcher", ".", "get", "(", "this", ",", "this", ")", ";", "tagDispatcher", ".", "enableExclusiveNfc", "(", ")", ";", "}", "@", "Override", "public", "void", "onPause", "(", ")", "{", "super", ".", "onPause", "(", ")", ";", "tagDispatcher", ".", "disableExclusiveNfc", "(", ")", ";", "}", "/**\n * This method is called when a contactless device is detected at the NFC interface\n * @param intent the PendingIntent declared in onResume\n */", "@", "Override", "protected", "void", "onNewIntent", "(", "Intent", "intent", ")", "{", "tagDispatcher", ".", "interceptIntent", "(", "intent", ")", ";", "}", "@", "Override", "public", "void", "tagDiscovered", "(", "Tag", "tag", ")", "{", "setMainMessage", "(", "R", ".", "string", ".", "reading_card", ")", ";", "try", "{", "IsoCard", "isoCard", "=", "AndroidCard", ".", "get", "(", "tag", ")", ";", "communicateWithCard", "(", "isoCard", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "}", "/**\n * Sends a SELECT APDU to the HelloFidesmo cardlet on the card and parses the response\n * - If the response's status bytes are '90 00' (=APDU successfully executed, Apdu.OK_APDU), it displays the response payload\n * - If not, it assumes that HelloFidesmo cardlet was not installed and shows a button\n * so the user can launch the installation process\n * @param isoCard card detected at the NFC interface, supporting ISO 14443/4 standard\n */", "private", "void", "communicateWithCard", "(", "IsoCard", "isoCard", ")", "{", "try", "{", "isoCard", ".", "connect", "(", ")", ";", "byte", "[", "]", "response", "=", "isoCard", ".", "transceive", "(", "Apdu", ".", "select", "(", "APPLICATION_ID", ",", "APP_VERSION", ")", ")", ";", "if", "(", "Apdu", ".", "hasStatus", "(", "response", ",", "Apdu", ".", "OK_APDU", ")", ")", "{", "setMainMessage", "(", "getString", "(", "R", ".", "string", ".", "select_ok", ")", ")", ";", "byte", "[", "]", "payload", "=", "Apdu", ".", "responseData", "(", "response", ")", ";", "String", "printableResponse", "=", "new", "String", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "payload", ".", "length", ";", "i", "++", ")", "printableResponse", "+=", "(", "char", ")", "payload", "[", "i", "]", ";", "setMainMessage", "(", "printableResponse", ")", ";", "}", "else", "{", "setMainMessage", "(", "getString", "(", "R", ".", "string", ".", "select_not_ok", ")", ")", ";", "setMainMessage", "(", "R", ".", "string", ".", "cardlet_not_installed", ")", ";", "showInstallButton", "(", "true", ")", ";", "}", "isoCard", ".", "close", "(", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "Log", ".", "e", "(", "TAG", ",", "\"", "Error reading card", "\"", ",", "e", ")", ";", "}", "}", "@", "UiThread", "void", "showInstallButton", "(", "boolean", "visibility", ")", "{", "if", "(", "visibility", ")", "{", "installButton", ".", "setVisibility", "(", "View", ".", "VISIBLE", ")", ";", "}", "else", "{", "installButton", ".", "setVisibility", "(", "View", ".", "GONE", ")", ";", "}", "}", "/**\n * Calls the Fidesmo App in order to install the HelloFidesmo cardlet into the Fidesmo Card\n * First, it checks whether the Fidesmo App is installed; if not, it opens Google Play\n */", "@", "Click", "void", "installButtonClicked", "(", ")", "{", "if", "(", "appInstalledOrNot", "(", "FIDESMO_APP", ")", ")", "{", "try", "{", "Intent", "intent", "=", "new", "Intent", "(", "\"", "android.intent.action.VIEW", "\"", ",", "Uri", ".", "parse", "(", "SERVICE_URI", "+", "APPLICATION_ID", "+", "\"", "/services/", "\"", "+", "SERVICE_ID", ")", ")", ";", "startActivityForResult", "(", "intent", ",", "SERVICE_DELIVERY_REQUEST_CODE", ")", ";", "}", "catch", "(", "IllegalArgumentException", "e", ")", "{", "Log", ".", "e", "(", "TAG", ",", "\"", "Error when parsing URI", "\"", ")", ";", "}", "}", "else", "{", "notifyMustInstall", "(", ")", ";", "}", "}", "@", "OnActivityResult", "(", "SERVICE_DELIVERY_REQUEST_CODE", ")", "void", "onResult", "(", "int", "resultCode", ")", "{", "if", "(", "resultCode", "==", "RESULT_OK", ")", "{", "Log", ".", "i", "(", "TAG", ",", "\"", "Cardlet installation returned SUCCESS", "\"", ")", ";", "setMainMessage", "(", "R", ".", "string", ".", "put_card", ")", ";", "installButton", ".", "setVisibility", "(", "View", ".", "GONE", ")", ";", "}", "else", "{", "Log", ".", "i", "(", "TAG", ",", "\"", "Cardlet installation returned FAILURE", "\"", ")", ";", "Toast", ".", "makeText", "(", "getApplicationContext", "(", ")", ",", "getString", "(", "R", ".", "string", ".", "failure", ")", ",", "Toast", ".", "LENGTH_LONG", ")", ".", "show", "(", ")", ";", "}", "}", "/**\n * Use the package manager to detect if an application is installed on the phone\n * @param uri an URI identifying the application's package\n * @return 'true' is the app is installed\n */", "private", "boolean", "appInstalledOrNot", "(", "String", "uri", ")", "{", "PackageManager", "pm", "=", "getPackageManager", "(", ")", ";", "boolean", "app_installed", "=", "false", ";", "try", "{", "pm", ".", "getPackageInfo", "(", "uri", ",", "PackageManager", ".", "GET_ACTIVITIES", ")", ";", "app_installed", "=", "true", ";", "}", "catch", "(", "PackageManager", ".", "NameNotFoundException", "e", ")", "{", "Log", ".", "i", "(", "TAG", ",", "\"", "Fidesmo App not installed in phone", "\"", ")", ";", "app_installed", "=", "false", ";", "}", "return", "app_installed", ";", "}", "/**\n * Show a Toast message to the user informing that Fidesmo App must be installed and launch the Google Play app-store\n */", "private", "void", "notifyMustInstall", "(", ")", "{", "Toast", ".", "makeText", "(", "getApplicationContext", "(", ")", ",", "R", ".", "string", ".", "install_app_message", ",", "Toast", ".", "LENGTH_LONG", ")", ".", "show", "(", ")", ";", "try", "{", "startActivity", "(", "new", "Intent", "(", "Intent", ".", "ACTION_VIEW", ",", "Uri", ".", "parse", "(", "MARKET_URI", "+", "FIDESMO_APP", ")", ")", ")", ";", "}", "catch", "(", "android", ".", "content", ".", "ActivityNotFoundException", "exception", ")", "{", "startActivity", "(", "new", "Intent", "(", "Intent", ".", "ACTION_VIEW", ",", "Uri", ".", "parse", "(", "MARKET_VIA_BROWSER_URI", "+", "FIDESMO_APP", ")", ")", ")", ";", "}", "}", "}" ]
Unique Activity in the HelloFidesmo example app, written for the Fidesmo Android tutorial It attempts to open the NFC interface (if disabled, shows a dialog to the user) Once a card is detected, it sends a SELECT command towards the cardlet written in the tutorial - if successful, it displays the string returned by the card - if unsuccessful, it assumes the cardlet is not installed on the card and triggers the service delivery process using the Fidesmo App
[ "Unique", "Activity", "in", "the", "HelloFidesmo", "example", "app", "written", "for", "the", "Fidesmo", "Android", "tutorial", "It", "attempts", "to", "open", "the", "NFC", "interface", "(", "if", "disabled", "shows", "a", "dialog", "to", "the", "user", ")", "Once", "a", "card", "is", "detected", "it", "sends", "a", "SELECT", "command", "towards", "the", "cardlet", "written", "in", "the", "tutorial", "-", "if", "successful", "it", "displays", "the", "string", "returned", "by", "the", "card", "-", "if", "unsuccessful", "it", "assumes", "the", "cardlet", "is", "not", "installed", "on", "the", "card", "and", "triggers", "the", "service", "delivery", "process", "using", "the", "Fidesmo", "App" ]
[ "// APPLICATION_ID is the value assigned to your application by Fidesmo", "// Constants used to initiate cardlet delivery through the Fidesmo App", "// Code to identify the call when starting Intent for Result", "// URLs for Google Play app and to install apps via browser", "// The TagDispatcher is responsible for managing the NFC for the activity", "// UI elements", "//Two methods for setting the UI (on UI thread, because, threading...)", "// The first argument is the activity for which the NFC is managed", "// The second argument is the OnDiscoveredTagListener which is also implemented by this activity", "// This means that tagDiscovered will be called whenever a new tag appears", "// Start listening on the NFC interface when the app gains focus.", "// Stop listening on the NFC interface if the app loses focus", "//This is where you use your appId to select your app on the card (the one assigned to you when signing up to the Dev Portal)", "// Analyze the response. Its last two bytes are the status bytes - '90 00'/Apdu.OK_APDU means 'success'", "// print the message", "// enable the button so the user can install the cardlet", "// create Intent to the Action exposed by the Fidesmo App", "// method called when the Fidesmo App activity has finished", "// Will redraw the screen if it finished successfully", "// if the Google Play app is not installed, call the browser" ]
[ { "param": "AppCompatActivity", "type": null }, { "param": "OnDiscoveredTagListener", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "AppCompatActivity", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "OnDiscoveredTagListener", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
18
1,573
111
5a0ac4d01204228767c0a8a3f36d0f327bb76569
jdvelasq/techminer-api
techminer2/chord_diagram.py
[ "MIT" ]
Python
ChordDiagram
Class for plotting chord diagrams. Examples ---------------------------------------------------------------------------------------------- >>> chord = ChordDiagram() >>> chord.add_nodes_from('abcdef', color='black', s=10) >>> chord.add_edge('a', 'b') >>> chord.add_edges_from([('a', 'b'), ('c', 'd'), ('e', 'f')]) >>> _ = pyplot.figure(figsize=(6, 6)) >>> _ = chord.plot(R=1, dist=0.05, fontsize=20, color='red') >>> pyplot.savefig('sphinx/images/chord_demo_1.png') .. image:: images/chord_demo_1.png :width: 700px :align: center >>> chord = ChordDiagram() >>> chord.add_nodes_from('abcd', color='black', s=20) >>> chord.add_node('e', s=100, color='black') >>> chord.add_node('g', s=200, color='black') >>> chord.add_edge('a', 'b', linestyle=':', color='red') >>> _ = pyplot.figure(figsize=(6, 6)) >>> _ = chord.plot(R=1, dist=0.05, fontsize=20, color='red') >>> pyplot.savefig('sphinx/images/chord_demo_2.png') .. image:: images/chord_demo_2.png :width: 700px :align: center
Class for plotting chord diagrams. Examples
[ "Class", "for", "plotting", "chord", "diagrams", ".", "Examples" ]
class ChordDiagram: """Class for plotting chord diagrams. Examples ---------------------------------------------------------------------------------------------- >>> chord = ChordDiagram() >>> chord.add_nodes_from('abcdef', color='black', s=10) >>> chord.add_edge('a', 'b') >>> chord.add_edges_from([('a', 'b'), ('c', 'd'), ('e', 'f')]) >>> _ = pyplot.figure(figsize=(6, 6)) >>> _ = chord.plot(R=1, dist=0.05, fontsize=20, color='red') >>> pyplot.savefig('sphinx/images/chord_demo_1.png') .. image:: images/chord_demo_1.png :width: 700px :align: center >>> chord = ChordDiagram() >>> chord.add_nodes_from('abcd', color='black', s=20) >>> chord.add_node('e', s=100, color='black') >>> chord.add_node('g', s=200, color='black') >>> chord.add_edge('a', 'b', linestyle=':', color='red') >>> _ = pyplot.figure(figsize=(6, 6)) >>> _ = chord.plot(R=1, dist=0.05, fontsize=20, color='red') >>> pyplot.savefig('sphinx/images/chord_demo_2.png') .. image:: images/chord_demo_2.png :width: 700px :align: center """ def __init__(self): self._nodes = {} self._edges = {} def add_node(self, node_to_add, **attr): """ Examples ---------------------------------------------------------------------------------------------- >>> chord = ChordDiagram() >>> chord.add_node('A', nodeA_prop=1) >>> chord.add_node('B', nodeB_prop=2) >>> chord._nodes {'A': {'nodeA_prop': 1}, 'B': {'nodeB_prop': 2}} >>> chord.add_node('C', nodeC_prop1=10, nodeC_prop2=20) """ if node_to_add in self._nodes: self._nodes[node_to_add] = {**self._nodes[node_to_add], **attr} else: self._nodes[node_to_add] = attr def add_nodes_from(self, nodes_for_adding, **attr): """ Examples ---------------------------------------------------------------------------------------------- >>> chord = ChordDiagram() >>> chord.add_nodes_from('abcde') >>> chord._nodes {'a': {}, 'b': {}, 'c': {}, 'd': {}, 'e': {}} >>> chord = ChordDiagram() >>> chord.add_nodes_from('abc', linewidth=1) >>> chord._nodes {'a': {'linewidth': 1}, 'b': {'linewidth': 1}, 'c': {'linewidth': 1}} >>> chord = ChordDiagram() >>> chord.add_nodes_from( [('a', dict(linewidth=1)), ('b', {'linewidth':2}), ('c',{}) ], linewidth=10) >>> chord._nodes {'a': {'linewidth': 1}, 'b': {'linewidth': 2}, 'c': {'linewidth': 10}} """ for n in nodes_for_adding: if isinstance(n, tuple): nn, ndict = n self.add_node(nn, **{**attr, **ndict}) else: self.add_node(n, **attr) def add_edge(self, u, v, **attr): """ Examples ---------------------------------------------------------------------------------------------- >>> chord = ChordDiagram() >>> chord.add_edge('A','B', edgeAB_prop1=1, edgeAB_prop2=2) >>> chord._edges {('A', 'B'): {'edgeAB_prop1': 1, 'edgeAB_prop2': 2}} """ u, v = sorted([u, v]) edge = (u, v) if edge in self._edges: self._edges[edge] = {**self._edges[edge], **attr} else: self._edges[edge] = attr def add_edges_from(self, edges_to_add, **attr): """ Examples ---------------------------------------------------------------------------------------------- >>> chord = ChordDiagram() >>> chord.add_edges_from([(2, 3, {'linewidth': 1}), (3, 4), (5, 4)], linewidth=20) >>> chord._edges {(2, 3): {'linewidth': 1}, (3, 4): {'linewidth': 20}, (4, 5): {'linewidth': 20}} """ for e in edges_to_add: if len(e) == 3: u, v, d = e else: u, v = e d = {} u, v = sorted([e[0], e[1]]) d = {**attr, **d} self.add_edge(u, v, **d) def get_node_data(self, node, **default): """ Examples ---------------------------------------------------------------------------------------------- """ if node not in self._nodes: return default else: return {**default, **self._nodes[node]} def get_edge_data(self, u, v, **default): """ Examples ---------------------------------------------------------------------------------------------- """ u, v = sorted([u, v]) key = (u, v) if key not in self._edges: return default else: return {**default, **self._edges[key]} def plot(self, figsize=(7, 7), R=3, dist=0.2, n_bezier=100, **text_attr): """Plots the diagram""" def compute_node_properties(): n_nodes = len(self._nodes) theta = np.linspace(0.0, 2 * np.pi, n_nodes, endpoint=False) node_x = [R * np.cos(t) for t in theta] node_y = [R * np.sin(t) for t in theta] label_x = [(R + dist) * np.cos(t) for t in theta] label_y = [(R + dist) * np.sin(t) for t in theta] rotation = [t / (2 * np.pi) * 360 for t in theta] rotation = [t - 180 if t > 180 else t for t in rotation] rotation = [t - 180 if t > 90 else t for t in rotation] ha = ["left" if xt >= 0 else "right" for xt in label_x] return dict( theta={n: p for n, p in zip(self._nodes.keys(), theta)}, node_x={n: p for n, p in zip(self._nodes.keys(), node_x)}, node_y={n: p for n, p in zip(self._nodes.keys(), node_y)}, label_x={n: p for n, p in zip(self._nodes.keys(), label_x)}, label_y={n: p for n, p in zip(self._nodes.keys(), label_y)}, rotation={n: p for n, p in zip(self._nodes.keys(), rotation)}, ha={n: p for n, p in zip(self._nodes.keys(), ha)}, s={n: p for n, p in zip(self._nodes.keys(), ha)}, ) def draw_points(): """Draws node and label.""" for node in self._nodes: x = node_properties["node_x"][node] y = node_properties["node_y"][node] ax.scatter( x, y, zorder=10, edgecolors="k", linewidths=0.5, **self.get_node_data(node), ) for label in self._nodes: x = node_properties["label_x"][label] y = node_properties["label_y"][label] rotation = node_properties["rotation"][label] ha = node_properties["ha"][label] attr = {**dict(backgroundcolor="white"), **text_attr} ax.text( x, y, textwrap.shorten(text=label, width=TEXTLEN), rotation=rotation, ha=ha, va="center", rotation_mode="anchor", bbox=dict( facecolor="w", alpha=1.0, edgecolor="gray", boxstyle="round,pad=0.5", ), fontsize=7, zorder=11, **attr, ) def draw_edges(): """Draws edges on the plot.""" def bezier(p0, p1, p2, **kwargs): x0, y0 = p0 x1, y1 = p1 x2, y2 = p2 xb = [ (1 - t) ** 2 * x0 + 2 * t * (1 - t) * x1 + t ** 2 * x2 for t in np.linspace(0.0, 1.0, n_bezier) ] yb = [ (1 - t) ** 2 * y0 + 2 * t * (1 - t) * y1 + t ** 2 * y2 for t in np.linspace(0.0, 1.0, n_bezier) ] ax.plot(xb, yb, **kwargs) for edge in self._edges: u, v = edge x0, y0, a0 = ( node_properties["node_x"][u], node_properties["node_y"][u], node_properties["theta"][u], ) x2, y2, a2 = ( node_properties["node_x"][v], node_properties["node_y"][v], node_properties["theta"][v], ) angle = a0 + (a2 - a0) / 2 # if angle > np.pi: # angle_corr = angle - np.pi # else: # angle_corr = angle distance = np.abs(a2 - a0) if distance > np.pi: distance = distance - np.pi distance = (1.0 - 1.0 * distance / np.pi) * R / 2.5 x1 = distance * np.cos(angle) y1 = distance * np.sin(angle) x1 = 0 y1 = 0 ## dibuja los arcos bezier( [x0, y0], [x1, y1], [x2, y2], **self._edges[edge], ) fig = pyplot.Figure(figsize=figsize) ax = fig.subplots() node_properties = compute_node_properties() draw_points() draw_edges() # # Figure size # xlim = ax.get_xlim() ylim = ax.get_ylim() dx = 0.15 * (xlim[1] - xlim[0]) dy = 0.15 * (ylim[1] - ylim[0]) ax.set_xlim(xlim[0] - dx, xlim[1] + dx) ax.set_ylim(ylim[0] - dy, ylim[1] + dy) ax.set_axis_off() ax.set_aspect("equal") fig.set_tight_layout(True) return fig
[ "class", "ChordDiagram", ":", "def", "__init__", "(", "self", ")", ":", "self", ".", "_nodes", "=", "{", "}", "self", ".", "_edges", "=", "{", "}", "def", "add_node", "(", "self", ",", "node_to_add", ",", "**", "attr", ")", ":", "\"\"\"\n\n Examples\n ----------------------------------------------------------------------------------------------\n\n\n >>> chord = ChordDiagram()\n >>> chord.add_node('A', nodeA_prop=1)\n >>> chord.add_node('B', nodeB_prop=2)\n >>> chord._nodes\n {'A': {'nodeA_prop': 1}, 'B': {'nodeB_prop': 2}}\n\n >>> chord.add_node('C', nodeC_prop1=10, nodeC_prop2=20)\n\n \"\"\"", "if", "node_to_add", "in", "self", ".", "_nodes", ":", "self", ".", "_nodes", "[", "node_to_add", "]", "=", "{", "**", "self", ".", "_nodes", "[", "node_to_add", "]", ",", "**", "attr", "}", "else", ":", "self", ".", "_nodes", "[", "node_to_add", "]", "=", "attr", "def", "add_nodes_from", "(", "self", ",", "nodes_for_adding", ",", "**", "attr", ")", ":", "\"\"\"\n\n Examples\n ----------------------------------------------------------------------------------------------\n\n >>> chord = ChordDiagram()\n >>> chord.add_nodes_from('abcde')\n >>> chord._nodes\n {'a': {}, 'b': {}, 'c': {}, 'd': {}, 'e': {}}\n\n >>> chord = ChordDiagram()\n >>> chord.add_nodes_from('abc', linewidth=1)\n >>> chord._nodes\n {'a': {'linewidth': 1}, 'b': {'linewidth': 1}, 'c': {'linewidth': 1}}\n\n >>> chord = ChordDiagram()\n >>> chord.add_nodes_from( [('a', dict(linewidth=1)), ('b', {'linewidth':2}), ('c',{}) ], linewidth=10)\n >>> chord._nodes\n {'a': {'linewidth': 1}, 'b': {'linewidth': 2}, 'c': {'linewidth': 10}}\n\n \"\"\"", "for", "n", "in", "nodes_for_adding", ":", "if", "isinstance", "(", "n", ",", "tuple", ")", ":", "nn", ",", "ndict", "=", "n", "self", ".", "add_node", "(", "nn", ",", "**", "{", "**", "attr", ",", "**", "ndict", "}", ")", "else", ":", "self", ".", "add_node", "(", "n", ",", "**", "attr", ")", "def", "add_edge", "(", "self", ",", "u", ",", "v", ",", "**", "attr", ")", ":", "\"\"\"\n\n Examples\n ----------------------------------------------------------------------------------------------\n\n >>> chord = ChordDiagram()\n >>> chord.add_edge('A','B', edgeAB_prop1=1, edgeAB_prop2=2)\n >>> chord._edges\n {('A', 'B'): {'edgeAB_prop1': 1, 'edgeAB_prop2': 2}}\n\n\n \"\"\"", "u", ",", "v", "=", "sorted", "(", "[", "u", ",", "v", "]", ")", "edge", "=", "(", "u", ",", "v", ")", "if", "edge", "in", "self", ".", "_edges", ":", "self", ".", "_edges", "[", "edge", "]", "=", "{", "**", "self", ".", "_edges", "[", "edge", "]", ",", "**", "attr", "}", "else", ":", "self", ".", "_edges", "[", "edge", "]", "=", "attr", "def", "add_edges_from", "(", "self", ",", "edges_to_add", ",", "**", "attr", ")", ":", "\"\"\"\n\n Examples\n ----------------------------------------------------------------------------------------------\n\n >>> chord = ChordDiagram()\n >>> chord.add_edges_from([(2, 3, {'linewidth': 1}), (3, 4), (5, 4)], linewidth=20)\n >>> chord._edges\n {(2, 3): {'linewidth': 1}, (3, 4): {'linewidth': 20}, (4, 5): {'linewidth': 20}}\n\n \"\"\"", "for", "e", "in", "edges_to_add", ":", "if", "len", "(", "e", ")", "==", "3", ":", "u", ",", "v", ",", "d", "=", "e", "else", ":", "u", ",", "v", "=", "e", "d", "=", "{", "}", "u", ",", "v", "=", "sorted", "(", "[", "e", "[", "0", "]", ",", "e", "[", "1", "]", "]", ")", "d", "=", "{", "**", "attr", ",", "**", "d", "}", "self", ".", "add_edge", "(", "u", ",", "v", ",", "**", "d", ")", "def", "get_node_data", "(", "self", ",", "node", ",", "**", "default", ")", ":", "\"\"\"\n\n\n Examples\n ----------------------------------------------------------------------------------------------\n\n \"\"\"", "if", "node", "not", "in", "self", ".", "_nodes", ":", "return", "default", "else", ":", "return", "{", "**", "default", ",", "**", "self", ".", "_nodes", "[", "node", "]", "}", "def", "get_edge_data", "(", "self", ",", "u", ",", "v", ",", "**", "default", ")", ":", "\"\"\"\n\n Examples\n ----------------------------------------------------------------------------------------------\n\n \"\"\"", "u", ",", "v", "=", "sorted", "(", "[", "u", ",", "v", "]", ")", "key", "=", "(", "u", ",", "v", ")", "if", "key", "not", "in", "self", ".", "_edges", ":", "return", "default", "else", ":", "return", "{", "**", "default", ",", "**", "self", ".", "_edges", "[", "key", "]", "}", "def", "plot", "(", "self", ",", "figsize", "=", "(", "7", ",", "7", ")", ",", "R", "=", "3", ",", "dist", "=", "0.2", ",", "n_bezier", "=", "100", ",", "**", "text_attr", ")", ":", "\"\"\"Plots the diagram\"\"\"", "def", "compute_node_properties", "(", ")", ":", "n_nodes", "=", "len", "(", "self", ".", "_nodes", ")", "theta", "=", "np", ".", "linspace", "(", "0.0", ",", "2", "*", "np", ".", "pi", ",", "n_nodes", ",", "endpoint", "=", "False", ")", "node_x", "=", "[", "R", "*", "np", ".", "cos", "(", "t", ")", "for", "t", "in", "theta", "]", "node_y", "=", "[", "R", "*", "np", ".", "sin", "(", "t", ")", "for", "t", "in", "theta", "]", "label_x", "=", "[", "(", "R", "+", "dist", ")", "*", "np", ".", "cos", "(", "t", ")", "for", "t", "in", "theta", "]", "label_y", "=", "[", "(", "R", "+", "dist", ")", "*", "np", ".", "sin", "(", "t", ")", "for", "t", "in", "theta", "]", "rotation", "=", "[", "t", "/", "(", "2", "*", "np", ".", "pi", ")", "*", "360", "for", "t", "in", "theta", "]", "rotation", "=", "[", "t", "-", "180", "if", "t", ">", "180", "else", "t", "for", "t", "in", "rotation", "]", "rotation", "=", "[", "t", "-", "180", "if", "t", ">", "90", "else", "t", "for", "t", "in", "rotation", "]", "ha", "=", "[", "\"left\"", "if", "xt", ">=", "0", "else", "\"right\"", "for", "xt", "in", "label_x", "]", "return", "dict", "(", "theta", "=", "{", "n", ":", "p", "for", "n", ",", "p", "in", "zip", "(", "self", ".", "_nodes", ".", "keys", "(", ")", ",", "theta", ")", "}", ",", "node_x", "=", "{", "n", ":", "p", "for", "n", ",", "p", "in", "zip", "(", "self", ".", "_nodes", ".", "keys", "(", ")", ",", "node_x", ")", "}", ",", "node_y", "=", "{", "n", ":", "p", "for", "n", ",", "p", "in", "zip", "(", "self", ".", "_nodes", ".", "keys", "(", ")", ",", "node_y", ")", "}", ",", "label_x", "=", "{", "n", ":", "p", "for", "n", ",", "p", "in", "zip", "(", "self", ".", "_nodes", ".", "keys", "(", ")", ",", "label_x", ")", "}", ",", "label_y", "=", "{", "n", ":", "p", "for", "n", ",", "p", "in", "zip", "(", "self", ".", "_nodes", ".", "keys", "(", ")", ",", "label_y", ")", "}", ",", "rotation", "=", "{", "n", ":", "p", "for", "n", ",", "p", "in", "zip", "(", "self", ".", "_nodes", ".", "keys", "(", ")", ",", "rotation", ")", "}", ",", "ha", "=", "{", "n", ":", "p", "for", "n", ",", "p", "in", "zip", "(", "self", ".", "_nodes", ".", "keys", "(", ")", ",", "ha", ")", "}", ",", "s", "=", "{", "n", ":", "p", "for", "n", ",", "p", "in", "zip", "(", "self", ".", "_nodes", ".", "keys", "(", ")", ",", "ha", ")", "}", ",", ")", "def", "draw_points", "(", ")", ":", "\"\"\"Draws node and label.\"\"\"", "for", "node", "in", "self", ".", "_nodes", ":", "x", "=", "node_properties", "[", "\"node_x\"", "]", "[", "node", "]", "y", "=", "node_properties", "[", "\"node_y\"", "]", "[", "node", "]", "ax", ".", "scatter", "(", "x", ",", "y", ",", "zorder", "=", "10", ",", "edgecolors", "=", "\"k\"", ",", "linewidths", "=", "0.5", ",", "**", "self", ".", "get_node_data", "(", "node", ")", ",", ")", "for", "label", "in", "self", ".", "_nodes", ":", "x", "=", "node_properties", "[", "\"label_x\"", "]", "[", "label", "]", "y", "=", "node_properties", "[", "\"label_y\"", "]", "[", "label", "]", "rotation", "=", "node_properties", "[", "\"rotation\"", "]", "[", "label", "]", "ha", "=", "node_properties", "[", "\"ha\"", "]", "[", "label", "]", "attr", "=", "{", "**", "dict", "(", "backgroundcolor", "=", "\"white\"", ")", ",", "**", "text_attr", "}", "ax", ".", "text", "(", "x", ",", "y", ",", "textwrap", ".", "shorten", "(", "text", "=", "label", ",", "width", "=", "TEXTLEN", ")", ",", "rotation", "=", "rotation", ",", "ha", "=", "ha", ",", "va", "=", "\"center\"", ",", "rotation_mode", "=", "\"anchor\"", ",", "bbox", "=", "dict", "(", "facecolor", "=", "\"w\"", ",", "alpha", "=", "1.0", ",", "edgecolor", "=", "\"gray\"", ",", "boxstyle", "=", "\"round,pad=0.5\"", ",", ")", ",", "fontsize", "=", "7", ",", "zorder", "=", "11", ",", "**", "attr", ",", ")", "def", "draw_edges", "(", ")", ":", "\"\"\"Draws edges on the plot.\"\"\"", "def", "bezier", "(", "p0", ",", "p1", ",", "p2", ",", "**", "kwargs", ")", ":", "x0", ",", "y0", "=", "p0", "x1", ",", "y1", "=", "p1", "x2", ",", "y2", "=", "p2", "xb", "=", "[", "(", "1", "-", "t", ")", "**", "2", "*", "x0", "+", "2", "*", "t", "*", "(", "1", "-", "t", ")", "*", "x1", "+", "t", "**", "2", "*", "x2", "for", "t", "in", "np", ".", "linspace", "(", "0.0", ",", "1.0", ",", "n_bezier", ")", "]", "yb", "=", "[", "(", "1", "-", "t", ")", "**", "2", "*", "y0", "+", "2", "*", "t", "*", "(", "1", "-", "t", ")", "*", "y1", "+", "t", "**", "2", "*", "y2", "for", "t", "in", "np", ".", "linspace", "(", "0.0", ",", "1.0", ",", "n_bezier", ")", "]", "ax", ".", "plot", "(", "xb", ",", "yb", ",", "**", "kwargs", ")", "for", "edge", "in", "self", ".", "_edges", ":", "u", ",", "v", "=", "edge", "x0", ",", "y0", ",", "a0", "=", "(", "node_properties", "[", "\"node_x\"", "]", "[", "u", "]", ",", "node_properties", "[", "\"node_y\"", "]", "[", "u", "]", ",", "node_properties", "[", "\"theta\"", "]", "[", "u", "]", ",", ")", "x2", ",", "y2", ",", "a2", "=", "(", "node_properties", "[", "\"node_x\"", "]", "[", "v", "]", ",", "node_properties", "[", "\"node_y\"", "]", "[", "v", "]", ",", "node_properties", "[", "\"theta\"", "]", "[", "v", "]", ",", ")", "angle", "=", "a0", "+", "(", "a2", "-", "a0", ")", "/", "2", "distance", "=", "np", ".", "abs", "(", "a2", "-", "a0", ")", "if", "distance", ">", "np", ".", "pi", ":", "distance", "=", "distance", "-", "np", ".", "pi", "distance", "=", "(", "1.0", "-", "1.0", "*", "distance", "/", "np", ".", "pi", ")", "*", "R", "/", "2.5", "x1", "=", "distance", "*", "np", ".", "cos", "(", "angle", ")", "y1", "=", "distance", "*", "np", ".", "sin", "(", "angle", ")", "x1", "=", "0", "y1", "=", "0", "bezier", "(", "[", "x0", ",", "y0", "]", ",", "[", "x1", ",", "y1", "]", ",", "[", "x2", ",", "y2", "]", ",", "**", "self", ".", "_edges", "[", "edge", "]", ",", ")", "fig", "=", "pyplot", ".", "Figure", "(", "figsize", "=", "figsize", ")", "ax", "=", "fig", ".", "subplots", "(", ")", "node_properties", "=", "compute_node_properties", "(", ")", "draw_points", "(", ")", "draw_edges", "(", ")", "xlim", "=", "ax", ".", "get_xlim", "(", ")", "ylim", "=", "ax", ".", "get_ylim", "(", ")", "dx", "=", "0.15", "*", "(", "xlim", "[", "1", "]", "-", "xlim", "[", "0", "]", ")", "dy", "=", "0.15", "*", "(", "ylim", "[", "1", "]", "-", "ylim", "[", "0", "]", ")", "ax", ".", "set_xlim", "(", "xlim", "[", "0", "]", "-", "dx", ",", "xlim", "[", "1", "]", "+", "dx", ")", "ax", ".", "set_ylim", "(", "ylim", "[", "0", "]", "-", "dy", ",", "ylim", "[", "1", "]", "+", "dy", ")", "ax", ".", "set_axis_off", "(", ")", "ax", ".", "set_aspect", "(", "\"equal\"", ")", "fig", ".", "set_tight_layout", "(", "True", ")", "return", "fig" ]
Class for plotting chord diagrams.
[ "Class", "for", "plotting", "chord", "diagrams", "." ]
[ "\"\"\"Class for plotting chord diagrams.\n\n\n Examples\n ----------------------------------------------------------------------------------------------\n\n >>> chord = ChordDiagram()\n >>> chord.add_nodes_from('abcdef', color='black', s=10)\n >>> chord.add_edge('a', 'b')\n >>> chord.add_edges_from([('a', 'b'), ('c', 'd'), ('e', 'f')])\n >>> _ = pyplot.figure(figsize=(6, 6))\n >>> _ = chord.plot(R=1, dist=0.05, fontsize=20, color='red')\n >>> pyplot.savefig('sphinx/images/chord_demo_1.png')\n\n .. image:: images/chord_demo_1.png\n :width: 700px\n :align: center\n\n >>> chord = ChordDiagram()\n >>> chord.add_nodes_from('abcd', color='black', s=20)\n >>> chord.add_node('e', s=100, color='black')\n >>> chord.add_node('g', s=200, color='black')\n >>> chord.add_edge('a', 'b', linestyle=':', color='red')\n >>> _ = pyplot.figure(figsize=(6, 6))\n >>> _ = chord.plot(R=1, dist=0.05, fontsize=20, color='red')\n >>> pyplot.savefig('sphinx/images/chord_demo_2.png')\n\n .. image:: images/chord_demo_2.png\n :width: 700px\n :align: center\n\n\n \"\"\"", "\"\"\"\n\n Examples\n ----------------------------------------------------------------------------------------------\n\n\n >>> chord = ChordDiagram()\n >>> chord.add_node('A', nodeA_prop=1)\n >>> chord.add_node('B', nodeB_prop=2)\n >>> chord._nodes\n {'A': {'nodeA_prop': 1}, 'B': {'nodeB_prop': 2}}\n\n >>> chord.add_node('C', nodeC_prop1=10, nodeC_prop2=20)\n\n \"\"\"", "\"\"\"\n\n Examples\n ----------------------------------------------------------------------------------------------\n\n >>> chord = ChordDiagram()\n >>> chord.add_nodes_from('abcde')\n >>> chord._nodes\n {'a': {}, 'b': {}, 'c': {}, 'd': {}, 'e': {}}\n\n >>> chord = ChordDiagram()\n >>> chord.add_nodes_from('abc', linewidth=1)\n >>> chord._nodes\n {'a': {'linewidth': 1}, 'b': {'linewidth': 1}, 'c': {'linewidth': 1}}\n\n >>> chord = ChordDiagram()\n >>> chord.add_nodes_from( [('a', dict(linewidth=1)), ('b', {'linewidth':2}), ('c',{}) ], linewidth=10)\n >>> chord._nodes\n {'a': {'linewidth': 1}, 'b': {'linewidth': 2}, 'c': {'linewidth': 10}}\n\n \"\"\"", "\"\"\"\n\n Examples\n ----------------------------------------------------------------------------------------------\n\n >>> chord = ChordDiagram()\n >>> chord.add_edge('A','B', edgeAB_prop1=1, edgeAB_prop2=2)\n >>> chord._edges\n {('A', 'B'): {'edgeAB_prop1': 1, 'edgeAB_prop2': 2}}\n\n\n \"\"\"", "\"\"\"\n\n Examples\n ----------------------------------------------------------------------------------------------\n\n >>> chord = ChordDiagram()\n >>> chord.add_edges_from([(2, 3, {'linewidth': 1}), (3, 4), (5, 4)], linewidth=20)\n >>> chord._edges\n {(2, 3): {'linewidth': 1}, (3, 4): {'linewidth': 20}, (4, 5): {'linewidth': 20}}\n\n \"\"\"", "\"\"\"\n\n\n Examples\n ----------------------------------------------------------------------------------------------\n\n \"\"\"", "\"\"\"\n\n Examples\n ----------------------------------------------------------------------------------------------\n\n \"\"\"", "\"\"\"Plots the diagram\"\"\"", "\"\"\"Draws node and label.\"\"\"", "\"\"\"Draws edges on the plot.\"\"\"", "# if angle > np.pi:", "# angle_corr = angle - np.pi", "# else:", "# angle_corr = angle", "## dibuja los arcos", "#", "# Figure size", "#" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
18
2,493
319
2b2e735b477891afaadc309a5751b32d4cdb94f0
framaz/AsyncSiteParser
phf/abstracthook.py
[ "MIT" ]
Python
AbstractHook
Base hook class for all other hooks. To make a hook, user should inherit this class and override async method hook_action(self, data). It can be created manually before the start of PHFSystem work and connected to a provider or it can be created dynamically with help AbstractCommandInput's inhabitants. To make dynamical creation of hooks, they can have aliases set in _alias as a list of string. Class attributes: _alias: List of strings, alases for the class. Attributes: _asyncio_queue: asyncio.Queue obj to transport data from provider to hook. _callback_queue: asyncio.Queue obj to transport data from hook to provider. _provider: provider.AbstractContentProvider obj, hooks target. Example: Creating a simple MyHook class with some aliases that prints "MyHook!" every time provider sends it data and returns "MyHook!". class MyHook: _alias = ["my_hook", "MYHOOK", "MH"] async def hook_action(self, data): print("MyHook!") return "MyHook!
Base hook class for all other hooks. To make a hook, user should inherit this class and override async method hook_action(self, data). It can be created manually before the start of PHFSystem work and connected to a provider or it can be created dynamically with help AbstractCommandInput's inhabitants. To make dynamical creation of hooks, they can have aliases set in _alias as a list of string. Class attributes: _alias: List of strings, alases for the class.
[ "Base", "hook", "class", "for", "all", "other", "hooks", ".", "To", "make", "a", "hook", "user", "should", "inherit", "this", "class", "and", "override", "async", "method", "hook_action", "(", "self", "data", ")", ".", "It", "can", "be", "created", "manually", "before", "the", "start", "of", "PHFSystem", "work", "and", "connected", "to", "a", "provider", "or", "it", "can", "be", "created", "dynamically", "with", "help", "AbstractCommandInput", "'", "s", "inhabitants", ".", "To", "make", "dynamical", "creation", "of", "hooks", "they", "can", "have", "aliases", "set", "in", "_alias", "as", "a", "list", "of", "string", ".", "Class", "attributes", ":", "_alias", ":", "List", "of", "strings", "alases", "for", "the", "class", "." ]
class AbstractHook: """Base hook class for all other hooks. To make a hook, user should inherit this class and override async method hook_action(self, data). It can be created manually before the start of PHFSystem work and connected to a provider or it can be created dynamically with help AbstractCommandInput's inhabitants. To make dynamical creation of hooks, they can have aliases set in _alias as a list of string. Class attributes: _alias: List of strings, alases for the class. Attributes: _asyncio_queue: asyncio.Queue obj to transport data from provider to hook. _callback_queue: asyncio.Queue obj to transport data from hook to provider. _provider: provider.AbstractContentProvider obj, hooks target. Example: Creating a simple MyHook class with some aliases that prints "MyHook!" every time provider sends it data and returns "MyHook!". class MyHook: _alias = ["my_hook", "MYHOOK", "MH"] async def hook_action(self, data): print("MyHook!") return "MyHook! """ _alias = [] def __new__(cls, *args, **kwargs): obj = object.__new__(cls) obj._asyncio_queue = None obj._callback_queue = None obj._provider = None obj._running = False return obj def __init__(self, *args, **kwargs): pass def get_straight_queue(self) -> asyncio.Queue: """Create if not created and return provider -> hook queue. Returns: Queue to transfer data from provider to hook's action. """ if self._asyncio_queue is None: self._asyncio_queue = asyncio.Queue() return self._asyncio_queue def get_callback_queue(self) -> asyncio.Queue: """Create if not created and return hook -> provider queue. Returns: queue to transfer data returned by hook's action to provider """ if self._callback_queue is None: self._callback_queue = asyncio.Queue() return self._callback_queue def _is_running(self) -> bool: """Returns whether hook is running now""" return self._running # TODO better stop def stop(self) -> None: """Stops the hook.""" self._running = False self.get_straight_queue().put_nowait(asyncio.CancelledError()) async def cycle_call(self) -> None: """Make hook start doing its work. In a cycle hook gets data from provider, executes hook_action and sends it's result to provider. Can be stopped. """ self._running = True while self._is_running(): target = await self.get_straight_queue().get() if isinstance(target, asyncio.CancelledError): break result = await self.hook_action(target) self.get_callback_queue().put_nowait(result) async def hook_action(self, data: typing.Any) -> typing.Any: """Do hook action on the data provided by provider. User has to override it in subclasses. This method specifies what exactly the hook does. It may return some resulting data which will be sent to provider's result_callback(self, results) method as an element of results list. Args: data: data received from provider. Returns: Any data you want to be sent to provider. """ raise NotImplementedError(f"hook_action of {self.__class__} not overridden") @classmethod def get_aliases(cls) -> typing.List[str]: """Returns a copy of aliases list. Returns: list of class's aliases. """ return copy.deepcopy(cls._alias)
[ "class", "AbstractHook", ":", "_alias", "=", "[", "]", "def", "__new__", "(", "cls", ",", "*", "args", ",", "**", "kwargs", ")", ":", "obj", "=", "object", ".", "__new__", "(", "cls", ")", "obj", ".", "_asyncio_queue", "=", "None", "obj", ".", "_callback_queue", "=", "None", "obj", ".", "_provider", "=", "None", "obj", ".", "_running", "=", "False", "return", "obj", "def", "__init__", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "pass", "def", "get_straight_queue", "(", "self", ")", "->", "asyncio", ".", "Queue", ":", "\"\"\"Create if not created and return provider -> hook queue.\n\n Returns:\n Queue to transfer data from provider to hook's action.\n \"\"\"", "if", "self", ".", "_asyncio_queue", "is", "None", ":", "self", ".", "_asyncio_queue", "=", "asyncio", ".", "Queue", "(", ")", "return", "self", ".", "_asyncio_queue", "def", "get_callback_queue", "(", "self", ")", "->", "asyncio", ".", "Queue", ":", "\"\"\"Create if not created and return hook -> provider queue.\n\n Returns:\n queue to transfer data returned by hook's action to provider\n \"\"\"", "if", "self", ".", "_callback_queue", "is", "None", ":", "self", ".", "_callback_queue", "=", "asyncio", ".", "Queue", "(", ")", "return", "self", ".", "_callback_queue", "def", "_is_running", "(", "self", ")", "->", "bool", ":", "\"\"\"Returns whether hook is running now\"\"\"", "return", "self", ".", "_running", "def", "stop", "(", "self", ")", "->", "None", ":", "\"\"\"Stops the hook.\"\"\"", "self", ".", "_running", "=", "False", "self", ".", "get_straight_queue", "(", ")", ".", "put_nowait", "(", "asyncio", ".", "CancelledError", "(", ")", ")", "async", "def", "cycle_call", "(", "self", ")", "->", "None", ":", "\"\"\"Make hook start doing its work.\n\n In a cycle hook gets data from provider, executes hook_action and sends it's result\n to provider.\n Can be stopped.\n \"\"\"", "self", ".", "_running", "=", "True", "while", "self", ".", "_is_running", "(", ")", ":", "target", "=", "await", "self", ".", "get_straight_queue", "(", ")", ".", "get", "(", ")", "if", "isinstance", "(", "target", ",", "asyncio", ".", "CancelledError", ")", ":", "break", "result", "=", "await", "self", ".", "hook_action", "(", "target", ")", "self", ".", "get_callback_queue", "(", ")", ".", "put_nowait", "(", "result", ")", "async", "def", "hook_action", "(", "self", ",", "data", ":", "typing", ".", "Any", ")", "->", "typing", ".", "Any", ":", "\"\"\"Do hook action on the data provided by provider.\n\n User has to override it in subclasses.\n This method specifies what exactly the hook does. It may return some resulting data\n which will be sent to provider's result_callback(self, results) method as an element\n of results list.\n\n Args:\n data: data received from provider.\n\n Returns:\n Any data you want to be sent to provider.\n\n \"\"\"", "raise", "NotImplementedError", "(", "f\"hook_action of {self.__class__} not overridden\"", ")", "@", "classmethod", "def", "get_aliases", "(", "cls", ")", "->", "typing", ".", "List", "[", "str", "]", ":", "\"\"\"Returns a copy of aliases list.\n\n Returns:\n list of class's aliases.\n \"\"\"", "return", "copy", ".", "deepcopy", "(", "cls", ".", "_alias", ")" ]
Base hook class for all other hooks.
[ "Base", "hook", "class", "for", "all", "other", "hooks", "." ]
[ "\"\"\"Base hook class for all other hooks.\n\n To make a hook, user should inherit this class and override async method hook_action(self, data).\n\n It can be created manually before the start of PHFSystem work and connected to a provider\n or it can be created dynamically with help AbstractCommandInput's inhabitants.\n To make dynamical creation of hooks, they can have aliases set in _alias as a list of string.\n\n Class attributes:\n _alias: List of strings, alases for the class.\n\n Attributes:\n _asyncio_queue: asyncio.Queue obj to transport data from provider to hook.\n _callback_queue: asyncio.Queue obj to transport data from hook to provider.\n _provider: provider.AbstractContentProvider obj, hooks target.\n\n Example:\n Creating a simple MyHook class with some aliases that prints \"MyHook!\" every\n time provider sends it data and returns \"MyHook!\".\n\n class MyHook:\n _alias = [\"my_hook\", \"MYHOOK\", \"MH\"]\n\n async def hook_action(self, data):\n print(\"MyHook!\")\n return \"MyHook!\n \"\"\"", "\"\"\"Create if not created and return provider -> hook queue.\n\n Returns:\n Queue to transfer data from provider to hook's action.\n \"\"\"", "\"\"\"Create if not created and return hook -> provider queue.\n\n Returns:\n queue to transfer data returned by hook's action to provider\n \"\"\"", "\"\"\"Returns whether hook is running now\"\"\"", "# TODO better stop", "\"\"\"Stops the hook.\"\"\"", "\"\"\"Make hook start doing its work.\n\n In a cycle hook gets data from provider, executes hook_action and sends it's result\n to provider.\n Can be stopped.\n \"\"\"", "\"\"\"Do hook action on the data provided by provider.\n\n User has to override it in subclasses.\n This method specifies what exactly the hook does. It may return some resulting data\n which will be sent to provider's result_callback(self, results) method as an element\n of results list.\n\n Args:\n data: data received from provider.\n\n Returns:\n Any data you want to be sent to provider.\n\n \"\"\"", "\"\"\"Returns a copy of aliases list.\n\n Returns:\n list of class's aliases.\n \"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [ { "identifier": "_asyncio_queue", "type": null, "docstring": "asyncio.Queue obj to transport data from provider to hook.", "docstring_tokens": [ "asyncio", ".", "Queue", "obj", "to", "transport", "data", "from", "provider", "to", "hook", "." ], "default": null, "is_optional": null }, { "identifier": "_callback_queue", "type": null, "docstring": "asyncio.Queue obj to transport data from hook to provider.", "docstring_tokens": [ "asyncio", ".", "Queue", "obj", "to", "transport", "data", "from", "hook", "to", "provider", "." ], "default": null, "is_optional": null }, { "identifier": "_provider", "type": null, "docstring": "provider.AbstractContentProvider obj, hooks target.", "docstring_tokens": [ "provider", ".", "AbstractContentProvider", "obj", "hooks", "target", "." ], "default": null, "is_optional": null } ], "others": [ { "identifier": "examples", "docstring": "Creating a simple MyHook class with some aliases that prints \"MyHook!\" every\ntime provider sends it data and returns \"MyHook!\".\n\nclass MyHook:\n_alias = [\"my_hook\", \"MYHOOK\", \"MH\"]\n\nasync def hook_action(self, data):\nprint(\"MyHook!\")\nreturn \"MyHook!", "docstring_tokens": [ "Creating", "a", "simple", "MyHook", "class", "with", "some", "aliases", "that", "prints", "\"", "MyHook!", "\"", "every", "time", "provider", "sends", "it", "data", "and", "returns", "\"", "MyHook!", "\"", ".", "class", "MyHook", ":", "_alias", "=", "[", "\"", "my_hook", "\"", "\"", "MYHOOK", "\"", "\"", "MH", "\"", "]", "async", "def", "hook_action", "(", "self", "data", ")", ":", "print", "(", "\"", "MyHook!", "\"", ")", "return", "\"", "MyHook!" ] } ] }
false
14
796
230
80f2dd109f71bd842a2ec36ff04a0bf62d07ad45
CslaGenFork/CslaGenFork
trunk/CoverageTest/TestProject/CS/TestProject.Business/DocRO.Designer.cs
[ "MIT" ]
C#
DocRO
/// <summary> /// Documents (read only object).<br/> /// This is a generated <see cref="DocRO"/> business object. /// This class is a root object. /// </summary> /// <remarks> /// This class contains one child collection:<br/> /// - <see cref="Folders"/> of type <see cref="DocFolderCollRO"/> (1:M relation to <see cref="DocFolderRO"/>) /// This is a remark /// </remarks>
Documents (read only object). This is a generated business object. This class is a root object.
[ "Documents", "(", "read", "only", "object", ")", ".", "This", "is", "a", "generated", "business", "object", ".", "This", "class", "is", "a", "root", "object", "." ]
[Attributable] [Serializable] public partial class DocRO : ReadOnlyBase<DocRO>, IHaveInterface { #region Business Properties public static readonly PropertyInfo<int> DocIDProperty = RegisterProperty<int>(p => p.DocID, "Doc ID", -1); public int DocID { get { return GetProperty(DocIDProperty); } } public static readonly PropertyInfo<int> DocTypeIDProperty = RegisterProperty<int>(p => p.DocTypeID, "Doc Type ID"); public int DocTypeID { get { return GetProperty(DocTypeIDProperty); } } public static readonly PropertyInfo<string> DocRefProperty = RegisterProperty<string>(p => p.DocRef, "Doc Ref", null); public string DocRef { get { return GetProperty(DocRefProperty); } } public static readonly PropertyInfo<SmartDate> DocDateProperty = RegisterProperty<SmartDate>(p => p.DocDate, "Doc Date"); public string DocDate { get { return GetPropertyConvert<SmartDate, string>(DocDateProperty); } } public static readonly PropertyInfo<string> SubjectProperty = RegisterProperty<string>(p => p.Subject, "Subject"); public string Subject { get { return GetProperty(SubjectProperty); } } public static readonly PropertyInfo<DocFolderCollRO> FoldersProperty = RegisterProperty<DocFolderCollRO>(p => p.Folders, "Folders"); public DocFolderCollRO Folders { get { return GetProperty(FoldersProperty); } private set { LoadProperty(FoldersProperty, value); } } #endregion #region Factory Methods public static DocRO GetDocRO(int docID) { return DataPortal.Fetch<DocRO>(docID); } #endregion #region Constructor [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public DocRO() { } #endregion #region Data Access protected void DataPortal_Fetch(int docID) { using (var ctx = ConnectionManager<SqlConnection>.GetManager(Database.TestProjectConnection, false)) { using (var cmd = new SqlCommand("GetDocRO", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@DocID", docID).DbType = DbType.Int32; var args = new DataPortalHookArgs(cmd, docID); OnFetchPre(args); Fetch(cmd); OnFetchPost(args); } } BusinessRules.CheckRules(); } private void Fetch(SqlCommand cmd) { using (var dr = new SafeDataReader(cmd.ExecuteReader())) { if (dr.Read()) { Fetch(dr); FetchChildren(dr); } } } private void Fetch(SafeDataReader dr) { LoadProperty(DocIDProperty, dr.GetInt32("DocID")); LoadProperty(DocTypeIDProperty, dr.GetInt32("DocTypeID")); LoadProperty(DocRefProperty, dr.IsDBNull("DocRef") ? null : dr.GetString("DocRef")); LoadProperty(DocDateProperty, dr.GetSmartDate("DocDate", true)); LoadProperty(SubjectProperty, dr.GetString("Subject")); var args = new DataPortalHookArgs(dr); OnFetchRead(args); } private void FetchChildren(SafeDataReader dr) { dr.NextResult(); LoadProperty(FoldersProperty, DataPortal.FetchChild<DocFolderCollRO>(dr)); } #endregion #region DataPortal Hooks partial void OnFetchPre(DataPortalHookArgs args); partial void OnFetchPost(DataPortalHookArgs args); partial void OnFetchRead(DataPortalHookArgs args); #endregion }
[ "[", "Attributable", "]", "[", "Serializable", "]", "public", "partial", "class", "DocRO", ":", "ReadOnlyBase", "<", "DocRO", ">", ",", "IHaveInterface", "{", "region", " Business Properties", "public", "static", "readonly", "PropertyInfo", "<", "int", ">", "DocIDProperty", "=", "RegisterProperty", "<", "int", ">", "(", "p", "=>", "p", ".", "DocID", ",", "\"", "Doc ID", "\"", ",", "-", "1", ")", ";", "public", "int", "DocID", "{", "get", "{", "return", "GetProperty", "(", "DocIDProperty", ")", ";", "}", "}", "public", "static", "readonly", "PropertyInfo", "<", "int", ">", "DocTypeIDProperty", "=", "RegisterProperty", "<", "int", ">", "(", "p", "=>", "p", ".", "DocTypeID", ",", "\"", "Doc Type ID", "\"", ")", ";", "public", "int", "DocTypeID", "{", "get", "{", "return", "GetProperty", "(", "DocTypeIDProperty", ")", ";", "}", "}", "public", "static", "readonly", "PropertyInfo", "<", "string", ">", "DocRefProperty", "=", "RegisterProperty", "<", "string", ">", "(", "p", "=>", "p", ".", "DocRef", ",", "\"", "Doc Ref", "\"", ",", "null", ")", ";", "public", "string", "DocRef", "{", "get", "{", "return", "GetProperty", "(", "DocRefProperty", ")", ";", "}", "}", "public", "static", "readonly", "PropertyInfo", "<", "SmartDate", ">", "DocDateProperty", "=", "RegisterProperty", "<", "SmartDate", ">", "(", "p", "=>", "p", ".", "DocDate", ",", "\"", "Doc Date", "\"", ")", ";", "public", "string", "DocDate", "{", "get", "{", "return", "GetPropertyConvert", "<", "SmartDate", ",", "string", ">", "(", "DocDateProperty", ")", ";", "}", "}", "public", "static", "readonly", "PropertyInfo", "<", "string", ">", "SubjectProperty", "=", "RegisterProperty", "<", "string", ">", "(", "p", "=>", "p", ".", "Subject", ",", "\"", "Subject", "\"", ")", ";", "public", "string", "Subject", "{", "get", "{", "return", "GetProperty", "(", "SubjectProperty", ")", ";", "}", "}", "public", "static", "readonly", "PropertyInfo", "<", "DocFolderCollRO", ">", "FoldersProperty", "=", "RegisterProperty", "<", "DocFolderCollRO", ">", "(", "p", "=>", "p", ".", "Folders", ",", "\"", "Folders", "\"", ")", ";", "public", "DocFolderCollRO", "Folders", "{", "get", "{", "return", "GetProperty", "(", "FoldersProperty", ")", ";", "}", "private", "set", "{", "LoadProperty", "(", "FoldersProperty", ",", "value", ")", ";", "}", "}", "endregion", "region", " Factory Methods", "public", "static", "DocRO", "GetDocRO", "(", "int", "docID", ")", "{", "return", "DataPortal", ".", "Fetch", "<", "DocRO", ">", "(", "docID", ")", ";", "}", "endregion", "region", " Constructor", "[", "System", ".", "ComponentModel", ".", "EditorBrowsable", "(", "System", ".", "ComponentModel", ".", "EditorBrowsableState", ".", "Never", ")", "]", "public", "DocRO", "(", ")", "{", "}", "endregion", "region", " Data Access", "protected", "void", "DataPortal_Fetch", "(", "int", "docID", ")", "{", "using", "(", "var", "ctx", "=", "ConnectionManager", "<", "SqlConnection", ">", ".", "GetManager", "(", "Database", ".", "TestProjectConnection", ",", "false", ")", ")", "{", "using", "(", "var", "cmd", "=", "new", "SqlCommand", "(", "\"", "GetDocRO", "\"", ",", "ctx", ".", "Connection", ")", ")", "{", "cmd", ".", "CommandType", "=", "CommandType", ".", "StoredProcedure", ";", "cmd", ".", "Parameters", ".", "AddWithValue", "(", "\"", "@DocID", "\"", ",", "docID", ")", ".", "DbType", "=", "DbType", ".", "Int32", ";", "var", "args", "=", "new", "DataPortalHookArgs", "(", "cmd", ",", "docID", ")", ";", "OnFetchPre", "(", "args", ")", ";", "Fetch", "(", "cmd", ")", ";", "OnFetchPost", "(", "args", ")", ";", "}", "}", "BusinessRules", ".", "CheckRules", "(", ")", ";", "}", "private", "void", "Fetch", "(", "SqlCommand", "cmd", ")", "{", "using", "(", "var", "dr", "=", "new", "SafeDataReader", "(", "cmd", ".", "ExecuteReader", "(", ")", ")", ")", "{", "if", "(", "dr", ".", "Read", "(", ")", ")", "{", "Fetch", "(", "dr", ")", ";", "FetchChildren", "(", "dr", ")", ";", "}", "}", "}", "private", "void", "Fetch", "(", "SafeDataReader", "dr", ")", "{", "LoadProperty", "(", "DocIDProperty", ",", "dr", ".", "GetInt32", "(", "\"", "DocID", "\"", ")", ")", ";", "LoadProperty", "(", "DocTypeIDProperty", ",", "dr", ".", "GetInt32", "(", "\"", "DocTypeID", "\"", ")", ")", ";", "LoadProperty", "(", "DocRefProperty", ",", "dr", ".", "IsDBNull", "(", "\"", "DocRef", "\"", ")", "?", "null", ":", "dr", ".", "GetString", "(", "\"", "DocRef", "\"", ")", ")", ";", "LoadProperty", "(", "DocDateProperty", ",", "dr", ".", "GetSmartDate", "(", "\"", "DocDate", "\"", ",", "true", ")", ")", ";", "LoadProperty", "(", "SubjectProperty", ",", "dr", ".", "GetString", "(", "\"", "Subject", "\"", ")", ")", ";", "var", "args", "=", "new", "DataPortalHookArgs", "(", "dr", ")", ";", "OnFetchRead", "(", "args", ")", ";", "}", "private", "void", "FetchChildren", "(", "SafeDataReader", "dr", ")", "{", "dr", ".", "NextResult", "(", ")", ";", "LoadProperty", "(", "FoldersProperty", ",", "DataPortal", ".", "FetchChild", "<", "DocFolderCollRO", ">", "(", "dr", ")", ")", ";", "}", "endregion", "region", " DataPortal Hooks", "partial", "void", "OnFetchPre", "(", "DataPortalHookArgs", "args", ")", ";", "partial", "void", "OnFetchPost", "(", "DataPortalHookArgs", "args", ")", ";", "partial", "void", "OnFetchRead", "(", "DataPortalHookArgs", "args", ")", ";", "endregion", "}" ]
Documents (read only object).
[ "Documents", "(", "read", "only", "object", ")", "." ]
[ "/// <summary>", "/// Maintains metadata about <see cref=\"DocID\"/> property.", "/// </summary>", "/// <summary>", "/// Document ID", "/// </summary>", "/// <value>The Doc ID.</value>", "/// <summary>", "/// Maintains metadata about <see cref=\"DocTypeID\"/> property.", "/// </summary>", "/// <summary>", "/// Document Type ID", "/// </summary>", "/// <value>The Doc Type ID.</value>", "/// <summary>", "/// Maintains metadata about <see cref=\"DocRef\"/> property.", "/// </summary>", "/// <summary>", "/// Gets the Doc Ref.", "/// </summary>", "/// <value>The Doc Ref.</value>", "/// <summary>", "/// Maintains metadata about <see cref=\"DocDate\"/> property.", "/// </summary>", "/// <summary>", "/// Gets the Doc Date.", "/// </summary>", "/// <value>The Doc Date.</value>", "/// <summary>", "/// Maintains metadata about <see cref=\"Subject\"/> property.", "/// </summary>", "/// <summary>", "/// Gets the Subject.", "/// </summary>", "/// <value>The Subject.</value>", "/// <summary>", "/// Maintains metadata about child <see cref=\"Folders\"/> property.", "/// </summary>", "/// <summary>", "/// Gets the Folders (\"parent load\" child property).", "/// </summary>", "/// <value>The Folders.</value>", "/// <summary>", "/// Factory method. Loads a <see cref=\"DocRO\"/> object, based on given parameters.", "/// </summary>", "/// <param name=\"docID\">The DocID parameter of the DocRO to fetch.</param>", "/// <returns>A reference to the fetched <see cref=\"DocRO\"/> object.</returns>", "/// <summary>", "/// Initializes a new instance of the <see cref=\"DocRO\"/> class.", "/// </summary>", "/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>", "// Use factory methods and do not use direct creation.", "/// <summary>", "/// Loads a <see cref=\"DocRO\"/> object from the database, based on given criteria.", "/// </summary>", "/// <param name=\"docID\">The Doc ID.</param>", "// check all object rules and property rules", "/// <summary>", "/// Loads a <see cref=\"DocRO\"/> object from the given SafeDataReader.", "/// </summary>", "/// <param name=\"dr\">The SafeDataReader to use.</param>", "// Value properties", "/// <summary>", "/// Loads child objects from the given SafeDataReader.", "/// </summary>", "/// <param name=\"dr\">The SafeDataReader to use.</param>", "/// <summary>", "/// Occurs after setting query parameters and before the fetch operation.", "/// </summary>", "/// <summary>", "/// Occurs after the fetch operation (object or collection is fully loaded and set up).", "/// </summary>", "/// <summary>", "/// Occurs after the low level fetch operation, before the data reader is destroyed.", "/// </summary>" ]
[ { "param": "IHaveInterface", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "IHaveInterface", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [ { "identifier": "remarks", "docstring": "This class contains one child collection:\nof type (1:M relation to )\nThis is a remark", "docstring_tokens": [ "This", "class", "contains", "one", "child", "collection", ":", "of", "type", "(", "1", ":", "M", "relation", "to", ")", "This", "is", "a", "remark" ] } ] }
false
16
800
98
babb780a6f60b39452c2dfaa1899e1e85ca28616
khiem2/quanlyhocsinh
cms_form/Web_CMS/WebMedi/App_GlobalResources/Resource.designer.cs
[ "MIT" ]
C#
Resource
/// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option or rebuild the Visual Studio project.
A strongly-typed resource class, for looking up localized strings, etc.
[ "A", "strongly", "-", "typed", "resource", "class", "for", "looking", "up", "localized", "strings", "etc", "." ]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Web.Application.StronglyTypedResourceProxyBuilder", "10.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resource { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resource() { } [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Resources.Resource", global::System.Reflection.Assembly.Load("App_GlobalResources")); resourceMan = temp; } return resourceMan; } } [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } internal static string AddNewsSuccessful { get { return ResourceManager.GetString("AddNewsSuccessful", resourceCulture); } } internal static string Address { get { return ResourceManager.GetString("Address", resourceCulture); } } internal static string Browsing_Users { get { return ResourceManager.GetString("Browsing_Users", resourceCulture); } } internal static string City { get { return ResourceManager.GetString("City", resourceCulture); } } internal static string Company { get { return ResourceManager.GetString("Company", resourceCulture); } } internal static string ContactSuccess { get { return ResourceManager.GetString("ContactSuccess", resourceCulture); } } internal static string Counter { get { return ResourceManager.GetString("Counter", resourceCulture); } } internal static string Email { get { return ResourceManager.GetString("Email", resourceCulture); } } internal static string Faq { get { return ResourceManager.GetString("Faq", resourceCulture); } } internal static string Fax { get { return ResourceManager.GetString("Fax", resourceCulture); } } internal static string Home { get { return ResourceManager.GetString("Home", resourceCulture); } } internal static string Libraries_Images { get { return ResourceManager.GetString("Libraries_Images", resourceCulture); } } internal static string Name { get { return ResourceManager.GetString("Name", resourceCulture); } } internal static string OtherNews { get { return ResourceManager.GetString("OtherNews", resourceCulture); } } internal static string Refresh { get { return ResourceManager.GetString("Refresh", resourceCulture); } } internal static string register_contact { get { return ResourceManager.GetString("register_contact", resourceCulture); } } internal static string Require { get { return ResourceManager.GetString("Require", resourceCulture); } } internal static string Reset { get { return ResourceManager.GetString("Reset", resourceCulture); } } internal static string Send { get { return ResourceManager.GetString("Send", resourceCulture); } } internal static string Telephone { get { return ResourceManager.GetString("Telephone", resourceCulture); } } internal static string ThanksComment { get { return ResourceManager.GetString("ThanksComment", resourceCulture); } } internal static string Video_Gallery { get { return ResourceManager.GetString("Video_Gallery", resourceCulture); } } internal static string WebLink { get { return ResourceManager.GetString("WebLink", resourceCulture); } } }
[ "[", "global", "::", "System", ".", "CodeDom", ".", "Compiler", ".", "GeneratedCodeAttribute", "(", "\"", "Microsoft.VisualStudio.Web.Application.StronglyTypedResourceProxyBuilder", "\"", ",", "\"", "10.0.0.0", "\"", ")", "]", "[", "global", "::", "System", ".", "Diagnostics", ".", "DebuggerNonUserCodeAttribute", "(", ")", "]", "[", "global", "::", "System", ".", "Runtime", ".", "CompilerServices", ".", "CompilerGeneratedAttribute", "(", ")", "]", "internal", "class", "Resource", "{", "private", "static", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "resourceMan", ";", "private", "static", "global", "::", "System", ".", "Globalization", ".", "CultureInfo", "resourceCulture", ";", "[", "global", "::", "System", ".", "Diagnostics", ".", "CodeAnalysis", ".", "SuppressMessageAttribute", "(", "\"", "Microsoft.Performance", "\"", ",", "\"", "CA1811:AvoidUncalledPrivateCode", "\"", ")", "]", "internal", "Resource", "(", ")", "{", "}", "[", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableAttribute", "(", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableState", ".", "Advanced", ")", "]", "internal", "static", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "ResourceManager", "{", "get", "{", "if", "(", "object", ".", "ReferenceEquals", "(", "resourceMan", ",", "null", ")", ")", "{", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "temp", "=", "new", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "(", "\"", "Resources.Resource", "\"", ",", "global", "::", "System", ".", "Reflection", ".", "Assembly", ".", "Load", "(", "\"", "App_GlobalResources", "\"", ")", ")", ";", "resourceMan", "=", "temp", ";", "}", "return", "resourceMan", ";", "}", "}", "[", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableAttribute", "(", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableState", ".", "Advanced", ")", "]", "internal", "static", "global", "::", "System", ".", "Globalization", ".", "CultureInfo", "Culture", "{", "get", "{", "return", "resourceCulture", ";", "}", "set", "{", "resourceCulture", "=", "value", ";", "}", "}", "internal", "static", "string", "AddNewsSuccessful", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "AddNewsSuccessful", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "Address", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Address", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "Browsing_Users", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Browsing_Users", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "City", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "City", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "Company", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Company", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "ContactSuccess", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "ContactSuccess", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "Counter", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Counter", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "Email", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Email", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "Faq", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Faq", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "Fax", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Fax", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "Home", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Home", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "Libraries_Images", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Libraries_Images", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "Name", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Name", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "OtherNews", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "OtherNews", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "Refresh", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Refresh", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "register_contact", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "register_contact", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "Require", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Require", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "Reset", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Reset", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "Send", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Send", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "Telephone", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Telephone", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "ThanksComment", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "ThanksComment", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "Video_Gallery", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Video_Gallery", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "WebLink", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "WebLink", "\"", ",", "resourceCulture", ")", ";", "}", "}", "}" ]
A strongly-typed resource class, for looking up localized strings, etc.
[ "A", "strongly", "-", "typed", "resource", "class", "for", "looking", "up", "localized", "strings", "etc", "." ]
[ "/// <summary>", "/// Returns the cached ResourceManager instance used by this class.", "/// </summary>", "/// <summary>", "/// Overrides the current thread's CurrentUICulture property for all", "/// resource lookups using this strongly typed resource class.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to AddNewsSuccessful.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Address.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Browsing Users.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to City.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Company.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Thank you for contact me.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Counter.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Email.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Faq.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Fax.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Home.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Image libraries.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Name.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Other News.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Refresh.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Register Contact.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Require.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Reset.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Send.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Telephone.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Thanks Comment.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Video Gallery.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to --- Web Link ---.", "/// </summary>" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
21
827
84
b3c422238986e36698d778ab8368f9ed59760170
ArchOrn/droid4me
library/src/main/java/com/smartnsoft/droid4me/download/DownloadInstructions.java
[ "MIT" ]
Java
AbstractInstructions
/** * An implementation of the {@link Instructions}, which returns the <code>bitmapUid</code> as an URL, and which does not present any temporary nor * local bitmap. * <p> * <p> * Caution: this implementation supposes that the provided {@link View view} is actually an {@link ImageView} in the * {@link DownloadInstructions.AbstractInstructions#onBindBitmap(boolean, View, Bitmap, String, Object)} method. * </p> */
An implementation of the Instructions, which returns the bitmapUid as an URL, and which does not present any temporary nor local bitmap. Caution: this implementation supposes that the provided View view is actually an ImageView in the DownloadInstructions.AbstractInstructions#onBindBitmap(boolean, View, Bitmap, String, Object) method.
[ "An", "implementation", "of", "the", "Instructions", "which", "returns", "the", "bitmapUid", "as", "an", "URL", "and", "which", "does", "not", "present", "any", "temporary", "nor", "local", "bitmap", ".", "Caution", ":", "this", "implementation", "supposes", "that", "the", "provided", "View", "view", "is", "actually", "an", "ImageView", "in", "the", "DownloadInstructions", ".", "AbstractInstructions#onBindBitmap", "(", "boolean", "View", "Bitmap", "String", "Object", ")", "method", "." ]
public static class AbstractInstructions extends SimpleInstructions { @Override public Bitmap hasLocalBitmap(View view, String bitmapUid, Object imageSpecs) { return null; } @Override public void onBindLocalBitmap(View view, Bitmap bitmap, String bitmapUid, Object imageSpecs) { } @Override public String computeUrl(String bitmapUid, Object imageSpecs) { return bitmapUid; } @Override public Bitmap hasTemporaryBitmap(View view, String bitmapUid, Object imageSpecs) { return null; } @Override public void onBindTemporaryBitmap(View view, Bitmap bitmap, String bitmapUid, Object imageSpecs) { } @Override public InputStream downloadInputStream(String bitmapUid, Object imageSpecs, String url) throws IOException { final URL aURL = new URL(url); final URLConnection connection = aURL.openConnection(); connection.connect(); final InputStream inputStream = connection.getInputStream(); return inputStream; } /** * Is responsible for turning the provided input stream into a bitmap representation. * <p> * <p> * The method measures the time taken for the conversion, and logs that duration. The technical part of the method is delegated to the * {@link #convertInputStreamToBitmap(InputStream, String, Object, String)} method. * </p> * * @param inputStream the implementation should not close the input stream, because the caller will {@link InputStream#close()} it (no problem if it is * closed, but this will impact the performance) * @return by default, the returned wrapped {@link Bitmap} will have the device density * @see #convert(InputStream, String, Object, String) */ @Override public DownloadInstructions.BitmapableBitmap convert(InputStream inputStream, String bitmapUid, Object imageSpecs, String url) { final long start = System.currentTimeMillis(); final Bitmap theBitmap = convertInputStreamToBitmap(inputStream, bitmapUid, imageSpecs, url); if (theBitmap != null) { if (CoreBitmapDownloader.IS_DEBUG_TRACE && CoreBitmapDownloader.log.isDebugEnabled()) { final long stop = System.currentTimeMillis(); CoreBitmapDownloader.log.debug("The thread '" + Thread.currentThread().getName() + "' decoded in " + (stop - start) + " ms the bitmap with density " + theBitmap.getDensity() + " relative to the URL '" + url + "'"); } } return theBitmap == null ? null : new BitmapableBitmap(theBitmap); } @Override public void onBitmapReady(boolean allright, View view, Bitmap bitmap, String bitmapUid, Object imageSpecs) { } @Override public boolean onBindBitmap(boolean downloaded, View view, Bitmap bitmap, String bitmapUid, Object imageSpecs) { ((ImageView) (view)).setImageBitmap(bitmap); return true; } @Override public void onBitmapBound(boolean result, View view, String bitmapUid, Object imageSpecs) { } @Override public void onOver(boolean aborted, ViewableView view, String bitmapUid, Object imageSpecs) { } /** * Actually converts the given {@link InputStream} into an Android {@link Bitmap}. * <p> * <p> * The hereby implementation does not perform any scaling. * </p> * * @param inputStream the representation of the {@link Bitmap} to be decoded * @return the decoded {@link Bitmap} if the conversion could be performed properly ; {@code null} otherwise * @see #convert(InputStream, String, Object, String) */ protected Bitmap convertInputStreamToBitmap(InputStream inputStream, String bitmapUid, Object imageSpecs, String url) { final BitmapFactory.Options options = new BitmapFactory.Options(); options.inScaled = false; options.inDither = false; options.inDensity = 0; if (getClass().isAnnotationPresent(BitmapConfigAnnotation.class) == true) { options.inPreferredConfig = getClass().getAnnotation(BitmapConfigAnnotation.class).bitmapConfig(); if (getClass().getAnnotation(BitmapConfigAnnotation.class).bitmapConfig() == Config.RGB_565) { options.inDither = true; } } return BitmapFactory.decodeStream(inputStream, null, options); } }
[ "public", "static", "class", "AbstractInstructions", "extends", "SimpleInstructions", "{", "@", "Override", "public", "Bitmap", "hasLocalBitmap", "(", "View", "view", ",", "String", "bitmapUid", ",", "Object", "imageSpecs", ")", "{", "return", "null", ";", "}", "@", "Override", "public", "void", "onBindLocalBitmap", "(", "View", "view", ",", "Bitmap", "bitmap", ",", "String", "bitmapUid", ",", "Object", "imageSpecs", ")", "{", "}", "@", "Override", "public", "String", "computeUrl", "(", "String", "bitmapUid", ",", "Object", "imageSpecs", ")", "{", "return", "bitmapUid", ";", "}", "@", "Override", "public", "Bitmap", "hasTemporaryBitmap", "(", "View", "view", ",", "String", "bitmapUid", ",", "Object", "imageSpecs", ")", "{", "return", "null", ";", "}", "@", "Override", "public", "void", "onBindTemporaryBitmap", "(", "View", "view", ",", "Bitmap", "bitmap", ",", "String", "bitmapUid", ",", "Object", "imageSpecs", ")", "{", "}", "@", "Override", "public", "InputStream", "downloadInputStream", "(", "String", "bitmapUid", ",", "Object", "imageSpecs", ",", "String", "url", ")", "throws", "IOException", "{", "final", "URL", "aURL", "=", "new", "URL", "(", "url", ")", ";", "final", "URLConnection", "connection", "=", "aURL", ".", "openConnection", "(", ")", ";", "connection", ".", "connect", "(", ")", ";", "final", "InputStream", "inputStream", "=", "connection", ".", "getInputStream", "(", ")", ";", "return", "inputStream", ";", "}", "/**\n * Is responsible for turning the provided input stream into a bitmap representation.\n * <p>\n * <p>\n * The method measures the time taken for the conversion, and logs that duration. The technical part of the method is delegated to the\n * {@link #convertInputStreamToBitmap(InputStream, String, Object, String)} method.\n * </p>\n *\n * @param inputStream the implementation should not close the input stream, because the caller will {@link InputStream#close()} it (no problem if it is\n * closed, but this will impact the performance)\n * @return by default, the returned wrapped {@link Bitmap} will have the device density\n * @see #convert(InputStream, String, Object, String)\n */", "@", "Override", "public", "DownloadInstructions", ".", "BitmapableBitmap", "convert", "(", "InputStream", "inputStream", ",", "String", "bitmapUid", ",", "Object", "imageSpecs", ",", "String", "url", ")", "{", "final", "long", "start", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "final", "Bitmap", "theBitmap", "=", "convertInputStreamToBitmap", "(", "inputStream", ",", "bitmapUid", ",", "imageSpecs", ",", "url", ")", ";", "if", "(", "theBitmap", "!=", "null", ")", "{", "if", "(", "CoreBitmapDownloader", ".", "IS_DEBUG_TRACE", "&&", "CoreBitmapDownloader", ".", "log", ".", "isDebugEnabled", "(", ")", ")", "{", "final", "long", "stop", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "CoreBitmapDownloader", ".", "log", ".", "debug", "(", "\"", "The thread '", "\"", "+", "Thread", ".", "currentThread", "(", ")", ".", "getName", "(", ")", "+", "\"", "' decoded in ", "\"", "+", "(", "stop", "-", "start", ")", "+", "\"", " ms the bitmap with density ", "\"", "+", "theBitmap", ".", "getDensity", "(", ")", "+", "\"", " relative to the URL '", "\"", "+", "url", "+", "\"", "'", "\"", ")", ";", "}", "}", "return", "theBitmap", "==", "null", "?", "null", ":", "new", "BitmapableBitmap", "(", "theBitmap", ")", ";", "}", "@", "Override", "public", "void", "onBitmapReady", "(", "boolean", "allright", ",", "View", "view", ",", "Bitmap", "bitmap", ",", "String", "bitmapUid", ",", "Object", "imageSpecs", ")", "{", "}", "@", "Override", "public", "boolean", "onBindBitmap", "(", "boolean", "downloaded", ",", "View", "view", ",", "Bitmap", "bitmap", ",", "String", "bitmapUid", ",", "Object", "imageSpecs", ")", "{", "(", "(", "ImageView", ")", "(", "view", ")", ")", ".", "setImageBitmap", "(", "bitmap", ")", ";", "return", "true", ";", "}", "@", "Override", "public", "void", "onBitmapBound", "(", "boolean", "result", ",", "View", "view", ",", "String", "bitmapUid", ",", "Object", "imageSpecs", ")", "{", "}", "@", "Override", "public", "void", "onOver", "(", "boolean", "aborted", ",", "ViewableView", "view", ",", "String", "bitmapUid", ",", "Object", "imageSpecs", ")", "{", "}", "/**\n * Actually converts the given {@link InputStream} into an Android {@link Bitmap}.\n * <p>\n * <p>\n * The hereby implementation does not perform any scaling.\n * </p>\n *\n * @param inputStream the representation of the {@link Bitmap} to be decoded\n * @return the decoded {@link Bitmap} if the conversion could be performed properly ; {@code null} otherwise\n * @see #convert(InputStream, String, Object, String)\n */", "protected", "Bitmap", "convertInputStreamToBitmap", "(", "InputStream", "inputStream", ",", "String", "bitmapUid", ",", "Object", "imageSpecs", ",", "String", "url", ")", "{", "final", "BitmapFactory", ".", "Options", "options", "=", "new", "BitmapFactory", ".", "Options", "(", ")", ";", "options", ".", "inScaled", "=", "false", ";", "options", ".", "inDither", "=", "false", ";", "options", ".", "inDensity", "=", "0", ";", "if", "(", "getClass", "(", ")", ".", "isAnnotationPresent", "(", "BitmapConfigAnnotation", ".", "class", ")", "==", "true", ")", "{", "options", ".", "inPreferredConfig", "=", "getClass", "(", ")", ".", "getAnnotation", "(", "BitmapConfigAnnotation", ".", "class", ")", ".", "bitmapConfig", "(", ")", ";", "if", "(", "getClass", "(", ")", ".", "getAnnotation", "(", "BitmapConfigAnnotation", ".", "class", ")", ".", "bitmapConfig", "(", ")", "==", "Config", ".", "RGB_565", ")", "{", "options", ".", "inDither", "=", "true", ";", "}", "}", "return", "BitmapFactory", ".", "decodeStream", "(", "inputStream", ",", "null", ",", "options", ")", ";", "}", "}" ]
An implementation of the {@link Instructions}, which returns the <code>bitmapUid</code> as an URL, and which does not present any temporary nor local bitmap.
[ "An", "implementation", "of", "the", "{", "@link", "Instructions", "}", "which", "returns", "the", "<code", ">", "bitmapUid<", "/", "code", ">", "as", "an", "URL", "and", "which", "does", "not", "present", "any", "temporary", "nor", "local", "bitmap", "." ]
[]
[ { "param": "SimpleInstructions", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "SimpleInstructions", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
23
940
108
f3fd6980833f3891e469ed5dac2acc6aca167e5b
cadet29manikandan/ForMoreReactNative
React Native Swipeview/src/index.js
[ "Apache-2.0" ]
JavaScript
SwipeView
/** * react-native-swipeview * @author rishabhbhatia<[email protected]> * SwipeView can be rendered individually or within a list by passing three child views. * * e.g. <SwipeView renderVisibleContent={() => <Text>Visible Row</Text>} renderLeftView={() => <Text>Left Row</Text>} renderRightView={() => <Text>Right Row</Text>} /> */
react-native-swipeview @author rishabhbhatia SwipeView can be rendered individually or within a list by passing three child views.
[ "react", "-", "native", "-", "swipeview", "@author", "rishabhbhatia", "SwipeView", "can", "be", "rendered", "individually", "or", "within", "a", "list", "by", "passing", "three", "child", "views", "." ]
class SwipeView extends Component { constructor(props) { super(props); this.horizontalSwipeGestureBegan = false; this.horizontalSwipeGestureEnded = false; this.rowItemJustSwiped = false; this.swipeInitialX = null; this.ranPreview = false; this.state = { dimensionsSet: false, hiddenHeight: 0, hiddenWidth: 0, swipingLeft: this.props.swipingLeft, }; this._translateX = new Animated.Value(0); } componentWillMount() { this._panResponder = PanResponder.create({ onMoveShouldSetPanResponder: (e, gs) => this.handleOnMoveShouldSetPanResponder(e, gs), onPanResponderMove: (e, gs) => this.handlePanResponderMove(e, gs), onPanResponderRelease: (e, gs) => this.handlePanResponderEnd(e, gs), onPanResponderTerminate: (e, gs) => this.handlePanResponderEnd(e, gs), onShouldBlockNativeResponder: (_) => false, }); } getPreviewAnimation = (toValue, delay) => { return Animated.timing(this._translateX, { duration: this.props.previewDuration, toValue, delay, }); }; onContentLayout = (e) => { this.setState({ dimensionsSet: !this.props.recalculateHiddenLayout, hiddenHeight: e.nativeEvent.layout.height, hiddenWidth: e.nativeEvent.layout.width, }); if (this.props.previewSwipeDemo && !this.ranPreview) { let { previewOpenValue } = this.props; this.ranPreview = true; this.getPreviewAnimation( previewOpenValue, this.props.previewOpenDelay ).start((_) => { this.getPreviewAnimation(0, this.props.previewCloseDelay).start(); }); } }; handleOnMoveShouldSetPanResponder = (e, gs) => { const { dx } = gs; return Math.abs(dx) > this.props.directionalDistanceChangeThreshold; }; handlePanResponderMove = (e, gestureState) => { const { dx, dy } = gestureState; const absDx = Math.abs(dx); const absDy = Math.abs(dy); if (this.horizontalSwipeGestureEnded) return; if (absDx > this.props.directionalDistanceChangeThreshold) { if (this.swipeInitialX === null) { this.swipeInitialX = this._translateX._value; } if (!this.horizontalSwipeGestureBegan) { this.horizontalSwipeGestureBegan = true; this.props.swipeGestureBegan && this.props.swipeGestureBegan(); } let newDX = this.swipeInitialX + dx; if (this.props.disableSwipeToLeft && newDX < 0) { newDX = 0; } if (this.props.disableSwipeToRight && newDX > 0) { newDX = 0; } this._translateX.setValue(newDX); let toValue = 0; if (this._translateX._value >= 0) { this.setState({ ...this.state, swipingLeft: false, }); if ( this._translateX._value > this.props.leftOpenValue * (this.props.swipeToOpenPercent / 100) ) { toValue = this.props.leftOpenValue; this.onSwipedRight(toValue); } } else { this.setState({ ...this.state, swipingLeft: true, }); if ( this._translateX._value < this.props.rightOpenValue * (this.props.swipeToOpenPercent / 100) ) { toValue = this.props.rightOpenValue; this.onSwipedLeft(toValue); } } } }; handlePanResponderEnd = (e, gestureState) => { if (!this.horizontalSwipeGestureEnded) this.closeRow(); }; closeRow = () => { if (this.rowItemJustSwiped) { this.forceCloseRow(); } else { this.manuallySwipeView(0); } }; forceCloseRow = () => { Animated.timing(this._translateX, { duration: 0, toValue: 0, }).start(); }; onSwipedLeft = (toValue) => { const { onSwipedLeft } = this.props; this.horizontalSwipeGestureEnded = true; this.rowItemJustSwiped = true; this.manuallySwipeView(toValue).then(() => { if (onSwipedLeft) onSwipedLeft(); this.closeRow(); }); }; onSwipedRight = (toValue) => { const { onSwipedRight } = this.props; this.horizontalSwipeGestureEnded = true; this.rowItemJustSwiped = true; this.manuallySwipeView(toValue).then(() => { if (onSwipedRight) onSwipedRight(); this.closeRow(); }); }; manuallySwipeView = (toValue) => { return new Promise((resolve, reject) => { Animated.timing(this._translateX, { duration: this.props.swipeDuration, toValue, }).start((_) => { this.swipeInitialX = null; this.horizontalSwipeGestureBegan = false; this.horizontalSwipeGestureEnded = false; resolve(); }); }); }; renderVisibleContent = () => { return this.props.renderVisibleContent(); }; renderRowContent = () => { if (this.state.dimensionsSet) { return ( <Animated.View {...this._panResponder.panHandlers} style={{ transform: [{ translateX: this._translateX }], }} > {this.renderVisibleContent()} </Animated.View> ); } else { return ( <Animated.View {...this._panResponder.panHandlers} onLayout={(e) => this.onContentLayout(e)} style={{ transform: [{ translateX: this._translateX }], }} > {this.renderVisibleContent()} </Animated.View> ); } }; render() { return ( <View> <View style={[ styles.hidden, { height: this.state.hiddenHeight, width: this.state.hiddenWidth, }, ]} > {this.state.swipingLeft ? (this.props.renderRightView && this.props.renderRightView()) || null : (this.props.renderLeftView && this.props.renderLeftView()) || null} </View> {this.renderRowContent()} </View> ); } }
[ "class", "SwipeView", "extends", "Component", "{", "constructor", "(", "props", ")", "{", "super", "(", "props", ")", ";", "this", ".", "horizontalSwipeGestureBegan", "=", "false", ";", "this", ".", "horizontalSwipeGestureEnded", "=", "false", ";", "this", ".", "rowItemJustSwiped", "=", "false", ";", "this", ".", "swipeInitialX", "=", "null", ";", "this", ".", "ranPreview", "=", "false", ";", "this", ".", "state", "=", "{", "dimensionsSet", ":", "false", ",", "hiddenHeight", ":", "0", ",", "hiddenWidth", ":", "0", ",", "swipingLeft", ":", "this", ".", "props", ".", "swipingLeft", ",", "}", ";", "this", ".", "_translateX", "=", "new", "Animated", ".", "Value", "(", "0", ")", ";", "}", "componentWillMount", "(", ")", "{", "this", ".", "_panResponder", "=", "PanResponder", ".", "create", "(", "{", "onMoveShouldSetPanResponder", ":", "(", "e", ",", "gs", ")", "=>", "this", ".", "handleOnMoveShouldSetPanResponder", "(", "e", ",", "gs", ")", ",", "onPanResponderMove", ":", "(", "e", ",", "gs", ")", "=>", "this", ".", "handlePanResponderMove", "(", "e", ",", "gs", ")", ",", "onPanResponderRelease", ":", "(", "e", ",", "gs", ")", "=>", "this", ".", "handlePanResponderEnd", "(", "e", ",", "gs", ")", ",", "onPanResponderTerminate", ":", "(", "e", ",", "gs", ")", "=>", "this", ".", "handlePanResponderEnd", "(", "e", ",", "gs", ")", ",", "onShouldBlockNativeResponder", ":", "(", "_", ")", "=>", "false", ",", "}", ")", ";", "}", "getPreviewAnimation", "=", "(", "toValue", ",", "delay", ")", "=>", "{", "return", "Animated", ".", "timing", "(", "this", ".", "_translateX", ",", "{", "duration", ":", "this", ".", "props", ".", "previewDuration", ",", "toValue", ",", "delay", ",", "}", ")", ";", "}", ";", "onContentLayout", "=", "(", "e", ")", "=>", "{", "this", ".", "setState", "(", "{", "dimensionsSet", ":", "!", "this", ".", "props", ".", "recalculateHiddenLayout", ",", "hiddenHeight", ":", "e", ".", "nativeEvent", ".", "layout", ".", "height", ",", "hiddenWidth", ":", "e", ".", "nativeEvent", ".", "layout", ".", "width", ",", "}", ")", ";", "if", "(", "this", ".", "props", ".", "previewSwipeDemo", "&&", "!", "this", ".", "ranPreview", ")", "{", "let", "{", "previewOpenValue", "}", "=", "this", ".", "props", ";", "this", ".", "ranPreview", "=", "true", ";", "this", ".", "getPreviewAnimation", "(", "previewOpenValue", ",", "this", ".", "props", ".", "previewOpenDelay", ")", ".", "start", "(", "(", "_", ")", "=>", "{", "this", ".", "getPreviewAnimation", "(", "0", ",", "this", ".", "props", ".", "previewCloseDelay", ")", ".", "start", "(", ")", ";", "}", ")", ";", "}", "}", ";", "handleOnMoveShouldSetPanResponder", "=", "(", "e", ",", "gs", ")", "=>", "{", "const", "{", "dx", "}", "=", "gs", ";", "return", "Math", ".", "abs", "(", "dx", ")", ">", "this", ".", "props", ".", "directionalDistanceChangeThreshold", ";", "}", ";", "handlePanResponderMove", "=", "(", "e", ",", "gestureState", ")", "=>", "{", "const", "{", "dx", ",", "dy", "}", "=", "gestureState", ";", "const", "absDx", "=", "Math", ".", "abs", "(", "dx", ")", ";", "const", "absDy", "=", "Math", ".", "abs", "(", "dy", ")", ";", "if", "(", "this", ".", "horizontalSwipeGestureEnded", ")", "return", ";", "if", "(", "absDx", ">", "this", ".", "props", ".", "directionalDistanceChangeThreshold", ")", "{", "if", "(", "this", ".", "swipeInitialX", "===", "null", ")", "{", "this", ".", "swipeInitialX", "=", "this", ".", "_translateX", ".", "_value", ";", "}", "if", "(", "!", "this", ".", "horizontalSwipeGestureBegan", ")", "{", "this", ".", "horizontalSwipeGestureBegan", "=", "true", ";", "this", ".", "props", ".", "swipeGestureBegan", "&&", "this", ".", "props", ".", "swipeGestureBegan", "(", ")", ";", "}", "let", "newDX", "=", "this", ".", "swipeInitialX", "+", "dx", ";", "if", "(", "this", ".", "props", ".", "disableSwipeToLeft", "&&", "newDX", "<", "0", ")", "{", "newDX", "=", "0", ";", "}", "if", "(", "this", ".", "props", ".", "disableSwipeToRight", "&&", "newDX", ">", "0", ")", "{", "newDX", "=", "0", ";", "}", "this", ".", "_translateX", ".", "setValue", "(", "newDX", ")", ";", "let", "toValue", "=", "0", ";", "if", "(", "this", ".", "_translateX", ".", "_value", ">=", "0", ")", "{", "this", ".", "setState", "(", "{", "...", "this", ".", "state", ",", "swipingLeft", ":", "false", ",", "}", ")", ";", "if", "(", "this", ".", "_translateX", ".", "_value", ">", "this", ".", "props", ".", "leftOpenValue", "*", "(", "this", ".", "props", ".", "swipeToOpenPercent", "/", "100", ")", ")", "{", "toValue", "=", "this", ".", "props", ".", "leftOpenValue", ";", "this", ".", "onSwipedRight", "(", "toValue", ")", ";", "}", "}", "else", "{", "this", ".", "setState", "(", "{", "...", "this", ".", "state", ",", "swipingLeft", ":", "true", ",", "}", ")", ";", "if", "(", "this", ".", "_translateX", ".", "_value", "<", "this", ".", "props", ".", "rightOpenValue", "*", "(", "this", ".", "props", ".", "swipeToOpenPercent", "/", "100", ")", ")", "{", "toValue", "=", "this", ".", "props", ".", "rightOpenValue", ";", "this", ".", "onSwipedLeft", "(", "toValue", ")", ";", "}", "}", "}", "}", ";", "handlePanResponderEnd", "=", "(", "e", ",", "gestureState", ")", "=>", "{", "if", "(", "!", "this", ".", "horizontalSwipeGestureEnded", ")", "this", ".", "closeRow", "(", ")", ";", "}", ";", "closeRow", "=", "(", ")", "=>", "{", "if", "(", "this", ".", "rowItemJustSwiped", ")", "{", "this", ".", "forceCloseRow", "(", ")", ";", "}", "else", "{", "this", ".", "manuallySwipeView", "(", "0", ")", ";", "}", "}", ";", "forceCloseRow", "=", "(", ")", "=>", "{", "Animated", ".", "timing", "(", "this", ".", "_translateX", ",", "{", "duration", ":", "0", ",", "toValue", ":", "0", ",", "}", ")", ".", "start", "(", ")", ";", "}", ";", "onSwipedLeft", "=", "(", "toValue", ")", "=>", "{", "const", "{", "onSwipedLeft", "}", "=", "this", ".", "props", ";", "this", ".", "horizontalSwipeGestureEnded", "=", "true", ";", "this", ".", "rowItemJustSwiped", "=", "true", ";", "this", ".", "manuallySwipeView", "(", "toValue", ")", ".", "then", "(", "(", ")", "=>", "{", "if", "(", "onSwipedLeft", ")", "onSwipedLeft", "(", ")", ";", "this", ".", "closeRow", "(", ")", ";", "}", ")", ";", "}", ";", "onSwipedRight", "=", "(", "toValue", ")", "=>", "{", "const", "{", "onSwipedRight", "}", "=", "this", ".", "props", ";", "this", ".", "horizontalSwipeGestureEnded", "=", "true", ";", "this", ".", "rowItemJustSwiped", "=", "true", ";", "this", ".", "manuallySwipeView", "(", "toValue", ")", ".", "then", "(", "(", ")", "=>", "{", "if", "(", "onSwipedRight", ")", "onSwipedRight", "(", ")", ";", "this", ".", "closeRow", "(", ")", ";", "}", ")", ";", "}", ";", "manuallySwipeView", "=", "(", "toValue", ")", "=>", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "Animated", ".", "timing", "(", "this", ".", "_translateX", ",", "{", "duration", ":", "this", ".", "props", ".", "swipeDuration", ",", "toValue", ",", "}", ")", ".", "start", "(", "(", "_", ")", "=>", "{", "this", ".", "swipeInitialX", "=", "null", ";", "this", ".", "horizontalSwipeGestureBegan", "=", "false", ";", "this", ".", "horizontalSwipeGestureEnded", "=", "false", ";", "resolve", "(", ")", ";", "}", ")", ";", "}", ")", ";", "}", ";", "renderVisibleContent", "=", "(", ")", "=>", "{", "return", "this", ".", "props", ".", "renderVisibleContent", "(", ")", ";", "}", ";", "renderRowContent", "=", "(", ")", "=>", "{", "if", "(", "this", ".", "state", ".", "dimensionsSet", ")", "{", "return", "(", "<", "Animated", ".", "View", "{", "...", "this", ".", "_panResponder", ".", "panHandlers", "}", "style", "=", "{", "{", "transform", ":", "[", "{", "translateX", ":", "this", ".", "_translateX", "}", "]", ",", "}", "}", ">", "\n ", "{", "this", ".", "renderVisibleContent", "(", ")", "}", "\n ", "<", "/", "Animated", ".", "View", ">", ")", ";", "}", "else", "{", "return", "(", "<", "Animated", ".", "View", "{", "...", "this", ".", "_panResponder", ".", "panHandlers", "}", "onLayout", "=", "{", "(", "e", ")", "=>", "this", ".", "onContentLayout", "(", "e", ")", "}", "style", "=", "{", "{", "transform", ":", "[", "{", "translateX", ":", "this", ".", "_translateX", "}", "]", ",", "}", "}", ">", "\n ", "{", "this", ".", "renderVisibleContent", "(", ")", "}", "\n ", "<", "/", "Animated", ".", "View", ">", ")", ";", "}", "}", ";", "render", "(", ")", "{", "return", "(", "<", "View", ">", "\n ", "<", "View", "style", "=", "{", "[", "styles", ".", "hidden", ",", "{", "height", ":", "this", ".", "state", ".", "hiddenHeight", ",", "width", ":", "this", ".", "state", ".", "hiddenWidth", ",", "}", ",", "]", "}", ">", "\n ", "{", "this", ".", "state", ".", "swipingLeft", "?", "(", "this", ".", "props", ".", "renderRightView", "&&", "this", ".", "props", ".", "renderRightView", "(", ")", ")", "||", "null", ":", "(", "this", ".", "props", ".", "renderLeftView", "&&", "this", ".", "props", ".", "renderLeftView", "(", ")", ")", "||", "null", "}", "\n ", "<", "/", "View", ">", "\n ", "{", "this", ".", "renderRowContent", "(", ")", "}", "\n ", "<", "/", "View", ">", ")", ";", "}", "}" ]
react-native-swipeview @author rishabhbhatia<[email protected]> SwipeView can be rendered individually or within a list by passing three child views.
[ "react", "-", "native", "-", "swipeview", "@author", "rishabhbhatia<rishabh", ".", "bhatia08@gmail", ".", "com", ">", "SwipeView", "can", "be", "rendered", "individually", "or", "within", "a", "list", "by", "passing", "three", "child", "views", "." ]
[]
[ { "param": "Component", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Component", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
21
1,450
101
fd1a41df046c8688a99e7d40eed3c8d2b4c4e55e
HeroicosHM/CIS131SourceFiles
Lab1ParkingGarage.java
[ "MIT" ]
Java
Lab1ParkingGarage
/** * <h1>Houghton Mayfield Lab 1 - Wegougem Parking Garage</h1> * <p> * This is a program which allows for a parking garage to create receipts for parking, and keep * track of total daily sales. * </p> * @author Houghton Mayfield * @version 1.1 * @since 2020-09-16 */
Houghton Mayfield Lab 1 - Wegougem Parking Garage This is a program which allows for a parking garage to create receipts for parking, and keep track of total daily sales. @author Houghton Mayfield @version 1.1 @since 2020-09-16
[ "Houghton", "Mayfield", "Lab", "1", "-", "Wegougem", "Parking", "Garage", "This", "is", "a", "program", "which", "allows", "for", "a", "parking", "garage", "to", "create", "receipts", "for", "parking", "and", "keep", "track", "of", "total", "daily", "sales", ".", "@author", "Houghton", "Mayfield", "@version", "1", ".", "1", "@since", "2020", "-", "09", "-", "16" ]
public class Lab1ParkingGarage { // Defining pricing constants private final static double WEEKDAY_RATE = 1.25; private final static double WEEKDAY_MIN_FEE = 3.0; private final static double WEEKDAY_MAX_FEE = 15.0; private final static double WEEKEND_RATE = 0.5; private final static double WEEKEND_MIN_FEE = 2.0; private final static double WEEKEND_MAX_FEE = 10.0; // Define information about valid days and inputs for the days private static final String [] D_ABBREVIATIONS = {"q", "m", "tu", "w", "th", "f", "sa", "su"}; private static final String [] DAYS = {"quit", "Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"}; // Questions for user interaction private static final String DAY_QUESTION = "Please enter the day of the week (mon, tue, wed, thu, fri, sat, sun) or quit: "; private final static String ARRIVAL_TIME_QUESTION = "Please enter the vehicle's arrival time (HHMM): "; private final static String DEPARTURE_TIME_QUESTION = "Please enter the vehicle's departure time (HHMM): "; /** The method which controls the input, creation, and addition of receipts for the * daily sales in a parking garage. * * @param args - Not used in this program */ public static void main(String[] args) { printIntro(); double totalCharge = 0; // Use created input functions to get user inputs for the day of the week int dayOfWeek = getValidDayOfWeek(DAY_QUESTION); // Declare other variables for the loop int arrivalTime, departureTime, duration; double charge; // Continue looping until the user inputs q or quit to quit the program while (dayOfWeek != 0) { // Use created input functions to get user inputs for the arrival time and departure time arrivalTime = getValidTime(ARRIVAL_TIME_QUESTION); departureTime = getValidTime(DEPARTURE_TIME_QUESTION); // Perform necessary calculations for the output duration = getDuration(arrivalTime, departureTime); charge = getCharge(duration, dayOfWeek); // Add the charge to the total amount charged for the day totalCharge += charge; // Printing receipt outputs printReceiptHeader(); System.out.printf("Day of Week: %s\n", DAYS[dayOfWeek]); // Print the input day of the week printDailyRate(dayOfWeek); // Print the sales rate for the day System.out.printf("Arrival time: %8d\n", arrivalTime); // Print the arrival time System.out.printf("Departure time: %6d\n", departureTime); // Print the departure time. System.out.printf("Parking Duration: %4d minutes\n\n", duration); // Print the duration of a car's stay System.out.printf("Amount Charged: $%.2f\n", charge); System.out.println("*******************************\n"); // Use created input functions to get user inputs for the day of the week dayOfWeek = getValidDayOfWeek(DAY_QUESTION); } System.out.printf("\nTotal Charged Today: $ %.2f", totalCharge); } //------------------------------------------------------------------------------------------------------------------ /** Prints the introductory statement to the program. * */ public static void printIntro() { System.out.println("*******************************"); System.out.println(" Wegougem Parking Garage"); System.out.println("*******************************"); } //------------------------------------------------------------------------------------------------------------------ /** Prints the header for a sales receipt. * */ public static void printReceiptHeader() { System.out.println("\n*******************************"); System.out.println(" Wegougem Parking Garage"); System.out.println(" Sales Receipt"); System.out.println("*******************************"); } //------------------------------------------------------------------------------------------------------------------ /** Prints the price rate for the provided day. * * @param day - An integer representing the day of the week. */ public static void printDailyRate(int day) { if (day == 6 || day == 7) { System.out.printf("Rate: $%.2f per 15 minute interval\n\n", WEEKEND_RATE); } else { System.out.printf("Rate: $%.2f per 15 minute interval\n\n", WEEKDAY_RATE); } } //------------------------------------------------------------------------------------------------------------------ /** Get a valid day of the week. * * @param msg - The message displayed to the user. * @return Returns a valid day of the week: 0=m, 1=tu, 2=w, etc... 8=q */ public static int getValidDayOfWeek(String msg) { // Get original user input String day = HeroIR.getString(msg); // While the user input is not a valid day while (isInvalidDayOfWeek(day) == -1) { System.err.println("Error: Invalid day of the week."); day = HeroIR.getString(msg); } return isInvalidDayOfWeek(day); // The validation function returns the integer day of the week already } //------------------------------------------------------------------------------------------------------------------ /** Validates the day entered by the user is valid (or q for quit). * Any word starting with a valid day of the week text value is acceptable. (m for monday, tu for tuesday, etc) * * @param day - The user's entered value of the day of the week. * @return An integer weekday value: 0=m, 1=tu, 2=w, etc... 8=q, -1=not valid */ public static int isInvalidDayOfWeek(String day) { // Get the lowercase form of the input day String lowerDay = day.toLowerCase(); for (int i = 0; i < D_ABBREVIATIONS.length; i ++) { if (lowerDay.startsWith(D_ABBREVIATIONS[i])) { return i; // Return as soon as a match is found to remove extraneous loops } } return -1; //invalid day of week } //------------------------------------------------------------------------------------------------------------------ /** Get a valid time from the user in the format HHMM. * * @param msg - The message displayed to the user. * @return time - Returns a valid time in HHMM format. */ public static int getValidTime(String msg) { int time; //Get input from the user using the below getIntegerBetweenLowAndHigh function time = HeroIR.getIntegerInRange(msg, 0000, 2359); while (isInvalidTime(time)) { time = HeroIR.getIntegerInRange(msg, 0000, 2359); } return time; } //------------------------------------------------------------------------------------------------------------------ /** Determines if the input is valid in HHMM format. * * @param time - The message displayed to the user. * @return Boolean - false if valid, true if invalid. */ public static boolean isInvalidTime(int time) { // Find the number of hours by dividing the time by 100. // Because both are integers, result is automatically cast to an int. int hours = time / 100; // Find the number of minutes by using the remainder operator when dividing by 100. int minutes = time % 100; // Check resulting values to make sure they are valid, // or return a response declaring why it is invalid. if (hours < 0 || hours > 23) { System.err.println("Invalid hour number: The number of hours must be between 0 and 23, inclusive\n"); return true; } else if (minutes < 0 || minutes > 59) { System.err.println("Invalid minute number: The number of minutes must be between 0 and 59, inclusive\n"); return true; } return false; // Means the time is OK } //------------------------------------------------------------------------------------------------------------------ /** This function is used to determine the length of time between the provided start and end times. * * @param startTime - The start of the time period, in a 24 hour HHMM integer format. * @param endTime - The end of the time period, in a 24 hour HHMM integer format. * @return An integer number of minutes between the start and end of the time period. */ public static int getDuration(int startTime, int endTime) { // Convert the HHMM format into just a minute total int startMins = ((startTime / 100) * 60) + (startTime % 100); int endMins = ((endTime / 100) * 60) + (endTime % 100); // If the minute of the end time is less than arrival time, the clock has rolled over. // This is accounted for by adding 24 hours to the departure time, allowing to find the difference. if (endMins > startMins) { return endMins - startMins; } else { return (endMins + (24 * 60)) - startMins; } } //------------------------------------------------------------------------------------------------------------------ /** Calculates the charge to give a car depending on the amount of time spent in the garage, * and the day of the week. * * @param minutes - An integer representing the number of minutes spent in the garage. * @param dayOfWeek - An integer representing the day of the week. * @return A double representing the amount of money the car is getting charged. */ public static double getCharge(int minutes, int dayOfWeek) { double charge = 0.0; int fifteenMinIncrements = minutes / 15; // Find the number of 15 minute increments // If the car was in the garage for less than 15 minutes, return no charge. if (fifteenMinIncrements == 0) { return charge; } // If there are extra minutes in the next increment, add one 15 minute charge if (minutes % 15 != 0) { fifteenMinIncrements += 1; } if (dayOfWeek == 6 || dayOfWeek == 7) { // If it is a weekend charge = fifteenMinIncrements * WEEKEND_RATE; // Calculate charge based on time spent // Adjust the charge to min or max fees depending on the charge up to this point if (charge < WEEKEND_MIN_FEE) { charge = WEEKEND_MIN_FEE; } else if (charge > WEEKEND_MAX_FEE) { charge = WEEKEND_MAX_FEE; } } else { charge = fifteenMinIncrements * WEEKDAY_RATE; // Calculate charge based on time spent // Adjust the charge to min or max fees depending on the charge up to this point if (charge < WEEKDAY_MIN_FEE) { charge = WEEKDAY_MIN_FEE; } else if (charge > WEEKDAY_MAX_FEE) { charge = WEEKDAY_MAX_FEE; } } return charge; } }
[ "public", "class", "Lab1ParkingGarage", "{", "private", "final", "static", "double", "WEEKDAY_RATE", "=", "1.25", ";", "private", "final", "static", "double", "WEEKDAY_MIN_FEE", "=", "3.0", ";", "private", "final", "static", "double", "WEEKDAY_MAX_FEE", "=", "15.0", ";", "private", "final", "static", "double", "WEEKEND_RATE", "=", "0.5", ";", "private", "final", "static", "double", "WEEKEND_MIN_FEE", "=", "2.0", ";", "private", "final", "static", "double", "WEEKEND_MAX_FEE", "=", "10.0", ";", "private", "static", "final", "String", "[", "]", "D_ABBREVIATIONS", "=", "{", "\"", "q", "\"", ",", "\"", "m", "\"", ",", "\"", "tu", "\"", ",", "\"", "w", "\"", ",", "\"", "th", "\"", ",", "\"", "f", "\"", ",", "\"", "sa", "\"", ",", "\"", "su", "\"", "}", ";", "private", "static", "final", "String", "[", "]", "DAYS", "=", "{", "\"", "quit", "\"", ",", "\"", "Monday", "\"", ",", "\"", "Tuesday", "\"", ",", "\"", "Wednesday", "\"", ",", "\"", "Thursday", "\"", ",", "\"", "Friday", "\"", ",", "\"", "Saturday", "\"", ",", "\"", "Sunday", "\"", "}", ";", "private", "static", "final", "String", "DAY_QUESTION", "=", "\"", "Please enter the day of the week (mon, tue, wed, thu, fri, sat, sun) or quit: ", "\"", ";", "private", "final", "static", "String", "ARRIVAL_TIME_QUESTION", "=", "\"", "Please enter the vehicle's arrival time (HHMM): ", "\"", ";", "private", "final", "static", "String", "DEPARTURE_TIME_QUESTION", "=", "\"", "Please enter the vehicle's departure time (HHMM): ", "\"", ";", "/** The method which controls the input, creation, and addition of receipts for the\n * daily sales in a parking garage.\n *\n * @param args - Not used in this program\n */", "public", "static", "void", "main", "(", "String", "[", "]", "args", ")", "{", "printIntro", "(", ")", ";", "double", "totalCharge", "=", "0", ";", "int", "dayOfWeek", "=", "getValidDayOfWeek", "(", "DAY_QUESTION", ")", ";", "int", "arrivalTime", ",", "departureTime", ",", "duration", ";", "double", "charge", ";", "while", "(", "dayOfWeek", "!=", "0", ")", "{", "arrivalTime", "=", "getValidTime", "(", "ARRIVAL_TIME_QUESTION", ")", ";", "departureTime", "=", "getValidTime", "(", "DEPARTURE_TIME_QUESTION", ")", ";", "duration", "=", "getDuration", "(", "arrivalTime", ",", "departureTime", ")", ";", "charge", "=", "getCharge", "(", "duration", ",", "dayOfWeek", ")", ";", "totalCharge", "+=", "charge", ";", "printReceiptHeader", "(", ")", ";", "System", ".", "out", ".", "printf", "(", "\"", "Day of Week: %s", "\\n", "\"", ",", "DAYS", "[", "dayOfWeek", "]", ")", ";", "printDailyRate", "(", "dayOfWeek", ")", ";", "System", ".", "out", ".", "printf", "(", "\"", "Arrival time: %8d", "\\n", "\"", ",", "arrivalTime", ")", ";", "System", ".", "out", ".", "printf", "(", "\"", "Departure time: %6d", "\\n", "\"", ",", "departureTime", ")", ";", "System", ".", "out", ".", "printf", "(", "\"", "Parking Duration: %4d minutes", "\\n", "\\n", "\"", ",", "duration", ")", ";", "System", ".", "out", ".", "printf", "(", "\"", "Amount Charged: $%.2f", "\\n", "\"", ",", "charge", ")", ";", "System", ".", "out", ".", "println", "(", "\"", "*******************************", "\\n", "\"", ")", ";", "dayOfWeek", "=", "getValidDayOfWeek", "(", "DAY_QUESTION", ")", ";", "}", "System", ".", "out", ".", "printf", "(", "\"", "\\n", "Total Charged Today: $ %.2f", "\"", ",", "totalCharge", ")", ";", "}", "/** Prints the introductory statement to the program.\n *\n */", "public", "static", "void", "printIntro", "(", ")", "{", "System", ".", "out", ".", "println", "(", "\"", "*******************************", "\"", ")", ";", "System", ".", "out", ".", "println", "(", "\"", " Wegougem Parking Garage", "\"", ")", ";", "System", ".", "out", ".", "println", "(", "\"", "*******************************", "\"", ")", ";", "}", "/** Prints the header for a sales receipt.\n *\n */", "public", "static", "void", "printReceiptHeader", "(", ")", "{", "System", ".", "out", ".", "println", "(", "\"", "\\n", "*******************************", "\"", ")", ";", "System", ".", "out", ".", "println", "(", "\"", " Wegougem Parking Garage", "\"", ")", ";", "System", ".", "out", ".", "println", "(", "\"", " Sales Receipt", "\"", ")", ";", "System", ".", "out", ".", "println", "(", "\"", "*******************************", "\"", ")", ";", "}", "/** Prints the price rate for the provided day.\n *\n * @param day - An integer representing the day of the week.\n */", "public", "static", "void", "printDailyRate", "(", "int", "day", ")", "{", "if", "(", "day", "==", "6", "||", "day", "==", "7", ")", "{", "System", ".", "out", ".", "printf", "(", "\"", "Rate: $%.2f per 15 minute interval", "\\n", "\\n", "\"", ",", "WEEKEND_RATE", ")", ";", "}", "else", "{", "System", ".", "out", ".", "printf", "(", "\"", "Rate: $%.2f per 15 minute interval", "\\n", "\\n", "\"", ",", "WEEKDAY_RATE", ")", ";", "}", "}", "/** Get a valid day of the week.\n *\n * @param msg - The message displayed to the user.\n * @return Returns a valid day of the week: 0=m, 1=tu, 2=w, etc... 8=q\n */", "public", "static", "int", "getValidDayOfWeek", "(", "String", "msg", ")", "{", "String", "day", "=", "HeroIR", ".", "getString", "(", "msg", ")", ";", "while", "(", "isInvalidDayOfWeek", "(", "day", ")", "==", "-", "1", ")", "{", "System", ".", "err", ".", "println", "(", "\"", "Error: Invalid day of the week.", "\"", ")", ";", "day", "=", "HeroIR", ".", "getString", "(", "msg", ")", ";", "}", "return", "isInvalidDayOfWeek", "(", "day", ")", ";", "}", "/** Validates the day entered by the user is valid (or q for quit).\n * Any word starting with a valid day of the week text value is acceptable. (m for monday, tu for tuesday, etc)\n *\n * @param day - The user's entered value of the day of the week.\n * @return An integer weekday value: 0=m, 1=tu, 2=w, etc... 8=q, -1=not valid\n */", "public", "static", "int", "isInvalidDayOfWeek", "(", "String", "day", ")", "{", "String", "lowerDay", "=", "day", ".", "toLowerCase", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "D_ABBREVIATIONS", ".", "length", ";", "i", "++", ")", "{", "if", "(", "lowerDay", ".", "startsWith", "(", "D_ABBREVIATIONS", "[", "i", "]", ")", ")", "{", "return", "i", ";", "}", "}", "return", "-", "1", ";", "}", "/** Get a valid time from the user in the format HHMM.\n *\n * @param msg - The message displayed to the user.\n * @return time - Returns a valid time in HHMM format.\n */", "public", "static", "int", "getValidTime", "(", "String", "msg", ")", "{", "int", "time", ";", "time", "=", "HeroIR", ".", "getIntegerInRange", "(", "msg", ",", "0000", ",", "2359", ")", ";", "while", "(", "isInvalidTime", "(", "time", ")", ")", "{", "time", "=", "HeroIR", ".", "getIntegerInRange", "(", "msg", ",", "0000", ",", "2359", ")", ";", "}", "return", "time", ";", "}", "/** Determines if the input is valid in HHMM format.\n *\n * @param time - The message displayed to the user.\n * @return Boolean - false if valid, true if invalid.\n */", "public", "static", "boolean", "isInvalidTime", "(", "int", "time", ")", "{", "int", "hours", "=", "time", "/", "100", ";", "int", "minutes", "=", "time", "%", "100", ";", "if", "(", "hours", "<", "0", "||", "hours", ">", "23", ")", "{", "System", ".", "err", ".", "println", "(", "\"", "Invalid hour number: The number of hours must be between 0 and 23, inclusive", "\\n", "\"", ")", ";", "return", "true", ";", "}", "else", "if", "(", "minutes", "<", "0", "||", "minutes", ">", "59", ")", "{", "System", ".", "err", ".", "println", "(", "\"", "Invalid minute number: The number of minutes must be between 0 and 59, inclusive", "\\n", "\"", ")", ";", "return", "true", ";", "}", "return", "false", ";", "}", "/** This function is used to determine the length of time between the provided start and end times.\n *\n * @param startTime - The start of the time period, in a 24 hour HHMM integer format.\n * @param endTime - The end of the time period, in a 24 hour HHMM integer format.\n * @return An integer number of minutes between the start and end of the time period.\n */", "public", "static", "int", "getDuration", "(", "int", "startTime", ",", "int", "endTime", ")", "{", "int", "startMins", "=", "(", "(", "startTime", "/", "100", ")", "*", "60", ")", "+", "(", "startTime", "%", "100", ")", ";", "int", "endMins", "=", "(", "(", "endTime", "/", "100", ")", "*", "60", ")", "+", "(", "endTime", "%", "100", ")", ";", "if", "(", "endMins", ">", "startMins", ")", "{", "return", "endMins", "-", "startMins", ";", "}", "else", "{", "return", "(", "endMins", "+", "(", "24", "*", "60", ")", ")", "-", "startMins", ";", "}", "}", "/** Calculates the charge to give a car depending on the amount of time spent in the garage,\n * and the day of the week.\n *\n * @param minutes - An integer representing the number of minutes spent in the garage.\n * @param dayOfWeek - An integer representing the day of the week.\n * @return A double representing the amount of money the car is getting charged.\n */", "public", "static", "double", "getCharge", "(", "int", "minutes", ",", "int", "dayOfWeek", ")", "{", "double", "charge", "=", "0.0", ";", "int", "fifteenMinIncrements", "=", "minutes", "/", "15", ";", "if", "(", "fifteenMinIncrements", "==", "0", ")", "{", "return", "charge", ";", "}", "if", "(", "minutes", "%", "15", "!=", "0", ")", "{", "fifteenMinIncrements", "+=", "1", ";", "}", "if", "(", "dayOfWeek", "==", "6", "||", "dayOfWeek", "==", "7", ")", "{", "charge", "=", "fifteenMinIncrements", "*", "WEEKEND_RATE", ";", "if", "(", "charge", "<", "WEEKEND_MIN_FEE", ")", "{", "charge", "=", "WEEKEND_MIN_FEE", ";", "}", "else", "if", "(", "charge", ">", "WEEKEND_MAX_FEE", ")", "{", "charge", "=", "WEEKEND_MAX_FEE", ";", "}", "}", "else", "{", "charge", "=", "fifteenMinIncrements", "*", "WEEKDAY_RATE", ";", "if", "(", "charge", "<", "WEEKDAY_MIN_FEE", ")", "{", "charge", "=", "WEEKDAY_MIN_FEE", ";", "}", "else", "if", "(", "charge", ">", "WEEKDAY_MAX_FEE", ")", "{", "charge", "=", "WEEKDAY_MAX_FEE", ";", "}", "}", "return", "charge", ";", "}", "}" ]
<h1>Houghton Mayfield Lab 1 - Wegougem Parking Garage</h1> <p> This is a program which allows for a parking garage to create receipts for parking, and keep track of total daily sales.
[ "<h1", ">", "Houghton", "Mayfield", "Lab", "1", "-", "Wegougem", "Parking", "Garage<", "/", "h1", ">", "<p", ">", "This", "is", "a", "program", "which", "allows", "for", "a", "parking", "garage", "to", "create", "receipts", "for", "parking", "and", "keep", "track", "of", "total", "daily", "sales", "." ]
[ "// Defining pricing constants", "// Define information about valid days and inputs for the days", "// Questions for user interaction", "// Use created input functions to get user inputs for the day of the week", "// Declare other variables for the loop", "// Continue looping until the user inputs q or quit to quit the program", "// Use created input functions to get user inputs for the arrival time and departure time", "// Perform necessary calculations for the output", "// Add the charge to the total amount charged for the day", "// Printing receipt outputs", "// Print the input day of the week", "// Print the sales rate for the day", "// Print the arrival time", "// Print the departure time.", "// Print the duration of a car's stay", "// Use created input functions to get user inputs for the day of the week", "//------------------------------------------------------------------------------------------------------------------", "//------------------------------------------------------------------------------------------------------------------", "//------------------------------------------------------------------------------------------------------------------", "//------------------------------------------------------------------------------------------------------------------", "// Get original user input", "// While the user input is not a valid day", "// The validation function returns the integer day of the week already", "//------------------------------------------------------------------------------------------------------------------", "// Get the lowercase form of the input day", "// Return as soon as a match is found to remove extraneous loops", "//invalid day of week", "//------------------------------------------------------------------------------------------------------------------", "//Get input from the user using the below getIntegerBetweenLowAndHigh function", "//------------------------------------------------------------------------------------------------------------------", "// Find the number of hours by dividing the time by 100.", "// Because both are integers, result is automatically cast to an int.", "// Find the number of minutes by using the remainder operator when dividing by 100.", "// Check resulting values to make sure they are valid,", "// or return a response declaring why it is invalid.", "// Means the time is OK", "//------------------------------------------------------------------------------------------------------------------", "// Convert the HHMM format into just a minute total", "// If the minute of the end time is less than arrival time, the clock has rolled over.", "// This is accounted for by adding 24 hours to the departure time, allowing to find the difference.", "//------------------------------------------------------------------------------------------------------------------", "// Find the number of 15 minute increments", "// If the car was in the garage for less than 15 minutes, return no charge.", "// If there are extra minutes in the next increment, add one 15 minute charge", "// If it is a weekend", "// Calculate charge based on time spent", "// Adjust the charge to min or max fees depending on the charge up to this point", "// Calculate charge based on time spent", "// Adjust the charge to min or max fees depending on the charge up to this point" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
13
2,441
99
b5f90d36c31ca8c57ae530406b9b129ed62206a5
veriktig/scandium
old-external/felix/gogo/jline/src/test/java/org/apache/felix/gogo/jline/telnet/Connection.java
[ "Apache-2.0" ]
Java
Connection
/** * Class that implements a connection with this telnet daemon.<br> * It is derived from java.lang.Thread, which reflects the architecture * constraint of one thread per connection. This might seem a waste of * resources, but as a matter of fact sharing threads would require a * far more complex imlementation, due to the fact that telnet is not a * stateless protocol (i.e. alive throughout a session of multiple requests * and responses).<br> * Each Connection instance is created by the listeners ConnectionManager * instance, making it part of a threadgroup and passing in an associated * ConnectionData instance, that holds vital information about the connection. * Be sure to take a look at their documention.<br> * <p/> * Once the thread has started and is running, it will get a login * shell instance from the ShellManager and run passing its own reference. * * @author Dieter Wimberger * @version 2.0 (16/07/2006) * @see ConnectionManager * @see ConnectionData */
Class that implements a connection with this telnet daemon. It is derived from java.lang.Thread, which reflects the architecture constraint of one thread per connection. This might seem a waste of resources, but as a matter of fact sharing threads would require a far more complex imlementation, due to the fact that telnet is not a stateless protocol . Each Connection instance is created by the listeners ConnectionManager instance, making it part of a threadgroup and passing in an associated ConnectionData instance, that holds vital information about the connection. Be sure to take a look at their documention. Once the thread has started and is running, it will get a login shell instance from the ShellManager and run passing its own reference. @author Dieter Wimberger @version 2.0 (16/07/2006) @see ConnectionManager @see ConnectionData
[ "Class", "that", "implements", "a", "connection", "with", "this", "telnet", "daemon", ".", "It", "is", "derived", "from", "java", ".", "lang", ".", "Thread", "which", "reflects", "the", "architecture", "constraint", "of", "one", "thread", "per", "connection", ".", "This", "might", "seem", "a", "waste", "of", "resources", "but", "as", "a", "matter", "of", "fact", "sharing", "threads", "would", "require", "a", "far", "more", "complex", "imlementation", "due", "to", "the", "fact", "that", "telnet", "is", "not", "a", "stateless", "protocol", ".", "Each", "Connection", "instance", "is", "created", "by", "the", "listeners", "ConnectionManager", "instance", "making", "it", "part", "of", "a", "threadgroup", "and", "passing", "in", "an", "associated", "ConnectionData", "instance", "that", "holds", "vital", "information", "about", "the", "connection", ".", "Be", "sure", "to", "take", "a", "look", "at", "their", "documention", ".", "Once", "the", "thread", "has", "started", "and", "is", "running", "it", "will", "get", "a", "login", "shell", "instance", "from", "the", "ShellManager", "and", "run", "passing", "its", "own", "reference", ".", "@author", "Dieter", "Wimberger", "@version", "2", ".", "0", "(", "16", "/", "07", "/", "2006", ")", "@see", "ConnectionManager", "@see", "ConnectionData" ]
public abstract class Connection extends Thread { private static final Logger LOG = Logger.getLogger(Connection.class.getName()); private static int number; //unique number for a thread in the thread group private boolean dead; private List<ConnectionListener> listeners; //Associations private ConnectionData connectionData; //associated information /** * Constructs a TelnetConnection by invoking its parent constructor * and setting of various members.<br> * Subsequently instantiates the whole i/o subsystem, negotiating * telnet protocol level options etc.<br> * * @param tcg ThreadGroup that this instance is running in. * @param cd ConnectionData instance containing all vital information * of this connection. * @see ConnectionData */ public Connection(ThreadGroup tcg, ConnectionData cd) { super(tcg, ("Connection" + (++number))); connectionData = cd; //init the connection listeners for events //(there should actually be only one or two) listeners = new CopyOnWriteArrayList<ConnectionListener>(); dead = false; }//constructor /** * Method overloaded to implement following behaviour: * <ol> * <li> On first entry, retrieve an instance of the configured * login shell from the ShellManager and run it. * <li> Handle a shell switch or close down disgracefully when * problems (i.e. unhandled unchecked exceptions) occur in the * running shell. * </ol> */ public void run() { try { doRun(); } catch (Exception ex) { LOG.log(Level.SEVERE, "run()", ex); //Handle properly } finally { //call close if not dead already if (!dead) { close(); } } LOG.log(Level.FINE, "run():: Returning from " + this.toString()); }//run protected abstract void doRun() throws Exception; protected abstract void doClose() throws Exception; /** * Method to access the associated connection data. * * @return ConnectionData associated with the Connection instance. * @see ConnectionData */ public ConnectionData getConnectionData() { return connectionData; }//getConnectionData /** * Closes the connection and its underlying i/o and network * resources.<br> */ public synchronized void close() { if (dead) { return; } else { try { //connection dead dead = true; //close i/o doClose(); } catch (Exception ex) { LOG.log(Level.SEVERE, "close()", ex); //handle } try { //close socket connectionData.getSocket().close(); } catch (Exception ex) { LOG.log(Level.SEVERE, "close()", ex); //handle } try { //register closed connection in ConnectionManager connectionData.getManager().registerClosedConnection(this); } catch (Exception ex) { LOG.log(Level.SEVERE, "close()", ex); //handle } try { //try to interrupt it interrupt(); } catch (Exception ex) { LOG.log(Level.SEVERE, "close()", ex); //handle } LOG.log(Level.FINE, "Closed " + this.toString() + " and inactive."); } }//close /** * Returns if a connection has been closed.<br> * * @return the state of the connection. */ public boolean isActive() { return !dead; }//isClosed /****** Event handling ****************/ /** * Method that registers a ConnectionListener with the * Connection instance. * * @param cl ConnectionListener to be registered. * @see ConnectionListener */ public void addConnectionListener(ConnectionListener cl) { listeners.add(cl); }//addConnectionListener /** * Method that removes a ConnectionListener from the * Connection instance. * * @param cl ConnectionListener to be removed. * @see ConnectionListener */ public void removeConnectionListener(ConnectionListener cl) { listeners.remove(cl); }//removeConnectionListener /** * Method called by the io subsystem to pass on a * "low-level" event. It will be properly delegated to * all registered listeners. * * @param ce ConnectionEvent to be processed. * @see ConnectionEvent */ public void processConnectionEvent(ConnectionEvent ce) { for (ConnectionListener cl : listeners) { switch (ce.getType()) { case CONNECTION_IDLE: cl.connectionIdle(ce); break; case CONNECTION_TIMEDOUT: cl.connectionTimedOut(ce); break; case CONNECTION_LOGOUTREQUEST: cl.connectionLogoutRequest(ce); break; case CONNECTION_BREAK: cl.connectionSentBreak(ce); break; case CONNECTION_TERMINAL_GEOMETRY_CHANGED: cl.connectionTerminalGeometryChanged(ce); } } }//processConnectionEvent }
[ "public", "abstract", "class", "Connection", "extends", "Thread", "{", "private", "static", "final", "Logger", "LOG", "=", "Logger", ".", "getLogger", "(", "Connection", ".", "class", ".", "getName", "(", ")", ")", ";", "private", "static", "int", "number", ";", "private", "boolean", "dead", ";", "private", "List", "<", "ConnectionListener", ">", "listeners", ";", "private", "ConnectionData", "connectionData", ";", "/**\n * Constructs a TelnetConnection by invoking its parent constructor\n * and setting of various members.<br>\n * Subsequently instantiates the whole i/o subsystem, negotiating\n * telnet protocol level options etc.<br>\n *\n * @param tcg ThreadGroup that this instance is running in.\n * @param cd ConnectionData instance containing all vital information\n * of this connection.\n * @see ConnectionData\n */", "public", "Connection", "(", "ThreadGroup", "tcg", ",", "ConnectionData", "cd", ")", "{", "super", "(", "tcg", ",", "(", "\"", "Connection", "\"", "+", "(", "++", "number", ")", ")", ")", ";", "connectionData", "=", "cd", ";", "listeners", "=", "new", "CopyOnWriteArrayList", "<", "ConnectionListener", ">", "(", ")", ";", "dead", "=", "false", ";", "}", "/**\n * Method overloaded to implement following behaviour:\n * <ol>\n * <li> On first entry, retrieve an instance of the configured\n * login shell from the ShellManager and run it.\n * <li> Handle a shell switch or close down disgracefully when\n * problems (i.e. unhandled unchecked exceptions) occur in the\n * running shell.\n * </ol>\n */", "public", "void", "run", "(", ")", "{", "try", "{", "doRun", "(", ")", ";", "}", "catch", "(", "Exception", "ex", ")", "{", "LOG", ".", "log", "(", "Level", ".", "SEVERE", ",", "\"", "run()", "\"", ",", "ex", ")", ";", "}", "finally", "{", "if", "(", "!", "dead", ")", "{", "close", "(", ")", ";", "}", "}", "LOG", ".", "log", "(", "Level", ".", "FINE", ",", "\"", "run():: Returning from ", "\"", "+", "this", ".", "toString", "(", ")", ")", ";", "}", "protected", "abstract", "void", "doRun", "(", ")", "throws", "Exception", ";", "protected", "abstract", "void", "doClose", "(", ")", "throws", "Exception", ";", "/**\n * Method to access the associated connection data.\n *\n * @return ConnectionData associated with the Connection instance.\n * @see ConnectionData\n */", "public", "ConnectionData", "getConnectionData", "(", ")", "{", "return", "connectionData", ";", "}", "/**\n * Closes the connection and its underlying i/o and network\n * resources.<br>\n */", "public", "synchronized", "void", "close", "(", ")", "{", "if", "(", "dead", ")", "{", "return", ";", "}", "else", "{", "try", "{", "dead", "=", "true", ";", "doClose", "(", ")", ";", "}", "catch", "(", "Exception", "ex", ")", "{", "LOG", ".", "log", "(", "Level", ".", "SEVERE", ",", "\"", "close()", "\"", ",", "ex", ")", ";", "}", "try", "{", "connectionData", ".", "getSocket", "(", ")", ".", "close", "(", ")", ";", "}", "catch", "(", "Exception", "ex", ")", "{", "LOG", ".", "log", "(", "Level", ".", "SEVERE", ",", "\"", "close()", "\"", ",", "ex", ")", ";", "}", "try", "{", "connectionData", ".", "getManager", "(", ")", ".", "registerClosedConnection", "(", "this", ")", ";", "}", "catch", "(", "Exception", "ex", ")", "{", "LOG", ".", "log", "(", "Level", ".", "SEVERE", ",", "\"", "close()", "\"", ",", "ex", ")", ";", "}", "try", "{", "interrupt", "(", ")", ";", "}", "catch", "(", "Exception", "ex", ")", "{", "LOG", ".", "log", "(", "Level", ".", "SEVERE", ",", "\"", "close()", "\"", ",", "ex", ")", ";", "}", "LOG", ".", "log", "(", "Level", ".", "FINE", ",", "\"", "Closed ", "\"", "+", "this", ".", "toString", "(", ")", "+", "\"", " and inactive.", "\"", ")", ";", "}", "}", "/**\n * Returns if a connection has been closed.<br>\n *\n * @return the state of the connection.\n */", "public", "boolean", "isActive", "(", ")", "{", "return", "!", "dead", ";", "}", "/****** Event handling ****************/", "/**\n * Method that registers a ConnectionListener with the\n * Connection instance.\n *\n * @param cl ConnectionListener to be registered.\n * @see ConnectionListener\n */", "public", "void", "addConnectionListener", "(", "ConnectionListener", "cl", ")", "{", "listeners", ".", "add", "(", "cl", ")", ";", "}", "/**\n * Method that removes a ConnectionListener from the\n * Connection instance.\n *\n * @param cl ConnectionListener to be removed.\n * @see ConnectionListener\n */", "public", "void", "removeConnectionListener", "(", "ConnectionListener", "cl", ")", "{", "listeners", ".", "remove", "(", "cl", ")", ";", "}", "/**\n * Method called by the io subsystem to pass on a\n * \"low-level\" event. It will be properly delegated to\n * all registered listeners.\n *\n * @param ce ConnectionEvent to be processed.\n * @see ConnectionEvent\n */", "public", "void", "processConnectionEvent", "(", "ConnectionEvent", "ce", ")", "{", "for", "(", "ConnectionListener", "cl", ":", "listeners", ")", "{", "switch", "(", "ce", ".", "getType", "(", ")", ")", "{", "case", "CONNECTION_IDLE", ":", "cl", ".", "connectionIdle", "(", "ce", ")", ";", "break", ";", "case", "CONNECTION_TIMEDOUT", ":", "cl", ".", "connectionTimedOut", "(", "ce", ")", ";", "break", ";", "case", "CONNECTION_LOGOUTREQUEST", ":", "cl", ".", "connectionLogoutRequest", "(", "ce", ")", ";", "break", ";", "case", "CONNECTION_BREAK", ":", "cl", ".", "connectionSentBreak", "(", "ce", ")", ";", "break", ";", "case", "CONNECTION_TERMINAL_GEOMETRY_CHANGED", ":", "cl", ".", "connectionTerminalGeometryChanged", "(", "ce", ")", ";", "}", "}", "}", "}" ]
Class that implements a connection with this telnet daemon.<br> It is derived from java.lang.Thread, which reflects the architecture constraint of one thread per connection.
[ "Class", "that", "implements", "a", "connection", "with", "this", "telnet", "daemon", ".", "<br", ">", "It", "is", "derived", "from", "java", ".", "lang", ".", "Thread", "which", "reflects", "the", "architecture", "constraint", "of", "one", "thread", "per", "connection", "." ]
[ "//unique number for a thread in the thread group", "//Associations", "//associated information", "//init the connection listeners for events", "//(there should actually be only one or two)", "//constructor", "//Handle properly", "//call close if not dead already", "//run", "//getConnectionData", "//connection dead", "//close i/o", "//handle", "//close socket", "//handle", "//register closed connection in ConnectionManager", "//handle", "//try to interrupt it", "//handle", "//close", "//isClosed", "//addConnectionListener", "//removeConnectionListener", "//processConnectionEvent" ]
[ { "param": "Thread", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Thread", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
14
1,087
232
5a819ec555cdaac9c3f6395b382a4887840691df
hashansilva/vaadin-example
node_modules/.pnpm/@vaadin/[email protected]/node_modules/@vaadin/vaadin-avatar/src/vaadin-avatar.js
[ "Unlicense" ]
JavaScript
AvatarElement
/** * `<vaadin-avatar>` is a Web Component providing avatar displaying functionality. * * ```html * <vaadin-avatar img="avatars/avatar-1.jpg"></vaadin-avatar> * ``` * * ### Styling * * The following shadow DOM parts are exposed for styling: * * Part name | Description * --------- | --------------- * `abbr` | The abbreviation element * `icon` | The icon element * * The following attributes are exposed for styling: * * Attribute | Description * --------- | ----------- * `has-color-index` | Set when the avatar has `colorIndex` and the corresponding custom CSS property exists. * * See [Styling Components](https://vaadin.com/docs/v14/themes/styling-components.html) documentation. * * @extends HTMLElement * @mixes ElementMixin * @mixes ThemableMixin */
`` is a Web Component providing avatar displaying functionality. Styling The following shadow DOM parts are exposed for styling. Part name | Description | `abbr` | The abbreviation element `icon` | The icon element The following attributes are exposed for styling. Attribute | Description | `has-color-index` | Set when the avatar has `colorIndex` and the corresponding custom CSS property exists. See [Styling Components] documentation.
[ "`", "`", "is", "a", "Web", "Component", "providing", "avatar", "displaying", "functionality", ".", "Styling", "The", "following", "shadow", "DOM", "parts", "are", "exposed", "for", "styling", ".", "Part", "name", "|", "Description", "|", "`", "abbr", "`", "|", "The", "abbreviation", "element", "`", "icon", "`", "|", "The", "icon", "element", "The", "following", "attributes", "are", "exposed", "for", "styling", ".", "Attribute", "|", "Description", "|", "`", "has", "-", "color", "-", "index", "`", "|", "Set", "when", "the", "avatar", "has", "`", "colorIndex", "`", "and", "the", "corresponding", "custom", "CSS", "property", "exists", ".", "See", "[", "Styling", "Components", "]", "documentation", "." ]
class AvatarElement extends ElementMixin(ThemableMixin(PolymerElement)) { static get template() { return html` <style> :host { display: inline-block; flex: none; border-radius: 50%; overflow: hidden; height: var(--vaadin-avatar-size); width: var(--vaadin-avatar-size); border: var(--vaadin-avatar-outline-width) solid transparent; margin: calc(var(--vaadin-avatar-outline-width) * -1); background-clip: content-box; --vaadin-avatar-outline-width: 2px; --vaadin-avatar-size: 64px; } img { height: 100%; width: 100%; } [part='icon'] { font-size: 5.6em; } [part='abbr'] { font-size: 2.2em; } [part='icon'] > text { font-family: 'vaadin-avatar-icons'; } :host([hidden]) { display: none !important; } svg[hidden] { display: none !important; } :host([has-color-index]) { position: relative; background-color: var(--vaadin-avatar-user-color); } :host([has-color-index])::before { position: absolute; z-index: 1; content: ''; top: 0; left: 0; bottom: 0; right: 0; border-radius: 50%; box-shadow: inset 0 0 0 2px var(--vaadin-avatar-user-color); } </style> <img hidden$="[[!__imgVisible]]" src$="[[img]]" aria-hidden="true" /> <svg part="icon" hidden$="[[!__iconVisible]]" id="avatar-icon" viewBox="-50 -50 100 100" preserveAspectRatio="xMidYMid meet" aria-hidden="true" > <text dy=".35em" text-anchor="middle"></text> </svg> <svg part="abbr" hidden$="[[!__abbrVisible]]" id="avatar-abbr" viewBox="-50 -50 100 100" preserveAspectRatio="xMidYMid meet" aria-hidden="true" > <text dy=".35em" text-anchor="middle">[[abbr]]</text> </svg> `; } static get is() { return 'vaadin-avatar'; } static get version() { return '2.0.2'; } static get properties() { return { /** * The path to the image */ img: { type: String, reflectToAttribute: true }, /** * A shortened form of name that is displayed * in the avatar when `img` is not provided. */ abbr: { type: String, reflectToAttribute: true }, /** * Full name of the user * used for the title of the avatar. */ name: { type: String, reflectToAttribute: true }, /** * Color index used for avatar background. */ colorIndex: { type: Number, observer: '__colorIndexChanged' }, /** * The object used to localize this component. * To change the default localization, replace the entire * _i18n_ object or just the property you want to modify. * * The object has the following JSON structure and default values: { // Translation of the anonymous user avatar title. anonymous: 'anonymous' } * @type {!AvatarI18n} * @default {English/US} */ i18n: { type: Object, value: () => { return { anonymous: 'anonymous' }; } }, /** @private */ __imgVisible: Boolean, /** @private */ __iconVisible: Boolean, /** @private */ __abbrVisible: Boolean }; } static get observers() { return ['__imgOrAbbrOrNameChanged(img, abbr, name)', '__i18nChanged(i18n.*)']; } /** @protected */ ready() { super.ready(); this.__updateVisibility(); // Should set `anonymous` if name / abbr is not provided if (!this.name && !this.abbr) { this.__setTitle(this.name); } this.setAttribute('role', 'button'); if (!this.hasAttribute('tabindex')) { this.setAttribute('tabindex', '0'); } this.addEventListener('focusin', () => { this.__setFocused(true); }); this.addEventListener('focusout', () => { this.__setFocused(false); }); } /** @private */ __setFocused(focused) { if (focused) { this.setAttribute('focused', ''); if (keyboardActive) { this.setAttribute('focus-ring', ''); } } else { this.removeAttribute('focused'); this.removeAttribute('focus-ring'); } } /** @private */ __colorIndexChanged(index) { if (index != null) { const prop = `--vaadin-user-color-${index}`; // check if custom CSS property is defined const isValid = Boolean(getComputedStyle(document.documentElement).getPropertyValue(prop)); if (isValid) { this.setAttribute('has-color-index', ''); this.style.setProperty('--vaadin-avatar-user-color', `var(${prop})`); } else { this.removeAttribute('has-color-index'); console.warn(`The CSS property --vaadin-user-color-${index} is not defined`); } } else { this.removeAttribute('has-color-index'); } } /** @private */ __imgOrAbbrOrNameChanged(img, abbr, name) { this.__updateVisibility(); if (abbr && abbr !== this.__generatedAbbr) { this.__setTitle(name ? `${name} (${abbr})` : abbr); return; } if (name) { this.abbr = this.__generatedAbbr = name .split(' ') .map((word) => word.charAt(0)) .join(''); } else { this.abbr = undefined; } this.__setTitle(name); } /** @private */ __i18nChanged(i18n) { if (i18n.base && i18n.base.anonymous) { if (this.__oldAnonymous && this.getAttribute('title') === this.__oldAnonymous) { this.__setTitle(); } this.__oldAnonymous = i18n.base.anonymous; } } /** @private */ __updateVisibility() { this.__imgVisible = !!this.img; this.__abbrVisible = !this.img && !!this.abbr; this.__iconVisible = !this.img && !this.abbr; } /** @private */ __setTitle(title) { if (title) { this.setAttribute('title', title); } else { this.setAttribute('title', this.i18n.anonymous); } } }
[ "class", "AvatarElement", "extends", "ElementMixin", "(", "ThemableMixin", "(", "PolymerElement", ")", ")", "{", "static", "get", "template", "(", ")", "{", "return", "html", "`", "`", ";", "}", "static", "get", "is", "(", ")", "{", "return", "'vaadin-avatar'", ";", "}", "static", "get", "version", "(", ")", "{", "return", "'2.0.2'", ";", "}", "static", "get", "properties", "(", ")", "{", "return", "{", "img", ":", "{", "type", ":", "String", ",", "reflectToAttribute", ":", "true", "}", ",", "abbr", ":", "{", "type", ":", "String", ",", "reflectToAttribute", ":", "true", "}", ",", "name", ":", "{", "type", ":", "String", ",", "reflectToAttribute", ":", "true", "}", ",", "colorIndex", ":", "{", "type", ":", "Number", ",", "observer", ":", "'__colorIndexChanged'", "}", ",", "i18n", ":", "{", "type", ":", "Object", ",", "value", ":", "(", ")", "=>", "{", "return", "{", "anonymous", ":", "'anonymous'", "}", ";", "}", "}", ",", "__imgVisible", ":", "Boolean", ",", "__iconVisible", ":", "Boolean", ",", "__abbrVisible", ":", "Boolean", "}", ";", "}", "static", "get", "observers", "(", ")", "{", "return", "[", "'__imgOrAbbrOrNameChanged(img, abbr, name)'", ",", "'__i18nChanged(i18n.*)'", "]", ";", "}", "ready", "(", ")", "{", "super", ".", "ready", "(", ")", ";", "this", ".", "__updateVisibility", "(", ")", ";", "if", "(", "!", "this", ".", "name", "&&", "!", "this", ".", "abbr", ")", "{", "this", ".", "__setTitle", "(", "this", ".", "name", ")", ";", "}", "this", ".", "setAttribute", "(", "'role'", ",", "'button'", ")", ";", "if", "(", "!", "this", ".", "hasAttribute", "(", "'tabindex'", ")", ")", "{", "this", ".", "setAttribute", "(", "'tabindex'", ",", "'0'", ")", ";", "}", "this", ".", "addEventListener", "(", "'focusin'", ",", "(", ")", "=>", "{", "this", ".", "__setFocused", "(", "true", ")", ";", "}", ")", ";", "this", ".", "addEventListener", "(", "'focusout'", ",", "(", ")", "=>", "{", "this", ".", "__setFocused", "(", "false", ")", ";", "}", ")", ";", "}", "__setFocused", "(", "focused", ")", "{", "if", "(", "focused", ")", "{", "this", ".", "setAttribute", "(", "'focused'", ",", "''", ")", ";", "if", "(", "keyboardActive", ")", "{", "this", ".", "setAttribute", "(", "'focus-ring'", ",", "''", ")", ";", "}", "}", "else", "{", "this", ".", "removeAttribute", "(", "'focused'", ")", ";", "this", ".", "removeAttribute", "(", "'focus-ring'", ")", ";", "}", "}", "__colorIndexChanged", "(", "index", ")", "{", "if", "(", "index", "!=", "null", ")", "{", "const", "prop", "=", "`", "${", "index", "}", "`", ";", "const", "isValid", "=", "Boolean", "(", "getComputedStyle", "(", "document", ".", "documentElement", ")", ".", "getPropertyValue", "(", "prop", ")", ")", ";", "if", "(", "isValid", ")", "{", "this", ".", "setAttribute", "(", "'has-color-index'", ",", "''", ")", ";", "this", ".", "style", ".", "setProperty", "(", "'--vaadin-avatar-user-color'", ",", "`", "${", "prop", "}", "`", ")", ";", "}", "else", "{", "this", ".", "removeAttribute", "(", "'has-color-index'", ")", ";", "console", ".", "warn", "(", "`", "${", "index", "}", "`", ")", ";", "}", "}", "else", "{", "this", ".", "removeAttribute", "(", "'has-color-index'", ")", ";", "}", "}", "__imgOrAbbrOrNameChanged", "(", "img", ",", "abbr", ",", "name", ")", "{", "this", ".", "__updateVisibility", "(", ")", ";", "if", "(", "abbr", "&&", "abbr", "!==", "this", ".", "__generatedAbbr", ")", "{", "this", ".", "__setTitle", "(", "name", "?", "`", "${", "name", "}", "${", "abbr", "}", "`", ":", "abbr", ")", ";", "return", ";", "}", "if", "(", "name", ")", "{", "this", ".", "abbr", "=", "this", ".", "__generatedAbbr", "=", "name", ".", "split", "(", "' '", ")", ".", "map", "(", "(", "word", ")", "=>", "word", ".", "charAt", "(", "0", ")", ")", ".", "join", "(", "''", ")", ";", "}", "else", "{", "this", ".", "abbr", "=", "undefined", ";", "}", "this", ".", "__setTitle", "(", "name", ")", ";", "}", "__i18nChanged", "(", "i18n", ")", "{", "if", "(", "i18n", ".", "base", "&&", "i18n", ".", "base", ".", "anonymous", ")", "{", "if", "(", "this", ".", "__oldAnonymous", "&&", "this", ".", "getAttribute", "(", "'title'", ")", "===", "this", ".", "__oldAnonymous", ")", "{", "this", ".", "__setTitle", "(", ")", ";", "}", "this", ".", "__oldAnonymous", "=", "i18n", ".", "base", ".", "anonymous", ";", "}", "}", "__updateVisibility", "(", ")", "{", "this", ".", "__imgVisible", "=", "!", "!", "this", ".", "img", ";", "this", ".", "__abbrVisible", "=", "!", "this", ".", "img", "&&", "!", "!", "this", ".", "abbr", ";", "this", ".", "__iconVisible", "=", "!", "this", ".", "img", "&&", "!", "this", ".", "abbr", ";", "}", "__setTitle", "(", "title", ")", "{", "if", "(", "title", ")", "{", "this", ".", "setAttribute", "(", "'title'", ",", "title", ")", ";", "}", "else", "{", "this", ".", "setAttribute", "(", "'title'", ",", "this", ".", "i18n", ".", "anonymous", ")", ";", "}", "}", "}" ]
`<vaadin-avatar>` is a Web Component providing avatar displaying functionality.
[ "`", "<vaadin", "-", "avatar", ">", "`", "is", "a", "Web", "Component", "providing", "avatar", "displaying", "functionality", "." ]
[ "/**\n * The path to the image\n */", "/**\n * A shortened form of name that is displayed\n * in the avatar when `img` is not provided.\n */", "/**\n * Full name of the user\n * used for the title of the avatar.\n */", "/**\n * Color index used for avatar background.\n */", "/**\n * The object used to localize this component.\n * To change the default localization, replace the entire\n * _i18n_ object or just the property you want to modify.\n *\n * The object has the following JSON structure and default values:\n {\n // Translation of the anonymous user avatar title.\n anonymous: 'anonymous'\n }\n * @type {!AvatarI18n}\n * @default {English/US}\n */", "/** @private */", "/** @private */", "/** @private */", "/** @protected */", "// Should set `anonymous` if name / abbr is not provided", "/** @private */", "/** @private */", "// check if custom CSS property is defined", "/** @private */", "/** @private */", "/** @private */", "/** @private */" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
17
1,607
182
e384c22d794747fa62aea18f6568e02e5f8150ce
Axiologic/apars
cardinal/libs/zxing.js
[ "MIT" ]
JavaScript
AbstractUPCEANReader
/** * <p>Encapsulates functionality and implementation that is common to UPC and EAN families * of one-dimensional barcodes.</p> * * @author [email protected] (Daniel Switkin) * @author Sean Owen * @author [email protected] (Alasdair Mackintosh) */
Encapsulates functionality and implementation that is common to UPC and EAN families of one-dimensional barcodes.
[ "Encapsulates", "functionality", "and", "implementation", "that", "is", "common", "to", "UPC", "and", "EAN", "families", "of", "one", "-", "dimensional", "barcodes", "." ]
class AbstractUPCEANReader extends OneDReader { constructor() { super(...arguments); this.decodeRowStringBuffer = ''; } // private final UPCEANExtensionSupport extensionReader; // private final EANManufacturerOrgSupport eanManSupport; /* protected UPCEANReader() { decodeRowStringBuffer = new StringBuilder(20); extensionReader = new UPCEANExtensionSupport(); eanManSupport = new EANManufacturerOrgSupport(); } */ static findStartGuardPattern(row) { let foundStart = false; let startRange; let nextStart = 0; let counters = Int32Array.from([0, 0, 0]); while (!foundStart) { counters = Int32Array.from([0, 0, 0]); startRange = AbstractUPCEANReader.findGuardPattern(row, nextStart, false, this.START_END_PATTERN, counters); let start = startRange[0]; nextStart = startRange[1]; let quietStart = start - (nextStart - start); if (quietStart >= 0) { foundStart = row.isRange(quietStart, start, false); } } return startRange; } static checkChecksum(s) { return AbstractUPCEANReader.checkStandardUPCEANChecksum(s); } static checkStandardUPCEANChecksum(s) { let length = s.length; if (length === 0) return false; let check = parseInt(s.charAt(length - 1), 10); return AbstractUPCEANReader.getStandardUPCEANChecksum(s.substring(0, length - 1)) === check; } static getStandardUPCEANChecksum(s) { let length = s.length; let sum = 0; for (let i = length - 1; i >= 0; i -= 2) { let digit = s.charAt(i).charCodeAt(0) - '0'.charCodeAt(0); if (digit < 0 || digit > 9) { throw new FormatException(); } sum += digit; } sum *= 3; for (let i = length - 2; i >= 0; i -= 2) { let digit = s.charAt(i).charCodeAt(0) - '0'.charCodeAt(0); if (digit < 0 || digit > 9) { throw new FormatException(); } sum += digit; } return (1000 - sum) % 10; } static decodeEnd(row, endStart) { return AbstractUPCEANReader.findGuardPattern(row, endStart, false, AbstractUPCEANReader.START_END_PATTERN, new Int32Array(AbstractUPCEANReader.START_END_PATTERN.length).fill(0)); } /** * @throws NotFoundException */ static findGuardPatternWithoutCounters(row, rowOffset, whiteFirst, pattern) { return this.findGuardPattern(row, rowOffset, whiteFirst, pattern, new Int32Array(pattern.length)); } /** * @param row row of black/white values to search * @param rowOffset position to start search * @param whiteFirst if true, indicates that the pattern specifies white/black/white/... * pixel counts, otherwise, it is interpreted as black/white/black/... * @param pattern pattern of counts of number of black and white pixels that are being * searched for as a pattern * @param counters array of counters, as long as pattern, to re-use * @return start/end horizontal offset of guard pattern, as an array of two ints * @throws NotFoundException if pattern is not found */ static findGuardPattern(row, rowOffset, whiteFirst, pattern, counters) { let width = row.getSize(); rowOffset = whiteFirst ? row.getNextUnset(rowOffset) : row.getNextSet(rowOffset); let counterPosition = 0; let patternStart = rowOffset; let patternLength = pattern.length; let isWhite = whiteFirst; for (let x = rowOffset; x < width; x++) { if (row.get(x) !== isWhite) { counters[counterPosition]++; } else { if (counterPosition === patternLength - 1) { if (OneDReader.patternMatchVariance(counters, pattern, AbstractUPCEANReader.MAX_INDIVIDUAL_VARIANCE) < AbstractUPCEANReader.MAX_AVG_VARIANCE) { return Int32Array.from([patternStart, x]); } patternStart += counters[0] + counters[1]; let slice = counters.slice(2, counters.length - 1); for (let i = 0; i < counterPosition - 1; i++) { counters[i] = slice[i]; } counters[counterPosition - 1] = 0; counters[counterPosition] = 0; counterPosition--; } else { counterPosition++; } counters[counterPosition] = 1; isWhite = !isWhite; } } throw new NotFoundException(); } static decodeDigit(row, counters, rowOffset, patterns) { this.recordPattern(row, rowOffset, counters); let bestVariance = this.MAX_AVG_VARIANCE; let bestMatch = -1; let max = patterns.length; for (let i = 0; i < max; i++) { let pattern = patterns[i]; let variance = OneDReader.patternMatchVariance(counters, pattern, AbstractUPCEANReader.MAX_INDIVIDUAL_VARIANCE); if (variance < bestVariance) { bestVariance = variance; bestMatch = i; } } if (bestMatch >= 0) { return bestMatch; } else { throw new NotFoundException(); } } }
[ "class", "AbstractUPCEANReader", "extends", "OneDReader", "{", "constructor", "(", ")", "{", "super", "(", "...", "arguments", ")", ";", "this", ".", "decodeRowStringBuffer", "=", "''", ";", "}", "static", "findStartGuardPattern", "(", "row", ")", "{", "let", "foundStart", "=", "false", ";", "let", "startRange", ";", "let", "nextStart", "=", "0", ";", "let", "counters", "=", "Int32Array", ".", "from", "(", "[", "0", ",", "0", ",", "0", "]", ")", ";", "while", "(", "!", "foundStart", ")", "{", "counters", "=", "Int32Array", ".", "from", "(", "[", "0", ",", "0", ",", "0", "]", ")", ";", "startRange", "=", "AbstractUPCEANReader", ".", "findGuardPattern", "(", "row", ",", "nextStart", ",", "false", ",", "this", ".", "START_END_PATTERN", ",", "counters", ")", ";", "let", "start", "=", "startRange", "[", "0", "]", ";", "nextStart", "=", "startRange", "[", "1", "]", ";", "let", "quietStart", "=", "start", "-", "(", "nextStart", "-", "start", ")", ";", "if", "(", "quietStart", ">=", "0", ")", "{", "foundStart", "=", "row", ".", "isRange", "(", "quietStart", ",", "start", ",", "false", ")", ";", "}", "}", "return", "startRange", ";", "}", "static", "checkChecksum", "(", "s", ")", "{", "return", "AbstractUPCEANReader", ".", "checkStandardUPCEANChecksum", "(", "s", ")", ";", "}", "static", "checkStandardUPCEANChecksum", "(", "s", ")", "{", "let", "length", "=", "s", ".", "length", ";", "if", "(", "length", "===", "0", ")", "return", "false", ";", "let", "check", "=", "parseInt", "(", "s", ".", "charAt", "(", "length", "-", "1", ")", ",", "10", ")", ";", "return", "AbstractUPCEANReader", ".", "getStandardUPCEANChecksum", "(", "s", ".", "substring", "(", "0", ",", "length", "-", "1", ")", ")", "===", "check", ";", "}", "static", "getStandardUPCEANChecksum", "(", "s", ")", "{", "let", "length", "=", "s", ".", "length", ";", "let", "sum", "=", "0", ";", "for", "(", "let", "i", "=", "length", "-", "1", ";", "i", ">=", "0", ";", "i", "-=", "2", ")", "{", "let", "digit", "=", "s", ".", "charAt", "(", "i", ")", ".", "charCodeAt", "(", "0", ")", "-", "'0'", ".", "charCodeAt", "(", "0", ")", ";", "if", "(", "digit", "<", "0", "||", "digit", ">", "9", ")", "{", "throw", "new", "FormatException", "(", ")", ";", "}", "sum", "+=", "digit", ";", "}", "sum", "*=", "3", ";", "for", "(", "let", "i", "=", "length", "-", "2", ";", "i", ">=", "0", ";", "i", "-=", "2", ")", "{", "let", "digit", "=", "s", ".", "charAt", "(", "i", ")", ".", "charCodeAt", "(", "0", ")", "-", "'0'", ".", "charCodeAt", "(", "0", ")", ";", "if", "(", "digit", "<", "0", "||", "digit", ">", "9", ")", "{", "throw", "new", "FormatException", "(", ")", ";", "}", "sum", "+=", "digit", ";", "}", "return", "(", "1000", "-", "sum", ")", "%", "10", ";", "}", "static", "decodeEnd", "(", "row", ",", "endStart", ")", "{", "return", "AbstractUPCEANReader", ".", "findGuardPattern", "(", "row", ",", "endStart", ",", "false", ",", "AbstractUPCEANReader", ".", "START_END_PATTERN", ",", "new", "Int32Array", "(", "AbstractUPCEANReader", ".", "START_END_PATTERN", ".", "length", ")", ".", "fill", "(", "0", ")", ")", ";", "}", "static", "findGuardPatternWithoutCounters", "(", "row", ",", "rowOffset", ",", "whiteFirst", ",", "pattern", ")", "{", "return", "this", ".", "findGuardPattern", "(", "row", ",", "rowOffset", ",", "whiteFirst", ",", "pattern", ",", "new", "Int32Array", "(", "pattern", ".", "length", ")", ")", ";", "}", "static", "findGuardPattern", "(", "row", ",", "rowOffset", ",", "whiteFirst", ",", "pattern", ",", "counters", ")", "{", "let", "width", "=", "row", ".", "getSize", "(", ")", ";", "rowOffset", "=", "whiteFirst", "?", "row", ".", "getNextUnset", "(", "rowOffset", ")", ":", "row", ".", "getNextSet", "(", "rowOffset", ")", ";", "let", "counterPosition", "=", "0", ";", "let", "patternStart", "=", "rowOffset", ";", "let", "patternLength", "=", "pattern", ".", "length", ";", "let", "isWhite", "=", "whiteFirst", ";", "for", "(", "let", "x", "=", "rowOffset", ";", "x", "<", "width", ";", "x", "++", ")", "{", "if", "(", "row", ".", "get", "(", "x", ")", "!==", "isWhite", ")", "{", "counters", "[", "counterPosition", "]", "++", ";", "}", "else", "{", "if", "(", "counterPosition", "===", "patternLength", "-", "1", ")", "{", "if", "(", "OneDReader", ".", "patternMatchVariance", "(", "counters", ",", "pattern", ",", "AbstractUPCEANReader", ".", "MAX_INDIVIDUAL_VARIANCE", ")", "<", "AbstractUPCEANReader", ".", "MAX_AVG_VARIANCE", ")", "{", "return", "Int32Array", ".", "from", "(", "[", "patternStart", ",", "x", "]", ")", ";", "}", "patternStart", "+=", "counters", "[", "0", "]", "+", "counters", "[", "1", "]", ";", "let", "slice", "=", "counters", ".", "slice", "(", "2", ",", "counters", ".", "length", "-", "1", ")", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "counterPosition", "-", "1", ";", "i", "++", ")", "{", "counters", "[", "i", "]", "=", "slice", "[", "i", "]", ";", "}", "counters", "[", "counterPosition", "-", "1", "]", "=", "0", ";", "counters", "[", "counterPosition", "]", "=", "0", ";", "counterPosition", "--", ";", "}", "else", "{", "counterPosition", "++", ";", "}", "counters", "[", "counterPosition", "]", "=", "1", ";", "isWhite", "=", "!", "isWhite", ";", "}", "}", "throw", "new", "NotFoundException", "(", ")", ";", "}", "static", "decodeDigit", "(", "row", ",", "counters", ",", "rowOffset", ",", "patterns", ")", "{", "this", ".", "recordPattern", "(", "row", ",", "rowOffset", ",", "counters", ")", ";", "let", "bestVariance", "=", "this", ".", "MAX_AVG_VARIANCE", ";", "let", "bestMatch", "=", "-", "1", ";", "let", "max", "=", "patterns", ".", "length", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "max", ";", "i", "++", ")", "{", "let", "pattern", "=", "patterns", "[", "i", "]", ";", "let", "variance", "=", "OneDReader", ".", "patternMatchVariance", "(", "counters", ",", "pattern", ",", "AbstractUPCEANReader", ".", "MAX_INDIVIDUAL_VARIANCE", ")", ";", "if", "(", "variance", "<", "bestVariance", ")", "{", "bestVariance", "=", "variance", ";", "bestMatch", "=", "i", ";", "}", "}", "if", "(", "bestMatch", ">=", "0", ")", "{", "return", "bestMatch", ";", "}", "else", "{", "throw", "new", "NotFoundException", "(", ")", ";", "}", "}", "}" ]
<p>Encapsulates functionality and implementation that is common to UPC and EAN families of one-dimensional barcodes.</p>
[ "<p", ">", "Encapsulates", "functionality", "and", "implementation", "that", "is", "common", "to", "UPC", "and", "EAN", "families", "of", "one", "-", "dimensional", "barcodes", ".", "<", "/", "p", ">" ]
[ "// private final UPCEANExtensionSupport extensionReader;", "// private final EANManufacturerOrgSupport eanManSupport;", "/*\n protected UPCEANReader() {\n decodeRowStringBuffer = new StringBuilder(20);\n extensionReader = new UPCEANExtensionSupport();\n eanManSupport = new EANManufacturerOrgSupport();\n }\n */", "/**\n * @throws NotFoundException\n */", "/**\n * @param row row of black/white values to search\n * @param rowOffset position to start search\n * @param whiteFirst if true, indicates that the pattern specifies white/black/white/...\n * pixel counts, otherwise, it is interpreted as black/white/black/...\n * @param pattern pattern of counts of number of black and white pixels that are being\n * searched for as a pattern\n * @param counters array of counters, as long as pattern, to re-use\n * @return start/end horizontal offset of guard pattern, as an array of two ints\n * @throws NotFoundException if pattern is not found\n */" ]
[ { "param": "OneDReader", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "OneDReader", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
18
1,290
77
b6e84fd308de89f3a945612791579fe4b1d994dd
natke/QuantumLibraries
Chemistry/src/DataModel/JsonSerialization/FermionWavefunctionJsonConverter.cs
[ "MIT" ]
C#
FermionWavefunctionJsonConverter
/// <summary> /// This <see href="Newtonsoft.Json.JsonConverter" /> allows correctly serialized HamiltonianTerms. /// This terms are in general problematic because their keys are not strings, /// but <see href="HamiltonianTerm" /> instances, which <see href="Newtonsoft.Json" /> doesn't like by default. /// This converts the Dictionaries to List of Tuples, in which the first /// item of the tuple is the key and the second the value. /// </summary>
This allows correctly serialized HamiltonianTerms. This terms are in general problematic because their keys are not strings, but instances, which doesn't like by default. This converts the Dictionaries to List of Tuples, in which the first item of the tuple is the key and the second the value.
[ "This", "allows", "correctly", "serialized", "HamiltonianTerms", ".", "This", "terms", "are", "in", "general", "problematic", "because", "their", "keys", "are", "not", "strings", "but", "instances", "which", "doesn", "'", "t", "like", "by", "default", ".", "This", "converts", "the", "Dictionaries", "to", "List", "of", "Tuples", "in", "which", "the", "first", "item", "of", "the", "tuple", "is", "the", "key", "and", "the", "second", "the", "value", "." ]
public class FermionWavefunctionJsonConverter : JsonConverter { public override bool CanConvert(Type objectType) => objectType.IsGenericType && (objectType.GetGenericTypeDefinition() == typeof(Dictionary<,>)); public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { var dictionary = (IDictionary)value; writer.WriteStartArray(); foreach (var key in dictionary.Keys) { var item = (key, dictionary[key]); serializer.Serialize(writer, item); } writer.WriteEndArray(); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { Debug.Assert(CanConvert(objectType)); var keyType = objectType.GetBasestType().GetGenericArguments()[0]; var valueType = objectType.GetBasestType().GetGenericArguments()[1]; var tupleType = typeof(ValueTuple<,>).MakeGenericType(keyType, valueType); var dictionaryType = typeof(Dictionary<,>).MakeGenericType(keyType, valueType); var result = (IDictionary)Activator.CreateInstance(dictionaryType); if (reader.TokenType == JsonToken.Null) return null; while (reader.Read()) { if (reader.TokenType == JsonToken.EndArray) { return result; } if (reader.TokenType == JsonToken.StartObject) { dynamic item = serializer.Deserialize(reader, tupleType); result.Add(item.Item1, item.Item2); } } return result; } }
[ "public", "class", "FermionWavefunctionJsonConverter", ":", "JsonConverter", "{", "public", "override", "bool", "CanConvert", "(", "Type", "objectType", ")", "=>", "objectType", ".", "IsGenericType", "&&", "(", "objectType", ".", "GetGenericTypeDefinition", "(", ")", "==", "typeof", "(", "Dictionary", "<", ",", ">", ")", ")", ";", "public", "override", "void", "WriteJson", "(", "JsonWriter", "writer", ",", "object", "value", ",", "JsonSerializer", "serializer", ")", "{", "var", "dictionary", "=", "(", "IDictionary", ")", "value", ";", "writer", ".", "WriteStartArray", "(", ")", ";", "foreach", "(", "var", "key", "in", "dictionary", ".", "Keys", ")", "{", "var", "item", "=", "(", "key", ",", "dictionary", "[", "key", "]", ")", ";", "serializer", ".", "Serialize", "(", "writer", ",", "item", ")", ";", "}", "writer", ".", "WriteEndArray", "(", ")", ";", "}", "public", "override", "object", "ReadJson", "(", "JsonReader", "reader", ",", "Type", "objectType", ",", "object", "existingValue", ",", "JsonSerializer", "serializer", ")", "{", "Debug", ".", "Assert", "(", "CanConvert", "(", "objectType", ")", ")", ";", "var", "keyType", "=", "objectType", ".", "GetBasestType", "(", ")", ".", "GetGenericArguments", "(", ")", "[", "0", "]", ";", "var", "valueType", "=", "objectType", ".", "GetBasestType", "(", ")", ".", "GetGenericArguments", "(", ")", "[", "1", "]", ";", "var", "tupleType", "=", "typeof", "(", "ValueTuple", "<", ",", ">", ")", ".", "MakeGenericType", "(", "keyType", ",", "valueType", ")", ";", "var", "dictionaryType", "=", "typeof", "(", "Dictionary", "<", ",", ">", ")", ".", "MakeGenericType", "(", "keyType", ",", "valueType", ")", ";", "var", "result", "=", "(", "IDictionary", ")", "Activator", ".", "CreateInstance", "(", "dictionaryType", ")", ";", "if", "(", "reader", ".", "TokenType", "==", "JsonToken", ".", "Null", ")", "return", "null", ";", "while", "(", "reader", ".", "Read", "(", ")", ")", "{", "if", "(", "reader", ".", "TokenType", "==", "JsonToken", ".", "EndArray", ")", "{", "return", "result", ";", "}", "if", "(", "reader", ".", "TokenType", "==", "JsonToken", ".", "StartObject", ")", "{", "dynamic", "item", "=", "serializer", ".", "Deserialize", "(", "reader", ",", "tupleType", ")", ";", "result", ".", "Add", "(", "item", ".", "Item1", ",", "item", ".", "Item2", ")", ";", "}", "}", "return", "result", ";", "}", "}" ]
This allows correctly serialized HamiltonianTerms.
[ "This", "allows", "correctly", "serialized", "HamiltonianTerms", "." ]
[ "/// <summary>", "/// Returns true only if the Type is HamitonianTerm or HamiltonianTerms", "/// </summary>", "/// <summary>", "/// Writers the HamiltonianTerms as a list of (Key, Value) tuples.", "/// </summary>", "/// <summary>", "/// Reads the HamiltonianTerms from a list of (Key, Value) tuples.", "/// </summary>" ]
[ { "param": "JsonConverter", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "JsonConverter", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
15
320
104
1f419c06ab15a037a87fc2768816124c0a71e94d
liketic/leetcode-java
src/DeleteOperationforTwoStrings/Solution.java
[ "Apache-2.0" ]
Java
Solution
/** * Given two words word1 and word2, find the minimum number of steps required to make word1 and * word2 the same, where in each step you can delete one character in either string. * * <pre> * Example 1: * Input: "sea", "eat" * Output: 2 * Explanation: You need one step to make "sea" to "ea" and another step to make "eat" to "ea". * Note: * The length of given words won't exceed 500. * Characters in given words can only be lower-case letters. * </pre> */
Given two words word1 and word2, find the minimum number of steps required to make word1 and word2 the same, where in each step you can delete one character in either string.
[ "Given", "two", "words", "word1", "and", "word2", "find", "the", "minimum", "number", "of", "steps", "required", "to", "make", "word1", "and", "word2", "the", "same", "where", "in", "each", "step", "you", "can", "delete", "one", "character", "in", "either", "string", "." ]
class Solution { public int minDistance(String word1, String word2) { int n = word1.length(); int l = word2.length(); int[][] dp = new int[n + 1][l + 1]; // The left string must be the LCS for (int i = 1; i <= n; i++) { for (int j = 1; j <= l; j++) { if (word1.charAt(i - 1) == word2.charAt(j - 1)) { dp[i][j] = dp[i - 1][j - 1] + 1; } else { dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]); } } } return (n + l - dp[n][l] * 2); } }
[ "class", "Solution", "{", "public", "int", "minDistance", "(", "String", "word1", ",", "String", "word2", ")", "{", "int", "n", "=", "word1", ".", "length", "(", ")", ";", "int", "l", "=", "word2", ".", "length", "(", ")", ";", "int", "[", "]", "[", "]", "dp", "=", "new", "int", "[", "n", "+", "1", "]", "[", "l", "+", "1", "]", ";", "for", "(", "int", "i", "=", "1", ";", "i", "<=", "n", ";", "i", "++", ")", "{", "for", "(", "int", "j", "=", "1", ";", "j", "<=", "l", ";", "j", "++", ")", "{", "if", "(", "word1", ".", "charAt", "(", "i", "-", "1", ")", "==", "word2", ".", "charAt", "(", "j", "-", "1", ")", ")", "{", "dp", "[", "i", "]", "[", "j", "]", "=", "dp", "[", "i", "-", "1", "]", "[", "j", "-", "1", "]", "+", "1", ";", "}", "else", "{", "dp", "[", "i", "]", "[", "j", "]", "=", "Math", ".", "max", "(", "dp", "[", "i", "-", "1", "]", "[", "j", "]", ",", "dp", "[", "i", "]", "[", "j", "-", "1", "]", ")", ";", "}", "}", "}", "return", "(", "n", "+", "l", "-", "dp", "[", "n", "]", "[", "l", "]", "*", "2", ")", ";", "}", "}" ]
Given two words word1 and word2, find the minimum number of steps required to make word1 and word2 the same, where in each step you can delete one character in either string.
[ "Given", "two", "words", "word1", "and", "word2", "find", "the", "minimum", "number", "of", "steps", "required", "to", "make", "word1", "and", "word2", "the", "same", "where", "in", "each", "step", "you", "can", "delete", "one", "character", "in", "either", "string", "." ]
[ "// The left string must be the LCS" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
18
190
130
dfec7626377db76cf399b37271aad460d2497632
katzer/mruby-yeah
mrblib/yeah/controller.rb
[ "MIT" ]
Ruby
Yeah
# MIT License # # Copyright (c) Sebastian Katzer 2017 # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE.
MIT License Copyright (c) Sebastian Katzer 2017 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
[ "MIT", "License", "Copyright", "(", "c", ")", "Sebastian", "Katzer", "2017", "Permission", "is", "hereby", "granted", "free", "of", "charge", "to", "any", "person", "obtaining", "a", "copy", "of", "this", "software", "and", "associated", "documentation", "files", "(", "the", "\"", "Software", "\"", ")", "to", "deal", "in", "the", "Software", "without", "restriction", "including", "without", "limitation", "the", "rights", "to", "use", "copy", "modify", "merge", "publish", "distribute", "sublicense", "and", "/", "or", "sell", "copies", "of", "the", "Software", "and", "to", "permit", "persons", "to", "whom", "the", "Software", "is", "furnished", "to", "do", "so", "subject", "to", "the", "following", "conditions", ".", "The", "above", "copyright", "notice", "and", "this", "permission", "notice", "shall", "be", "included", "in", "all", "copies", "or", "substantial", "portions", "of", "the", "Software", "." ]
module Yeah # Helper methods to use to generate responses class Controller # Calls the callback to generate a Shelf response. # # @param [ Hash ] env The shelf request. # @param [ Proc ] blk The app callback. # # @return [ Void ] def initialize(env, &blk) @env = env args = [] params.each { |key, val| args << val if key.is_a? Symbol } if blk res = instance_exec(*args, &blk) else dat = env[Shelf::SHELF_R3_DATA] __send__(dat[:action]&.to_s || 'index', *args) end @body = res unless @res end # The Shelf request object. # # @return [ Hash ] def request @env end # The query hash constructed by Shelf. # # @return [ Hash ] def params @env[Shelf::SHELF_REQUEST_QUERY_HASH] end # The Shelf logger if any. # # @return [ Object ] def logger @env[Shelf::SHELF_LOGGER] end # Render Shelf response. # # render 200 # => [200, { Content-Type: 'text/plain', Content-Length: 2 }, ['OK']] # render 'OK' # => [200, { Content-Type: 'text/plain', Content-Length: 2 }, ['OK']] # render json: 'OK', status: 200, headers: {} # => [200, { Content-Type: 'application/json', ... }, ['OK']] # # @params [ Hash|String|Int ] opts Either the status code, the plain body # or a hash with all attributes. # # @return [ Array ] def render(opts = {}) return @res if @res case opts when String opts = { plain: opts } when Integer opts = { status: opts } end status = opts[:status] || 200 headers = opts[:headers] || {} body = [] if opts.include? :redirect status = 303 headers['Location'] = opts[:redirect] else body, type = self.class.render_body(status, @body, opts) headers[Shelf::CONTENT_TYPE] = type headers[Shelf::CONTENT_LENGTH] = body.bytesize end @res = [status, headers, [*body]] end # @private # # Search for key like :json or :plain in opts and render their value. # # @param [ Int ] status # @param [ String ] body # @param [ Hash ] opts # # @return [ Array<String, String> ] Body and its content type. def self.render_body(status, body, opts) return [body, Shelf::Mime.mime_type('.txt')] if body if opts.include? :plain [opts[:plain], Shelf::Mime.mime_type('.txt')] elsif opts.include? :html [opts[:html], Shelf::Mime.mime_type('.html')] elsif opts.include? :json [opts[:json].to_json, Shelf::Mime.mime_type('.json')] else [Shelf::Utils::HTTP_STATUS_CODES[status], Shelf::Mime.mime_type('.txt')] end end end end
[ "module", "Yeah", "class", "Controller", "def", "initialize", "(", "env", ",", "&", "blk", ")", "@env", "=", "env", "args", "=", "[", "]", "params", ".", "each", "{", "|", "key", ",", "val", "|", "args", "<<", "val", "if", "key", ".", "is_a?", "Symbol", "}", "if", "blk", "res", "=", "instance_exec", "(", "*", "args", ",", "&", "blk", ")", "else", "dat", "=", "env", "[", "Shelf", "::", "SHELF_R3_DATA", "]", "__send__", "(", "dat", "[", ":action", "]", "&.", "to_s", "||", "'index'", ",", "*", "args", ")", "end", "@body", "=", "res", "unless", "@res", "end", "def", "request", "@env", "end", "def", "params", "@env", "[", "Shelf", "::", "SHELF_REQUEST_QUERY_HASH", "]", "end", "def", "logger", "@env", "[", "Shelf", "::", "SHELF_LOGGER", "]", "end", "def", "render", "(", "opts", "=", "{", "}", ")", "return", "@res", "if", "@res", "case", "opts", "when", "String", "opts", "=", "{", "plain", ":", "opts", "}", "when", "Integer", "opts", "=", "{", "status", ":", "opts", "}", "end", "status", "=", "opts", "[", ":status", "]", "||", "200", "headers", "=", "opts", "[", ":headers", "]", "||", "{", "}", "body", "=", "[", "]", "if", "opts", ".", "include?", ":redirect", "status", "=", "303", "headers", "[", "'Location'", "]", "=", "opts", "[", ":redirect", "]", "else", "body", ",", "type", "=", "self", ".", "class", ".", "render_body", "(", "status", ",", "@body", ",", "opts", ")", "headers", "[", "Shelf", "::", "CONTENT_TYPE", "]", "=", "type", "headers", "[", "Shelf", "::", "CONTENT_LENGTH", "]", "=", "body", ".", "bytesize", "end", "@res", "=", "[", "status", ",", "headers", ",", "[", "*", "body", "]", "]", "end", "def", "self", ".", "render_body", "(", "status", ",", "body", ",", "opts", ")", "return", "[", "body", ",", "Shelf", "::", "Mime", ".", "mime_type", "(", "'.txt'", ")", "]", "if", "body", "if", "opts", ".", "include?", ":plain", "[", "opts", "[", ":plain", "]", ",", "Shelf", "::", "Mime", ".", "mime_type", "(", "'.txt'", ")", "]", "elsif", "opts", ".", "include?", ":html", "[", "opts", "[", ":html", "]", ",", "Shelf", "::", "Mime", ".", "mime_type", "(", "'.html'", ")", "]", "elsif", "opts", ".", "include?", ":json", "[", "opts", "[", ":json", "]", ".", "to_json", ",", "Shelf", "::", "Mime", ".", "mime_type", "(", "'.json'", ")", "]", "else", "[", "Shelf", "::", "Utils", "::", "HTTP_STATUS_CODES", "[", "status", "]", ",", "Shelf", "::", "Mime", ".", "mime_type", "(", "'.txt'", ")", "]", "end", "end", "end", "end" ]
MIT License Copyright (c) Sebastian Katzer 2017
[ "MIT", "License", "Copyright", "(", "c", ")", "Sebastian", "Katzer", "2017" ]
[ "# Helper methods to use to generate responses", "# Calls the callback to generate a Shelf response.", "#", "# @param [ Hash ] env The shelf request.", "# @param [ Proc ] blk The app callback.", "#", "# @return [ Void ]", "# The Shelf request object.", "#", "# @return [ Hash ]", "# The query hash constructed by Shelf.", "#", "# @return [ Hash ]", "# The Shelf logger if any.", "#", "# @return [ Object ]", "# Render Shelf response.", "#", "# render 200", "# => [200, { Content-Type: 'text/plain', Content-Length: 2 }, ['OK']]", "# render 'OK'", "# => [200, { Content-Type: 'text/plain', Content-Length: 2 }, ['OK']]", "# render json: 'OK', status: 200, headers: {}", "# => [200, { Content-Type: 'application/json', ... }, ['OK']]", "#", "# @params [ Hash|String|Int ] opts Either the status code, the plain body", "# or a hash with all attributes.", "#", "# @return [ Array ]", "# @private", "#", "# Search for key like :json or :plain in opts and render their value.", "#", "# @param [ Int ] status", "# @param [ String ] body", "# @param [ Hash ] opts", "#", "# @return [ Array<String, String> ] Body and its content type." ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
15
797
239
6fad9e39a5931c66dacbb9dd4859c24121e46696
assimilate-interactive/akit
akit-frame.js
[ "MIT" ]
JavaScript
AKIT_ObjectARTypePlaneVideoEffectVignette
/* renderer.domElement.addEventListener("click", function(){ //- video.play(); //- }); window.onload = function() { initCanvas(); } var worker = new Worker("code_c7_6.js"); var context, media.video, sctxt, count, canvas; var calls = 0; function initCanvas() { media.video = document.getElementsByTagName("media.video")[0]; canvas = document.getElementsByTagName("canvas")[0]; context = canvas.getContext("2d"); scratch = document.getElementById("scratch"); sctxt = scratch.getContext("2d"); count = document.getElementById("count"); media.video.addEventListener("play", postFrame, false); worker.addEventListener("message", drawFrame, false); } function postFrame() { w = 320; h = 160; sctxt.drawImage(media.video, 0, 0, w, h); frame = sctxt.getImageData(0, 0, w, h); arg = { frame: frame, height: h, width: w } worker.postMessage(arg); } function drawFrame (event) { msg = event.data; outframe = msg.frame; if (media.video.paused || media.video.ended) { return; } context.putImageData(outframe, 0, 0); // draw rectangle on canvas context.strokeRect(msg.x, msg.y, msg.w, msg.h); calls += 1; count.textContent = calls; setTimeout(function () { postFrame(); }, 0); } */
function postFrame() { w = 320; h = 160; sctxt.drawImage(media.video, 0, 0, w, h); frame = sctxt.getImageData(0, 0, w, h); arg = { frame: frame, height: h, width: w } worker.postMessage(arg); }
[ "function", "postFrame", "()", "{", "w", "=", "320", ";", "h", "=", "160", ";", "sctxt", ".", "drawImage", "(", "media", ".", "video", "0", "0", "w", "h", ")", ";", "frame", "=", "sctxt", ".", "getImageData", "(", "0", "0", "w", "h", ")", ";", "arg", "=", "{", "frame", ":", "frame", "height", ":", "h", "width", ":", "w", "}", "worker", ".", "postMessage", "(", "arg", ")", ";", "}" ]
class AKIT_ObjectARTypePlaneVideoEffectVignette extends AKIT_ObjectARType { constructor(planeX, planeY, imageWidth, imageHeight, hostName, videoSrc, debug) { super(); this.properties['planeX'] = planeX; this.properties['planeY'] = planeY; this.properties['scale'] = 0.1; this.properties['imageHeight'] = imageHeight; this.properties['imageWidth'] = imageWidth; this.properties['hostName'] = hostName; this.properties['videoSrc'] = videoSrc; this.properties['debug'] = debug; this.properties['artype'] = 'video'; this.setType('planeVideo', 'planeVideo-' + planeX + '_' + planeY); // console.log(this.properties); // this.init(); } init() { if (this.properties['video'] == undefined) { this.video(); this.material(); this.geometry(); this.mesh(); this.meshObjectUpdateAll(); } else { this.reinit(); } } reconstruct(planeX, planeY, imageWidth, imageHeight, hostName, videoSrc, debug) { this.properties['planeX'] = planeX; this.properties['planeY'] = planeY; this.properties['scale'] = 0.1; this.properties['imageHeight'] = imageHeight; this.properties['imageWidth'] = imageWidth; this.properties['hostName'] = hostName; this.properties['videoSrc'] = videoSrc; // this.reinit(); } reinit() { this.properties.video.reinit(this.properties.videoSrc); // this.setTexture() // this.meshObjectUpdateAll(); } ///////////////////////////////////////////////////// // getVideoSrc() { // return 'http://' + this.properties.host + '/' + this.properties.filename + '.webm'; //} video() { const videoSrc = this.properties.videoSrc; const posterSrc = ''; let imageWidth = this.properties.imageWidth; let imageHeight = this.properties.imageHeight; // console.log(videoSrc, ima this.properties['video'] = new AKIT_ObjectVideoGroup$1(videoSrc, posterSrc, imageWidth, imageHeight); // this.initVideoMaterial(); } material() { if (this.properties.debug) this.addChild('material', new AKIT_ObjectMaterialWire());else { // let m = new AKIT_ObjectEffectVignette(this.properties.video.properties.canvas); // console.log(this.properties.video.properties); var defaultImage = undefined; this.addChild('material', new AKIT_ObjectEffectVignette(defaultImage)); } } geometry() { this.properties['geometry'] = new THREE.PlaneBufferGeometry(this.properties.planeX, this.properties.planeY, this.properties.imageWidth, this.properties.imageHeight); } mesh() { this.meshObject(this.properties.geometry, this.child.material.getMaterial()); this.properties.geometry.dynamic = true; } isready() { this.loadVideo(); if (this.checkVideo()) return true; return false; } checkVideo() { if (this.properties['video'] != undefined) { if (this.properties.video.check()) { this.setVideoMaterial(); this.textureUpdate(); this.meshObjectUpdateAll(); this.set(); this.properties.video.startVideo(); return true; } } return false; } setVideoMaterial() { this.child.material.setTexture(this.properties.video.properties.video); } loadVideo() { if (this.properties.video != undefined) { if (this.properties.video.checkImageReady()) { this.setVideoMaterial(); // console.log('set'); // this.properties.video.videoUpdate(); // this.textureUpdate(); return true; } } } stepVideo() { // this.properties.video.videoUpdate(); this.setVideoMaterial(); } runVideo() { this.properties.video.videoTime(0); this.properties.video.videoCue(0); AKIT.video.focus = this.properties.video; } clickVideo() { this.properties.video.videoTime(0); this.properties.video.videoCue(0); } stopVideo() { this.properties.video.videoStop(); } reinitVideo(videoSrc) { this.video.reloader(videoSrc); this.video.videoReinit(videoSrc); } //////////////////////////////////////////// eventUp(id, pter, opts) {//alert('clicked') // console.log('eventup1', id, pter, opts ) } eventDown(id, grp, data, opts, pt) { this.clickVideo(); // console.log('eventDown1', grp,data,opts,pt,this.isVisible() ) } }
[ "class", "AKIT_ObjectARTypePlaneVideoEffectVignette", "extends", "AKIT_ObjectARType", "{", "constructor", "(", "planeX", ",", "planeY", ",", "imageWidth", ",", "imageHeight", ",", "hostName", ",", "videoSrc", ",", "debug", ")", "{", "super", "(", ")", ";", "this", ".", "properties", "[", "'planeX'", "]", "=", "planeX", ";", "this", ".", "properties", "[", "'planeY'", "]", "=", "planeY", ";", "this", ".", "properties", "[", "'scale'", "]", "=", "0.1", ";", "this", ".", "properties", "[", "'imageHeight'", "]", "=", "imageHeight", ";", "this", ".", "properties", "[", "'imageWidth'", "]", "=", "imageWidth", ";", "this", ".", "properties", "[", "'hostName'", "]", "=", "hostName", ";", "this", ".", "properties", "[", "'videoSrc'", "]", "=", "videoSrc", ";", "this", ".", "properties", "[", "'debug'", "]", "=", "debug", ";", "this", ".", "properties", "[", "'artype'", "]", "=", "'video'", ";", "this", ".", "setType", "(", "'planeVideo'", ",", "'planeVideo-'", "+", "planeX", "+", "'_'", "+", "planeY", ")", ";", "}", "init", "(", ")", "{", "if", "(", "this", ".", "properties", "[", "'video'", "]", "==", "undefined", ")", "{", "this", ".", "video", "(", ")", ";", "this", ".", "material", "(", ")", ";", "this", ".", "geometry", "(", ")", ";", "this", ".", "mesh", "(", ")", ";", "this", ".", "meshObjectUpdateAll", "(", ")", ";", "}", "else", "{", "this", ".", "reinit", "(", ")", ";", "}", "}", "reconstruct", "(", "planeX", ",", "planeY", ",", "imageWidth", ",", "imageHeight", ",", "hostName", ",", "videoSrc", ",", "debug", ")", "{", "this", ".", "properties", "[", "'planeX'", "]", "=", "planeX", ";", "this", ".", "properties", "[", "'planeY'", "]", "=", "planeY", ";", "this", ".", "properties", "[", "'scale'", "]", "=", "0.1", ";", "this", ".", "properties", "[", "'imageHeight'", "]", "=", "imageHeight", ";", "this", ".", "properties", "[", "'imageWidth'", "]", "=", "imageWidth", ";", "this", ".", "properties", "[", "'hostName'", "]", "=", "hostName", ";", "this", ".", "properties", "[", "'videoSrc'", "]", "=", "videoSrc", ";", "}", "reinit", "(", ")", "{", "this", ".", "properties", ".", "video", ".", "reinit", "(", "this", ".", "properties", ".", "videoSrc", ")", ";", "}", "video", "(", ")", "{", "const", "videoSrc", "=", "this", ".", "properties", ".", "videoSrc", ";", "const", "posterSrc", "=", "''", ";", "let", "imageWidth", "=", "this", ".", "properties", ".", "imageWidth", ";", "let", "imageHeight", "=", "this", ".", "properties", ".", "imageHeight", ";", "this", ".", "properties", "[", "'video'", "]", "=", "new", "AKIT_ObjectVideoGroup$1", "(", "videoSrc", ",", "posterSrc", ",", "imageWidth", ",", "imageHeight", ")", ";", "}", "material", "(", ")", "{", "if", "(", "this", ".", "properties", ".", "debug", ")", "this", ".", "addChild", "(", "'material'", ",", "new", "AKIT_ObjectMaterialWire", "(", ")", ")", ";", "else", "{", "var", "defaultImage", "=", "undefined", ";", "this", ".", "addChild", "(", "'material'", ",", "new", "AKIT_ObjectEffectVignette", "(", "defaultImage", ")", ")", ";", "}", "}", "geometry", "(", ")", "{", "this", ".", "properties", "[", "'geometry'", "]", "=", "new", "THREE", ".", "PlaneBufferGeometry", "(", "this", ".", "properties", ".", "planeX", ",", "this", ".", "properties", ".", "planeY", ",", "this", ".", "properties", ".", "imageWidth", ",", "this", ".", "properties", ".", "imageHeight", ")", ";", "}", "mesh", "(", ")", "{", "this", ".", "meshObject", "(", "this", ".", "properties", ".", "geometry", ",", "this", ".", "child", ".", "material", ".", "getMaterial", "(", ")", ")", ";", "this", ".", "properties", ".", "geometry", ".", "dynamic", "=", "true", ";", "}", "isready", "(", ")", "{", "this", ".", "loadVideo", "(", ")", ";", "if", "(", "this", ".", "checkVideo", "(", ")", ")", "return", "true", ";", "return", "false", ";", "}", "checkVideo", "(", ")", "{", "if", "(", "this", ".", "properties", "[", "'video'", "]", "!=", "undefined", ")", "{", "if", "(", "this", ".", "properties", ".", "video", ".", "check", "(", ")", ")", "{", "this", ".", "setVideoMaterial", "(", ")", ";", "this", ".", "textureUpdate", "(", ")", ";", "this", ".", "meshObjectUpdateAll", "(", ")", ";", "this", ".", "set", "(", ")", ";", "this", ".", "properties", ".", "video", ".", "startVideo", "(", ")", ";", "return", "true", ";", "}", "}", "return", "false", ";", "}", "setVideoMaterial", "(", ")", "{", "this", ".", "child", ".", "material", ".", "setTexture", "(", "this", ".", "properties", ".", "video", ".", "properties", ".", "video", ")", ";", "}", "loadVideo", "(", ")", "{", "if", "(", "this", ".", "properties", ".", "video", "!=", "undefined", ")", "{", "if", "(", "this", ".", "properties", ".", "video", ".", "checkImageReady", "(", ")", ")", "{", "this", ".", "setVideoMaterial", "(", ")", ";", "return", "true", ";", "}", "}", "}", "stepVideo", "(", ")", "{", "this", ".", "setVideoMaterial", "(", ")", ";", "}", "runVideo", "(", ")", "{", "this", ".", "properties", ".", "video", ".", "videoTime", "(", "0", ")", ";", "this", ".", "properties", ".", "video", ".", "videoCue", "(", "0", ")", ";", "AKIT", ".", "video", ".", "focus", "=", "this", ".", "properties", ".", "video", ";", "}", "clickVideo", "(", ")", "{", "this", ".", "properties", ".", "video", ".", "videoTime", "(", "0", ")", ";", "this", ".", "properties", ".", "video", ".", "videoCue", "(", "0", ")", ";", "}", "stopVideo", "(", ")", "{", "this", ".", "properties", ".", "video", ".", "videoStop", "(", ")", ";", "}", "reinitVideo", "(", "videoSrc", ")", "{", "this", ".", "video", ".", "reloader", "(", "videoSrc", ")", ";", "this", ".", "video", ".", "videoReinit", "(", "videoSrc", ")", ";", "}", "eventUp", "(", "id", ",", "pter", ",", "opts", ")", "{", "}", "eventDown", "(", "id", ",", "grp", ",", "data", ",", "opts", ",", "pt", ")", "{", "this", ".", "clickVideo", "(", ")", ";", "}", "}" ]
renderer.domElement.addEventListener("click", function(){ video.play(); });
[ "renderer", ".", "domElement", ".", "addEventListener", "(", "\"", "click", "\"", "function", "()", "{", "video", ".", "play", "()", ";", "}", ")", ";" ]
[ "// console.log(this.properties);", "// this.init();", "// this.reinit();", "// this.setTexture()", "// this.meshObjectUpdateAll();", "/////////////////////////////////////////////////////", "// getVideoSrc() {", "// return 'http://' + this.properties.host + '/' + this.properties.filename + '.webm';", "//}", "// console.log(videoSrc, ima", "// this.initVideoMaterial();", "// let m = new AKIT_ObjectEffectVignette(this.properties.video.properties.canvas);", "// console.log(this.properties.video.properties);", "// console.log('set');", "// this.properties.video.videoUpdate();", "// this.textureUpdate();", "// this.properties.video.videoUpdate();", "////////////////////////////////////////////", "//alert('clicked')", "// console.log('eventup1', id, pter, opts )", "// console.log('eventDown1', grp,data,opts,pt,this.isVisible() )" ]
[ { "param": "AKIT_ObjectARType", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "AKIT_ObjectARType", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
14
1,017
345
67b5de6da696434154233b83667341ea2a0e8e03
barchart/common-node-js
aws/dynamo/TableContainer.js
[ "MIT" ]
JavaScript
TableContainer
/** * A container that houses functions for interacting with a * single DynamoDB table. In other words, this is the base * class for a implementing a repository pattern. * * @public * @abstract * @extends {Disposable} * @param {DynamoProvider} provider * @param {Table} definition */
A container that houses functions for interacting with a single DynamoDB table. In other words, this is the base class for a implementing a repository pattern.
[ "A", "container", "that", "houses", "functions", "for", "interacting", "with", "a", "single", "DynamoDB", "table", ".", "In", "other", "words", "this", "is", "the", "base", "class", "for", "a", "implementing", "a", "repository", "pattern", "." ]
class TableContainer extends Disposable { constructor(provider, definition) { super(); assert.argumentIsRequired(provider, 'provider', DynamoProvider, 'DynamoProvider'); assert.argumentIsRequired(definition, 'definition', Definition, 'Definition'); this._provider = provider; this._definition = definition; this._startPromise = null; this._started = false; } /** * The table definition. * * @public * @returns {Table} */ get definition() { return this._definition; } /** * Returns a key, suitable as a starting point for queries and scans. * * @public * @param {*} hash * @param {*|null|undefined} range * @returns {Object} */ getPagingKey(hash, range) { const pagingKey = { }; attributes.write(pagingKey, this._definition.hashKey.attribute.name, hash); if (this._definition.rangeKey !== null) { attributes.write(pagingKey, this._definition.rangeKey.attribute.name, range); } return pagingKey; } /** * Given a record, returns the record's hash key value. * * @public * @param {Object} record * @returns {*|null} */ getHashKey(record) { assert.argumentIsRequired(record, 'record', Object); return attributes.read(record, this._definition.hashKey.attribute.name); } /** * Given a record, returns the record's range key value (or a null value). * * @public * @param {Object} record * @returns {*|null} */ getRangeKey(record) { assert.argumentIsRequired(record, 'record', Object); return attributes.read(record, this._definition.rangeKey.attribute.name); } /** * Initializes the table. Call this before invoking any other instance * functions. * * @public * @param {Boolean=} skipVerification - If true, verification of table's existence and schema is skipped. This could be considered unsafe, but startup will be faster. * @returns {Promise<Boolean>} */ start(skipVerification) { if (this._startPromise === null) { this._startPromise = Promise.resolve() .then(() => { if (this.getIsDisposed()) { return Promise.reject(`The ${this.toString()} has been disposed.`); } assert.argumentIsOptional(skipVerification, 'skipVerification', Boolean); return this._provider.start(); }).then(() => { let createPromise; if (is.boolean(skipVerification) && skipVerification) { createPromise = Promise.resolve(); } else { createPromise = this._provider.createTable(this.definition); } return createPromise; }).then(() => { logger.debug('Dynamo table wrapper for', this._definition.name, 'initialized'); this._started = true; return this._started; }).catch((e) => { logger.error('Dynamo table wrapper failed to start', e); throw e; }); } return this._startPromise; } /** * Returns true, if the item conforms to the table's schema; otherwise false. * * @protected * @abstract * @param {Object} item * @returns {Boolean} */ _validate(item) { return is.object(item); } /** * Creates a new item. * * @protected * @param {Object} item * @param {Boolean=} preventOverwrite * @returns {Promise<Boolean>} */ _createItem(item, preventOverwrite) { return Promise.resolve() .then(() => { checkReady.call(this); if (!this._validate(item)) { logger.trace('Failed to create item in [', this.definition.name, '] table', item); throw new Error(`Unable to insert item into [ ${this.definition.name} ] table.`); } return this._provider.saveItem(item, this.definition, preventOverwrite); }); } /** * Creates multiple items, in an batch operation. * * @protected * @param {Object[]} items * @returns {Promise<Boolean>} */ _createItems(items) { return Promise.resolve() .then(() => { checkReady.call(this); items.forEach((item) => { if (!this._validate(item)) { logger.trace('Failed to create item in [', this.definition.name, '] table', item); throw new Error(`Unable to insert items into [ ${this.definition.name} ] table.`); } }); return this._provider.createItems(items, this.definition); }); } /** * Deletes an item from the table. * * @protected * @param {Object} item * @returns {Promise<Boolean>} */ _deleteItem(item) { return Promise.resolve() .then(() => { checkReady.call(this); if (!this._validate(item)) { logger.trace('Failed to delete item from [', this.definition.name, '] table', item); throw new Error(`Unable to delete item from [ ${this.definition.name} ] table.`); } return this._provider.deleteItem(item, this.definition); }); } /** * Deletes multiple items, in an batch operation. * * @protected * @param {Object[]} items * @returns {Promise<Boolean>} */ _deleteItems(items) { return Promise.resolve() .then(() => { checkReady.call(this); items.forEach((item) => { if (!this._validate(item)) { logger.trace('Failed to create delete item from [', this.definition.name, '] table', item); throw new Error(`Unable to delete items from [ ${this.definition.name} ] table.`); } }); return this._provider.deleteItems(items, this.definition); }); } /** * Deletes a table. * * @public * @returns {Promise<Object>} */ deleteTable() { return Promise.resolve() .then(() => { checkReady.call(this); return this._provider.deleteTable(this.definition.name) .then((data) => { this.dispose(); return data; }); }); } /** * Runs an update of the table item. * * @public * @param {Update} update * @returns {Promise<Object>} */ updateItem(update) { return Promise.resolve() .then(() => { checkReady.call(this); return this._provider.updateItem(update); }); } /** * Runs a scan on the table. * * @public * @param {Scan} scan * @returns {Promise<Object[]>} */ scan(scan) { return Promise.resolve() .then(() => { checkReady.call(this); return this._provider.scan(scan); }); } /** * Runs a scan, returning a page of results. * * @public * @param {Scan} scan * @param {Object=} startKey * @return {Promise} */ scanChunk(scan, startKey) { return Promise.resolve() .then(() => { checkReady.call(this); return this._provider.scanChunk(scan, startKey); }); } /** * Runs a query on the table. * * @protected * @param {Query} query * @returns {Promise<Object[]>} */ query(query) { return Promise.resolve() .then(() => { checkReady.call(this); return this._provider.query(query); }); } /** * Runs parallel queries. * * @public * @param {Query[]} queries * @returns {Promise<Object[]>} */ queryParallel(queries) { return Promise.resolve() .then(() => { checkReady.call(this); return this._provider.queryParallel(queries); }); } /** * Runs a query, returning a page of results. * * @public * @param {Query} query * @param {Object=} startKey * @return {Promise} */ queryChunk(query, startKey) { return Promise.resolve() .then(() => { checkReady.call(this); return this._provider.queryChunk(query, startKey); }); } _onDispose() { return; } toString() { return '[Table]'; } }
[ "class", "TableContainer", "extends", "Disposable", "{", "constructor", "(", "provider", ",", "definition", ")", "{", "super", "(", ")", ";", "assert", ".", "argumentIsRequired", "(", "provider", ",", "'provider'", ",", "DynamoProvider", ",", "'DynamoProvider'", ")", ";", "assert", ".", "argumentIsRequired", "(", "definition", ",", "'definition'", ",", "Definition", ",", "'Definition'", ")", ";", "this", ".", "_provider", "=", "provider", ";", "this", ".", "_definition", "=", "definition", ";", "this", ".", "_startPromise", "=", "null", ";", "this", ".", "_started", "=", "false", ";", "}", "get", "definition", "(", ")", "{", "return", "this", ".", "_definition", ";", "}", "getPagingKey", "(", "hash", ",", "range", ")", "{", "const", "pagingKey", "=", "{", "}", ";", "attributes", ".", "write", "(", "pagingKey", ",", "this", ".", "_definition", ".", "hashKey", ".", "attribute", ".", "name", ",", "hash", ")", ";", "if", "(", "this", ".", "_definition", ".", "rangeKey", "!==", "null", ")", "{", "attributes", ".", "write", "(", "pagingKey", ",", "this", ".", "_definition", ".", "rangeKey", ".", "attribute", ".", "name", ",", "range", ")", ";", "}", "return", "pagingKey", ";", "}", "getHashKey", "(", "record", ")", "{", "assert", ".", "argumentIsRequired", "(", "record", ",", "'record'", ",", "Object", ")", ";", "return", "attributes", ".", "read", "(", "record", ",", "this", ".", "_definition", ".", "hashKey", ".", "attribute", ".", "name", ")", ";", "}", "getRangeKey", "(", "record", ")", "{", "assert", ".", "argumentIsRequired", "(", "record", ",", "'record'", ",", "Object", ")", ";", "return", "attributes", ".", "read", "(", "record", ",", "this", ".", "_definition", ".", "rangeKey", ".", "attribute", ".", "name", ")", ";", "}", "start", "(", "skipVerification", ")", "{", "if", "(", "this", ".", "_startPromise", "===", "null", ")", "{", "this", ".", "_startPromise", "=", "Promise", ".", "resolve", "(", ")", ".", "then", "(", "(", ")", "=>", "{", "if", "(", "this", ".", "getIsDisposed", "(", ")", ")", "{", "return", "Promise", ".", "reject", "(", "`", "${", "this", ".", "toString", "(", ")", "}", "`", ")", ";", "}", "assert", ".", "argumentIsOptional", "(", "skipVerification", ",", "'skipVerification'", ",", "Boolean", ")", ";", "return", "this", ".", "_provider", ".", "start", "(", ")", ";", "}", ")", ".", "then", "(", "(", ")", "=>", "{", "let", "createPromise", ";", "if", "(", "is", ".", "boolean", "(", "skipVerification", ")", "&&", "skipVerification", ")", "{", "createPromise", "=", "Promise", ".", "resolve", "(", ")", ";", "}", "else", "{", "createPromise", "=", "this", ".", "_provider", ".", "createTable", "(", "this", ".", "definition", ")", ";", "}", "return", "createPromise", ";", "}", ")", ".", "then", "(", "(", ")", "=>", "{", "logger", ".", "debug", "(", "'Dynamo table wrapper for'", ",", "this", ".", "_definition", ".", "name", ",", "'initialized'", ")", ";", "this", ".", "_started", "=", "true", ";", "return", "this", ".", "_started", ";", "}", ")", ".", "catch", "(", "(", "e", ")", "=>", "{", "logger", ".", "error", "(", "'Dynamo table wrapper failed to start'", ",", "e", ")", ";", "throw", "e", ";", "}", ")", ";", "}", "return", "this", ".", "_startPromise", ";", "}", "_validate", "(", "item", ")", "{", "return", "is", ".", "object", "(", "item", ")", ";", "}", "_createItem", "(", "item", ",", "preventOverwrite", ")", "{", "return", "Promise", ".", "resolve", "(", ")", ".", "then", "(", "(", ")", "=>", "{", "checkReady", ".", "call", "(", "this", ")", ";", "if", "(", "!", "this", ".", "_validate", "(", "item", ")", ")", "{", "logger", ".", "trace", "(", "'Failed to create item in ['", ",", "this", ".", "definition", ".", "name", ",", "'] table'", ",", "item", ")", ";", "throw", "new", "Error", "(", "`", "${", "this", ".", "definition", ".", "name", "}", "`", ")", ";", "}", "return", "this", ".", "_provider", ".", "saveItem", "(", "item", ",", "this", ".", "definition", ",", "preventOverwrite", ")", ";", "}", ")", ";", "}", "_createItems", "(", "items", ")", "{", "return", "Promise", ".", "resolve", "(", ")", ".", "then", "(", "(", ")", "=>", "{", "checkReady", ".", "call", "(", "this", ")", ";", "items", ".", "forEach", "(", "(", "item", ")", "=>", "{", "if", "(", "!", "this", ".", "_validate", "(", "item", ")", ")", "{", "logger", ".", "trace", "(", "'Failed to create item in ['", ",", "this", ".", "definition", ".", "name", ",", "'] table'", ",", "item", ")", ";", "throw", "new", "Error", "(", "`", "${", "this", ".", "definition", ".", "name", "}", "`", ")", ";", "}", "}", ")", ";", "return", "this", ".", "_provider", ".", "createItems", "(", "items", ",", "this", ".", "definition", ")", ";", "}", ")", ";", "}", "_deleteItem", "(", "item", ")", "{", "return", "Promise", ".", "resolve", "(", ")", ".", "then", "(", "(", ")", "=>", "{", "checkReady", ".", "call", "(", "this", ")", ";", "if", "(", "!", "this", ".", "_validate", "(", "item", ")", ")", "{", "logger", ".", "trace", "(", "'Failed to delete item from ['", ",", "this", ".", "definition", ".", "name", ",", "'] table'", ",", "item", ")", ";", "throw", "new", "Error", "(", "`", "${", "this", ".", "definition", ".", "name", "}", "`", ")", ";", "}", "return", "this", ".", "_provider", ".", "deleteItem", "(", "item", ",", "this", ".", "definition", ")", ";", "}", ")", ";", "}", "_deleteItems", "(", "items", ")", "{", "return", "Promise", ".", "resolve", "(", ")", ".", "then", "(", "(", ")", "=>", "{", "checkReady", ".", "call", "(", "this", ")", ";", "items", ".", "forEach", "(", "(", "item", ")", "=>", "{", "if", "(", "!", "this", ".", "_validate", "(", "item", ")", ")", "{", "logger", ".", "trace", "(", "'Failed to create delete item from ['", ",", "this", ".", "definition", ".", "name", ",", "'] table'", ",", "item", ")", ";", "throw", "new", "Error", "(", "`", "${", "this", ".", "definition", ".", "name", "}", "`", ")", ";", "}", "}", ")", ";", "return", "this", ".", "_provider", ".", "deleteItems", "(", "items", ",", "this", ".", "definition", ")", ";", "}", ")", ";", "}", "deleteTable", "(", ")", "{", "return", "Promise", ".", "resolve", "(", ")", ".", "then", "(", "(", ")", "=>", "{", "checkReady", ".", "call", "(", "this", ")", ";", "return", "this", ".", "_provider", ".", "deleteTable", "(", "this", ".", "definition", ".", "name", ")", ".", "then", "(", "(", "data", ")", "=>", "{", "this", ".", "dispose", "(", ")", ";", "return", "data", ";", "}", ")", ";", "}", ")", ";", "}", "updateItem", "(", "update", ")", "{", "return", "Promise", ".", "resolve", "(", ")", ".", "then", "(", "(", ")", "=>", "{", "checkReady", ".", "call", "(", "this", ")", ";", "return", "this", ".", "_provider", ".", "updateItem", "(", "update", ")", ";", "}", ")", ";", "}", "scan", "(", "scan", ")", "{", "return", "Promise", ".", "resolve", "(", ")", ".", "then", "(", "(", ")", "=>", "{", "checkReady", ".", "call", "(", "this", ")", ";", "return", "this", ".", "_provider", ".", "scan", "(", "scan", ")", ";", "}", ")", ";", "}", "scanChunk", "(", "scan", ",", "startKey", ")", "{", "return", "Promise", ".", "resolve", "(", ")", ".", "then", "(", "(", ")", "=>", "{", "checkReady", ".", "call", "(", "this", ")", ";", "return", "this", ".", "_provider", ".", "scanChunk", "(", "scan", ",", "startKey", ")", ";", "}", ")", ";", "}", "query", "(", "query", ")", "{", "return", "Promise", ".", "resolve", "(", ")", ".", "then", "(", "(", ")", "=>", "{", "checkReady", ".", "call", "(", "this", ")", ";", "return", "this", ".", "_provider", ".", "query", "(", "query", ")", ";", "}", ")", ";", "}", "queryParallel", "(", "queries", ")", "{", "return", "Promise", ".", "resolve", "(", ")", ".", "then", "(", "(", ")", "=>", "{", "checkReady", ".", "call", "(", "this", ")", ";", "return", "this", ".", "_provider", ".", "queryParallel", "(", "queries", ")", ";", "}", ")", ";", "}", "queryChunk", "(", "query", ",", "startKey", ")", "{", "return", "Promise", ".", "resolve", "(", ")", ".", "then", "(", "(", ")", "=>", "{", "checkReady", ".", "call", "(", "this", ")", ";", "return", "this", ".", "_provider", ".", "queryChunk", "(", "query", ",", "startKey", ")", ";", "}", ")", ";", "}", "_onDispose", "(", ")", "{", "return", ";", "}", "toString", "(", ")", "{", "return", "'[Table]'", ";", "}", "}" ]
A container that houses functions for interacting with a single DynamoDB table.
[ "A", "container", "that", "houses", "functions", "for", "interacting", "with", "a", "single", "DynamoDB", "table", "." ]
[ "/**\n\t\t * The table definition.\n\t\t *\n\t\t * @public\n\t\t * @returns {Table}\n\t\t */", "/**\n\t\t * Returns a key, suitable as a starting point for queries and scans.\n\t\t *\n\t\t * @public\n\t\t * @param {*} hash\n\t\t * @param {*|null|undefined} range\n\t\t * @returns {Object}\n\t\t */", "/**\n\t\t * Given a record, returns the record's hash key value.\n\t\t *\n\t\t * @public\n\t\t * @param {Object} record\n\t\t * @returns {*|null}\n\t\t */", "/**\n\t\t * Given a record, returns the record's range key value (or a null value).\n\t\t *\n\t\t * @public\n\t\t * @param {Object} record\n\t\t * @returns {*|null}\n\t\t */", "/**\n\t\t * Initializes the table. Call this before invoking any other instance\n\t\t * functions.\n\t\t *\n\t\t * @public\n\t\t * @param {Boolean=} skipVerification - If true, verification of table's existence and schema is skipped. This could be considered unsafe, but startup will be faster.\n\t\t * @returns {Promise<Boolean>}\n\t\t */", "/**\n\t\t * Returns true, if the item conforms to the table's schema; otherwise false.\n\t\t *\n\t\t * @protected\n\t\t * @abstract\n\t\t * @param {Object} item\n\t\t * @returns {Boolean}\n\t\t */", "/**\n\t\t * Creates a new item.\n\t\t *\n\t\t * @protected\n\t\t * @param {Object} item\n\t\t * @param {Boolean=} preventOverwrite\n\t\t * @returns {Promise<Boolean>}\n\t\t */", "/**\n\t\t * Creates multiple items, in an batch operation.\n\t\t *\n\t\t * @protected\n\t\t * @param {Object[]} items\n\t\t * @returns {Promise<Boolean>}\n\t\t */", "/**\n\t\t * Deletes an item from the table.\n\t\t *\n\t\t * @protected\n\t\t * @param {Object} item\n\t\t * @returns {Promise<Boolean>}\n\t\t */", "/**\n\t\t * Deletes multiple items, in an batch operation.\n\t\t *\n\t\t * @protected\n\t\t * @param {Object[]} items\n\t\t * @returns {Promise<Boolean>}\n\t\t */", "/**\n\t\t * Deletes a table.\n\t\t *\n\t\t * @public\n\t\t * @returns {Promise<Object>}\n\t\t */", "/**\n\t\t * Runs an update of the table item.\n\t\t *\n\t\t * @public\n\t\t * @param {Update} update\n\t\t * @returns {Promise<Object>}\n\t\t */", "/**\n\t\t * Runs a scan on the table.\n\t\t *\n\t\t * @public\n\t\t * @param {Scan} scan\n\t\t * @returns {Promise<Object[]>}\n\t\t */", "/**\n\t\t * Runs a scan, returning a page of results.\n\t\t *\n\t\t * @public\n\t\t * @param {Scan} scan\n\t\t * @param {Object=} startKey\n\t\t * @return {Promise}\n\t\t */", "/**\n\t\t * Runs a query on the table.\n\t\t *\n\t\t * @protected\n\t\t * @param {Query} query\n\t\t * @returns {Promise<Object[]>}\n\t\t */", "/**\n\t\t * Runs parallel queries.\n\t\t *\n\t\t * @public\n\t\t * @param {Query[]} queries\n\t\t * @returns {Promise<Object[]>}\n\t\t */", "/**\n\t\t * Runs a query, returning a page of results.\n\t\t *\n\t\t * @public\n\t\t * @param {Query} query\n\t\t * @param {Object=} startKey\n\t\t * @return {Promise}\n\t\t */" ]
[ { "param": "Disposable", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Disposable", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
28
1,938
80
d311b636b075199c1cbb10a06acf988e0adf8426
Novarizark/easy-era5-trck
post_process/draw_complete_nc_polar.py
[ "MIT" ]
Python
painter_class
Construct a painting controller to dispatch the painting Attributes ------------ glb_clock, global clock, datetime date_range list infile_lst, input file list, string list pulse_clock, infile pulse clock, datetime date_range list forward_option, int curr_time, datetime airp_lat_set, list of painted air parcel lat tracks, [0..n] for n+1 individual files structure:[ifile][itime, idx] airp_lon_set, list of painted air parcel lon tracks, [0..n] for n+1 individual files structure:[ifile][itime, idx] firework_lat, list of current parcels lat firework_lon, list of current parcels lon Methods ------------ advance, advance the painter to the next painting
Construct a painting controller to dispatch the painting Attributes glb_clock, global clock, datetime date_range list infile_lst, input file list, string list pulse_clock, infile pulse clock, datetime date_range list forward_option, int airp_lat_set, list of painted air parcel lat tracks, [0..n] for n+1 individual files structure:[ifile][itime, idx] airp_lon_set, list of painted air parcel lon tracks, [0..n] for n+1 individual files structure:[ifile][itime, idx] firework_lat, list of current parcels lat firework_lon, list of current parcels lon Methods advance, advance the painter to the next painting
[ "Construct", "a", "painting", "controller", "to", "dispatch", "the", "painting", "Attributes", "glb_clock", "global", "clock", "datetime", "date_range", "list", "infile_lst", "input", "file", "list", "string", "list", "pulse_clock", "infile", "pulse", "clock", "datetime", "date_range", "list", "forward_option", "int", "airp_lat_set", "list", "of", "painted", "air", "parcel", "lat", "tracks", "[", "0", "..", "n", "]", "for", "n", "+", "1", "individual", "files", "structure", ":", "[", "ifile", "]", "[", "itime", "idx", "]", "airp_lon_set", "list", "of", "painted", "air", "parcel", "lon", "tracks", "[", "0", "..", "n", "]", "for", "n", "+", "1", "individual", "files", "structure", ":", "[", "ifile", "]", "[", "itime", "idx", "]", "firework_lat", "list", "of", "current", "parcels", "lat", "firework_lon", "list", "of", "current", "parcels", "lon", "Methods", "advance", "advance", "the", "painter", "to", "the", "next", "painting" ]
class painter_class: ''' Construct a painting controller to dispatch the painting Attributes ------------ glb_clock, global clock, datetime date_range list infile_lst, input file list, string list pulse_clock, infile pulse clock, datetime date_range list forward_option, int curr_time, datetime airp_lat_set, list of painted air parcel lat tracks, [0..n] for n+1 individual files structure:[ifile][itime, idx] airp_lon_set, list of painted air parcel lon tracks, [0..n] for n+1 individual files structure:[ifile][itime, idx] firework_lat, list of current parcels lat firework_lon, list of current parcels lon Methods ------------ advance, advance the painter to the next painting ''' def __init__(self, config, ini_date, final_date, ini_delta): self.int_length=int(config['CORE']['integration_length']) self.out_frq=int(config['OUTPUT']['out_frq'])/60 # to hours self.out_prefix=config['OUTPUT']['out_prefix'] self.forward_option=int(config['CORE']['forward_option']) self.airp_lat_set=[] self.airp_lon_set=[] ''' if self.forward_option > 0: painting_ini_date=ini_date else: painting_ini_date=ini_date+datetime.timedelta(hours=self.forward_option*self.int_length) ''' self.glb_clock=pd.date_range(ini_date, final_date, freq=str(self.out_frq)+'H') self.pulse_clock=pd.date_range(ini_date, final_date, freq=ini_delta) def stoke(self): ''' Add fuel to the fire work!''' print('!!!STOKE: Read Traj Rec...') later_date_str=(self.curr_time+datetime.timedelta(hours=self.int_length)).strftime('%Y%m%d%H%M%S') earlier_date_str=self.curr_time.strftime('%Y%m%d%H%M%S') if self.forward_option >0: fn='../output/%s.I%s.E%s.nc' % (self.out_prefix, earlier_date_str, later_date_str) else: fn='../output/%s.I%s.E%s.nc' % (self.out_prefix, later_date_str, earlier_date_str) ds = xr.open_dataset(fn) self.airp_lat_set.append(ds['xlat'][::-1,:]) self.airp_lon_set.append(ds['xlon'][::-1,:]) self.aim_lat_set=ds['xlat'][0,:].values self.aim_lon_set=ds['xlon'][0,:].values def collect_cinders(self): ''' Remove cinder from the fire work!''' print('!!!Cinder Collect...') self.airp_lat_set=[airpset for airpset in self.airp_lat_set if airpset.time[-1] != self.curr_time] self.airp_lon_set=[airpset for airpset in self.airp_lon_set if airpset.time[-1] != self.curr_time] def cast_firework(self): ''' Select air parcels for the current firework!''' self.firework_lat=[] self.firework_lon=[] for elem_lat_set, elem_lon_set in zip(self.airp_lat_set, self.airp_lon_set): self.firework_lat.extend(elem_lat_set.sel(time=self.curr_time).values) self.firework_lon.extend(elem_lon_set.sel(time=self.curr_time).values)
[ "class", "painter_class", ":", "def", "__init__", "(", "self", ",", "config", ",", "ini_date", ",", "final_date", ",", "ini_delta", ")", ":", "self", ".", "int_length", "=", "int", "(", "config", "[", "'CORE'", "]", "[", "'integration_length'", "]", ")", "self", ".", "out_frq", "=", "int", "(", "config", "[", "'OUTPUT'", "]", "[", "'out_frq'", "]", ")", "/", "60", "self", ".", "out_prefix", "=", "config", "[", "'OUTPUT'", "]", "[", "'out_prefix'", "]", "self", ".", "forward_option", "=", "int", "(", "config", "[", "'CORE'", "]", "[", "'forward_option'", "]", ")", "self", ".", "airp_lat_set", "=", "[", "]", "self", ".", "airp_lon_set", "=", "[", "]", "''' \n if self.forward_option > 0:\n painting_ini_date=ini_date\n else:\n painting_ini_date=ini_date+datetime.timedelta(hours=self.forward_option*self.int_length)\n '''", "self", ".", "glb_clock", "=", "pd", ".", "date_range", "(", "ini_date", ",", "final_date", ",", "freq", "=", "str", "(", "self", ".", "out_frq", ")", "+", "'H'", ")", "self", ".", "pulse_clock", "=", "pd", ".", "date_range", "(", "ini_date", ",", "final_date", ",", "freq", "=", "ini_delta", ")", "def", "stoke", "(", "self", ")", ":", "''' Add fuel to the fire work!'''", "print", "(", "'!!!STOKE: Read Traj Rec...'", ")", "later_date_str", "=", "(", "self", ".", "curr_time", "+", "datetime", ".", "timedelta", "(", "hours", "=", "self", ".", "int_length", ")", ")", ".", "strftime", "(", "'%Y%m%d%H%M%S'", ")", "earlier_date_str", "=", "self", ".", "curr_time", ".", "strftime", "(", "'%Y%m%d%H%M%S'", ")", "if", "self", ".", "forward_option", ">", "0", ":", "fn", "=", "'../output/%s.I%s.E%s.nc'", "%", "(", "self", ".", "out_prefix", ",", "earlier_date_str", ",", "later_date_str", ")", "else", ":", "fn", "=", "'../output/%s.I%s.E%s.nc'", "%", "(", "self", ".", "out_prefix", ",", "later_date_str", ",", "earlier_date_str", ")", "ds", "=", "xr", ".", "open_dataset", "(", "fn", ")", "self", ".", "airp_lat_set", ".", "append", "(", "ds", "[", "'xlat'", "]", "[", ":", ":", "-", "1", ",", ":", "]", ")", "self", ".", "airp_lon_set", ".", "append", "(", "ds", "[", "'xlon'", "]", "[", ":", ":", "-", "1", ",", ":", "]", ")", "self", ".", "aim_lat_set", "=", "ds", "[", "'xlat'", "]", "[", "0", ",", ":", "]", ".", "values", "self", ".", "aim_lon_set", "=", "ds", "[", "'xlon'", "]", "[", "0", ",", ":", "]", ".", "values", "def", "collect_cinders", "(", "self", ")", ":", "''' Remove cinder from the fire work!'''", "print", "(", "'!!!Cinder Collect...'", ")", "self", ".", "airp_lat_set", "=", "[", "airpset", "for", "airpset", "in", "self", ".", "airp_lat_set", "if", "airpset", ".", "time", "[", "-", "1", "]", "!=", "self", ".", "curr_time", "]", "self", ".", "airp_lon_set", "=", "[", "airpset", "for", "airpset", "in", "self", ".", "airp_lon_set", "if", "airpset", ".", "time", "[", "-", "1", "]", "!=", "self", ".", "curr_time", "]", "def", "cast_firework", "(", "self", ")", ":", "''' Select air parcels for the current firework!'''", "self", ".", "firework_lat", "=", "[", "]", "self", ".", "firework_lon", "=", "[", "]", "for", "elem_lat_set", ",", "elem_lon_set", "in", "zip", "(", "self", ".", "airp_lat_set", ",", "self", ".", "airp_lon_set", ")", ":", "self", ".", "firework_lat", ".", "extend", "(", "elem_lat_set", ".", "sel", "(", "time", "=", "self", ".", "curr_time", ")", ".", "values", ")", "self", ".", "firework_lon", ".", "extend", "(", "elem_lon_set", ".", "sel", "(", "time", "=", "self", ".", "curr_time", ")", ".", "values", ")" ]
Construct a painting controller to dispatch the painting Attributes
[ "Construct", "a", "painting", "controller", "to", "dispatch", "the", "painting", "Attributes" ]
[ "'''\n Construct a painting controller to dispatch the painting\n\n Attributes\n ------------\n \n glb_clock, global clock, datetime date_range list\n infile_lst, input file list, string list\n pulse_clock, infile pulse clock, datetime date_range list\n forward_option, int\n\n curr_time, datetime\n \n airp_lat_set, list of painted air parcel lat tracks, \n [0..n] for n+1 individual files structure:[ifile][itime, idx]\n airp_lon_set, list of painted air parcel lon tracks,\n [0..n] for n+1 individual files structure:[ifile][itime, idx]\n\n firework_lat, list of current parcels lat\n firework_lon, list of current parcels lon\n\n Methods\n ------------\n advance, advance the painter to the next painting\n\n '''", "# to hours", "''' \n if self.forward_option > 0:\n painting_ini_date=ini_date\n else:\n painting_ini_date=ini_date+datetime.timedelta(hours=self.forward_option*self.int_length)\n '''", "''' Add fuel to the fire work!'''", "''' Remove cinder from the fire work!'''", "''' Select air parcels for the current firework!'''" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
15
749
179
14714581d7e5c68c09f5e2e24ba3beea37f1d23c
abhishekks831998/umple
Umplificator/UmplifiedProjects/weka-umplified-0/src/main/java/weka/datagenerators/Test.java
[ "MIT" ]
Java
Test
/** * Class to represent a test. <br/> * <br/> * The string representation of the test can be supplied in standard notation or * for a subset of types of attributes in Prolog notation.<br/> * * Following examples for all possible tests that can be represented by this * class, given in standard notation.<br/> * <br/> * Examples of tests for numeric attributes:<br/> * B &gt;= 2.333<br/> * B &lt; 4.56<br/> * <br/> * Examples of tests for nominal attributes with more then 2 values:<br/> * A = rain <br/> * A != rain<br/> * <br/> * Examples of tests for nominal attribute with exactly 2 values:<br/> * A = false <br/> * A = true<br/> * <br/> * <br/> * The Prolog notation is only supplied for numeric attributes and for nominal * attributes that have the values "true" and "false".<br/> * <br/> * Following examples for the Prolog notation provided.<br/> * <br/> * Examples of tests for numeric attributes:<br/> * The same as for standard notation above.<br/> * <br/> * Examples of tests for nominal attributes with values "true"and "false":<br/> * A<br/> * not(A)<br/> * <br/> * (Other nominal attributes are not supported by the Prolog notation.)<br/> * <br/> * * @author Gabi Schmidberger ([email protected]) * @version $Revision: 10203 $ **/
Class to represent a test. The string representation of the test can be supplied in standard notation or for a subset of types of attributes in Prolog notation. @author Gabi Schmidberger ([email protected]) @version $Revision: 10203 $
[ "Class", "to", "represent", "a", "test", ".", "The", "string", "representation", "of", "the", "test", "can", "be", "supplied", "in", "standard", "notation", "or", "for", "a", "subset", "of", "types", "of", "attributes", "in", "Prolog", "notation", ".", "@author", "Gabi", "Schmidberger", "(", "gabi@cs", ".", "waikato", ".", "ac", ".", "nz", ")", "@version", "$Revision", ":", "10203", "$" ]
public class Test implements Serializable, RevisionHandler { /** for serialization */ static final long serialVersionUID = -8890645875887157782L; /** the attribute index */ int m_AttIndex; /** the split */ double m_Split; /** whether to negate the test */ boolean m_Not; /** the dataset */ Instances m_Dataset; /** * Constructor * * @param i the attribute index * @param s the split * @param dataset the dataset */ public Test(int i, double s, Instances dataset) { m_AttIndex = i; m_Split = s; m_Dataset = dataset; m_Not = false; } /** * Constructor * * @param i the attribute index * @param s the split * @param dataset the dataset * @param n whether to negate the test */ public Test(int i, double s, Instances dataset, boolean n) { m_AttIndex = i; m_Split = s; m_Dataset = dataset; m_Not = n; } /** * Negates the test. * * @return the test itself negated */ public Test getNot() { // returns a modified copy return new Test(m_AttIndex, m_Split, m_Dataset, m_Not ? false : true); } /** * Determines whether an instance passes the test. * * @param inst the instance * @return true if the instance satisfies the test, false otherwise * @throws Exception if something goes wrong */ public boolean passesTest(Instance inst) throws Exception { if (inst.isMissing(m_AttIndex)) { return false; // missing values fail } boolean isNominal = inst.attribute(m_AttIndex).isNominal(); double attribVal = inst.value(m_AttIndex); if (!m_Not) { if (isNominal) { if (((int) attribVal) != ((int) m_Split)) { return false; } } else if (attribVal >= m_Split) { return false; } } else { if (isNominal) { if (((int) attribVal) == ((int) m_Split)) { return false; } } else if (attribVal < m_Split) { return false; } } return true; } /** * Returns the test represented by a string. * * @return a string representing the test */ @Override public String toString() { return (m_Dataset.attribute(m_AttIndex).name() + " " + testComparisonString()); } /** * Returns the test represented by a string in Prolog notation. * * @return a string representing the test in Prolog notation */ public String toPrologString() { Attribute att = m_Dataset.attribute(m_AttIndex); StringBuffer str = new StringBuffer(); String attName = m_Dataset.attribute(m_AttIndex).name(); if (att.isNumeric()) { str = str.append(attName + " "); if (m_Not) { str = str.append(">= " + Utils.doubleToString(m_Split, 3)); } else { str = str.append("< " + Utils.doubleToString(m_Split, 3)); } } else { String value = att.value((int) m_Split); if (value == "false") { str = str.append("not(" + attName + ")"); } else { str = str.append(attName); } } return str.toString(); } /** * Gives a string representation of the test, starting from the comparison * symbol. * * @return a string representing the test */ private String testComparisonString() { Attribute att = m_Dataset.attribute(m_AttIndex); if (att.isNumeric()) { return ((m_Not ? ">= " : "< ") + Utils.doubleToString(m_Split, 3)); } else { if (att.numValues() != 2) { return ((m_Not ? "!= " : "= ") + att.value((int) m_Split)); } else { return ("= " + (m_Not ? att.value((int) m_Split == 0 ? 1 : 0) : att .value((int) m_Split))); } } } /** * Compares the test with the test that is given as parameter. * * @param t the test the object is compared to * @return true if the two Tests are equal */ public boolean equalTo(Test t) { return (m_AttIndex == t.m_AttIndex && m_Split == t.m_Split && m_Not == t.m_Not); } /** * Returns the revision string. * * @return the revision */ @Override public String getRevision() { return RevisionUtils.extract("$Revision: 10203 $"); } }
[ "public", "class", "Test", "implements", "Serializable", ",", "RevisionHandler", "{", "/** for serialization */", "static", "final", "long", "serialVersionUID", "=", "-", "8890645875887157782L", ";", "/** the attribute index */", "int", "m_AttIndex", ";", "/** the split */", "double", "m_Split", ";", "/** whether to negate the test */", "boolean", "m_Not", ";", "/** the dataset */", "Instances", "m_Dataset", ";", "/**\n * Constructor\n * \n * @param i the attribute index\n * @param s the split\n * @param dataset the dataset\n */", "public", "Test", "(", "int", "i", ",", "double", "s", ",", "Instances", "dataset", ")", "{", "m_AttIndex", "=", "i", ";", "m_Split", "=", "s", ";", "m_Dataset", "=", "dataset", ";", "m_Not", "=", "false", ";", "}", "/**\n * Constructor\n * \n * @param i the attribute index\n * @param s the split\n * @param dataset the dataset\n * @param n whether to negate the test\n */", "public", "Test", "(", "int", "i", ",", "double", "s", ",", "Instances", "dataset", ",", "boolean", "n", ")", "{", "m_AttIndex", "=", "i", ";", "m_Split", "=", "s", ";", "m_Dataset", "=", "dataset", ";", "m_Not", "=", "n", ";", "}", "/**\n * Negates the test.\n * \n * @return the test itself negated\n */", "public", "Test", "getNot", "(", ")", "{", "return", "new", "Test", "(", "m_AttIndex", ",", "m_Split", ",", "m_Dataset", ",", "m_Not", "?", "false", ":", "true", ")", ";", "}", "/**\n * Determines whether an instance passes the test.\n * \n * @param inst the instance\n * @return true if the instance satisfies the test, false otherwise\n * @throws Exception if something goes wrong\n */", "public", "boolean", "passesTest", "(", "Instance", "inst", ")", "throws", "Exception", "{", "if", "(", "inst", ".", "isMissing", "(", "m_AttIndex", ")", ")", "{", "return", "false", ";", "}", "boolean", "isNominal", "=", "inst", ".", "attribute", "(", "m_AttIndex", ")", ".", "isNominal", "(", ")", ";", "double", "attribVal", "=", "inst", ".", "value", "(", "m_AttIndex", ")", ";", "if", "(", "!", "m_Not", ")", "{", "if", "(", "isNominal", ")", "{", "if", "(", "(", "(", "int", ")", "attribVal", ")", "!=", "(", "(", "int", ")", "m_Split", ")", ")", "{", "return", "false", ";", "}", "}", "else", "if", "(", "attribVal", ">=", "m_Split", ")", "{", "return", "false", ";", "}", "}", "else", "{", "if", "(", "isNominal", ")", "{", "if", "(", "(", "(", "int", ")", "attribVal", ")", "==", "(", "(", "int", ")", "m_Split", ")", ")", "{", "return", "false", ";", "}", "}", "else", "if", "(", "attribVal", "<", "m_Split", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}", "/**\n * Returns the test represented by a string.\n * \n * @return a string representing the test\n */", "@", "Override", "public", "String", "toString", "(", ")", "{", "return", "(", "m_Dataset", ".", "attribute", "(", "m_AttIndex", ")", ".", "name", "(", ")", "+", "\"", " ", "\"", "+", "testComparisonString", "(", ")", ")", ";", "}", "/**\n * Returns the test represented by a string in Prolog notation.\n * \n * @return a string representing the test in Prolog notation\n */", "public", "String", "toPrologString", "(", ")", "{", "Attribute", "att", "=", "m_Dataset", ".", "attribute", "(", "m_AttIndex", ")", ";", "StringBuffer", "str", "=", "new", "StringBuffer", "(", ")", ";", "String", "attName", "=", "m_Dataset", ".", "attribute", "(", "m_AttIndex", ")", ".", "name", "(", ")", ";", "if", "(", "att", ".", "isNumeric", "(", ")", ")", "{", "str", "=", "str", ".", "append", "(", "attName", "+", "\"", " ", "\"", ")", ";", "if", "(", "m_Not", ")", "{", "str", "=", "str", ".", "append", "(", "\"", ">= ", "\"", "+", "Utils", ".", "doubleToString", "(", "m_Split", ",", "3", ")", ")", ";", "}", "else", "{", "str", "=", "str", ".", "append", "(", "\"", "< ", "\"", "+", "Utils", ".", "doubleToString", "(", "m_Split", ",", "3", ")", ")", ";", "}", "}", "else", "{", "String", "value", "=", "att", ".", "value", "(", "(", "int", ")", "m_Split", ")", ";", "if", "(", "value", "==", "\"", "false", "\"", ")", "{", "str", "=", "str", ".", "append", "(", "\"", "not(", "\"", "+", "attName", "+", "\"", ")", "\"", ")", ";", "}", "else", "{", "str", "=", "str", ".", "append", "(", "attName", ")", ";", "}", "}", "return", "str", ".", "toString", "(", ")", ";", "}", "/**\n * Gives a string representation of the test, starting from the comparison\n * symbol.\n * \n * @return a string representing the test\n */", "private", "String", "testComparisonString", "(", ")", "{", "Attribute", "att", "=", "m_Dataset", ".", "attribute", "(", "m_AttIndex", ")", ";", "if", "(", "att", ".", "isNumeric", "(", ")", ")", "{", "return", "(", "(", "m_Not", "?", "\"", ">= ", "\"", ":", "\"", "< ", "\"", ")", "+", "Utils", ".", "doubleToString", "(", "m_Split", ",", "3", ")", ")", ";", "}", "else", "{", "if", "(", "att", ".", "numValues", "(", ")", "!=", "2", ")", "{", "return", "(", "(", "m_Not", "?", "\"", "!= ", "\"", ":", "\"", "= ", "\"", ")", "+", "att", ".", "value", "(", "(", "int", ")", "m_Split", ")", ")", ";", "}", "else", "{", "return", "(", "\"", "= ", "\"", "+", "(", "m_Not", "?", "att", ".", "value", "(", "(", "int", ")", "m_Split", "==", "0", "?", "1", ":", "0", ")", ":", "att", ".", "value", "(", "(", "int", ")", "m_Split", ")", ")", ")", ";", "}", "}", "}", "/**\n * Compares the test with the test that is given as parameter.\n * \n * @param t the test the object is compared to\n * @return true if the two Tests are equal\n */", "public", "boolean", "equalTo", "(", "Test", "t", ")", "{", "return", "(", "m_AttIndex", "==", "t", ".", "m_AttIndex", "&&", "m_Split", "==", "t", ".", "m_Split", "&&", "m_Not", "==", "t", ".", "m_Not", ")", ";", "}", "/**\n * Returns the revision string.\n * \n * @return the revision\n */", "@", "Override", "public", "String", "getRevision", "(", ")", "{", "return", "RevisionUtils", ".", "extract", "(", "\"", "$Revision: 10203 $", "\"", ")", ";", "}", "}" ]
Class to represent a test.
[ "Class", "to", "represent", "a", "test", "." ]
[ "// returns a modified copy", "// missing values fail" ]
[ { "param": "Serializable, RevisionHandler", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Serializable, RevisionHandler", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
20
1,131
351
e1498c7c59c1f29e0fa94c04ee41591d8be350c8
davide125/chef-cookbooks
cookbooks/fb_sysctl/libraries/sync.rb
[ "BSD-3-Clause" ]
Ruby
FB
# vim: syntax=ruby:expandtab:shiftwidth=2:softtabstop=2:tabstop=2 # Copyright (c) 2016-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. An additional grant # of patent rights can be found in the PATENTS file in the same directory. #
syntax=ruby:expandtab:shiftwidth=2:softtabstop=2:tabstop=2 Copyright (c) 2016-present, Facebook, Inc. All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. An additional grant of patent rights can be found in the PATENTS file in the same directory.
[ "syntax", "=", "ruby", ":", "expandtab", ":", "shiftwidth", "=", "2", ":", "softtabstop", "=", "2", ":", "tabstop", "=", "2", "Copyright", "(", "c", ")", "2016", "-", "present", "Facebook", "Inc", ".", "All", "rights", "reserved", ".", "This", "source", "code", "is", "licensed", "under", "the", "BSD", "-", "style", "license", "found", "in", "the", "LICENSE", "file", "in", "the", "root", "directory", "of", "this", "source", "tree", ".", "An", "additional", "grant", "of", "patent", "rights", "can", "be", "found", "in", "the", "PATENTS", "file", "in", "the", "same", "directory", "." ]
module FB # tools for the fb_sysctl cookbook module Sysctl def self.current_settings s = Mixlib::ShellOut.new('/sbin/sysctl -a') s.run_command s.error! current = {} s.stdout.each_line do |line| line.match(/^(\S+)\s*=\s*(.*)$/) current[$1] = $2 end current end def self.normalize(val) val.to_s.gsub(/\s+/, ' ') end def self.incorrect_settings(current, desired) out_of_spec = {} desired.each do |k, v| unless current[k] fail "fb_sysctl: Invalid setting #{k}" end cur_val = normalize(current[k]) Chef::Log.debug("fb_sysctl: current #{k} = #{cur_val}") des_val = normalize(v) Chef::Log.debug("fb_sysctl: desired #{k} = #{des_val}") unless cur_val == des_val out_of_spec[k] = cur_val end end return out_of_spec end end end
[ "module", "FB", "module", "Sysctl", "def", "self", ".", "current_settings", "s", "=", "Mixlib", "::", "ShellOut", ".", "new", "(", "'/sbin/sysctl -a'", ")", "s", ".", "run_command", "s", ".", "error!", "current", "=", "{", "}", "s", ".", "stdout", ".", "each_line", "do", "|", "line", "|", "line", ".", "match", "(", "/", "^(", "\\S", "+)", "\\s", "*=", "\\s", "*(.*)$", "/", ")", "current", "[", "$1", "]", "=", "$2", "end", "current", "end", "def", "self", ".", "normalize", "(", "val", ")", "val", ".", "to_s", ".", "gsub", "(", "/", "\\s", "+", "/", ",", "' '", ")", "end", "def", "self", ".", "incorrect_settings", "(", "current", ",", "desired", ")", "out_of_spec", "=", "{", "}", "desired", ".", "each", "do", "|", "k", ",", "v", "|", "unless", "current", "[", "k", "]", "fail", "\"fb_sysctl: Invalid setting #{k}\"", "end", "cur_val", "=", "normalize", "(", "current", "[", "k", "]", ")", "Chef", "::", "Log", ".", "debug", "(", "\"fb_sysctl: current #{k} = #{cur_val}\"", ")", "des_val", "=", "normalize", "(", "v", ")", "Chef", "::", "Log", ".", "debug", "(", "\"fb_sysctl: desired #{k} = #{des_val}\"", ")", "unless", "cur_val", "==", "des_val", "out_of_spec", "[", "k", "]", "=", "cur_val", "end", "end", "return", "out_of_spec", "end", "end", "end" ]
vim: syntax=ruby:expandtab:shiftwidth=2:softtabstop=2:tabstop=2 Copyright (c) 2016-present, Facebook, Inc. All rights reserved.
[ "vim", ":", "syntax", "=", "ruby", ":", "expandtab", ":", "shiftwidth", "=", "2", ":", "softtabstop", "=", "2", ":", "tabstop", "=", "2", "Copyright", "(", "c", ")", "2016", "-", "present", "Facebook", "Inc", ".", "All", "rights", "reserved", "." ]
[ "# tools for the fb_sysctl cookbook" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
16
250
97
95e1dca0d0269e8137211170dbb939b666373d05
mrmx/breadwallet-android
app/src/main/java/com/breadwallet/tools/util/BRStringFormatter.java
[ "MIT" ]
Java
BRStringFormatter
/** * BreadWallet * <p/> * Created by Mihail Gutan on 6/28/16. * Copyright (c) 2016 breadwallet llc <[email protected]> * <p/> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p/> * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * <p/> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */
BreadWallet Created by Mihail Gutan on 6/28/16. Copyright (c) 2016 breadwallet llc Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
[ "BreadWallet", "Created", "by", "Mihail", "Gutan", "on", "6", "/", "28", "/", "16", ".", "Copyright", "(", "c", ")", "2016", "breadwallet", "llc", "Permission", "is", "hereby", "granted", "free", "of", "charge", "to", "any", "person", "obtaining", "a", "copy", "of", "this", "software", "and", "associated", "documentation", "files", "(", "the", "\"", "Software", "\"", ")", "to", "deal", "in", "the", "Software", "without", "restriction", "including", "without", "limitation", "the", "rights", "to", "use", "copy", "modify", "merge", "publish", "distribute", "sublicense", "and", "/", "or", "sell", "copies", "of", "the", "Software", "and", "to", "permit", "persons", "to", "whom", "the", "Software", "is", "furnished", "to", "do", "so", "subject", "to", "the", "following", "conditions", ":", "The", "above", "copyright", "notice", "and", "this", "permission", "notice", "shall", "be", "included", "in", "all", "copies", "or", "substantial", "portions", "of", "the", "Software", "." ]
public class BRStringFormatter { public static final String TAG = BRStringFormatter.class.getName(); public static String getMiddleTextExchangeString(double rate, String iso, Activity ctx) { // Log.e(TAG, "result of the exchange rate calculation: " + result); if (rate == 0) rate = 1; if (ctx == null) ctx = MainActivity.app; if (ctx == null) return null; long result = BRWalletManager.getInstance(ctx).bitcoinAmount(100, new BigDecimal(String.valueOf(rate)).multiply(new BigDecimal("100")).doubleValue()); return getFormattedCurrencyString(iso, 100) + " = " + getFormattedCurrencyString("BTC", result); } public static String getBitsAndExchangeString(double rate, String iso, BigDecimal target, Activity ctx) { // Log.e(TAG, "result of the exchange rate calculation: " + result); if (rate == 0) rate = 1; long exchange = BRWalletManager.getInstance(ctx).localAmount(target.longValue(), new BigDecimal(String.valueOf(rate)).multiply(new BigDecimal("100")).doubleValue()); return getFormattedCurrencyString("BTC", target.longValue()) + " = " + getFormattedCurrencyString(iso, exchange); } public static String getExchangeForAmount(double rate, String iso, BigDecimal target, Activity ctx) { if (rate == 0) rate = 1; long exchange = BRWalletManager.getInstance(ctx).localAmount(target.longValue(), new BigDecimal(String.valueOf(rate)).multiply(new BigDecimal("100")).doubleValue()); return getFormattedCurrencyString(iso, exchange); } public static String getCurrentBalanceText(Activity ctx) { CurrencyManager cm = CurrencyManager.getInstance(ctx); String iso = SharedPreferencesManager.getIso(ctx); double rate = SharedPreferencesManager.getRate(ctx); long exchange = BRWalletManager.getInstance(ctx).localAmount(cm.getBALANCE(), new BigDecimal(String.valueOf(rate)).multiply(new BigDecimal("100")).doubleValue()); return getFormattedCurrencyString("BTC", cm.getBALANCE()) + " (" + getFormattedCurrencyString(iso, exchange) + ")"; } public static String getFormattedCurrencyString(String isoCurrencyCode, long amount) { Log.e(TAG, "amount: " + amount); DecimalFormat currencyFormat; BigDecimal result = new BigDecimal(String.valueOf(amount)).divide(new BigDecimal("100")); // This formats currency values as the user expects to read them (default locale). currencyFormat = (DecimalFormat) DecimalFormat.getCurrencyInstance(); // This specifies the actual currency that the value is in, and provide // s the currency symbol. DecimalFormatSymbols decimalFormatSymbols; Currency currency; String symbol = null; decimalFormatSymbols = currencyFormat.getDecimalFormatSymbols(); if (Objects.equals(isoCurrencyCode, "BTC")) { String currencySymbolString = BRConstants.bitcoinLowercase; MainActivity app = MainActivity.app; if (app != null) { int unit = SharedPreferencesManager.getCurrencyUnit(app); switch (unit) { case BRConstants.CURRENT_UNIT_BITS: currencySymbolString = BRConstants.bitcoinLowercase; currencyFormat.setMaximumFractionDigits(2); if (getNumberOfDecimalPlaces(result) == 1) currencyFormat.setMinimumFractionDigits(2); break; case BRConstants.CURRENT_UNIT_MBITS: currencySymbolString = "m" + BRConstants.bitcoinUppercase; currencyFormat.setMaximumFractionDigits(5); result = new BigDecimal(String.valueOf(amount)).divide(new BigDecimal("100000")); break; case BRConstants.CURRENT_UNIT_BITCOINS: currencySymbolString = BRConstants.bitcoinUppercase; currencyFormat.setMaximumFractionDigits(8); result = new BigDecimal(String.valueOf(amount)).divide(new BigDecimal("100000000")); break; } } symbol = currencySymbolString; } else { try { currency = Currency.getInstance(isoCurrencyCode); } catch (IllegalArgumentException e) { currency = Currency.getInstance(Locale.getDefault()); } symbol = currency.getSymbol(); } decimalFormatSymbols.setCurrencySymbol(symbol); currencyFormat.setMinimumFractionDigits(0); currencyFormat.setGroupingUsed(true); currencyFormat.setDecimalFormatSymbols(decimalFormatSymbols); currencyFormat.setNegativePrefix(decimalFormatSymbols.getCurrencySymbol() + "-"); currencyFormat.setNegativeSuffix(""); return currencyFormat.format(result.doubleValue()); } public static String getFormattedCurrencyStringForKeyboard(String isoCurrencyCode, long amount) { Log.e(TAG, "amount: " + amount); DecimalFormat currencyFormat; BigDecimal result = new BigDecimal(String.valueOf(amount)).divide(new BigDecimal("100")); // This formats currency values as the user expects to read them (default locale). currencyFormat = (DecimalFormat) DecimalFormat.getCurrencyInstance(); // This specifies the actual currency that the value is in, and provide // s the currency symbol. DecimalFormatSymbols decimalFormatSymbols; Currency currency; String symbol = null; decimalFormatSymbols = currencyFormat.getDecimalFormatSymbols(); if (Objects.equals(isoCurrencyCode, "BTC")) { String currencySymbolString = BRConstants.bitcoinLowercase; MainActivity app = MainActivity.app; if (app != null) { int unit = SharedPreferencesManager.getCurrencyUnit(app); switch (unit) { case BRConstants.CURRENT_UNIT_BITS: currencySymbolString = BRConstants.bitcoinLowercase; currencyFormat.setMaximumFractionDigits(2); if (getNumberOfDecimalPlaces(result) == 1) currencyFormat.setMinimumFractionDigits(2); break; case BRConstants.CURRENT_UNIT_MBITS: currencySymbolString = "m" + BRConstants.bitcoinUppercase; currencyFormat.setMaximumFractionDigits(5); result = new BigDecimal(String.valueOf(amount)).divide(new BigDecimal("100000")); break; case BRConstants.CURRENT_UNIT_BITCOINS: currencySymbolString = BRConstants.bitcoinUppercase; currencyFormat.setMaximumFractionDigits(8); result = new BigDecimal(String.valueOf(amount)).divide(new BigDecimal("100000000")); break; } } symbol = currencySymbolString; } else { try { currency = Currency.getInstance(isoCurrencyCode); } catch (IllegalArgumentException e) { currency = Currency.getInstance(Locale.getDefault()); } symbol = currency.getSymbol(); } currencyFormat.setDecimalSeparatorAlwaysShown(CurrencyManager.separatorNeedsToBeShown); decimalFormatSymbols.setCurrencySymbol(symbol); currencyFormat.setMinimumFractionDigits(AmountAdapter.digitsInserted); currencyFormat.setGroupingUsed(true); currencyFormat.setDecimalFormatSymbols(decimalFormatSymbols); currencyFormat.setNegativePrefix(decimalFormatSymbols.getCurrencySymbol() + "-"); currencyFormat.setNegativeSuffix(""); return currencyFormat.format(result.doubleValue()); } public static String getFormattedCurrencyStringForLocale(Locale locale, String isoCurrencyCode, double amount) { // This formats currency values as the user expects to read them (default locale). NumberFormat currencyFormat = NumberFormat.getCurrencyInstance(locale); // This specifies the actual currency that the value is in, and provides the currency symbol. Currency currency = Currency.getInstance(isoCurrencyCode); // Note we don't supply a locale to this method - uses default locale to format the currency symbol. String symbol = currency.getSymbol(locale); // We then tell our formatter to use this symbol. DecimalFormatSymbols decimalFormatSymbols = ((java.text.DecimalFormat) currencyFormat).getDecimalFormatSymbols(); decimalFormatSymbols.setCurrencySymbol(symbol); ((java.text.DecimalFormat) currencyFormat).setDecimalFormatSymbols(decimalFormatSymbols); return currencyFormat.format(amount); } public static String getFormattedCurrencyStringFixed(Locale locale, String isoCurrencyCode, double amount) { // This formats currency values as the user expects to read them in the supplied locale. NumberFormat currencyFormat = NumberFormat.getCurrencyInstance(locale); // This specifies the actual currency that the value is in, and provides // the currency symbol that is used Currency currency = Currency.getInstance(isoCurrencyCode); // Our fix is to use the US locale as default for the symbol, unless the currency is USD // and the locale is NOT the US, in which case we know it should be US$. String symbol; if (isoCurrencyCode.equalsIgnoreCase("usd") && !locale.equals(Locale.US)) { symbol = "US$";// currency.getSymbol(Locale.UK); } else { symbol = currency.getSymbol(Locale.US); // US locale has the best symbol formatting table. } // We tell our formatter to use this symbol DecimalFormatSymbols decimalFormatSymbols = ((java.text.DecimalFormat) currencyFormat).getDecimalFormatSymbols(); decimalFormatSymbols.setCurrencySymbol(symbol); ((java.text.DecimalFormat) currencyFormat).setDecimalFormatSymbols(decimalFormatSymbols); return currencyFormat.format(amount); } private static int getNumberOfDecimalPlaces(BigDecimal bigDecimal) { String string = bigDecimal.stripTrailingZeros().toPlainString(); int index = string.indexOf("."); return index < 0 ? 0 : string.length() - index - 1; } }
[ "public", "class", "BRStringFormatter", "{", "public", "static", "final", "String", "TAG", "=", "BRStringFormatter", ".", "class", ".", "getName", "(", ")", ";", "public", "static", "String", "getMiddleTextExchangeString", "(", "double", "rate", ",", "String", "iso", ",", "Activity", "ctx", ")", "{", "if", "(", "rate", "==", "0", ")", "rate", "=", "1", ";", "if", "(", "ctx", "==", "null", ")", "ctx", "=", "MainActivity", ".", "app", ";", "if", "(", "ctx", "==", "null", ")", "return", "null", ";", "long", "result", "=", "BRWalletManager", ".", "getInstance", "(", "ctx", ")", ".", "bitcoinAmount", "(", "100", ",", "new", "BigDecimal", "(", "String", ".", "valueOf", "(", "rate", ")", ")", ".", "multiply", "(", "new", "BigDecimal", "(", "\"", "100", "\"", ")", ")", ".", "doubleValue", "(", ")", ")", ";", "return", "getFormattedCurrencyString", "(", "iso", ",", "100", ")", "+", "\"", " = ", "\"", "+", "getFormattedCurrencyString", "(", "\"", "BTC", "\"", ",", "result", ")", ";", "}", "public", "static", "String", "getBitsAndExchangeString", "(", "double", "rate", ",", "String", "iso", ",", "BigDecimal", "target", ",", "Activity", "ctx", ")", "{", "if", "(", "rate", "==", "0", ")", "rate", "=", "1", ";", "long", "exchange", "=", "BRWalletManager", ".", "getInstance", "(", "ctx", ")", ".", "localAmount", "(", "target", ".", "longValue", "(", ")", ",", "new", "BigDecimal", "(", "String", ".", "valueOf", "(", "rate", ")", ")", ".", "multiply", "(", "new", "BigDecimal", "(", "\"", "100", "\"", ")", ")", ".", "doubleValue", "(", ")", ")", ";", "return", "getFormattedCurrencyString", "(", "\"", "BTC", "\"", ",", "target", ".", "longValue", "(", ")", ")", "+", "\"", " = ", "\"", "+", "getFormattedCurrencyString", "(", "iso", ",", "exchange", ")", ";", "}", "public", "static", "String", "getExchangeForAmount", "(", "double", "rate", ",", "String", "iso", ",", "BigDecimal", "target", ",", "Activity", "ctx", ")", "{", "if", "(", "rate", "==", "0", ")", "rate", "=", "1", ";", "long", "exchange", "=", "BRWalletManager", ".", "getInstance", "(", "ctx", ")", ".", "localAmount", "(", "target", ".", "longValue", "(", ")", ",", "new", "BigDecimal", "(", "String", ".", "valueOf", "(", "rate", ")", ")", ".", "multiply", "(", "new", "BigDecimal", "(", "\"", "100", "\"", ")", ")", ".", "doubleValue", "(", ")", ")", ";", "return", "getFormattedCurrencyString", "(", "iso", ",", "exchange", ")", ";", "}", "public", "static", "String", "getCurrentBalanceText", "(", "Activity", "ctx", ")", "{", "CurrencyManager", "cm", "=", "CurrencyManager", ".", "getInstance", "(", "ctx", ")", ";", "String", "iso", "=", "SharedPreferencesManager", ".", "getIso", "(", "ctx", ")", ";", "double", "rate", "=", "SharedPreferencesManager", ".", "getRate", "(", "ctx", ")", ";", "long", "exchange", "=", "BRWalletManager", ".", "getInstance", "(", "ctx", ")", ".", "localAmount", "(", "cm", ".", "getBALANCE", "(", ")", ",", "new", "BigDecimal", "(", "String", ".", "valueOf", "(", "rate", ")", ")", ".", "multiply", "(", "new", "BigDecimal", "(", "\"", "100", "\"", ")", ")", ".", "doubleValue", "(", ")", ")", ";", "return", "getFormattedCurrencyString", "(", "\"", "BTC", "\"", ",", "cm", ".", "getBALANCE", "(", ")", ")", "+", "\"", " (", "\"", "+", "getFormattedCurrencyString", "(", "iso", ",", "exchange", ")", "+", "\"", ")", "\"", ";", "}", "public", "static", "String", "getFormattedCurrencyString", "(", "String", "isoCurrencyCode", ",", "long", "amount", ")", "{", "Log", ".", "e", "(", "TAG", ",", "\"", "amount: ", "\"", "+", "amount", ")", ";", "DecimalFormat", "currencyFormat", ";", "BigDecimal", "result", "=", "new", "BigDecimal", "(", "String", ".", "valueOf", "(", "amount", ")", ")", ".", "divide", "(", "new", "BigDecimal", "(", "\"", "100", "\"", ")", ")", ";", "currencyFormat", "=", "(", "DecimalFormat", ")", "DecimalFormat", ".", "getCurrencyInstance", "(", ")", ";", "DecimalFormatSymbols", "decimalFormatSymbols", ";", "Currency", "currency", ";", "String", "symbol", "=", "null", ";", "decimalFormatSymbols", "=", "currencyFormat", ".", "getDecimalFormatSymbols", "(", ")", ";", "if", "(", "Objects", ".", "equals", "(", "isoCurrencyCode", ",", "\"", "BTC", "\"", ")", ")", "{", "String", "currencySymbolString", "=", "BRConstants", ".", "bitcoinLowercase", ";", "MainActivity", "app", "=", "MainActivity", ".", "app", ";", "if", "(", "app", "!=", "null", ")", "{", "int", "unit", "=", "SharedPreferencesManager", ".", "getCurrencyUnit", "(", "app", ")", ";", "switch", "(", "unit", ")", "{", "case", "BRConstants", ".", "CURRENT_UNIT_BITS", ":", "currencySymbolString", "=", "BRConstants", ".", "bitcoinLowercase", ";", "currencyFormat", ".", "setMaximumFractionDigits", "(", "2", ")", ";", "if", "(", "getNumberOfDecimalPlaces", "(", "result", ")", "==", "1", ")", "currencyFormat", ".", "setMinimumFractionDigits", "(", "2", ")", ";", "break", ";", "case", "BRConstants", ".", "CURRENT_UNIT_MBITS", ":", "currencySymbolString", "=", "\"", "m", "\"", "+", "BRConstants", ".", "bitcoinUppercase", ";", "currencyFormat", ".", "setMaximumFractionDigits", "(", "5", ")", ";", "result", "=", "new", "BigDecimal", "(", "String", ".", "valueOf", "(", "amount", ")", ")", ".", "divide", "(", "new", "BigDecimal", "(", "\"", "100000", "\"", ")", ")", ";", "break", ";", "case", "BRConstants", ".", "CURRENT_UNIT_BITCOINS", ":", "currencySymbolString", "=", "BRConstants", ".", "bitcoinUppercase", ";", "currencyFormat", ".", "setMaximumFractionDigits", "(", "8", ")", ";", "result", "=", "new", "BigDecimal", "(", "String", ".", "valueOf", "(", "amount", ")", ")", ".", "divide", "(", "new", "BigDecimal", "(", "\"", "100000000", "\"", ")", ")", ";", "break", ";", "}", "}", "symbol", "=", "currencySymbolString", ";", "}", "else", "{", "try", "{", "currency", "=", "Currency", ".", "getInstance", "(", "isoCurrencyCode", ")", ";", "}", "catch", "(", "IllegalArgumentException", "e", ")", "{", "currency", "=", "Currency", ".", "getInstance", "(", "Locale", ".", "getDefault", "(", ")", ")", ";", "}", "symbol", "=", "currency", ".", "getSymbol", "(", ")", ";", "}", "decimalFormatSymbols", ".", "setCurrencySymbol", "(", "symbol", ")", ";", "currencyFormat", ".", "setMinimumFractionDigits", "(", "0", ")", ";", "currencyFormat", ".", "setGroupingUsed", "(", "true", ")", ";", "currencyFormat", ".", "setDecimalFormatSymbols", "(", "decimalFormatSymbols", ")", ";", "currencyFormat", ".", "setNegativePrefix", "(", "decimalFormatSymbols", ".", "getCurrencySymbol", "(", ")", "+", "\"", "-", "\"", ")", ";", "currencyFormat", ".", "setNegativeSuffix", "(", "\"", "\"", ")", ";", "return", "currencyFormat", ".", "format", "(", "result", ".", "doubleValue", "(", ")", ")", ";", "}", "public", "static", "String", "getFormattedCurrencyStringForKeyboard", "(", "String", "isoCurrencyCode", ",", "long", "amount", ")", "{", "Log", ".", "e", "(", "TAG", ",", "\"", "amount: ", "\"", "+", "amount", ")", ";", "DecimalFormat", "currencyFormat", ";", "BigDecimal", "result", "=", "new", "BigDecimal", "(", "String", ".", "valueOf", "(", "amount", ")", ")", ".", "divide", "(", "new", "BigDecimal", "(", "\"", "100", "\"", ")", ")", ";", "currencyFormat", "=", "(", "DecimalFormat", ")", "DecimalFormat", ".", "getCurrencyInstance", "(", ")", ";", "DecimalFormatSymbols", "decimalFormatSymbols", ";", "Currency", "currency", ";", "String", "symbol", "=", "null", ";", "decimalFormatSymbols", "=", "currencyFormat", ".", "getDecimalFormatSymbols", "(", ")", ";", "if", "(", "Objects", ".", "equals", "(", "isoCurrencyCode", ",", "\"", "BTC", "\"", ")", ")", "{", "String", "currencySymbolString", "=", "BRConstants", ".", "bitcoinLowercase", ";", "MainActivity", "app", "=", "MainActivity", ".", "app", ";", "if", "(", "app", "!=", "null", ")", "{", "int", "unit", "=", "SharedPreferencesManager", ".", "getCurrencyUnit", "(", "app", ")", ";", "switch", "(", "unit", ")", "{", "case", "BRConstants", ".", "CURRENT_UNIT_BITS", ":", "currencySymbolString", "=", "BRConstants", ".", "bitcoinLowercase", ";", "currencyFormat", ".", "setMaximumFractionDigits", "(", "2", ")", ";", "if", "(", "getNumberOfDecimalPlaces", "(", "result", ")", "==", "1", ")", "currencyFormat", ".", "setMinimumFractionDigits", "(", "2", ")", ";", "break", ";", "case", "BRConstants", ".", "CURRENT_UNIT_MBITS", ":", "currencySymbolString", "=", "\"", "m", "\"", "+", "BRConstants", ".", "bitcoinUppercase", ";", "currencyFormat", ".", "setMaximumFractionDigits", "(", "5", ")", ";", "result", "=", "new", "BigDecimal", "(", "String", ".", "valueOf", "(", "amount", ")", ")", ".", "divide", "(", "new", "BigDecimal", "(", "\"", "100000", "\"", ")", ")", ";", "break", ";", "case", "BRConstants", ".", "CURRENT_UNIT_BITCOINS", ":", "currencySymbolString", "=", "BRConstants", ".", "bitcoinUppercase", ";", "currencyFormat", ".", "setMaximumFractionDigits", "(", "8", ")", ";", "result", "=", "new", "BigDecimal", "(", "String", ".", "valueOf", "(", "amount", ")", ")", ".", "divide", "(", "new", "BigDecimal", "(", "\"", "100000000", "\"", ")", ")", ";", "break", ";", "}", "}", "symbol", "=", "currencySymbolString", ";", "}", "else", "{", "try", "{", "currency", "=", "Currency", ".", "getInstance", "(", "isoCurrencyCode", ")", ";", "}", "catch", "(", "IllegalArgumentException", "e", ")", "{", "currency", "=", "Currency", ".", "getInstance", "(", "Locale", ".", "getDefault", "(", ")", ")", ";", "}", "symbol", "=", "currency", ".", "getSymbol", "(", ")", ";", "}", "currencyFormat", ".", "setDecimalSeparatorAlwaysShown", "(", "CurrencyManager", ".", "separatorNeedsToBeShown", ")", ";", "decimalFormatSymbols", ".", "setCurrencySymbol", "(", "symbol", ")", ";", "currencyFormat", ".", "setMinimumFractionDigits", "(", "AmountAdapter", ".", "digitsInserted", ")", ";", "currencyFormat", ".", "setGroupingUsed", "(", "true", ")", ";", "currencyFormat", ".", "setDecimalFormatSymbols", "(", "decimalFormatSymbols", ")", ";", "currencyFormat", ".", "setNegativePrefix", "(", "decimalFormatSymbols", ".", "getCurrencySymbol", "(", ")", "+", "\"", "-", "\"", ")", ";", "currencyFormat", ".", "setNegativeSuffix", "(", "\"", "\"", ")", ";", "return", "currencyFormat", ".", "format", "(", "result", ".", "doubleValue", "(", ")", ")", ";", "}", "public", "static", "String", "getFormattedCurrencyStringForLocale", "(", "Locale", "locale", ",", "String", "isoCurrencyCode", ",", "double", "amount", ")", "{", "NumberFormat", "currencyFormat", "=", "NumberFormat", ".", "getCurrencyInstance", "(", "locale", ")", ";", "Currency", "currency", "=", "Currency", ".", "getInstance", "(", "isoCurrencyCode", ")", ";", "String", "symbol", "=", "currency", ".", "getSymbol", "(", "locale", ")", ";", "DecimalFormatSymbols", "decimalFormatSymbols", "=", "(", "(", "java", ".", "text", ".", "DecimalFormat", ")", "currencyFormat", ")", ".", "getDecimalFormatSymbols", "(", ")", ";", "decimalFormatSymbols", ".", "setCurrencySymbol", "(", "symbol", ")", ";", "(", "(", "java", ".", "text", ".", "DecimalFormat", ")", "currencyFormat", ")", ".", "setDecimalFormatSymbols", "(", "decimalFormatSymbols", ")", ";", "return", "currencyFormat", ".", "format", "(", "amount", ")", ";", "}", "public", "static", "String", "getFormattedCurrencyStringFixed", "(", "Locale", "locale", ",", "String", "isoCurrencyCode", ",", "double", "amount", ")", "{", "NumberFormat", "currencyFormat", "=", "NumberFormat", ".", "getCurrencyInstance", "(", "locale", ")", ";", "Currency", "currency", "=", "Currency", ".", "getInstance", "(", "isoCurrencyCode", ")", ";", "String", "symbol", ";", "if", "(", "isoCurrencyCode", ".", "equalsIgnoreCase", "(", "\"", "usd", "\"", ")", "&&", "!", "locale", ".", "equals", "(", "Locale", ".", "US", ")", ")", "{", "symbol", "=", "\"", "US$", "\"", ";", "}", "else", "{", "symbol", "=", "currency", ".", "getSymbol", "(", "Locale", ".", "US", ")", ";", "}", "DecimalFormatSymbols", "decimalFormatSymbols", "=", "(", "(", "java", ".", "text", ".", "DecimalFormat", ")", "currencyFormat", ")", ".", "getDecimalFormatSymbols", "(", ")", ";", "decimalFormatSymbols", ".", "setCurrencySymbol", "(", "symbol", ")", ";", "(", "(", "java", ".", "text", ".", "DecimalFormat", ")", "currencyFormat", ")", ".", "setDecimalFormatSymbols", "(", "decimalFormatSymbols", ")", ";", "return", "currencyFormat", ".", "format", "(", "amount", ")", ";", "}", "private", "static", "int", "getNumberOfDecimalPlaces", "(", "BigDecimal", "bigDecimal", ")", "{", "String", "string", "=", "bigDecimal", ".", "stripTrailingZeros", "(", ")", ".", "toPlainString", "(", ")", ";", "int", "index", "=", "string", ".", "indexOf", "(", "\"", ".", "\"", ")", ";", "return", "index", "<", "0", "?", "0", ":", "string", ".", "length", "(", ")", "-", "index", "-", "1", ";", "}", "}" ]
BreadWallet <p/> Created by Mihail Gutan on 6/28/16.
[ "BreadWallet", "<p", "/", ">", "Created", "by", "Mihail", "Gutan", "on", "6", "/", "28", "/", "16", "." ]
[ "// Log.e(TAG, \"result of the exchange rate calculation: \" + result);", "// Log.e(TAG, \"result of the exchange rate calculation: \" + result);", "// This formats currency values as the user expects to read them (default locale).", "// This specifies the actual currency that the value is in, and provide", "// s the currency symbol.", "// This formats currency values as the user expects to read them (default locale).", "// This specifies the actual currency that the value is in, and provide", "// s the currency symbol.", "// This formats currency values as the user expects to read them (default locale).", "// This specifies the actual currency that the value is in, and provides the currency symbol.", "// Note we don't supply a locale to this method - uses default locale to format the currency symbol.", "// We then tell our formatter to use this symbol.", "// This formats currency values as the user expects to read them in the supplied locale.", "// This specifies the actual currency that the value is in, and provides", "// the currency symbol that is used", "// Our fix is to use the US locale as default for the symbol, unless the currency is USD", "// and the locale is NOT the US, in which case we know it should be US$.", "// currency.getSymbol(Locale.UK);", "// US locale has the best symbol formatting table.", "// We tell our formatter to use this symbol" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
19
1,971
280
4ba0a05ae8c885187c74f135bc3dafc9e0293773
edward/yard
lib/yard/tags/library.rb
[ "MIT" ]
Ruby
Library
## # Holds all the registered meta tags. If you want to extend YARD and add # a new meta tag, you can do it in one of two ways. # # == Method #1 # Write your own +tagname_tag+ method that takes the raw text as a parameter. # Example: # def mytag_tag(text) # Tag.parse_tag("mytag", text) # end # # This will allow you to use @mytag TEXT to add meta data to classes through # the docstring. {Tag} has a few convenience factory methods to create # # == Method #2 # Use {Library::define_tag!} to define a new tag by passing the tag name # and the factory method to use when creating the tag. These definitions will # be auto expanded into ruby code similar to what is shown in method #1. If you # do not provide a factory method to use, it will default to {Tag::parse_tag} # Example: # define_tag :param, :with_types_and_name # define_tag :author # # The first line will expand to the code: # def param_tag(text) Tag.parse_tag_with_types_and_name(text) end # # The second line will expand to: # def author_tag(text) Tag.parse_tag(text) end # # @see Library::define_tag
Holds all the registered meta tags. If you want to extend YARD and add a new meta tag, you can do it in one of two ways. Method #1 Write your own +tagname_tag+ method that takes the raw text as a parameter. This will allow you to use @mytag TEXT to add meta data to classes through the docstring. {Tag} has a few convenience factory methods to create Method #2 Use {Library::define_tag!} to define a new tag by passing the tag name and the factory method to use when creating the tag. These definitions will be auto expanded into ruby code similar to what is shown in method #1.
[ "Holds", "all", "the", "registered", "meta", "tags", ".", "If", "you", "want", "to", "extend", "YARD", "and", "add", "a", "new", "meta", "tag", "you", "can", "do", "it", "in", "one", "of", "two", "ways", ".", "Method", "#1", "Write", "your", "own", "+", "tagname_tag", "+", "method", "that", "takes", "the", "raw", "text", "as", "a", "parameter", ".", "This", "will", "allow", "you", "to", "use", "@mytag", "TEXT", "to", "add", "meta", "data", "to", "classes", "through", "the", "docstring", ".", "{", "Tag", "}", "has", "a", "few", "convenience", "factory", "methods", "to", "create", "Method", "#2", "Use", "{", "Library", "::", "define_tag!", "}", "to", "define", "a", "new", "tag", "by", "passing", "the", "tag", "name", "and", "the", "factory", "method", "to", "use", "when", "creating", "the", "tag", ".", "These", "definitions", "will", "be", "auto", "expanded", "into", "ruby", "code", "similar", "to", "what", "is", "shown", "in", "method", "#1", "." ]
class Library class << self attr_reader :labels attr_accessor :default_factory def default_factory @default_factory ||= DefaultFactory.new end def default_factory=(factory) @default_factory = factory.is_a?(Class) ? factory.new : factory end ## # Sorts the labels lexically by their label name, often used when displaying # the tags. # # @return [Array<Symbol>, String] the sorted labels as an array of the tag name and label def sorted_labels labels.sort_by {|a| a.last.downcase } end ## # Convenience method to define a new tag using one of {Tag}'s factory methods, or the # regular {Tag::parse_tag} factory method if none is supplied. # # @param [#to_s] tag the tag name to create # @param meth the {Tag} factory method to call when creating the tag def define_tag(label, tag, meth = "") class_eval <<-eof, __FILE__, __LINE__ def #{tag}_tag(text, raw_text) send_to_factory(#{tag.inspect}, #{meth.inspect}, text, raw_text) end eof @labels ||= SymbolHash.new(false) @labels.update(tag => label) tag end end private def send_to_factory(tag_name, meth, text, raw_text) meth = meth.to_s send_name = "parse_tag" + (meth.empty? ? "" : "_" + meth) if @factory.respond_to?(send_name) arity = @factory.method(send_name).arity @factory.send send_name, tag_name, text, *(arity == 3 ? [raw_text] : []) else raise NoMethodError, "Factory #{@factory.class_name} does not implement factory method :#{meth}." end end public def initialize(factory = Library.default_factory) @factory = factory end define_tag "Parameters", :param, :with_types_and_name define_tag "Yield Parameters", :yieldparam, :with_types_and_name define_tag "Yields", :yield, :with_types define_tag "Default Value", :default, :with_name define_tag "Returns", :return, :with_types define_tag "Deprecated", :deprecated define_tag "Author", :author define_tag "Raises", :raise, :with_types define_tag "See Also", :see define_tag "Since", :since define_tag "Version", :version define_tag "API Visibility", :api define_tag "Todo Item", :todo, :with_raw_title_and_text define_tag "Example", :example, :with_raw_title_and_text end
[ "class", "Library", "class", "<<", "self", "attr_reader", ":labels", "attr_accessor", ":default_factory", "def", "default_factory", "@default_factory", "||=", "DefaultFactory", ".", "new", "end", "def", "default_factory", "=", "(", "factory", ")", "@default_factory", "=", "factory", ".", "is_a?", "(", "Class", ")", "?", "factory", ".", "new", ":", "factory", "end", "def", "sorted_labels", "labels", ".", "sort_by", "{", "|", "a", "|", "a", ".", "last", ".", "downcase", "}", "end", "def", "define_tag", "(", "label", ",", "tag", ",", "meth", "=", "\"\"", ")", "class_eval", "<<-eof", ",", "__FILE__", ",", "__LINE__", "\n def ", "#{", "tag", "}", "_tag(text, raw_text)\n send_to_factory(", "#{", "tag", ".", "inspect", "}", ", ", "#{", "meth", ".", "inspect", "}", ", text, raw_text)\n end\n ", "eof", "@labels", "||=", "SymbolHash", ".", "new", "(", "false", ")", "@labels", ".", "update", "(", "tag", "=>", "label", ")", "tag", "end", "end", "private", "def", "send_to_factory", "(", "tag_name", ",", "meth", ",", "text", ",", "raw_text", ")", "meth", "=", "meth", ".", "to_s", "send_name", "=", "\"parse_tag\"", "+", "(", "meth", ".", "empty?", "?", "\"\"", ":", "\"_\"", "+", "meth", ")", "if", "@factory", ".", "respond_to?", "(", "send_name", ")", "arity", "=", "@factory", ".", "method", "(", "send_name", ")", ".", "arity", "@factory", ".", "send", "send_name", ",", "tag_name", ",", "text", ",", "*", "(", "arity", "==", "3", "?", "[", "raw_text", "]", ":", "[", "]", ")", "else", "raise", "NoMethodError", ",", "\"Factory #{@factory.class_name} does not implement factory method :#{meth}.\"", "end", "end", "public", "def", "initialize", "(", "factory", "=", "Library", ".", "default_factory", ")", "@factory", "=", "factory", "end", "define_tag", "\"Parameters\"", ",", ":param", ",", ":with_types_and_name", "define_tag", "\"Yield Parameters\"", ",", ":yieldparam", ",", ":with_types_and_name", "define_tag", "\"Yields\"", ",", ":yield", ",", ":with_types", "define_tag", "\"Default Value\"", ",", ":default", ",", ":with_name", "define_tag", "\"Returns\"", ",", ":return", ",", ":with_types", "define_tag", "\"Deprecated\"", ",", ":deprecated", "define_tag", "\"Author\"", ",", ":author", "define_tag", "\"Raises\"", ",", ":raise", ",", ":with_types", "define_tag", "\"See Also\"", ",", ":see", "define_tag", "\"Since\"", ",", ":since", "define_tag", "\"Version\"", ",", ":version", "define_tag", "\"API Visibility\"", ",", ":api", "define_tag", "\"Todo Item\"", ",", ":todo", ",", ":with_raw_title_and_text", "define_tag", "\"Example\"", ",", ":example", ",", ":with_raw_title_and_text", "end" ]
Holds all the registered meta tags.
[ "Holds", "all", "the", "registered", "meta", "tags", "." ]
[ "## ", "# Sorts the labels lexically by their label name, often used when displaying", "# the tags.", "# ", "# @return [Array<Symbol>, String] the sorted labels as an array of the tag name and label", "##", "# Convenience method to define a new tag using one of {Tag}'s factory methods, or the", "# regular {Tag::parse_tag} factory method if none is supplied.", "#", "# @param [#to_s] tag the tag name to create", "# @param meth the {Tag} factory method to call when creating the tag" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [ { "identifier": "see", "docstring": null, "docstring_tokens": [ "None" ] } ] }
false
13
639
290
fb078648ec57f9cd454ee22eb6bad6bcfcbf920d
kokosing/hue
desktop/core/ext-py/py4j-0.9/py4j-java/src/py4j/GatewayConnection.java
[ "Apache-2.0" ]
Java
GatewayConnection
/** * <p> * Manage the connection between a Python program and a Gateway. A * GatewayConnection lives in its own thread and is created on demand (e.g., one * per concurrent thread). * </p> * * <p> * The request to connect to the JVM goes through the {@link py4j.GatewayServer * GatewayServer} first and is then passed to a GatewayConnection. * </p> * * <p> * This class is not intended to be directly accessed by users. * </p> * * * @author Barthelemy Dagenais * */
Manage the connection between a Python program and a Gateway. A GatewayConnection lives in its own thread and is created on demand . The request to connect to the JVM goes through the {@link py4j.GatewayServer GatewayServer} first and is then passed to a GatewayConnection. This class is not intended to be directly accessed by users. @author Barthelemy Dagenais
[ "Manage", "the", "connection", "between", "a", "Python", "program", "and", "a", "Gateway", ".", "A", "GatewayConnection", "lives", "in", "its", "own", "thread", "and", "is", "created", "on", "demand", ".", "The", "request", "to", "connect", "to", "the", "JVM", "goes", "through", "the", "{", "@link", "py4j", ".", "GatewayServer", "GatewayServer", "}", "first", "and", "is", "then", "passed", "to", "a", "GatewayConnection", ".", "This", "class", "is", "not", "intended", "to", "be", "directly", "accessed", "by", "users", ".", "@author", "Barthelemy", "Dagenais" ]
public class GatewayConnection implements Runnable { protected final static List<Class<? extends Command>> baseCommands; protected final Socket socket; protected final BufferedWriter writer; protected final BufferedReader reader; protected final Map<String, Command> commands; protected final Logger logger = Logger.getLogger(GatewayConnection.class .getName()); protected final List<GatewayServerListener> listeners; static { baseCommands = new ArrayList<Class<? extends Command>>(); baseCommands.add(ArrayCommand.class); baseCommands.add(CallCommand.class); baseCommands.add(ConstructorCommand.class); baseCommands.add(FieldCommand.class); baseCommands.add(HelpPageCommand.class); baseCommands.add(ListCommand.class); baseCommands.add(MemoryCommand.class); baseCommands.add(ReflectionCommand.class); baseCommands.add(ShutdownGatewayServerCommand.class); baseCommands.add(JVMViewCommand.class); baseCommands.add(ExceptionCommand.class); baseCommands.add(DirCommand.class); } /** * * @return The list of base commands that are provided by default. Can be * hidden by custom commands with the same command id by passing a * list of custom commands to the {@link py4j.GatewayServer * GatewayServer}. */ public static List<Class<? extends Command>> getBaseCommands() { return baseCommands; } public GatewayConnection(Gateway gateway, Socket socket) throws IOException { this(gateway, socket, null, new ArrayList<GatewayServerListener>()); } public GatewayConnection(Gateway gateway, Socket socket, List<Class<? extends Command>> customCommands, List<GatewayServerListener> listeners) throws IOException { super(); this.socket = socket; this.reader = new BufferedReader(new InputStreamReader( socket.getInputStream(), Charset.forName("UTF-8"))); this.writer = new BufferedWriter(new OutputStreamWriter( socket.getOutputStream(), Charset.forName("UTF-8"))); this.commands = new HashMap<String, Command>(); initCommands(gateway, baseCommands); if (customCommands != null) { initCommands(gateway, customCommands); } this.listeners = listeners; Thread t = new Thread(this); t.start(); } protected void fireConnectionStopped() { logger.info("Connection Stopped"); for (GatewayServerListener listener : listeners) { try { listener.connectionStopped(this); } catch (Exception e) { logger.log(Level.SEVERE, "A listener crashed.", e); } } } /** * * @return The socket used by this gateway connection. */ public Socket getSocket() { return socket; } /** * <p> * Override this method to initialize custom commands. * </p> * * @param gateway */ protected void initCommands(Gateway gateway, List<Class<? extends Command>> commandsClazz) { for (Class<? extends Command> clazz : commandsClazz) { try { Command cmd = clazz.newInstance(); cmd.init(gateway); commands.put(cmd.getCommandName(), cmd); } catch (Exception e) { String name = "null"; if (clazz != null) { name = clazz.getName(); } logger.log(Level.SEVERE, "Could not initialize command " + name, e); } } } protected void quietSendError(BufferedWriter writer, Throwable exception) { try { String returnCommand = Protocol.getOutputErrorCommand(exception); logger.fine("Trying to return error: " + returnCommand); writer.write(returnCommand); writer.flush(); } catch (Exception e) { } } @Override public void run() { boolean executing = false; try { logger.info("Gateway Connection ready to receive messages"); String commandLine = null; do { commandLine = reader.readLine(); executing = true; logger.fine("Received command: " + commandLine); Command command = commands.get(commandLine); if (command != null) { command.execute(commandLine, reader, writer); executing = false; } else { logger.log(Level.WARNING, "Unknown command " + commandLine); } } while (commandLine != null && !commandLine.equals("q")); } catch (Exception e) { logger.log(Level.WARNING, "Error occurred while waiting for a command.", e); if (executing && writer != null) { quietSendError(writer, e); } } finally { NetworkUtil.quietlyClose(socket); fireConnectionStopped(); } } }
[ "public", "class", "GatewayConnection", "implements", "Runnable", "{", "protected", "final", "static", "List", "<", "Class", "<", "?", "extends", "Command", ">", ">", "baseCommands", ";", "protected", "final", "Socket", "socket", ";", "protected", "final", "BufferedWriter", "writer", ";", "protected", "final", "BufferedReader", "reader", ";", "protected", "final", "Map", "<", "String", ",", "Command", ">", "commands", ";", "protected", "final", "Logger", "logger", "=", "Logger", ".", "getLogger", "(", "GatewayConnection", ".", "class", ".", "getName", "(", ")", ")", ";", "protected", "final", "List", "<", "GatewayServerListener", ">", "listeners", ";", "static", "{", "baseCommands", "=", "new", "ArrayList", "<", "Class", "<", "?", "extends", "Command", ">", ">", "(", ")", ";", "baseCommands", ".", "add", "(", "ArrayCommand", ".", "class", ")", ";", "baseCommands", ".", "add", "(", "CallCommand", ".", "class", ")", ";", "baseCommands", ".", "add", "(", "ConstructorCommand", ".", "class", ")", ";", "baseCommands", ".", "add", "(", "FieldCommand", ".", "class", ")", ";", "baseCommands", ".", "add", "(", "HelpPageCommand", ".", "class", ")", ";", "baseCommands", ".", "add", "(", "ListCommand", ".", "class", ")", ";", "baseCommands", ".", "add", "(", "MemoryCommand", ".", "class", ")", ";", "baseCommands", ".", "add", "(", "ReflectionCommand", ".", "class", ")", ";", "baseCommands", ".", "add", "(", "ShutdownGatewayServerCommand", ".", "class", ")", ";", "baseCommands", ".", "add", "(", "JVMViewCommand", ".", "class", ")", ";", "baseCommands", ".", "add", "(", "ExceptionCommand", ".", "class", ")", ";", "baseCommands", ".", "add", "(", "DirCommand", ".", "class", ")", ";", "}", "/**\n\t * \n\t * @return The list of base commands that are provided by default. Can be\n\t * hidden by custom commands with the same command id by passing a\n\t * list of custom commands to the {@link py4j.GatewayServer\n\t * GatewayServer}.\n\t */", "public", "static", "List", "<", "Class", "<", "?", "extends", "Command", ">", ">", "getBaseCommands", "(", ")", "{", "return", "baseCommands", ";", "}", "public", "GatewayConnection", "(", "Gateway", "gateway", ",", "Socket", "socket", ")", "throws", "IOException", "{", "this", "(", "gateway", ",", "socket", ",", "null", ",", "new", "ArrayList", "<", "GatewayServerListener", ">", "(", ")", ")", ";", "}", "public", "GatewayConnection", "(", "Gateway", "gateway", ",", "Socket", "socket", ",", "List", "<", "Class", "<", "?", "extends", "Command", ">", ">", "customCommands", ",", "List", "<", "GatewayServerListener", ">", "listeners", ")", "throws", "IOException", "{", "super", "(", ")", ";", "this", ".", "socket", "=", "socket", ";", "this", ".", "reader", "=", "new", "BufferedReader", "(", "new", "InputStreamReader", "(", "socket", ".", "getInputStream", "(", ")", ",", "Charset", ".", "forName", "(", "\"", "UTF-8", "\"", ")", ")", ")", ";", "this", ".", "writer", "=", "new", "BufferedWriter", "(", "new", "OutputStreamWriter", "(", "socket", ".", "getOutputStream", "(", ")", ",", "Charset", ".", "forName", "(", "\"", "UTF-8", "\"", ")", ")", ")", ";", "this", ".", "commands", "=", "new", "HashMap", "<", "String", ",", "Command", ">", "(", ")", ";", "initCommands", "(", "gateway", ",", "baseCommands", ")", ";", "if", "(", "customCommands", "!=", "null", ")", "{", "initCommands", "(", "gateway", ",", "customCommands", ")", ";", "}", "this", ".", "listeners", "=", "listeners", ";", "Thread", "t", "=", "new", "Thread", "(", "this", ")", ";", "t", ".", "start", "(", ")", ";", "}", "protected", "void", "fireConnectionStopped", "(", ")", "{", "logger", ".", "info", "(", "\"", "Connection Stopped", "\"", ")", ";", "for", "(", "GatewayServerListener", "listener", ":", "listeners", ")", "{", "try", "{", "listener", ".", "connectionStopped", "(", "this", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "logger", ".", "log", "(", "Level", ".", "SEVERE", ",", "\"", "A listener crashed.", "\"", ",", "e", ")", ";", "}", "}", "}", "/**\n\t * \n\t * @return The socket used by this gateway connection.\n\t */", "public", "Socket", "getSocket", "(", ")", "{", "return", "socket", ";", "}", "/**\n\t * <p>\n\t * Override this method to initialize custom commands.\n\t * </p>\n\t * \n\t * @param gateway\n\t */", "protected", "void", "initCommands", "(", "Gateway", "gateway", ",", "List", "<", "Class", "<", "?", "extends", "Command", ">", ">", "commandsClazz", ")", "{", "for", "(", "Class", "<", "?", "extends", "Command", ">", "clazz", ":", "commandsClazz", ")", "{", "try", "{", "Command", "cmd", "=", "clazz", ".", "newInstance", "(", ")", ";", "cmd", ".", "init", "(", "gateway", ")", ";", "commands", ".", "put", "(", "cmd", ".", "getCommandName", "(", ")", ",", "cmd", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "String", "name", "=", "\"", "null", "\"", ";", "if", "(", "clazz", "!=", "null", ")", "{", "name", "=", "clazz", ".", "getName", "(", ")", ";", "}", "logger", ".", "log", "(", "Level", ".", "SEVERE", ",", "\"", "Could not initialize command ", "\"", "+", "name", ",", "e", ")", ";", "}", "}", "}", "protected", "void", "quietSendError", "(", "BufferedWriter", "writer", ",", "Throwable", "exception", ")", "{", "try", "{", "String", "returnCommand", "=", "Protocol", ".", "getOutputErrorCommand", "(", "exception", ")", ";", "logger", ".", "fine", "(", "\"", "Trying to return error: ", "\"", "+", "returnCommand", ")", ";", "writer", ".", "write", "(", "returnCommand", ")", ";", "writer", ".", "flush", "(", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "}", "}", "@", "Override", "public", "void", "run", "(", ")", "{", "boolean", "executing", "=", "false", ";", "try", "{", "logger", ".", "info", "(", "\"", "Gateway Connection ready to receive messages", "\"", ")", ";", "String", "commandLine", "=", "null", ";", "do", "{", "commandLine", "=", "reader", ".", "readLine", "(", ")", ";", "executing", "=", "true", ";", "logger", ".", "fine", "(", "\"", "Received command: ", "\"", "+", "commandLine", ")", ";", "Command", "command", "=", "commands", ".", "get", "(", "commandLine", ")", ";", "if", "(", "command", "!=", "null", ")", "{", "command", ".", "execute", "(", "commandLine", ",", "reader", ",", "writer", ")", ";", "executing", "=", "false", ";", "}", "else", "{", "logger", ".", "log", "(", "Level", ".", "WARNING", ",", "\"", "Unknown command ", "\"", "+", "commandLine", ")", ";", "}", "}", "while", "(", "commandLine", "!=", "null", "&&", "!", "commandLine", ".", "equals", "(", "\"", "q", "\"", ")", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "logger", ".", "log", "(", "Level", ".", "WARNING", ",", "\"", "Error occurred while waiting for a command.", "\"", ",", "e", ")", ";", "if", "(", "executing", "&&", "writer", "!=", "null", ")", "{", "quietSendError", "(", "writer", ",", "e", ")", ";", "}", "}", "finally", "{", "NetworkUtil", ".", "quietlyClose", "(", "socket", ")", ";", "fireConnectionStopped", "(", ")", ";", "}", "}", "}" ]
<p> Manage the connection between a Python program and a Gateway.
[ "<p", ">", "Manage", "the", "connection", "between", "a", "Python", "program", "and", "a", "Gateway", "." ]
[]
[ { "param": "Runnable", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Runnable", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
16
979
132
aa8a9565ccd04fc9102e564f5323fafc637882d6
fsciortino/Aurora
aurora/plot_tools.py
[ "MIT" ]
Python
DraggableColorbar
Create a draggable colorbar for matplotlib plots to enable quick changes in color scale. Example::: fig,ax = plt.subplots() cntr = ax.contourf(R, Z, vals) cbar = plt.colorbar(cntr, format='%.3g', ax=ax) cbar = DraggableColorbar(cbar,cntr) cbar.connect()
Create a draggable colorbar for matplotlib plots to enable quick changes in color scale. Example::.
[ "Create", "a", "draggable", "colorbar", "for", "matplotlib", "plots", "to", "enable", "quick", "changes", "in", "color", "scale", ".", "Example", "::", "." ]
class DraggableColorbar: '''Create a draggable colorbar for matplotlib plots to enable quick changes in color scale. Example::: fig,ax = plt.subplots() cntr = ax.contourf(R, Z, vals) cbar = plt.colorbar(cntr, format='%.3g', ax=ax) cbar = DraggableColorbar(cbar,cntr) cbar.connect() ''' def __init__(self, cbar, mapimage): self.cbar = cbar self.mapimage = mapimage self.press = None self.cycle = sorted([i for i in dir(plt.cm) if hasattr(getattr(plt.cm,i),'N')]) self.index = self.cycle.index(ScalarMappable.get_cmap(cbar).name) def connect(self): '''Matplotlib connection for button and key pressing, release, and motion. ''' self.cidpress = self.cbar.patch.figure.canvas.mpl_connect('button_press_event', self.on_press) self.cidrelease = self.cbar.patch.figure.canvas.mpl_connect('button_release_event', self.on_release) self.cidmotion = self.cbar.patch.figure.canvas.mpl_connect('motion_notify_event', self.on_motion) self.keypress = self.cbar.patch.figure.canvas.mpl_connect('key_press_event', self.key_press) def on_press(self, event): '''Button pressing; check if mouse is over colorbar. ''' if event.inaxes != self.cbar.ax: return self.press = event.x, event.y def key_press(self, event): '''Key pressing event ''' if event.key=='down': self.index += 1 elif event.key=='up': self.index -= 1 if self.index<0: self.index = len(self.cycle) elif self.index>=len(self.cycle): self.index = 0 cmap = self.cycle[self.index] self.cbar.set_cmap(cmap) self.cbar.draw_all() self.mapimage.set_cmap(cmap) self.mapimage.get_axes().set_title(cmap) self.cbar.patch.figure.canvas.draw() def on_motion(self, event): '''Move if the mouse is over the colorbar. ''' if self.press is None: return if event.inaxes != self.cbar.ax: return xprev, yprev = self.press dx = event.x - xprev dy = event.y - yprev self.press = event.x,event.y scale = self.cbar.norm.vmax - self.cbar.norm.vmin perc = 0.03 if event.button==1: self.cbar.norm.vmin -= (perc*scale)*np.sign(dy) self.cbar.norm.vmax -= (perc*scale)*np.sign(dy) elif event.button==3: self.cbar.norm.vmin -= (perc*scale)*np.sign(dy) self.cbar.norm.vmax += (perc*scale)*np.sign(dy) self.cbar.draw_all() self.mapimage.set_norm(self.cbar.norm) self.cbar.patch.figure.canvas.draw() def on_release(self, event): '''Upon release, reset press data ''' self.press = None self.mapimage.set_norm(self.cbar.norm) self.cbar.patch.figure.canvas.draw() def disconnect(self): self.cbar.patch.figure.canvas.mpl_disconnect(self.cidpress) self.cbar.patch.figure.canvas.mpl_disconnect(self.cidrelease) self.cbar.patch.figure.canvas.mpl_disconnect(self.cidmotion)
[ "class", "DraggableColorbar", ":", "def", "__init__", "(", "self", ",", "cbar", ",", "mapimage", ")", ":", "self", ".", "cbar", "=", "cbar", "self", ".", "mapimage", "=", "mapimage", "self", ".", "press", "=", "None", "self", ".", "cycle", "=", "sorted", "(", "[", "i", "for", "i", "in", "dir", "(", "plt", ".", "cm", ")", "if", "hasattr", "(", "getattr", "(", "plt", ".", "cm", ",", "i", ")", ",", "'N'", ")", "]", ")", "self", ".", "index", "=", "self", ".", "cycle", ".", "index", "(", "ScalarMappable", ".", "get_cmap", "(", "cbar", ")", ".", "name", ")", "def", "connect", "(", "self", ")", ":", "'''Matplotlib connection for button and key pressing, release, and motion.\n '''", "self", ".", "cidpress", "=", "self", ".", "cbar", ".", "patch", ".", "figure", ".", "canvas", ".", "mpl_connect", "(", "'button_press_event'", ",", "self", ".", "on_press", ")", "self", ".", "cidrelease", "=", "self", ".", "cbar", ".", "patch", ".", "figure", ".", "canvas", ".", "mpl_connect", "(", "'button_release_event'", ",", "self", ".", "on_release", ")", "self", ".", "cidmotion", "=", "self", ".", "cbar", ".", "patch", ".", "figure", ".", "canvas", ".", "mpl_connect", "(", "'motion_notify_event'", ",", "self", ".", "on_motion", ")", "self", ".", "keypress", "=", "self", ".", "cbar", ".", "patch", ".", "figure", ".", "canvas", ".", "mpl_connect", "(", "'key_press_event'", ",", "self", ".", "key_press", ")", "def", "on_press", "(", "self", ",", "event", ")", ":", "'''Button pressing; check if mouse is over colorbar.\n '''", "if", "event", ".", "inaxes", "!=", "self", ".", "cbar", ".", "ax", ":", "return", "self", ".", "press", "=", "event", ".", "x", ",", "event", ".", "y", "def", "key_press", "(", "self", ",", "event", ")", ":", "'''Key pressing event\n '''", "if", "event", ".", "key", "==", "'down'", ":", "self", ".", "index", "+=", "1", "elif", "event", ".", "key", "==", "'up'", ":", "self", ".", "index", "-=", "1", "if", "self", ".", "index", "<", "0", ":", "self", ".", "index", "=", "len", "(", "self", ".", "cycle", ")", "elif", "self", ".", "index", ">=", "len", "(", "self", ".", "cycle", ")", ":", "self", ".", "index", "=", "0", "cmap", "=", "self", ".", "cycle", "[", "self", ".", "index", "]", "self", ".", "cbar", ".", "set_cmap", "(", "cmap", ")", "self", ".", "cbar", ".", "draw_all", "(", ")", "self", ".", "mapimage", ".", "set_cmap", "(", "cmap", ")", "self", ".", "mapimage", ".", "get_axes", "(", ")", ".", "set_title", "(", "cmap", ")", "self", ".", "cbar", ".", "patch", ".", "figure", ".", "canvas", ".", "draw", "(", ")", "def", "on_motion", "(", "self", ",", "event", ")", ":", "'''Move if the mouse is over the colorbar.\n '''", "if", "self", ".", "press", "is", "None", ":", "return", "if", "event", ".", "inaxes", "!=", "self", ".", "cbar", ".", "ax", ":", "return", "xprev", ",", "yprev", "=", "self", ".", "press", "dx", "=", "event", ".", "x", "-", "xprev", "dy", "=", "event", ".", "y", "-", "yprev", "self", ".", "press", "=", "event", ".", "x", ",", "event", ".", "y", "scale", "=", "self", ".", "cbar", ".", "norm", ".", "vmax", "-", "self", ".", "cbar", ".", "norm", ".", "vmin", "perc", "=", "0.03", "if", "event", ".", "button", "==", "1", ":", "self", ".", "cbar", ".", "norm", ".", "vmin", "-=", "(", "perc", "*", "scale", ")", "*", "np", ".", "sign", "(", "dy", ")", "self", ".", "cbar", ".", "norm", ".", "vmax", "-=", "(", "perc", "*", "scale", ")", "*", "np", ".", "sign", "(", "dy", ")", "elif", "event", ".", "button", "==", "3", ":", "self", ".", "cbar", ".", "norm", ".", "vmin", "-=", "(", "perc", "*", "scale", ")", "*", "np", ".", "sign", "(", "dy", ")", "self", ".", "cbar", ".", "norm", ".", "vmax", "+=", "(", "perc", "*", "scale", ")", "*", "np", ".", "sign", "(", "dy", ")", "self", ".", "cbar", ".", "draw_all", "(", ")", "self", ".", "mapimage", ".", "set_norm", "(", "self", ".", "cbar", ".", "norm", ")", "self", ".", "cbar", ".", "patch", ".", "figure", ".", "canvas", ".", "draw", "(", ")", "def", "on_release", "(", "self", ",", "event", ")", ":", "'''Upon release, reset press data\n '''", "self", ".", "press", "=", "None", "self", ".", "mapimage", ".", "set_norm", "(", "self", ".", "cbar", ".", "norm", ")", "self", ".", "cbar", ".", "patch", ".", "figure", ".", "canvas", ".", "draw", "(", ")", "def", "disconnect", "(", "self", ")", ":", "self", ".", "cbar", ".", "patch", ".", "figure", ".", "canvas", ".", "mpl_disconnect", "(", "self", ".", "cidpress", ")", "self", ".", "cbar", ".", "patch", ".", "figure", ".", "canvas", ".", "mpl_disconnect", "(", "self", ".", "cidrelease", ")", "self", ".", "cbar", ".", "patch", ".", "figure", ".", "canvas", ".", "mpl_disconnect", "(", "self", ".", "cidmotion", ")" ]
Create a draggable colorbar for matplotlib plots to enable quick changes in color scale.
[ "Create", "a", "draggable", "colorbar", "for", "matplotlib", "plots", "to", "enable", "quick", "changes", "in", "color", "scale", "." ]
[ "'''Create a draggable colorbar for matplotlib plots to enable quick changes in color scale. \n\n Example:::\n\n fig,ax = plt.subplots()\n cntr = ax.contourf(R, Z, vals)\n cbar = plt.colorbar(cntr, format='%.3g', ax=ax)\n cbar = DraggableColorbar(cbar,cntr)\n cbar.connect()\n '''", "'''Matplotlib connection for button and key pressing, release, and motion.\n '''", "'''Button pressing; check if mouse is over colorbar.\n '''", "'''Key pressing event\n '''", "'''Move if the mouse is over the colorbar.\n '''", "'''Upon release, reset press data\n '''" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
16
767
81
3bec5c518a17c28d9512a3183358aea8345395a0
blackjyn/flex-sdk
modules/thirdparty/velocity/src/java/org/apache/flex/forks/velocity/test/IntrospectorTestCase2.java
[ "ECL-2.0", "Apache-2.0" ]
Java
IntrospectorTestCase2
/** * Test case for the Velocity Introspector which * tests the ability to find a 'best match' * * * @author <a href="mailto:[email protected]">Geir Magnusson Jr.</a> * @version $Id: IntrospectorTestCase2.java,v 1.1.8.1 2004/03/03 23:23:04 geirm Exp $ */
Test case for the Velocity Introspector which tests the ability to find a 'best match'
[ "Test", "case", "for", "the", "Velocity", "Introspector", "which", "tests", "the", "ability", "to", "find", "a", "'", "best", "match", "'" ]
public class IntrospectorTestCase2 extends BaseTestCase { IntrospectorTestCase2() { super("IntrospectorTestCase2"); } /** * Creates a new instance. */ public IntrospectorTestCase2(String name) { super(name); } /** * Get the containing <code>TestSuite</code>. * * @return The <code>TestSuite</code> to run. */ public static junit.framework.Test suite () { return new IntrospectorTestCase2(); } public void runTest() { try { Velocity.init(); Method method; String result; Tester t = new Tester(); Object[] params = { new Foo(), new Foo() }; method = RuntimeSingleton.getIntrospector() .getMethod( Tester.class, "find", params ); if ( method == null) fail("Returned method was null"); result = (String) method.invoke( t, params); if ( !result.equals( "Bar-Bar" ) ) { fail("Should have gotten 'Bar-Bar' : recieved '" + result + "'"); } /* * now test for failure due to ambiguity */ method = RuntimeSingleton.getIntrospector() .getMethod( Tester2.class, "find", params ); if ( method != null) fail("Introspector shouldn't have found a method as it's ambiguous."); } catch (Exception e) { fail( e.toString() ); } } public interface Woogie { } public static class Bar implements Woogie { int i; } public static class Foo extends Bar { int j; } public static class Tester { public static String find(Woogie w, Object o ) { return "Woogie-Object"; } public static String find(Object w, Bar o ) { return "Object-Bar"; } public static String find(Bar w, Bar o ) { return "Bar-Bar"; } public static String find( Object o ) { return "Object"; } public static String find( Woogie o ) { return "Woogie"; } } public static class Tester2 { public static String find(Woogie w, Object o ) { return "Woogie-Object"; } public static String find(Object w, Bar o ) { return "Object-Bar"; } public static String find(Bar w, Object o ) { return "Bar-Object"; } public static String find( Object o ) { return "Object"; } public static String find( Woogie o ) { return "Woogie"; } } }
[ "public", "class", "IntrospectorTestCase2", "extends", "BaseTestCase", "{", "IntrospectorTestCase2", "(", ")", "{", "super", "(", "\"", "IntrospectorTestCase2", "\"", ")", ";", "}", "/**\n * Creates a new instance.\n */", "public", "IntrospectorTestCase2", "(", "String", "name", ")", "{", "super", "(", "name", ")", ";", "}", "/**\n * Get the containing <code>TestSuite</code>. \n *\n * @return The <code>TestSuite</code> to run.\n */", "public", "static", "junit", ".", "framework", ".", "Test", "suite", "(", ")", "{", "return", "new", "IntrospectorTestCase2", "(", ")", ";", "}", "public", "void", "runTest", "(", ")", "{", "try", "{", "Velocity", ".", "init", "(", ")", ";", "Method", "method", ";", "String", "result", ";", "Tester", "t", "=", "new", "Tester", "(", ")", ";", "Object", "[", "]", "params", "=", "{", "new", "Foo", "(", ")", ",", "new", "Foo", "(", ")", "}", ";", "method", "=", "RuntimeSingleton", ".", "getIntrospector", "(", ")", ".", "getMethod", "(", "Tester", ".", "class", ",", "\"", "find", "\"", ",", "params", ")", ";", "if", "(", "method", "==", "null", ")", "fail", "(", "\"", "Returned method was null", "\"", ")", ";", "result", "=", "(", "String", ")", "method", ".", "invoke", "(", "t", ",", "params", ")", ";", "if", "(", "!", "result", ".", "equals", "(", "\"", "Bar-Bar", "\"", ")", ")", "{", "fail", "(", "\"", "Should have gotten 'Bar-Bar' : recieved '", "\"", "+", "result", "+", "\"", "'", "\"", ")", ";", "}", "/*\n * now test for failure due to ambiguity\n */", "method", "=", "RuntimeSingleton", ".", "getIntrospector", "(", ")", ".", "getMethod", "(", "Tester2", ".", "class", ",", "\"", "find", "\"", ",", "params", ")", ";", "if", "(", "method", "!=", "null", ")", "fail", "(", "\"", "Introspector shouldn't have found a method as it's ambiguous.", "\"", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "fail", "(", "e", ".", "toString", "(", ")", ")", ";", "}", "}", "public", "interface", "Woogie", "{", "}", "public", "static", "class", "Bar", "implements", "Woogie", "{", "int", "i", ";", "}", "public", "static", "class", "Foo", "extends", "Bar", "{", "int", "j", ";", "}", "public", "static", "class", "Tester", "{", "public", "static", "String", "find", "(", "Woogie", "w", ",", "Object", "o", ")", "{", "return", "\"", "Woogie-Object", "\"", ";", "}", "public", "static", "String", "find", "(", "Object", "w", ",", "Bar", "o", ")", "{", "return", "\"", "Object-Bar", "\"", ";", "}", "public", "static", "String", "find", "(", "Bar", "w", ",", "Bar", "o", ")", "{", "return", "\"", "Bar-Bar", "\"", ";", "}", "public", "static", "String", "find", "(", "Object", "o", ")", "{", "return", "\"", "Object", "\"", ";", "}", "public", "static", "String", "find", "(", "Woogie", "o", ")", "{", "return", "\"", "Woogie", "\"", ";", "}", "}", "public", "static", "class", "Tester2", "{", "public", "static", "String", "find", "(", "Woogie", "w", ",", "Object", "o", ")", "{", "return", "\"", "Woogie-Object", "\"", ";", "}", "public", "static", "String", "find", "(", "Object", "w", ",", "Bar", "o", ")", "{", "return", "\"", "Object-Bar", "\"", ";", "}", "public", "static", "String", "find", "(", "Bar", "w", ",", "Object", "o", ")", "{", "return", "\"", "Bar-Object", "\"", ";", "}", "public", "static", "String", "find", "(", "Object", "o", ")", "{", "return", "\"", "Object", "\"", ";", "}", "public", "static", "String", "find", "(", "Woogie", "o", ")", "{", "return", "\"", "Woogie", "\"", ";", "}", "}", "}" ]
Test case for the Velocity Introspector which tests the ability to find a 'best match'
[ "Test", "case", "for", "the", "Velocity", "Introspector", "which", "tests", "the", "ability", "to", "find", "a", "'", "best", "match", "'" ]
[]
[ { "param": "BaseTestCase", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "BaseTestCase", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
15
622
95
7fddae1027431d4d73cbdc52da3f79bd0c563b20
OneSageDude/HiBench
common/mahout-distribution-0.7-hadoop1/math/src/main/java/org/apache/mahout/common/RandomUtils.java
[ "Apache-2.0" ]
Java
RandomUtils
/** * <p> * The source of random stuff for the whole project. This lets us make all randomness in the project * predictable, if desired, for when we run unit tests, which should be repeatable. * </p> * * <p> * This class is increasingly incorrectly named as it also includes other mathematical utility methods. * </p> */
The source of random stuff for the whole project. This lets us make all randomness in the project predictable, if desired, for when we run unit tests, which should be repeatable. This class is increasingly incorrectly named as it also includes other mathematical utility methods.
[ "The", "source", "of", "random", "stuff", "for", "the", "whole", "project", ".", "This", "lets", "us", "make", "all", "randomness", "in", "the", "project", "predictable", "if", "desired", "for", "when", "we", "run", "unit", "tests", "which", "should", "be", "repeatable", ".", "This", "class", "is", "increasingly", "incorrectly", "named", "as", "it", "also", "includes", "other", "mathematical", "utility", "methods", "." ]
public final class RandomUtils { /** The largest prime less than 2<sup>31</sup>-1 that is the smaller of a twin prime pair. */ public static final int MAX_INT_SMALLER_TWIN_PRIME = 2147482949; private static final Map<RandomWrapper,Boolean> INSTANCES = Collections.synchronizedMap(new WeakHashMap<RandomWrapper,Boolean>()); private RandomUtils() { } public static void useTestSeed() { RandomWrapper.useTestSeed(); synchronized (INSTANCES) { for (RandomWrapper rng : INSTANCES.keySet()) { rng.reset(); } } } public static Random getRandom() { RandomWrapper random = new RandomWrapper(); INSTANCES.put(random, Boolean.TRUE); return random; } public static Random getRandom(long seed) { RandomWrapper random = new RandomWrapper(seed); INSTANCES.put(random, Boolean.TRUE); return random; } public static byte[] longSeedtoBytes(long seed) { byte[] seedBytes = new byte[16]; seedBytes[0] = (byte) (seed >>> 56); seedBytes[1] = (byte) (seed >>> 48); seedBytes[2] = (byte) (seed >>> 40); seedBytes[3] = (byte) (seed >>> 32); seedBytes[4] = (byte) (seed >>> 24); seedBytes[5] = (byte) (seed >>> 16); seedBytes[6] = (byte) (seed >>> 8); seedBytes[7] = (byte) seed; System.arraycopy(seedBytes, 0, seedBytes, 8, 8); return seedBytes; } public static long seedBytesToLong(byte[] seed) { long result = 0L; for (int i = 0; i < 8; i++) { result |= (seed[i] & 0xFFL) << (long) (8 * (7 - i)); } return result; } /** @return what {@link Double#hashCode()} would return for the same value */ public static int hashDouble(double value) { return Longs.hashCode(Double.doubleToLongBits(value)); } /** @return what {@link Float#hashCode()} would return for the same value */ public static int hashFloat(float value) { return Float.floatToIntBits(value); } /** * <p> * Finds next-largest "twin primes": numbers p and p+2 such that both are prime. Finds the smallest such p * such that the smaller twin, p, is greater than or equal to n. Returns p+2, the larger of the two twins. * </p> */ public static int nextTwinPrime(int n) { if (n > MAX_INT_SMALLER_TWIN_PRIME) { throw new IllegalArgumentException(); } if (n <= 3) { return 5; } int next = nextPrime(n); while (isNotPrime(next + 2)) { next = nextPrime(next + 4); } return next + 2; } /** * <p> * Finds smallest prime p such that p is greater than or equal to n. * </p> */ public static int nextPrime(int n) { if (n <= 2) { return 2; } // Make sure the number is odd. Is this too clever? n |= 0x1; // There is no problem with overflow since Integer.MAX_INT is prime, as it happens while (isNotPrime(n)) { n += 2; } return n; } /** @return {@code true} iff n is not a prime */ public static boolean isNotPrime(int n) { if (n < 2 || (n & 0x1) == 0) { // < 2 or even return n != 2; } int max = 1 + (int) Math.sqrt(n); for (int d = 3; d <= max; d += 2) { if (n % d == 0) { return true; } } return false; } }
[ "public", "final", "class", "RandomUtils", "{", "/** The largest prime less than 2<sup>31</sup>-1 that is the smaller of a twin prime pair. */", "public", "static", "final", "int", "MAX_INT_SMALLER_TWIN_PRIME", "=", "2147482949", ";", "private", "static", "final", "Map", "<", "RandomWrapper", ",", "Boolean", ">", "INSTANCES", "=", "Collections", ".", "synchronizedMap", "(", "new", "WeakHashMap", "<", "RandomWrapper", ",", "Boolean", ">", "(", ")", ")", ";", "private", "RandomUtils", "(", ")", "{", "}", "public", "static", "void", "useTestSeed", "(", ")", "{", "RandomWrapper", ".", "useTestSeed", "(", ")", ";", "synchronized", "(", "INSTANCES", ")", "{", "for", "(", "RandomWrapper", "rng", ":", "INSTANCES", ".", "keySet", "(", ")", ")", "{", "rng", ".", "reset", "(", ")", ";", "}", "}", "}", "public", "static", "Random", "getRandom", "(", ")", "{", "RandomWrapper", "random", "=", "new", "RandomWrapper", "(", ")", ";", "INSTANCES", ".", "put", "(", "random", ",", "Boolean", ".", "TRUE", ")", ";", "return", "random", ";", "}", "public", "static", "Random", "getRandom", "(", "long", "seed", ")", "{", "RandomWrapper", "random", "=", "new", "RandomWrapper", "(", "seed", ")", ";", "INSTANCES", ".", "put", "(", "random", ",", "Boolean", ".", "TRUE", ")", ";", "return", "random", ";", "}", "public", "static", "byte", "[", "]", "longSeedtoBytes", "(", "long", "seed", ")", "{", "byte", "[", "]", "seedBytes", "=", "new", "byte", "[", "16", "]", ";", "seedBytes", "[", "0", "]", "=", "(", "byte", ")", "(", "seed", ">>>", "56", ")", ";", "seedBytes", "[", "1", "]", "=", "(", "byte", ")", "(", "seed", ">>>", "48", ")", ";", "seedBytes", "[", "2", "]", "=", "(", "byte", ")", "(", "seed", ">>>", "40", ")", ";", "seedBytes", "[", "3", "]", "=", "(", "byte", ")", "(", "seed", ">>>", "32", ")", ";", "seedBytes", "[", "4", "]", "=", "(", "byte", ")", "(", "seed", ">>>", "24", ")", ";", "seedBytes", "[", "5", "]", "=", "(", "byte", ")", "(", "seed", ">>>", "16", ")", ";", "seedBytes", "[", "6", "]", "=", "(", "byte", ")", "(", "seed", ">>>", "8", ")", ";", "seedBytes", "[", "7", "]", "=", "(", "byte", ")", "seed", ";", "System", ".", "arraycopy", "(", "seedBytes", ",", "0", ",", "seedBytes", ",", "8", ",", "8", ")", ";", "return", "seedBytes", ";", "}", "public", "static", "long", "seedBytesToLong", "(", "byte", "[", "]", "seed", ")", "{", "long", "result", "=", "0L", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "8", ";", "i", "++", ")", "{", "result", "|=", "(", "seed", "[", "i", "]", "&", "0xFFL", ")", "<<", "(", "long", ")", "(", "8", "*", "(", "7", "-", "i", ")", ")", ";", "}", "return", "result", ";", "}", "/** @return what {@link Double#hashCode()} would return for the same value */", "public", "static", "int", "hashDouble", "(", "double", "value", ")", "{", "return", "Longs", ".", "hashCode", "(", "Double", ".", "doubleToLongBits", "(", "value", ")", ")", ";", "}", "/** @return what {@link Float#hashCode()} would return for the same value */", "public", "static", "int", "hashFloat", "(", "float", "value", ")", "{", "return", "Float", ".", "floatToIntBits", "(", "value", ")", ";", "}", "/**\n * <p>\n * Finds next-largest \"twin primes\": numbers p and p+2 such that both are prime. Finds the smallest such p\n * such that the smaller twin, p, is greater than or equal to n. Returns p+2, the larger of the two twins.\n * </p>\n */", "public", "static", "int", "nextTwinPrime", "(", "int", "n", ")", "{", "if", "(", "n", ">", "MAX_INT_SMALLER_TWIN_PRIME", ")", "{", "throw", "new", "IllegalArgumentException", "(", ")", ";", "}", "if", "(", "n", "<=", "3", ")", "{", "return", "5", ";", "}", "int", "next", "=", "nextPrime", "(", "n", ")", ";", "while", "(", "isNotPrime", "(", "next", "+", "2", ")", ")", "{", "next", "=", "nextPrime", "(", "next", "+", "4", ")", ";", "}", "return", "next", "+", "2", ";", "}", "/**\n * <p>\n * Finds smallest prime p such that p is greater than or equal to n.\n * </p>\n */", "public", "static", "int", "nextPrime", "(", "int", "n", ")", "{", "if", "(", "n", "<=", "2", ")", "{", "return", "2", ";", "}", "n", "|=", "0x1", ";", "while", "(", "isNotPrime", "(", "n", ")", ")", "{", "n", "+=", "2", ";", "}", "return", "n", ";", "}", "/** @return {@code true} iff n is not a prime */", "public", "static", "boolean", "isNotPrime", "(", "int", "n", ")", "{", "if", "(", "n", "<", "2", "||", "(", "n", "&", "0x1", ")", "==", "0", ")", "{", "return", "n", "!=", "2", ";", "}", "int", "max", "=", "1", "+", "(", "int", ")", "Math", ".", "sqrt", "(", "n", ")", ";", "for", "(", "int", "d", "=", "3", ";", "d", "<=", "max", ";", "d", "+=", "2", ")", "{", "if", "(", "n", "%", "d", "==", "0", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}", "}" ]
<p> The source of random stuff for the whole project.
[ "<p", ">", "The", "source", "of", "random", "stuff", "for", "the", "whole", "project", "." ]
[ "// Make sure the number is odd. Is this too clever?", "// There is no problem with overflow since Integer.MAX_INT is prime, as it happens", "// < 2 or even" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
15
954
76
5f046fd4de3211af53e132b17f73f91f154afbb7
henningn/myfaces-tobago
tobago-theme/tobago-theme-standard/src/main/js/tobago.js
[ "Apache-2.0" ]
JavaScript
TobagoReload
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. */
Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You 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 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.
[ "Licensed", "to", "the", "Apache", "Software", "Foundation", "(", "ASF", ")", "under", "one", "or", "more", "contributor", "license", "agreements", ".", "See", "the", "NOTICE", "file", "distributed", "with", "this", "work", "for", "additional", "information", "regarding", "copyright", "ownership", ".", "The", "ASF", "licenses", "this", "file", "to", "You", "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", "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", "." ]
class TobagoReload extends HTMLElement { constructor() { super(); } connectedCallback() { this.schedule(this.id, this.component.id, this.frequency); } schedule(reloadId, componentId, reloadMillis) { if (reloadMillis > 0) { // may remove old schedule const oldTimeout = TobagoReload.timeoutMap.get(componentId); if (oldTimeout) { console.debug("clear reload timeout '%s' for #'%s'", oldTimeout, componentId); window.clearTimeout(oldTimeout); TobagoReload.timeoutMap.delete(componentId); } // add new schedule const timeout = window.setTimeout(function () { console.debug("reloading #'%s'", componentId); jsf.ajax.request(reloadId, null, { "javax.faces.behavior.event": "reload", execute: `${reloadId} ${componentId}`, render: `${reloadId} ${componentId}` }); }, reloadMillis); console.debug("adding reload timeout '%s' for #'%s'", timeout, componentId); TobagoReload.timeoutMap.set(componentId, timeout); } } get component() { return this.parentElement; } /** frequency is the number of millis for the timeout */ get frequency() { const frequency = this.getAttribute("frequency"); if (frequency) { return Number.parseFloat(frequency); } else { return 0; } } }
[ "class", "TobagoReload", "extends", "HTMLElement", "{", "constructor", "(", ")", "{", "super", "(", ")", ";", "}", "connectedCallback", "(", ")", "{", "this", ".", "schedule", "(", "this", ".", "id", ",", "this", ".", "component", ".", "id", ",", "this", ".", "frequency", ")", ";", "}", "schedule", "(", "reloadId", ",", "componentId", ",", "reloadMillis", ")", "{", "if", "(", "reloadMillis", ">", "0", ")", "{", "const", "oldTimeout", "=", "TobagoReload", ".", "timeoutMap", ".", "get", "(", "componentId", ")", ";", "if", "(", "oldTimeout", ")", "{", "console", ".", "debug", "(", "\"clear reload timeout '%s' for #'%s'\"", ",", "oldTimeout", ",", "componentId", ")", ";", "window", ".", "clearTimeout", "(", "oldTimeout", ")", ";", "TobagoReload", ".", "timeoutMap", ".", "delete", "(", "componentId", ")", ";", "}", "const", "timeout", "=", "window", ".", "setTimeout", "(", "function", "(", ")", "{", "console", ".", "debug", "(", "\"reloading #'%s'\"", ",", "componentId", ")", ";", "jsf", ".", "ajax", ".", "request", "(", "reloadId", ",", "null", ",", "{", "\"javax.faces.behavior.event\"", ":", "\"reload\"", ",", "execute", ":", "`", "${", "reloadId", "}", "${", "componentId", "}", "`", ",", "render", ":", "`", "${", "reloadId", "}", "${", "componentId", "}", "`", "}", ")", ";", "}", ",", "reloadMillis", ")", ";", "console", ".", "debug", "(", "\"adding reload timeout '%s' for #'%s'\"", ",", "timeout", ",", "componentId", ")", ";", "TobagoReload", ".", "timeoutMap", ".", "set", "(", "componentId", ",", "timeout", ")", ";", "}", "}", "get", "component", "(", ")", "{", "return", "this", ".", "parentElement", ";", "}", "get", "frequency", "(", ")", "{", "const", "frequency", "=", "this", ".", "getAttribute", "(", "\"frequency\"", ")", ";", "if", "(", "frequency", ")", "{", "return", "Number", ".", "parseFloat", "(", "frequency", ")", ";", "}", "else", "{", "return", "0", ";", "}", "}", "}" ]
Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements.
[ "Licensed", "to", "the", "Apache", "Software", "Foundation", "(", "ASF", ")", "under", "one", "or", "more", "contributor", "license", "agreements", "." ]
[ "// may remove old schedule", "// add new schedule", "/** frequency is the number of millis for the timeout */" ]
[ { "param": "HTMLElement", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "HTMLElement", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
20
310
183
7b766e3ec7a51dc98719b627f60aebd8d815279a
dongshengfengniaowu/ShoppingWebCrawler
ShoppingWebCrawler.Cef.Core/Classes.Proxies/CefV8StackFrame.cs
[ "Apache-2.0" ]
C#
CefV8StackFrame
/// <summary> /// Class representing a V8 stack frame handle. V8 handles can only be accessed /// from the thread on which they are created. Valid threads for creating a V8 /// handle include the render process main thread (TID_RENDERER) and WebWorker /// threads. A task runner for posting tasks on the associated thread can be /// retrieved via the CefV8Context::GetTaskRunner() method. /// </summary>
Class representing a V8 stack frame handle. V8 handles can only be accessed from the thread on which they are created. Valid threads for creating a V8 handle include the render process main thread (TID_RENDERER) and WebWorker threads. A task runner for posting tasks on the associated thread can be retrieved via the CefV8Context::GetTaskRunner() method.
[ "Class", "representing", "a", "V8", "stack", "frame", "handle", ".", "V8", "handles", "can", "only", "be", "accessed", "from", "the", "thread", "on", "which", "they", "are", "created", ".", "Valid", "threads", "for", "creating", "a", "V8", "handle", "include", "the", "render", "process", "main", "thread", "(", "TID_RENDERER", ")", "and", "WebWorker", "threads", ".", "A", "task", "runner", "for", "posting", "tasks", "on", "the", "associated", "thread", "can", "be", "retrieved", "via", "the", "CefV8Context", "::", "GetTaskRunner", "()", "method", "." ]
public sealed unsafe partial class CefV8StackFrame { public bool IsValid { get { return cef_v8stack_frame_t.is_valid(_self) != 0; } } public string ScriptName { get { var n_result = cef_v8stack_frame_t.get_script_name(_self); return cef_string_userfree.ToString(n_result); } } public string ScriptNameOrSourceUrl { get { var n_result = cef_v8stack_frame_t.get_script_name_or_source_url(_self); return cef_string_userfree.ToString(n_result); } } public string FunctionName { get { var n_result = cef_v8stack_frame_t.get_function_name(_self); return cef_string_userfree.ToString(n_result); } } public int LineNumber { get { return cef_v8stack_frame_t.get_line_number(_self); } } public int Column { get { return cef_v8stack_frame_t.get_column(_self); } } public bool IsEval { get { return cef_v8stack_frame_t.is_eval(_self) != 0; } } public bool IsConstructor { get { return cef_v8stack_frame_t.is_constructor(_self) != 0; } } }
[ "public", "sealed", "unsafe", "partial", "class", "CefV8StackFrame", "{", "public", "bool", "IsValid", "{", "get", "{", "return", "cef_v8stack_frame_t", ".", "is_valid", "(", "_self", ")", "!=", "0", ";", "}", "}", "public", "string", "ScriptName", "{", "get", "{", "var", "n_result", "=", "cef_v8stack_frame_t", ".", "get_script_name", "(", "_self", ")", ";", "return", "cef_string_userfree", ".", "ToString", "(", "n_result", ")", ";", "}", "}", "public", "string", "ScriptNameOrSourceUrl", "{", "get", "{", "var", "n_result", "=", "cef_v8stack_frame_t", ".", "get_script_name_or_source_url", "(", "_self", ")", ";", "return", "cef_string_userfree", ".", "ToString", "(", "n_result", ")", ";", "}", "}", "public", "string", "FunctionName", "{", "get", "{", "var", "n_result", "=", "cef_v8stack_frame_t", ".", "get_function_name", "(", "_self", ")", ";", "return", "cef_string_userfree", ".", "ToString", "(", "n_result", ")", ";", "}", "}", "public", "int", "LineNumber", "{", "get", "{", "return", "cef_v8stack_frame_t", ".", "get_line_number", "(", "_self", ")", ";", "}", "}", "public", "int", "Column", "{", "get", "{", "return", "cef_v8stack_frame_t", ".", "get_column", "(", "_self", ")", ";", "}", "}", "public", "bool", "IsEval", "{", "get", "{", "return", "cef_v8stack_frame_t", ".", "is_eval", "(", "_self", ")", "!=", "0", ";", "}", "}", "public", "bool", "IsConstructor", "{", "get", "{", "return", "cef_v8stack_frame_t", ".", "is_constructor", "(", "_self", ")", "!=", "0", ";", "}", "}", "}" ]
Class representing a V8 stack frame handle.
[ "Class", "representing", "a", "V8", "stack", "frame", "handle", "." ]
[ "/// <summary>", "/// Returns true if the underlying handle is valid and it can be accessed on", "/// the current thread. Do not call any other methods if this method returns", "/// false.", "/// </summary>", "/// <summary>", "/// Returns the name of the resource script that contains the function.", "/// </summary>", "/// <summary>", "/// Returns the name of the resource script that contains the function or the", "/// sourceURL value if the script name is undefined and its source ends with", "/// a \"//@ sourceURL=...\" string.", "/// </summary>", "/// <summary>", "/// Returns the name of the function.", "/// </summary>", "/// <summary>", "/// Returns the 1-based line number for the function call or 0 if unknown.", "/// </summary>", "/// <summary>", "/// Returns the 1-based column offset on the line for the function call or 0 if", "/// unknown.", "/// </summary>", "/// <summary>", "/// Returns true if the function was compiled using eval().", "/// </summary>", "/// <summary>", "/// Returns true if the function was called as a constructor via \"new\".", "/// </summary>" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
13
306
93
eedb28aeb0c1bf903bb6d4310b184f065619a65c
dpr1005/Semisupervised-learning-and-instance-selection-methods
semisupervised/TriTraining.py
[ "MIT" ]
Python
TriTraining
Zhou, Z. H., & Li, M. (2005). Tri-training: Exploiting unlabeled data using three classifiers. IEEE Transactions on knowledge and Data Engineering, 17(11), 1529-1541. Parameters ---------- random_state : int, default=None The random seed used to initialize the classifiers c1 : base_estimator, default=KNeighborsClassifier The first classifier to be used c1_params : dict, default=None Parameters for the first classifier c2 : base_estimator, default=DecisionTreeClassifier The second classifier to be used c2_params : dict, default=None Parameters for the second classifier c3 : base_estimator, default=RandomForestClassifier The third classifier to be used c3_params : dict, default=None Parameters for the third classifier
Zhou, Z. Parameters random_state : int, default=None The random seed used to initialize the classifiers c1 : base_estimator, default=KNeighborsClassifier The first classifier to be used c1_params : dict, default=None Parameters for the first classifier c2 : base_estimator, default=DecisionTreeClassifier The second classifier to be used c2_params : dict, default=None Parameters for the second classifier c3 : base_estimator, default=RandomForestClassifier The third classifier to be used c3_params : dict, default=None Parameters for the third classifier
[ "Zhou", "Z", ".", "Parameters", "random_state", ":", "int", "default", "=", "None", "The", "random", "seed", "used", "to", "initialize", "the", "classifiers", "c1", ":", "base_estimator", "default", "=", "KNeighborsClassifier", "The", "first", "classifier", "to", "be", "used", "c1_params", ":", "dict", "default", "=", "None", "Parameters", "for", "the", "first", "classifier", "c2", ":", "base_estimator", "default", "=", "DecisionTreeClassifier", "The", "second", "classifier", "to", "be", "used", "c2_params", ":", "dict", "default", "=", "None", "Parameters", "for", "the", "second", "classifier", "c3", ":", "base_estimator", "default", "=", "RandomForestClassifier", "The", "third", "classifier", "to", "be", "used", "c3_params", ":", "dict", "default", "=", "None", "Parameters", "for", "the", "third", "classifier" ]
class TriTraining: """ Zhou, Z. H., & Li, M. (2005). Tri-training: Exploiting unlabeled data using three classifiers. IEEE Transactions on knowledge and Data Engineering, 17(11), 1529-1541. Parameters ---------- random_state : int, default=None The random seed used to initialize the classifiers c1 : base_estimator, default=KNeighborsClassifier The first classifier to be used c1_params : dict, default=None Parameters for the first classifier c2 : base_estimator, default=DecisionTreeClassifier The second classifier to be used c2_params : dict, default=None Parameters for the second classifier c3 : base_estimator, default=RandomForestClassifier The third classifier to be used c3_params : dict, default=None Parameters for the third classifier """ def __init__( self, random_state=None, c1=None, c1_params=None, c2=None, c2_params=None, c3=None, c3_params=None, ): """Tri-Training.""" classifiers = [c1, c2, c3] classifiers_params = [c1_params, c2_params, c3_params] default_classifiers = [ KNeighborsClassifier, DecisionTreeClassifier, RandomForestClassifier, ] configs = [] for index, (c, cp) in enumerate(zip(classifiers, classifiers_params)): if c is not None: if cp is not None: configs.append(c(**cp)) else: configs.append(c()) else: configs.append(default_classifiers[index]()) try: self.hj, self.hk, self.hi = configs except ValueError: raise AttributeError( "Classifiers and/or params were not correctly passed.") self.random_state = ( random_state if random_state is not None else np.random.randint(low=0, high=10e5, size=1)[0] ) def _subsample(self, l_t, s): """ > The function takes in a Bunch object, which is a dictionary-like object that contains the data and target arrays, and a sample size, and returns a Bunch object with the data and target arrays sub-sampled to the specified size :param l_t: the labeled and unlabeled data :param s: the number of samples to be drawn from the dataset :return: A Bunch object with the data and target attributes. """ np.random.seed(self.random_state) rng = np.random.default_rng() data = np.array(l_t["data"]) target = np.array(l_t["target"]) samples_index = rng.choice(len(data), size=s, replace=False) samples = data[samples_index] targets = target[samples_index] return Bunch(data=samples, target=targets) def fit(self, samples, y): """ The function takes in the training data and the labels, and then splits the data into three parts: labeled, unlabeled, and test. It then creates three classifiers, h_i, h_j, and h_k, and trains them on the labeled data. It then checks to see if the classifiers are accurate enough, and if they are, it returns them. If they are not, it trains them again on the labeled data, and then checks again :param samples: The samples to train the classifier on :param y: the labels """ try: labeled, u, y = split(samples, y) except IndexError: raise ValueError("Dimensions do not match.") le = LabelEncoder() le.fit(y) y = le.transform(y) train, _, test, _ = train_test_split( labeled, y, train_size=floor(len(labeled) / 3), stratify=y, random_state=self.random_state, ) h_j = self.hj.fit(train, test) ep_j = 0.5 lp_j = 0 train, _, test, _ = train_test_split( labeled, y, train_size=floor(len(labeled) / 3), stratify=y, random_state=self.random_state, ) h_k = self.hk.fit(train, test) ep_k = 0.5 lp_k = 0 train, _, test, _ = train_test_split( labeled, y, train_size=floor(len(labeled) / 3), stratify=y, random_state=self.random_state, ) h_i = self.hi.fit(train, test) ep_i = 0.5 lp_i = 0 while True: hash_i = h_i.__hash__() hash_j = h_j.__hash__() hash_k = h_k.__hash__() e_j, l_j, update_j = self._train_classifier( ep_j, h_i, h_j, h_k, labeled, lp_j, u ) e_k, l_k, update_k = self._train_classifier( ep_k, h_i, h_j, h_k, labeled, lp_k, u ) e_i, l_i, update_i = self._train_classifier( ep_i, h_i, h_j, h_k, labeled, lp_i, u ) ep_j, h_j, lp_j = self._check_for_update( e_j, ep_j, h_j, l_j, labeled, lp_j, update_j, y ) ep_k, h_k, lp_k = self._check_for_update( e_k, ep_k, h_k, l_k, labeled, lp_k, update_k, y ) ep_i, h_i, lp_i = self._check_for_update( e_i, ep_i, h_i, l_i, labeled, lp_i, update_i, y ) if ( h_i.__hash__() == hash_i and h_j.__hash__() == hash_j and h_k.__hash__() == hash_k ): break def _check_for_update(self, e_j, ep_j, h_j, l_j, labeled, lp_j, update_j, y): """ If the update_j flag is True, then we concatenate the labeled data with the new data, and fit the model to the new data :param e_j: the error of the current hypothesis :param ep_j: the error of the previous iteration :param h_j: the classifier for the jth class :param l_j: the labeled data :param labeled: the labeled data :param lp_j: the number of labeled points in the current iteration :param update_j: boolean, whether to update the model or not :param y: the true labels of the data :return: the error, the hypothesis, and the length of the labeled data. """ if update_j: train = np.concatenate((labeled, l_j["data"]), axis=0) test = np.concatenate((y, np.ravel(l_j["target"])), axis=0) h_j = self.hj.fit(train, test) ep_j = e_j lp_j = len(l_j) return ep_j, h_j, lp_j def _train_classifier(self, ep_k, h_i, h_j, h_k, labeled, lp_k, u): """ If the error of the classifier is less than the error threshold, and the number of samples in the labeled set is less than the number of samples in the unlabeled set, then add the samples to the labeled set :param ep_k: the error threshold for the classifier :param h_i: the classifier that is being trained :param h_j: the classifier that is being compared to h_k :param h_k: the classifier we're training :param labeled: the labeled data :param lp_k: the number of samples that have been labeled by h_k :param u: the unlabeled data :return: The error, the new labeled data, and a boolean indicating whether the classifier should be updated. """ update_k = False l_k = Bunch(data=np.array([]), target=np.array([])) e_k = self.measure_error(h_j, h_k, labeled) if e_k < ep_k: for sample in u: sample_s = sample.reshape(1, -1) if h_j.predict(sample_s) == h_k.predict(sample_s): pred = h_i.predict(sample_s) prev_dat = list(l_k["data"]) prev_tar = list(l_k["target"]) prev_dat.append(sample) l_k["data"] = np.array(prev_dat) prev_tar.append(pred) l_k["target"] = np.array(prev_tar) if lp_k == 0: lp_k = floor(e_k / (ep_k - e_k) + 1) if lp_k < len(l_k["data"]): if e_k * len(l_k["data"]) < ep_k * lp_k: update_k = True elif lp_k > e_k / (ep_k - e_k): l_k = self._subsample(l_k, ceil(((ep_k * lp_k) / e_k) - 1)) update_k = True return e_k, l_k, update_k def predict(self, samples): """ For each sample, we predict the label using each of the three classifiers, and then we take the majority vote of the three predictions :param samples: the data to be classified :return: The labels of the samples. """ labels = [] pred1 = self.hi.predict(samples) pred2 = self.hj.predict(samples) pred3 = self.hk.predict(samples) for p in zip(pred1, pred2, pred3): count = np.bincount(p) labels.append(np.where(count == np.amax(count))[0][0]) return np.array(labels) @staticmethod def measure_error(classifier_j, classifier_k, labeled_data): """ It returns the fraction of the time that classifiers j and k disagree on the labels of the labeled data :param classifier_j: the classifier you want to compare to :param classifier_k: the classifier that we want to measure the error of :param labeled_data: the labeled data that we're using to train the classifiers :return: The error rate of the two classifiers. """ pred_j = classifier_j.predict(labeled_data) pred_k = classifier_k.predict(labeled_data) same = len([0 for x, y in zip(pred_j, pred_k) if x == y]) return (len(pred_j) - same) / same
[ "class", "TriTraining", ":", "def", "__init__", "(", "self", ",", "random_state", "=", "None", ",", "c1", "=", "None", ",", "c1_params", "=", "None", ",", "c2", "=", "None", ",", "c2_params", "=", "None", ",", "c3", "=", "None", ",", "c3_params", "=", "None", ",", ")", ":", "\"\"\"Tri-Training.\"\"\"", "classifiers", "=", "[", "c1", ",", "c2", ",", "c3", "]", "classifiers_params", "=", "[", "c1_params", ",", "c2_params", ",", "c3_params", "]", "default_classifiers", "=", "[", "KNeighborsClassifier", ",", "DecisionTreeClassifier", ",", "RandomForestClassifier", ",", "]", "configs", "=", "[", "]", "for", "index", ",", "(", "c", ",", "cp", ")", "in", "enumerate", "(", "zip", "(", "classifiers", ",", "classifiers_params", ")", ")", ":", "if", "c", "is", "not", "None", ":", "if", "cp", "is", "not", "None", ":", "configs", ".", "append", "(", "c", "(", "**", "cp", ")", ")", "else", ":", "configs", ".", "append", "(", "c", "(", ")", ")", "else", ":", "configs", ".", "append", "(", "default_classifiers", "[", "index", "]", "(", ")", ")", "try", ":", "self", ".", "hj", ",", "self", ".", "hk", ",", "self", ".", "hi", "=", "configs", "except", "ValueError", ":", "raise", "AttributeError", "(", "\"Classifiers and/or params were not correctly passed.\"", ")", "self", ".", "random_state", "=", "(", "random_state", "if", "random_state", "is", "not", "None", "else", "np", ".", "random", ".", "randint", "(", "low", "=", "0", ",", "high", "=", "10e5", ",", "size", "=", "1", ")", "[", "0", "]", ")", "def", "_subsample", "(", "self", ",", "l_t", ",", "s", ")", ":", "\"\"\"\n > The function takes in a Bunch object, which is a dictionary-like\n object that contains the data and target arrays, and a sample size,\n and returns a Bunch object with the data and target arrays sub-sampled\n to the specified size\n\n :param l_t: the labeled and unlabeled data\n :param s: the number of samples to be drawn from the dataset\n :return: A Bunch object with the data and target attributes.\n \"\"\"", "np", ".", "random", ".", "seed", "(", "self", ".", "random_state", ")", "rng", "=", "np", ".", "random", ".", "default_rng", "(", ")", "data", "=", "np", ".", "array", "(", "l_t", "[", "\"data\"", "]", ")", "target", "=", "np", ".", "array", "(", "l_t", "[", "\"target\"", "]", ")", "samples_index", "=", "rng", ".", "choice", "(", "len", "(", "data", ")", ",", "size", "=", "s", ",", "replace", "=", "False", ")", "samples", "=", "data", "[", "samples_index", "]", "targets", "=", "target", "[", "samples_index", "]", "return", "Bunch", "(", "data", "=", "samples", ",", "target", "=", "targets", ")", "def", "fit", "(", "self", ",", "samples", ",", "y", ")", ":", "\"\"\"\n The function takes in the training data and the labels, and then splits\n the data into three parts: labeled, unlabeled, and test. It then\n creates three classifiers, h_i, h_j, and h_k, and trains them on the\n labeled data. It then checks to see if the classifiers are accurate\n enough, and if they are, it returns them. If they are not, it trains\n them again on the labeled data, and then checks again\n\n :param samples: The samples to train the classifier on\n :param y: the labels\n \"\"\"", "try", ":", "labeled", ",", "u", ",", "y", "=", "split", "(", "samples", ",", "y", ")", "except", "IndexError", ":", "raise", "ValueError", "(", "\"Dimensions do not match.\"", ")", "le", "=", "LabelEncoder", "(", ")", "le", ".", "fit", "(", "y", ")", "y", "=", "le", ".", "transform", "(", "y", ")", "train", ",", "_", ",", "test", ",", "_", "=", "train_test_split", "(", "labeled", ",", "y", ",", "train_size", "=", "floor", "(", "len", "(", "labeled", ")", "/", "3", ")", ",", "stratify", "=", "y", ",", "random_state", "=", "self", ".", "random_state", ",", ")", "h_j", "=", "self", ".", "hj", ".", "fit", "(", "train", ",", "test", ")", "ep_j", "=", "0.5", "lp_j", "=", "0", "train", ",", "_", ",", "test", ",", "_", "=", "train_test_split", "(", "labeled", ",", "y", ",", "train_size", "=", "floor", "(", "len", "(", "labeled", ")", "/", "3", ")", ",", "stratify", "=", "y", ",", "random_state", "=", "self", ".", "random_state", ",", ")", "h_k", "=", "self", ".", "hk", ".", "fit", "(", "train", ",", "test", ")", "ep_k", "=", "0.5", "lp_k", "=", "0", "train", ",", "_", ",", "test", ",", "_", "=", "train_test_split", "(", "labeled", ",", "y", ",", "train_size", "=", "floor", "(", "len", "(", "labeled", ")", "/", "3", ")", ",", "stratify", "=", "y", ",", "random_state", "=", "self", ".", "random_state", ",", ")", "h_i", "=", "self", ".", "hi", ".", "fit", "(", "train", ",", "test", ")", "ep_i", "=", "0.5", "lp_i", "=", "0", "while", "True", ":", "hash_i", "=", "h_i", ".", "__hash__", "(", ")", "hash_j", "=", "h_j", ".", "__hash__", "(", ")", "hash_k", "=", "h_k", ".", "__hash__", "(", ")", "e_j", ",", "l_j", ",", "update_j", "=", "self", ".", "_train_classifier", "(", "ep_j", ",", "h_i", ",", "h_j", ",", "h_k", ",", "labeled", ",", "lp_j", ",", "u", ")", "e_k", ",", "l_k", ",", "update_k", "=", "self", ".", "_train_classifier", "(", "ep_k", ",", "h_i", ",", "h_j", ",", "h_k", ",", "labeled", ",", "lp_k", ",", "u", ")", "e_i", ",", "l_i", ",", "update_i", "=", "self", ".", "_train_classifier", "(", "ep_i", ",", "h_i", ",", "h_j", ",", "h_k", ",", "labeled", ",", "lp_i", ",", "u", ")", "ep_j", ",", "h_j", ",", "lp_j", "=", "self", ".", "_check_for_update", "(", "e_j", ",", "ep_j", ",", "h_j", ",", "l_j", ",", "labeled", ",", "lp_j", ",", "update_j", ",", "y", ")", "ep_k", ",", "h_k", ",", "lp_k", "=", "self", ".", "_check_for_update", "(", "e_k", ",", "ep_k", ",", "h_k", ",", "l_k", ",", "labeled", ",", "lp_k", ",", "update_k", ",", "y", ")", "ep_i", ",", "h_i", ",", "lp_i", "=", "self", ".", "_check_for_update", "(", "e_i", ",", "ep_i", ",", "h_i", ",", "l_i", ",", "labeled", ",", "lp_i", ",", "update_i", ",", "y", ")", "if", "(", "h_i", ".", "__hash__", "(", ")", "==", "hash_i", "and", "h_j", ".", "__hash__", "(", ")", "==", "hash_j", "and", "h_k", ".", "__hash__", "(", ")", "==", "hash_k", ")", ":", "break", "def", "_check_for_update", "(", "self", ",", "e_j", ",", "ep_j", ",", "h_j", ",", "l_j", ",", "labeled", ",", "lp_j", ",", "update_j", ",", "y", ")", ":", "\"\"\"\n If the update_j flag is True, then we concatenate the labeled data with\n the new data, and fit the model to the new data\n\n :param e_j: the error of the current hypothesis\n :param ep_j: the error of the previous iteration\n :param h_j: the classifier for the jth class\n :param l_j: the labeled data\n :param labeled: the labeled data\n :param lp_j: the number of labeled points in the current iteration\n :param update_j: boolean, whether to update the model or not\n :param y: the true labels of the data\n :return: the error, the hypothesis, and the length of the labeled data.\n \"\"\"", "if", "update_j", ":", "train", "=", "np", ".", "concatenate", "(", "(", "labeled", ",", "l_j", "[", "\"data\"", "]", ")", ",", "axis", "=", "0", ")", "test", "=", "np", ".", "concatenate", "(", "(", "y", ",", "np", ".", "ravel", "(", "l_j", "[", "\"target\"", "]", ")", ")", ",", "axis", "=", "0", ")", "h_j", "=", "self", ".", "hj", ".", "fit", "(", "train", ",", "test", ")", "ep_j", "=", "e_j", "lp_j", "=", "len", "(", "l_j", ")", "return", "ep_j", ",", "h_j", ",", "lp_j", "def", "_train_classifier", "(", "self", ",", "ep_k", ",", "h_i", ",", "h_j", ",", "h_k", ",", "labeled", ",", "lp_k", ",", "u", ")", ":", "\"\"\"\n If the error of the classifier is less than the error threshold, and the\n number of samples in the labeled set is less than the number of samples\n in the unlabeled set, then add the samples to the labeled set\n\n :param ep_k: the error threshold for the classifier\n :param h_i: the classifier that is being trained\n :param h_j: the classifier that is being compared to h_k\n :param h_k: the classifier we're training\n :param labeled: the labeled data\n :param lp_k: the number of samples that have been labeled by h_k\n :param u: the unlabeled data\n :return: The error, the new labeled data, and a boolean indicating\n whether the classifier should be updated.\n \"\"\"", "update_k", "=", "False", "l_k", "=", "Bunch", "(", "data", "=", "np", ".", "array", "(", "[", "]", ")", ",", "target", "=", "np", ".", "array", "(", "[", "]", ")", ")", "e_k", "=", "self", ".", "measure_error", "(", "h_j", ",", "h_k", ",", "labeled", ")", "if", "e_k", "<", "ep_k", ":", "for", "sample", "in", "u", ":", "sample_s", "=", "sample", ".", "reshape", "(", "1", ",", "-", "1", ")", "if", "h_j", ".", "predict", "(", "sample_s", ")", "==", "h_k", ".", "predict", "(", "sample_s", ")", ":", "pred", "=", "h_i", ".", "predict", "(", "sample_s", ")", "prev_dat", "=", "list", "(", "l_k", "[", "\"data\"", "]", ")", "prev_tar", "=", "list", "(", "l_k", "[", "\"target\"", "]", ")", "prev_dat", ".", "append", "(", "sample", ")", "l_k", "[", "\"data\"", "]", "=", "np", ".", "array", "(", "prev_dat", ")", "prev_tar", ".", "append", "(", "pred", ")", "l_k", "[", "\"target\"", "]", "=", "np", ".", "array", "(", "prev_tar", ")", "if", "lp_k", "==", "0", ":", "lp_k", "=", "floor", "(", "e_k", "/", "(", "ep_k", "-", "e_k", ")", "+", "1", ")", "if", "lp_k", "<", "len", "(", "l_k", "[", "\"data\"", "]", ")", ":", "if", "e_k", "*", "len", "(", "l_k", "[", "\"data\"", "]", ")", "<", "ep_k", "*", "lp_k", ":", "update_k", "=", "True", "elif", "lp_k", ">", "e_k", "/", "(", "ep_k", "-", "e_k", ")", ":", "l_k", "=", "self", ".", "_subsample", "(", "l_k", ",", "ceil", "(", "(", "(", "ep_k", "*", "lp_k", ")", "/", "e_k", ")", "-", "1", ")", ")", "update_k", "=", "True", "return", "e_k", ",", "l_k", ",", "update_k", "def", "predict", "(", "self", ",", "samples", ")", ":", "\"\"\"\n For each sample, we predict the label using each of the three\n classifiers, and then we take the majority vote of the three predictions\n\n :param samples: the data to be classified\n :return: The labels of the samples.\n \"\"\"", "labels", "=", "[", "]", "pred1", "=", "self", ".", "hi", ".", "predict", "(", "samples", ")", "pred2", "=", "self", ".", "hj", ".", "predict", "(", "samples", ")", "pred3", "=", "self", ".", "hk", ".", "predict", "(", "samples", ")", "for", "p", "in", "zip", "(", "pred1", ",", "pred2", ",", "pred3", ")", ":", "count", "=", "np", ".", "bincount", "(", "p", ")", "labels", ".", "append", "(", "np", ".", "where", "(", "count", "==", "np", ".", "amax", "(", "count", ")", ")", "[", "0", "]", "[", "0", "]", ")", "return", "np", ".", "array", "(", "labels", ")", "@", "staticmethod", "def", "measure_error", "(", "classifier_j", ",", "classifier_k", ",", "labeled_data", ")", ":", "\"\"\"\n It returns the fraction of the time that classifiers j and k disagree on\n the labels of the labeled data\n\n :param classifier_j: the classifier you want to compare to\n :param classifier_k: the classifier that we want to measure the error of\n :param labeled_data: the labeled data that we're using to train the\n classifiers\n :return: The error rate of the two classifiers.\n \"\"\"", "pred_j", "=", "classifier_j", ".", "predict", "(", "labeled_data", ")", "pred_k", "=", "classifier_k", ".", "predict", "(", "labeled_data", ")", "same", "=", "len", "(", "[", "0", "for", "x", ",", "y", "in", "zip", "(", "pred_j", ",", "pred_k", ")", "if", "x", "==", "y", "]", ")", "return", "(", "len", "(", "pred_j", ")", "-", "same", ")", "/", "same" ]
Zhou, Z. H., & Li, M. (2005).
[ "Zhou", "Z", ".", "H", ".", "&", "Li", "M", ".", "(", "2005", ")", "." ]
[ "\"\"\"\n Zhou, Z. H., & Li, M. (2005). Tri-training: Exploiting unlabeled data\n using three classifiers. IEEE Transactions on knowledge and Data\n Engineering, 17(11), 1529-1541.\n\n Parameters\n ----------\n random_state : int, default=None\n The random seed used to initialize the classifiers\n\n c1 : base_estimator, default=KNeighborsClassifier\n The first classifier to be used\n\n c1_params : dict, default=None\n Parameters for the first classifier\n\n c2 : base_estimator, default=DecisionTreeClassifier\n The second classifier to be used\n\n c2_params : dict, default=None\n Parameters for the second classifier\n\n c3 : base_estimator, default=RandomForestClassifier\n The third classifier to be used\n\n c3_params : dict, default=None\n Parameters for the third classifier\n\n \"\"\"", "\"\"\"Tri-Training.\"\"\"", "\"\"\"\n > The function takes in a Bunch object, which is a dictionary-like\n object that contains the data and target arrays, and a sample size,\n and returns a Bunch object with the data and target arrays sub-sampled\n to the specified size\n\n :param l_t: the labeled and unlabeled data\n :param s: the number of samples to be drawn from the dataset\n :return: A Bunch object with the data and target attributes.\n \"\"\"", "\"\"\"\n The function takes in the training data and the labels, and then splits\n the data into three parts: labeled, unlabeled, and test. It then\n creates three classifiers, h_i, h_j, and h_k, and trains them on the\n labeled data. It then checks to see if the classifiers are accurate\n enough, and if they are, it returns them. If they are not, it trains\n them again on the labeled data, and then checks again\n\n :param samples: The samples to train the classifier on\n :param y: the labels\n \"\"\"", "\"\"\"\n If the update_j flag is True, then we concatenate the labeled data with\n the new data, and fit the model to the new data\n\n :param e_j: the error of the current hypothesis\n :param ep_j: the error of the previous iteration\n :param h_j: the classifier for the jth class\n :param l_j: the labeled data\n :param labeled: the labeled data\n :param lp_j: the number of labeled points in the current iteration\n :param update_j: boolean, whether to update the model or not\n :param y: the true labels of the data\n :return: the error, the hypothesis, and the length of the labeled data.\n \"\"\"", "\"\"\"\n If the error of the classifier is less than the error threshold, and the\n number of samples in the labeled set is less than the number of samples\n in the unlabeled set, then add the samples to the labeled set\n\n :param ep_k: the error threshold for the classifier\n :param h_i: the classifier that is being trained\n :param h_j: the classifier that is being compared to h_k\n :param h_k: the classifier we're training\n :param labeled: the labeled data\n :param lp_k: the number of samples that have been labeled by h_k\n :param u: the unlabeled data\n :return: The error, the new labeled data, and a boolean indicating\n whether the classifier should be updated.\n \"\"\"", "\"\"\"\n For each sample, we predict the label using each of the three\n classifiers, and then we take the majority vote of the three predictions\n\n :param samples: the data to be classified\n :return: The labels of the samples.\n \"\"\"", "\"\"\"\n It returns the fraction of the time that classifiers j and k disagree on\n the labels of the labeled data\n\n :param classifier_j: the classifier you want to compare to\n :param classifier_k: the classifier that we want to measure the error of\n :param labeled_data: the labeled data that we're using to train the\n classifiers\n :return: The error rate of the two classifiers.\n \"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
23
2,390
201
3169bc833df05aefe9236d98513f406786febefe
dsimop/Gotcha
src/common/Message.java
[ "BSD-4-Clause-UC" ]
Java
Message
/** * Message is the application-level communication protocol between the server and clients. This class has 3 field * variables: 1. userID is for identifying the user. 2. operation is the identifier for the operation to be processed by * the action dispatchers. 3. data is the context value such as a Question or Answer instance for this operation. * * @author Daohan Chong, Yang He, Dimitrios Simopoulos, Mel Trout * @version 2018-02-27 */
Message is the application-level communication protocol between the server and clients. This class has 3 field variables: 1. userID is for identifying the user. 2. operation is the identifier for the operation to be processed by the action dispatchers. 3. data is the context value such as a Question or Answer instance for this operation. @author Daohan Chong, Yang He, Dimitrios Simopoulos, Mel Trout @version 2018-02-27
[ "Message", "is", "the", "application", "-", "level", "communication", "protocol", "between", "the", "server", "and", "clients", ".", "This", "class", "has", "3", "field", "variables", ":", "1", ".", "userID", "is", "for", "identifying", "the", "user", ".", "2", ".", "operation", "is", "the", "identifier", "for", "the", "operation", "to", "be", "processed", "by", "the", "action", "dispatchers", ".", "3", ".", "data", "is", "the", "context", "value", "such", "as", "a", "Question", "or", "Answer", "instance", "for", "this", "operation", ".", "@author", "Daohan", "Chong", "Yang", "He", "Dimitrios", "Simopoulos", "Mel", "Trout", "@version", "2018", "-", "02", "-", "27" ]
public class Message<DataType> { // Enums for operations // Operations for server public final static class ServerOperations { public final static String CREATE_QUESTION = "S_CREATE_QUESTION"; public final static String UPDATE_QUESTION = "S_UPDATE_QUESTION"; public final static String DELETE_QUESTION = "S_DELETE_QUESTION"; public final static String GET_ANSWER_DISTRIBUTION = "S_GET_ANSWER_DISTRIBUTION"; public final static String CREATE_ANSWER = "S_CREATE_ANSWER"; public final static String GET_QUESTIONS = "S_GET_QUESTIONS"; public final static String CLOSE_CONNECTION = "S_CLOSE_CONNECTION"; public static final String DELETE_ANSWER = "S_DELETE_ANSWER"; public static final String UPDATE_ANSWER = "S_UPDATE_ANSWER"; public static final String GET_ALL_USERS = "S_GET_ALL_USERS"; public static final String ADD_NEW_USER = "S_ADD_NEW_USERS"; public static final String ANSWER_QUESTION="S_ANSWER_QUESTION"; public static final String GET_ALL_QUESTIONS_WITH_4_ANSWERS = "S_GET_ALL_QUESTIONS_WITH_4_ANSWERS"; public static final String GET_FIRST_QUESTION_FOR_USER = "S_GET_FIRST_QUESTION_FOR_USER"; public static final String GET_TOP_STUDENTS = "S_GET_TOP_STUDENTS"; public static final String GET_STUDENTS_PERFORMANCE = "S_GET_STUDENTS_PERFORMANCE"; // [Demo ] Step 1: Add the messages needed for communication } // Operations for client public final static class ClientOperations { public final static String LOGIN_SUCCEED_STUDENT = "C_LOGIN_SUCCEED_STUDENT"; public final static String LOGIN_SUCCEED_TEACHER = "C_LOGIN_SUCCEED_TEACHER"; public final static String LOGIN_FAILED = "C_LOGIN_FAILED"; public final static String REG_SUCCEED = "C_REG_SUCCEED"; public final static String REG_FAIL = "C_REG_FAIL"; public final static String UPDATE_QUESTIONS = "C_UPDATE_QUESTIONS"; public final static String QUESTIONS_RECEIVED = "C_QUESTIONS_RECEIVED"; public final static String UPDATE_ANSWER_DISTRIBUTION = "C_UPDATE_ANSWER_DISTRIBUTION"; public static final String UPDATE_FIRST_QUESTION_FOR_USER = "C_GET_FIRST_QUESTION_FOR_USER"; // [Demo ] Step 1:Add the messages needed for communication public final static String TOP_STUDENTS_RECEIVED = "C_TOP_STUDENTS_RECEIVED"; public final static String STUDENTS_PERFORMANCE_RECIEVED = "C_STUDENTS_PERFORMANCE_RECIEVED"; } private Integer userID; private String operation; private DataType data; /** * Construct a Message instance * * @param operation is the operation identifier * @param data is the data to be processed, which could also be null. * @param userID is the userID for this operation, which could be null. There is also a overloaded constructor * for that case. */ public Message(String operation, DataType data, Integer userID) { this.operation = operation; this.data = data; this.userID = userID; } /** * Construct a Message instance without userID * * @param operation is the operation identifier * @param data is the data to be processed, which could also be null. */ public Message(String operation, DataType data) { this(operation, data, null); } /** * Construct a Message instance without userID and data * * @param operation is the operation identifier */ public Message(String operation) { this(operation, null, null); } /** * This is a getter of the operation * * @return the current operation */ public String getOperation() { return operation; } public DataType getData() { return data; } /** * This is a getter of the user ID * * @return the userID */ public Integer getUserID() { return userID; } /** * This is a from Gson toJson converter * * @return a toJson String */ public String toJson() { Gson gson = createGson(); return gson.toJson(this, this.getClass()); } /** * Create a Message object from JSON string * * @param str is the JSON string * @return an * @throws JsonSyntaxException */ public static Message fromJson(String str) throws JsonSyntaxException { return createGson().fromJson(str, Message.class); } /** * This method creates a new Gson Object, using the imported gson jar * * @return a Gson Object */ public static Gson createGson() { return new GsonBuilder().serializeNulls().create(); } @Override public boolean equals(Object obj) { if( obj == null ) { return false; } else if( ! obj.getClass().equals(this.getClass()) ) { return false; } else { Message toBeCompared = (Message) obj; return equalsWithNulls(this.operation, toBeCompared.operation) && equalsWithNulls(this.data, toBeCompared.data) && equalsWithNulls(this.userID, toBeCompared.userID); } } /** * Convert the current message object into JSON string * * @return the JSON string */ public String toJsonString() { return createGson().toJson(this); } /** * Common logic to write the string into the output stream * * @param outputStream is the output stream to write the json string into * @throws IOException */ public void writeToOutputStream(ObjectOutputStream outputStream) throws IOException { outputStream.writeUTF(toJsonString()); outputStream.flush(); } }
[ "public", "class", "Message", "<", "DataType", ">", "{", "public", "final", "static", "class", "ServerOperations", "{", "public", "final", "static", "String", "CREATE_QUESTION", "=", "\"", "S_CREATE_QUESTION", "\"", ";", "public", "final", "static", "String", "UPDATE_QUESTION", "=", "\"", "S_UPDATE_QUESTION", "\"", ";", "public", "final", "static", "String", "DELETE_QUESTION", "=", "\"", "S_DELETE_QUESTION", "\"", ";", "public", "final", "static", "String", "GET_ANSWER_DISTRIBUTION", "=", "\"", "S_GET_ANSWER_DISTRIBUTION", "\"", ";", "public", "final", "static", "String", "CREATE_ANSWER", "=", "\"", "S_CREATE_ANSWER", "\"", ";", "public", "final", "static", "String", "GET_QUESTIONS", "=", "\"", "S_GET_QUESTIONS", "\"", ";", "public", "final", "static", "String", "CLOSE_CONNECTION", "=", "\"", "S_CLOSE_CONNECTION", "\"", ";", "public", "static", "final", "String", "DELETE_ANSWER", "=", "\"", "S_DELETE_ANSWER", "\"", ";", "public", "static", "final", "String", "UPDATE_ANSWER", "=", "\"", "S_UPDATE_ANSWER", "\"", ";", "public", "static", "final", "String", "GET_ALL_USERS", "=", "\"", "S_GET_ALL_USERS", "\"", ";", "public", "static", "final", "String", "ADD_NEW_USER", "=", "\"", "S_ADD_NEW_USERS", "\"", ";", "public", "static", "final", "String", "ANSWER_QUESTION", "=", "\"", "S_ANSWER_QUESTION", "\"", ";", "public", "static", "final", "String", "GET_ALL_QUESTIONS_WITH_4_ANSWERS", "=", "\"", "S_GET_ALL_QUESTIONS_WITH_4_ANSWERS", "\"", ";", "public", "static", "final", "String", "GET_FIRST_QUESTION_FOR_USER", "=", "\"", "S_GET_FIRST_QUESTION_FOR_USER", "\"", ";", "public", "static", "final", "String", "GET_TOP_STUDENTS", "=", "\"", "S_GET_TOP_STUDENTS", "\"", ";", "public", "static", "final", "String", "GET_STUDENTS_PERFORMANCE", "=", "\"", "S_GET_STUDENTS_PERFORMANCE", "\"", ";", "}", "public", "final", "static", "class", "ClientOperations", "{", "public", "final", "static", "String", "LOGIN_SUCCEED_STUDENT", "=", "\"", "C_LOGIN_SUCCEED_STUDENT", "\"", ";", "public", "final", "static", "String", "LOGIN_SUCCEED_TEACHER", "=", "\"", "C_LOGIN_SUCCEED_TEACHER", "\"", ";", "public", "final", "static", "String", "LOGIN_FAILED", "=", "\"", "C_LOGIN_FAILED", "\"", ";", "public", "final", "static", "String", "REG_SUCCEED", "=", "\"", "C_REG_SUCCEED", "\"", ";", "public", "final", "static", "String", "REG_FAIL", "=", "\"", "C_REG_FAIL", "\"", ";", "public", "final", "static", "String", "UPDATE_QUESTIONS", "=", "\"", "C_UPDATE_QUESTIONS", "\"", ";", "public", "final", "static", "String", "QUESTIONS_RECEIVED", "=", "\"", "C_QUESTIONS_RECEIVED", "\"", ";", "public", "final", "static", "String", "UPDATE_ANSWER_DISTRIBUTION", "=", "\"", "C_UPDATE_ANSWER_DISTRIBUTION", "\"", ";", "public", "static", "final", "String", "UPDATE_FIRST_QUESTION_FOR_USER", "=", "\"", "C_GET_FIRST_QUESTION_FOR_USER", "\"", ";", "public", "final", "static", "String", "TOP_STUDENTS_RECEIVED", "=", "\"", "C_TOP_STUDENTS_RECEIVED", "\"", ";", "public", "final", "static", "String", "STUDENTS_PERFORMANCE_RECIEVED", "=", "\"", "C_STUDENTS_PERFORMANCE_RECIEVED", "\"", ";", "}", "private", "Integer", "userID", ";", "private", "String", "operation", ";", "private", "DataType", "data", ";", "/**\n * Construct a Message instance\n *\n * @param operation is the operation identifier\n * @param data is the data to be processed, which could also be null.\n * @param userID is the userID for this operation, which could be null. There is also a overloaded constructor\n * for that case.\n */", "public", "Message", "(", "String", "operation", ",", "DataType", "data", ",", "Integer", "userID", ")", "{", "this", ".", "operation", "=", "operation", ";", "this", ".", "data", "=", "data", ";", "this", ".", "userID", "=", "userID", ";", "}", "/**\n * Construct a Message instance without userID\n *\n * @param operation is the operation identifier\n * @param data is the data to be processed, which could also be null.\n */", "public", "Message", "(", "String", "operation", ",", "DataType", "data", ")", "{", "this", "(", "operation", ",", "data", ",", "null", ")", ";", "}", "/**\n * Construct a Message instance without userID and data\n *\n * @param operation is the operation identifier\n */", "public", "Message", "(", "String", "operation", ")", "{", "this", "(", "operation", ",", "null", ",", "null", ")", ";", "}", "/**\n * This is a getter of the operation\n *\n * @return the current operation\n */", "public", "String", "getOperation", "(", ")", "{", "return", "operation", ";", "}", "public", "DataType", "getData", "(", ")", "{", "return", "data", ";", "}", "/**\n * This is a getter of the user ID\n *\n * @return the userID\n */", "public", "Integer", "getUserID", "(", ")", "{", "return", "userID", ";", "}", "/**\n * This is a from Gson toJson converter\n *\n * @return a toJson String\n */", "public", "String", "toJson", "(", ")", "{", "Gson", "gson", "=", "createGson", "(", ")", ";", "return", "gson", ".", "toJson", "(", "this", ",", "this", ".", "getClass", "(", ")", ")", ";", "}", "/**\n * Create a Message object from JSON string\n *\n * @param str is the JSON string\n * @return an\n * @throws JsonSyntaxException\n */", "public", "static", "Message", "fromJson", "(", "String", "str", ")", "throws", "JsonSyntaxException", "{", "return", "createGson", "(", ")", ".", "fromJson", "(", "str", ",", "Message", ".", "class", ")", ";", "}", "/**\n * This method creates a new Gson Object, using the imported gson jar\n *\n * @return a Gson Object\n */", "public", "static", "Gson", "createGson", "(", ")", "{", "return", "new", "GsonBuilder", "(", ")", ".", "serializeNulls", "(", ")", ".", "create", "(", ")", ";", "}", "@", "Override", "public", "boolean", "equals", "(", "Object", "obj", ")", "{", "if", "(", "obj", "==", "null", ")", "{", "return", "false", ";", "}", "else", "if", "(", "!", "obj", ".", "getClass", "(", ")", ".", "equals", "(", "this", ".", "getClass", "(", ")", ")", ")", "{", "return", "false", ";", "}", "else", "{", "Message", "toBeCompared", "=", "(", "Message", ")", "obj", ";", "return", "equalsWithNulls", "(", "this", ".", "operation", ",", "toBeCompared", ".", "operation", ")", "&&", "equalsWithNulls", "(", "this", ".", "data", ",", "toBeCompared", ".", "data", ")", "&&", "equalsWithNulls", "(", "this", ".", "userID", ",", "toBeCompared", ".", "userID", ")", ";", "}", "}", "/**\n * Convert the current message object into JSON string\n *\n * @return the JSON string\n */", "public", "String", "toJsonString", "(", ")", "{", "return", "createGson", "(", ")", ".", "toJson", "(", "this", ")", ";", "}", "/**\n * Common logic to write the string into the output stream\n *\n * @param outputStream is the output stream to write the json string into\n * @throws IOException\n */", "public", "void", "writeToOutputStream", "(", "ObjectOutputStream", "outputStream", ")", "throws", "IOException", "{", "outputStream", ".", "writeUTF", "(", "toJsonString", "(", ")", ")", ";", "outputStream", ".", "flush", "(", ")", ";", "}", "}" ]
Message is the application-level communication protocol between the server and clients.
[ "Message", "is", "the", "application", "-", "level", "communication", "protocol", "between", "the", "server", "and", "clients", "." ]
[ "// Enums for operations", "// Operations for server", "// [Demo ] Step 1: Add the messages needed for communication", "// Operations for client", "// [Demo ] Step 1:Add the messages needed for communication" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
14
1,251
111
a929b4ae4868112214f10a6b72f09d54c260e2e3
Newp/crc
Library/Crc.cs
[ "MIT" ]
C#
Crc
// TODO: consider endianness /// <summary> /// Library for computing CRCs of any algorithm in sizes of 8-64bits. /// </summary> /// <remarks> /// Based loosely on https://github.com/meetanthony/crccsharp and drawing from the fantastic work from R. Williams /// http://www.ross.net/crc/download/crc_v3.txt /// </remarks>
Library for computing CRCs of any algorithm in sizes of 8-64bits.
[ "Library", "for", "computing", "CRCs", "of", "any", "algorithm", "in", "sizes", "of", "8", "-", "64bits", "." ]
public class Crc { public readonly UInt64 Check; public readonly UInt64 Initial; public readonly Boolean IsInputReflected; public readonly Boolean IsOutputReflected; private readonly UInt64 Mask; public readonly String Name; public readonly UInt64 OutputXor; public readonly UInt64 Polynomial; private readonly UInt64[] PrecomputationTable = new UInt64[256]; private readonly Int32 ToRight; public readonly Int32 Width; private UInt64 Current; public Crc(String name, Int32 width, UInt64 polynomial, UInt64 initial, Boolean isInputReflected, Boolean isOutputReflected, UInt64 outputXor, UInt64 check = 0) { if (width < 8 || width > 64) { throw new ArgumentOutOfRangeException(nameof(width), "Must be a multiple of 8 and between 8 and 64."); } Name = name; Width = width; Polynomial = polynomial; Initial = initial; IsInputReflected = isInputReflected; IsOutputReflected = isOutputReflected; OutputXor = outputXor; Check = check; Mask = UInt64.MaxValue >> (64 - width); for (var i = 0; i < PrecomputationTable.Length; i++) { var r = (UInt64) i; if (IsInputReflected) { r = ReverseBits(r, width); } else if (width > 8) { r <<= width - 8; } var lastBit = 1ul << (width - 1); for (var j = 0; j < 8; j++) { if ((r & lastBit) != 0) { r = (r << 1) ^ Polynomial; } else { r <<= 1; } } if (IsInputReflected) { r = ReverseBits(r, width); } PrecomputationTable[i] = r; } if (!IsOutputReflected) { ToRight = Width - 8; ToRight = ToRight < 0 ? 0 : ToRight; } Clear(); } public Crc Append(Byte[] input) { Append(input, 0, input.Length); return this; } public Crc Append(Byte[] input, Int32 offset, Int32 count) { if (null == input) { throw new ArgumentNullException(nameof(input)); } if (offset < 0) { throw new ArgumentOutOfRangeException(nameof(offset)); } if (count < 0 || offset + count > input.Length) { throw new ArgumentOutOfRangeException(nameof(count)); } if (IsOutputReflected) { for (var i = offset; i < offset + count; i++) { Current = PrecomputationTable[(Current ^ input[i]) & 0xFF] ^ (Current >> 8); } } else { for (var i = offset; i < offset + count; i++) { Current = PrecomputationTable[((Current >> ToRight) ^ input[i]) & 0xFF] ^ (Current << 8); } } return this; } public UInt64 ToUInt64() { return (Current ^ OutputXor) & Mask; } public Byte[] ToByteArray() { var output = ToUInt64(); var result = BitConverter.GetBytes(output); if (!BitConverter.IsLittleEndian) { Array.Reverse(result); } Array.Resize(ref result, Width / 8); Array.Reverse(result); return result; } public String ToHexString() { return ToByteArray().ToHexString(); } public void Clear() { Current = IsOutputReflected ? ReverseBits(Initial, Width) : Initial; } private static UInt64 ReverseBits(UInt64 value, Int32 valueLength) { UInt64 output = 0; for (var i = valueLength - 1; i >= 0; i--) { output |= (value & 1) << i; value >>= 1; } return output; } }
[ "public", "class", "Crc", "{", "public", "readonly", "UInt64", "Check", ";", "public", "readonly", "UInt64", "Initial", ";", "public", "readonly", "Boolean", "IsInputReflected", ";", "public", "readonly", "Boolean", "IsOutputReflected", ";", "private", "readonly", "UInt64", "Mask", ";", "public", "readonly", "String", "Name", ";", "public", "readonly", "UInt64", "OutputXor", ";", "public", "readonly", "UInt64", "Polynomial", ";", "private", "readonly", "UInt64", "[", "]", "PrecomputationTable", "=", "new", "UInt64", "[", "256", "]", ";", "private", "readonly", "Int32", "ToRight", ";", "public", "readonly", "Int32", "Width", ";", "private", "UInt64", "Current", ";", "public", "Crc", "(", "String", "name", ",", "Int32", "width", ",", "UInt64", "polynomial", ",", "UInt64", "initial", ",", "Boolean", "isInputReflected", ",", "Boolean", "isOutputReflected", ",", "UInt64", "outputXor", ",", "UInt64", "check", "=", "0", ")", "{", "if", "(", "width", "<", "8", "||", "width", ">", "64", ")", "{", "throw", "new", "ArgumentOutOfRangeException", "(", "nameof", "(", "width", ")", ",", "\"", "Must be a multiple of 8 and between 8 and 64.", "\"", ")", ";", "}", "Name", "=", "name", ";", "Width", "=", "width", ";", "Polynomial", "=", "polynomial", ";", "Initial", "=", "initial", ";", "IsInputReflected", "=", "isInputReflected", ";", "IsOutputReflected", "=", "isOutputReflected", ";", "OutputXor", "=", "outputXor", ";", "Check", "=", "check", ";", "Mask", "=", "UInt64", ".", "MaxValue", ">>", "(", "64", "-", "width", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "PrecomputationTable", ".", "Length", ";", "i", "++", ")", "{", "var", "r", "=", "(", "UInt64", ")", "i", ";", "if", "(", "IsInputReflected", ")", "{", "r", "=", "ReverseBits", "(", "r", ",", "width", ")", ";", "}", "else", "if", "(", "width", ">", "8", ")", "{", "r", "<<=", "width", "-", "8", ";", "}", "var", "lastBit", "=", "1ul", "<<", "(", "width", "-", "1", ")", ";", "for", "(", "var", "j", "=", "0", ";", "j", "<", "8", ";", "j", "++", ")", "{", "if", "(", "(", "r", "&", "lastBit", ")", "!=", "0", ")", "{", "r", "=", "(", "r", "<<", "1", ")", "^", "Polynomial", ";", "}", "else", "{", "r", "<<=", "1", ";", "}", "}", "if", "(", "IsInputReflected", ")", "{", "r", "=", "ReverseBits", "(", "r", ",", "width", ")", ";", "}", "PrecomputationTable", "[", "i", "]", "=", "r", ";", "}", "if", "(", "!", "IsOutputReflected", ")", "{", "ToRight", "=", "Width", "-", "8", ";", "ToRight", "=", "ToRight", "<", "0", "?", "0", ":", "ToRight", ";", "}", "Clear", "(", ")", ";", "}", "public", "Crc", "Append", "(", "Byte", "[", "]", "input", ")", "{", "Append", "(", "input", ",", "0", ",", "input", ".", "Length", ")", ";", "return", "this", ";", "}", "public", "Crc", "Append", "(", "Byte", "[", "]", "input", ",", "Int32", "offset", ",", "Int32", "count", ")", "{", "if", "(", "null", "==", "input", ")", "{", "throw", "new", "ArgumentNullException", "(", "nameof", "(", "input", ")", ")", ";", "}", "if", "(", "offset", "<", "0", ")", "{", "throw", "new", "ArgumentOutOfRangeException", "(", "nameof", "(", "offset", ")", ")", ";", "}", "if", "(", "count", "<", "0", "||", "offset", "+", "count", ">", "input", ".", "Length", ")", "{", "throw", "new", "ArgumentOutOfRangeException", "(", "nameof", "(", "count", ")", ")", ";", "}", "if", "(", "IsOutputReflected", ")", "{", "for", "(", "var", "i", "=", "offset", ";", "i", "<", "offset", "+", "count", ";", "i", "++", ")", "{", "Current", "=", "PrecomputationTable", "[", "(", "Current", "^", "input", "[", "i", "]", ")", "&", "0xFF", "]", "^", "(", "Current", ">>", "8", ")", ";", "}", "}", "else", "{", "for", "(", "var", "i", "=", "offset", ";", "i", "<", "offset", "+", "count", ";", "i", "++", ")", "{", "Current", "=", "PrecomputationTable", "[", "(", "(", "Current", ">>", "ToRight", ")", "^", "input", "[", "i", "]", ")", "&", "0xFF", "]", "^", "(", "Current", "<<", "8", ")", ";", "}", "}", "return", "this", ";", "}", "public", "UInt64", "ToUInt64", "(", ")", "{", "return", "(", "Current", "^", "OutputXor", ")", "&", "Mask", ";", "}", "public", "Byte", "[", "]", "ToByteArray", "(", ")", "{", "var", "output", "=", "ToUInt64", "(", ")", ";", "var", "result", "=", "BitConverter", ".", "GetBytes", "(", "output", ")", ";", "if", "(", "!", "BitConverter", ".", "IsLittleEndian", ")", "{", "Array", ".", "Reverse", "(", "result", ")", ";", "}", "Array", ".", "Resize", "(", "ref", "result", ",", "Width", "/", "8", ")", ";", "Array", ".", "Reverse", "(", "result", ")", ";", "return", "result", ";", "}", "public", "String", "ToHexString", "(", ")", "{", "return", "ToByteArray", "(", ")", ".", "ToHexString", "(", ")", ";", "}", "public", "void", "Clear", "(", ")", "{", "Current", "=", "IsOutputReflected", "?", "ReverseBits", "(", "Initial", ",", "Width", ")", ":", "Initial", ";", "}", "private", "static", "UInt64", "ReverseBits", "(", "UInt64", "value", ",", "Int32", "valueLength", ")", "{", "UInt64", "output", "=", "0", ";", "for", "(", "var", "i", "=", "valueLength", "-", "1", ";", "i", ">=", "0", ";", "i", "--", ")", "{", "output", "|=", "(", "value", "&", "1", ")", "<<", "i", ";", "value", ">>=", "1", ";", "}", "return", "output", ";", "}", "}" ]
Library for computing CRCs of any algorithm in sizes of 8-64bits.
[ "Library", "for", "computing", "CRCs", "of", "any", "algorithm", "in", "sizes", "of", "8", "-", "64bits", "." ]
[ "/// <summary>", "/// The checksum obtained when the ASCII string \"123456789\" is fed through the specified algorithm (i.e.", "/// 0x313233...).", "/// </summary>", "/// <remarks>", "/// This field is not strictly part of the definition, and, in the event of an inconsistency between this field", "/// and the other field, the other fields take precedence. This field is a check value that can be used as a weak", "/// validator of implementations of the algorithm.", "/// </remarks>", "/// <summary>", "/// The initial value of the register when the algorithm starts.", "/// </summary>", "/// <summary>", "/// If the input is to be reflected before processing.", "/// </summary>", "/// <remarks>", "/// If it is FALSE, input bytes are processed with bit 7 being treated as the most significant bit (MSB) and bit 0", "/// being treated as the least significant bit. If this parameter is TRUE, each byte is reflected before being", "/// processed.", "/// </remarks>", "/// <summary>", "/// Is the output to be reflected.", "/// </summary>", "/// <remarks>", "/// If it is set to FALSE, the final value in the register is fed into the OutputXor stage directly, otherwise, if", "/// this parameter is TRUE, the final register value is reflected first.", "/// </remarks>", "/// <summary>", "/// Mask used internally to hide unwanted data in the 64bit working registers.", "/// </summary>", "/// <summary>", "/// Name given to the algorithm.", "/// </summary>", "/// <summary>", "/// This value is XORed to the final register value (after the IsOutputReflected stage) before the value is", "/// returned as the official checksum.", "/// </summary>", "/// <summary>", "/// The polynomial used for the CRC calculation, omitting the top bit.", "/// </summary>", "/// <remarks>", "/// The top bit of the poly should be omitted. For example, if the poly is 10110, you should specify 0x06. Also,", "/// an important aspect of this parameter is that it represents the unreflected poly; the bottom bit of this parameter", "/// is always the LSB of the divisor during the division regardless of whether the algorithm being modelled is", "/// reflected.", "/// </remarks>", "/// <summary>", "/// Lookup table that is populated at construction time to facilitate fastest possible computation.", "/// </summary>", "/// <summary>", "/// Width of the algorithm expressed in bits.", "/// </summary>", "/// <remarks>", "/// This is one less bit than the width of the Polynomial.", "/// </remarks>", "/// <summary>", "/// Accumulated CRC-32C of all buffers processed so far.", "/// </summary>", "// Store values", "// Compute mask", "// Create lookup table", "// Calculate non-reflected output adjustment", "// Initialise the current value", "/// <summary>", "/// Compute the hash of a byte array. This can be called multiple times for consecutive blocks of input.", "/// </summary>", "/// <summary>", "/// Compute the hash of a byte array with a defined offset and count. This can be called multiple times for", "/// consecutive blocks of input.", "/// </summary>", "/// <summary>", "/// Retrieve the CRC of the bytes that have been input so far.", "/// </summary>", "// Apply output XOR and mask unwanted bits", "/// <summary>", "/// Retrieve the CRC of the bytes that have been input so far.", "/// </summary>", "// TODO: this could be significantly optimised", "// Convert to byte array", "// Correct for big-endian ", "// Trim unwanted bytes", "// Reverse bytes", "/// <summary>", "/// Retrieve the CRC of the bytes that have been input so far.", "/// </summary>", "/// <summary>", "/// Reset the state so that a new set of data can be input without being affected by previous sets.", "/// </summary>", "/// <remarks>", "/// Typically this is called after retrieving a computed CRC (using ToByteArray() for example) and before calling", "/// Append for a new computation run.", "/// </remarks>", "// Initialise current" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [ { "identifier": "remarks", "docstring": null, "docstring_tokens": [ "None" ] } ] }
false
21
958
89
0661c961b6aff938f159a2b1fe8df0e08ec5cfba
CrossRef/tinypub
vendor/bundle/ruby/1.9.1/gems/actionpack-1.4.0/lib/action_view/helpers/url_helper.rb
[ "MIT" ]
Ruby
UrlHelper
# Provides a set of methods for making easy links and getting urls that depend on the controller and action. This means that # you can use the same format for links in the views that you do in the controller. The different methods are even named # synchronously, so link_to uses that same url as is generated by url_for, which again is the same url used for # redirection in redirect_to.
Provides a set of methods for making easy links and getting urls that depend on the controller and action. This means that you can use the same format for links in the views that you do in the controller. The different methods are even named synchronously, so link_to uses that same url as is generated by url_for, which again is the same url used for redirection in redirect_to.
[ "Provides", "a", "set", "of", "methods", "for", "making", "easy", "links", "and", "getting", "urls", "that", "depend", "on", "the", "controller", "and", "action", ".", "This", "means", "that", "you", "can", "use", "the", "same", "format", "for", "links", "in", "the", "views", "that", "you", "do", "in", "the", "controller", ".", "The", "different", "methods", "are", "even", "named", "synchronously", "so", "link_to", "uses", "that", "same", "url", "as", "is", "generated", "by", "url_for", "which", "again", "is", "the", "same", "url", "used", "for", "redirection", "in", "redirect_to", "." ]
module UrlHelper # Returns the URL for the set of +options+ provided. See the valid options in link:classes/ActionController/Base.html#M000021 def url_for(options = {}, *parameters_for_method_reference) if Hash === options then options = { :only_path => true }.merge(options) end @controller.send(:url_for, options, *parameters_for_method_reference) end # Creates a link tag of the given +name+ using an URL created by the set of +options+. See the valid options in # link:classes/ActionController/Base.html#M000021. It's also possible to pass a string instead of an options hash to # get a link tag that just points without consideration. If nil is passed as a name, the link itself will become the name. # The html_options have a special feature for creating javascript confirm alerts where if you pass :confirm => 'Are you sure?', # the link will be guarded with a JS popup asking that question. If the user accepts, the link is processed, otherwise not. def link_to(name, options = {}, html_options = {}, *parameters_for_method_reference) convert_confirm_option_to_javascript!(html_options) unless html_options.nil? if options.is_a?(String) content_tag "a", name || options, (html_options || {}).merge({ "href" => options }) else content_tag( "a", name || url_for(options, *parameters_for_method_reference), (html_options || {}).merge({ "href" => url_for(options, *parameters_for_method_reference) }) ) end end # Creates a link tag to the image residing at the +src+ using an URL created by the set of +options+. See the valid options in # link:classes/ActionController/Base.html#M000021. It's also possible to pass a string instead of an options hash to # get a link tag that just points without consideration. The <tt>html_options</tt> works jointly for the image and ahref tag by # letting the following special values enter the options on the image and the rest goes to the ahref: # # * <tt>alt</tt> - If no alt text is given, the file name part of the +src+ is used (capitalized and without the extension) # * <tt>size</tt> - Supplied as "XxY", so "30x45" becomes width="30" and height="45" # * <tt>border</tt> - Is set to 0 by default # * <tt>align</tt> - Sets the alignment, no special features # # The +src+ can be supplied as a... # * full path, like "/my_images/image.gif" # * file name, like "rss.gif", that gets expanded to "/images/rss.gif" # * file name without extension, like "logo", that gets expanded to "/images/logo.png" def link_to_image(src, options = {}, html_options = {}, *parameters_for_method_reference) image_options = { "src" => src.include?("/") ? src : "/images/#{src}" } image_options["src"] = image_options["src"] + ".png" unless image_options["src"].include?(".") if html_options["alt"] image_options["alt"] = html_options["alt"] html_options.delete "alt" else image_options["alt"] = src.split("/").last.split(".").first.capitalize end if html_options["size"] image_options["width"], image_options["height"] = html_options["size"].split("x") html_options.delete "size" end if html_options["border"] image_options["border"] = html_options["border"] html_options.delete "border" else image_options["border"] = "0" end if html_options["align"] image_options["align"] = html_options["align"] html_options.delete "align" end link_to(tag("img", image_options), options, html_options, *parameters_for_method_reference) end # Creates a link tag of the given +name+ using an URL created by the set of +options+, unless the current # controller, action, and id are the same as the link's, in which case only the name is returned (or the # given block is yielded, if one exists). This is useful for creating link bars where you don't want to link # to the page currently being viewed. def link_to_unless_current(name, options = {}, html_options = {}, *parameters_for_method_reference) assume_current_url_options!(options) if destination_equal_to_current(options) block_given? ? yield(name, options, html_options, *parameters_for_method_reference) : html_escape(name) else link_to name, options, html_options, *parameters_for_method_reference end end # Creates a link tag for starting an email to the specified <tt>email_address</tt>, which is also used as the name of the # link unless +name+ is specified. Additional HTML options, such as class or id, can be passed in the <tt>html_options</tt> hash. # # You can also make it difficult for spiders to harvest email address by obfuscating them. # Examples: # * mail_to "[email protected]", "My email", :encode => "javascript" # => <script type="text/javascript" language="javascript">eval(unescape('%64%6f%63%75%6d%65%6e%74%2e%77%72%69%74%65%28%27%3c%61%20%68%72%65%66%3d%22%6d%61%69%6c%74%6f%3a%6d%65%40%64%6f%6d%61%69%6e%2e%63%6f%6d%22%3e%4d%79%20%65%6d%61%69%6c%3c%2f%61%3e%27%29%3b'))</script> # * mail_to "[email protected]", "My email", :encode => "hex" # => <a href="mailto:%6d%65@%64%6f%6d%61%69%6e.%63%6f%6d">My email</a> def mail_to(email_address, name = nil, html_options = {}) encode = html_options[:encode] html_options.delete(:encode) string = '' if encode == 'javascript' tmp = "document.write('#{content_tag("a", name || email_address, html_options.merge({ "href" => "mailto:"+email_address.to_s }))}');" for i in 0...tmp.length string << sprintf("%%%x",tmp[i]) end "<script type=\"text/javascript\" language=\"javascript\">eval(unescape('#{string}'))</script>" elsif encode == 'hex' for i in 0...email_address.length if email_address[i,1] =~ /\w/ string << sprintf("%%%x",email_address[i]) else string << email_address[i,1] end end content_tag "a", name || email_address, html_options.merge({ "href" => "mailto:#{string}" }) else content_tag "a", name || email_address, html_options.merge({ "href" => "mailto:#{email_address}" }) end end private def destination_equal_to_current(options) params_without_location = @params.reject { |key, value| %w( controller action id ).include?(key) } options[:action].to_s == @params['action'].to_s && options[:id].to_s == @params['id'].to_s && options[:controller].to_s == @params['controller'].to_s && (options.has_key?(:params) ? params_without_location == options[:params] : true) end def assume_current_url_options!(options) if options[:controller].nil? options[:controller] = @params['controller'] if options[:action].nil? options[:action] = @params['action'] if options[:id].nil? then options[:id] ||= @params['id'] end end end end def convert_confirm_option_to_javascript!(html_options) if html_options.include?(:confirm) html_options["onclick"] = "return confirm('#{html_options[:confirm]}');" html_options.delete(:confirm) end end end
[ "module", "UrlHelper", "def", "url_for", "(", "options", "=", "{", "}", ",", "*", "parameters_for_method_reference", ")", "if", "Hash", "===", "options", "then", "options", "=", "{", ":only_path", "=>", "true", "}", ".", "merge", "(", "options", ")", "end", "@controller", ".", "send", "(", ":url_for", ",", "options", ",", "*", "parameters_for_method_reference", ")", "end", "def", "link_to", "(", "name", ",", "options", "=", "{", "}", ",", "html_options", "=", "{", "}", ",", "*", "parameters_for_method_reference", ")", "convert_confirm_option_to_javascript!", "(", "html_options", ")", "unless", "html_options", ".", "nil?", "if", "options", ".", "is_a?", "(", "String", ")", "content_tag", "\"a\"", ",", "name", "||", "options", ",", "(", "html_options", "||", "{", "}", ")", ".", "merge", "(", "{", "\"href\"", "=>", "options", "}", ")", "else", "content_tag", "(", "\"a\"", ",", "name", "||", "url_for", "(", "options", ",", "*", "parameters_for_method_reference", ")", ",", "(", "html_options", "||", "{", "}", ")", ".", "merge", "(", "{", "\"href\"", "=>", "url_for", "(", "options", ",", "*", "parameters_for_method_reference", ")", "}", ")", ")", "end", "end", "def", "link_to_image", "(", "src", ",", "options", "=", "{", "}", ",", "html_options", "=", "{", "}", ",", "*", "parameters_for_method_reference", ")", "image_options", "=", "{", "\"src\"", "=>", "src", ".", "include?", "(", "\"/\"", ")", "?", "src", ":", "\"/images/#{src}\"", "}", "image_options", "[", "\"src\"", "]", "=", "image_options", "[", "\"src\"", "]", "+", "\".png\"", "unless", "image_options", "[", "\"src\"", "]", ".", "include?", "(", "\".\"", ")", "if", "html_options", "[", "\"alt\"", "]", "image_options", "[", "\"alt\"", "]", "=", "html_options", "[", "\"alt\"", "]", "html_options", ".", "delete", "\"alt\"", "else", "image_options", "[", "\"alt\"", "]", "=", "src", ".", "split", "(", "\"/\"", ")", ".", "last", ".", "split", "(", "\".\"", ")", ".", "first", ".", "capitalize", "end", "if", "html_options", "[", "\"size\"", "]", "image_options", "[", "\"width\"", "]", ",", "image_options", "[", "\"height\"", "]", "=", "html_options", "[", "\"size\"", "]", ".", "split", "(", "\"x\"", ")", "html_options", ".", "delete", "\"size\"", "end", "if", "html_options", "[", "\"border\"", "]", "image_options", "[", "\"border\"", "]", "=", "html_options", "[", "\"border\"", "]", "html_options", ".", "delete", "\"border\"", "else", "image_options", "[", "\"border\"", "]", "=", "\"0\"", "end", "if", "html_options", "[", "\"align\"", "]", "image_options", "[", "\"align\"", "]", "=", "html_options", "[", "\"align\"", "]", "html_options", ".", "delete", "\"align\"", "end", "link_to", "(", "tag", "(", "\"img\"", ",", "image_options", ")", ",", "options", ",", "html_options", ",", "*", "parameters_for_method_reference", ")", "end", "def", "link_to_unless_current", "(", "name", ",", "options", "=", "{", "}", ",", "html_options", "=", "{", "}", ",", "*", "parameters_for_method_reference", ")", "assume_current_url_options!", "(", "options", ")", "if", "destination_equal_to_current", "(", "options", ")", "block_given?", "?", "yield", "(", "name", ",", "options", ",", "html_options", ",", "*", "parameters_for_method_reference", ")", ":", "html_escape", "(", "name", ")", "else", "link_to", "name", ",", "options", ",", "html_options", ",", "*", "parameters_for_method_reference", "end", "end", "def", "mail_to", "(", "email_address", ",", "name", "=", "nil", ",", "html_options", "=", "{", "}", ")", "encode", "=", "html_options", "[", ":encode", "]", "html_options", ".", "delete", "(", ":encode", ")", "string", "=", "''", "if", "encode", "==", "'javascript'", "tmp", "=", "\"document.write('#{content_tag(\"a\", name || email_address, html_options.merge({ \"href\" => \"mailto:\"+email_address.to_s }))}');\"", "for", "i", "in", "0", "...", "tmp", ".", "length", "string", "<<", "sprintf", "(", "\"%%%x\"", ",", "tmp", "[", "i", "]", ")", "end", "\"<script type=\\\"text/javascript\\\" language=\\\"javascript\\\">eval(unescape('#{string}'))</script>\"", "elsif", "encode", "==", "'hex'", "for", "i", "in", "0", "...", "email_address", ".", "length", "if", "email_address", "[", "i", ",", "1", "]", "=~", "/", "\\w", "/", "string", "<<", "sprintf", "(", "\"%%%x\"", ",", "email_address", "[", "i", "]", ")", "else", "string", "<<", "email_address", "[", "i", ",", "1", "]", "end", "end", "content_tag", "\"a\"", ",", "name", "||", "email_address", ",", "html_options", ".", "merge", "(", "{", "\"href\"", "=>", "\"mailto:#{string}\"", "}", ")", "else", "content_tag", "\"a\"", ",", "name", "||", "email_address", ",", "html_options", ".", "merge", "(", "{", "\"href\"", "=>", "\"mailto:#{email_address}\"", "}", ")", "end", "end", "private", "def", "destination_equal_to_current", "(", "options", ")", "params_without_location", "=", "@params", ".", "reject", "{", "|", "key", ",", "value", "|", "%w(", "controller", "action", "id", ")", ".", "include?", "(", "key", ")", "}", "options", "[", ":action", "]", ".", "to_s", "==", "@params", "[", "'action'", "]", ".", "to_s", "&&", "options", "[", ":id", "]", ".", "to_s", "==", "@params", "[", "'id'", "]", ".", "to_s", "&&", "options", "[", ":controller", "]", ".", "to_s", "==", "@params", "[", "'controller'", "]", ".", "to_s", "&&", "(", "options", ".", "has_key?", "(", ":params", ")", "?", "params_without_location", "==", "options", "[", ":params", "]", ":", "true", ")", "end", "def", "assume_current_url_options!", "(", "options", ")", "if", "options", "[", ":controller", "]", ".", "nil?", "options", "[", ":controller", "]", "=", "@params", "[", "'controller'", "]", "if", "options", "[", ":action", "]", ".", "nil?", "options", "[", ":action", "]", "=", "@params", "[", "'action'", "]", "if", "options", "[", ":id", "]", ".", "nil?", "then", "options", "[", ":id", "]", "||=", "@params", "[", "'id'", "]", "end", "end", "end", "end", "def", "convert_confirm_option_to_javascript!", "(", "html_options", ")", "if", "html_options", ".", "include?", "(", ":confirm", ")", "html_options", "[", "\"onclick\"", "]", "=", "\"return confirm('#{html_options[:confirm]}');\"", "html_options", ".", "delete", "(", ":confirm", ")", "end", "end", "end" ]
Provides a set of methods for making easy links and getting urls that depend on the controller and action.
[ "Provides", "a", "set", "of", "methods", "for", "making", "easy", "links", "and", "getting", "urls", "that", "depend", "on", "the", "controller", "and", "action", "." ]
[ "# Returns the URL for the set of +options+ provided. See the valid options in link:classes/ActionController/Base.html#M000021", "# Creates a link tag of the given +name+ using an URL created by the set of +options+. See the valid options in", "# link:classes/ActionController/Base.html#M000021. It's also possible to pass a string instead of an options hash to", "# get a link tag that just points without consideration. If nil is passed as a name, the link itself will become the name. ", "# The html_options have a special feature for creating javascript confirm alerts where if you pass :confirm => 'Are you sure?', ", "# the link will be guarded with a JS popup asking that question. If the user accepts, the link is processed, otherwise not.", "# Creates a link tag to the image residing at the +src+ using an URL created by the set of +options+. See the valid options in", "# link:classes/ActionController/Base.html#M000021. It's also possible to pass a string instead of an options hash to", "# get a link tag that just points without consideration. The <tt>html_options</tt> works jointly for the image and ahref tag by", "# letting the following special values enter the options on the image and the rest goes to the ahref:", "#", "# * <tt>alt</tt> - If no alt text is given, the file name part of the +src+ is used (capitalized and without the extension)", "# * <tt>size</tt> - Supplied as \"XxY\", so \"30x45\" becomes width=\"30\" and height=\"45\"", "# * <tt>border</tt> - Is set to 0 by default", "# * <tt>align</tt> - Sets the alignment, no special features", "#", "# The +src+ can be supplied as a... ", "# * full path, like \"/my_images/image.gif\"", "# * file name, like \"rss.gif\", that gets expanded to \"/images/rss.gif\"", "# * file name without extension, like \"logo\", that gets expanded to \"/images/logo.png\"", "# Creates a link tag of the given +name+ using an URL created by the set of +options+, unless the current ", "# controller, action, and id are the same as the link's, in which case only the name is returned (or the", "# given block is yielded, if one exists). This is useful for creating link bars where you don't want to link ", "# to the page currently being viewed.", "# Creates a link tag for starting an email to the specified <tt>email_address</tt>, which is also used as the name of the", "# link unless +name+ is specified. Additional HTML options, such as class or id, can be passed in the <tt>html_options</tt> hash.", "#", "# You can also make it difficult for spiders to harvest email address by obfuscating them.", "# Examples:", "# * mail_to \"[email protected]\", \"My email\", :encode => \"javascript\"", "# => <script type=\"text/javascript\" language=\"javascript\">eval(unescape('%64%6f%63%75%6d%65%6e%74%2e%77%72%69%74%65%28%27%3c%61%20%68%72%65%66%3d%22%6d%61%69%6c%74%6f%3a%6d%65%40%64%6f%6d%61%69%6e%2e%63%6f%6d%22%3e%4d%79%20%65%6d%61%69%6c%3c%2f%61%3e%27%29%3b'))</script>", "# * mail_to \"[email protected]\", \"My email\", :encode => \"hex\"", "# => <a href=\"mailto:%6d%65@%64%6f%6d%61%69%6e.%63%6f%6d\">My email</a>" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
18
1,974
84
767775d63e89fd0443bde796090e86a9b5bd6fd9
joaocpsantos/hazelcast
hazelcast/src/main/java/com/hazelcast/quorum/impl/QuorumServiceImpl.java
[ "Apache-2.0" ]
Java
QuorumServiceImpl
/** * Service containing logic for cluster quorum. * * IMPORTANT: The term "quorum" simply refers to the count of members in the cluster required for an operation to succeed. * It does NOT refer to an implementation of Paxos or Raft protocols as used in many NoSQL and distributed systems. * The mechanism it provides in Hazelcast protects the user in case the number of nodes in a cluster drops below the * specified one. */
Service containing logic for cluster quorum. IMPORTANT: The term "quorum" simply refers to the count of members in the cluster required for an operation to succeed. It does NOT refer to an implementation of Paxos or Raft protocols as used in many NoSQL and distributed systems. The mechanism it provides in Hazelcast protects the user in case the number of nodes in a cluster drops below the specified one.
[ "Service", "containing", "logic", "for", "cluster", "quorum", ".", "IMPORTANT", ":", "The", "term", "\"", "quorum", "\"", "simply", "refers", "to", "the", "count", "of", "members", "in", "the", "cluster", "required", "for", "an", "operation", "to", "succeed", ".", "It", "does", "NOT", "refer", "to", "an", "implementation", "of", "Paxos", "or", "Raft", "protocols", "as", "used", "in", "many", "NoSQL", "and", "distributed", "systems", ".", "The", "mechanism", "it", "provides", "in", "Hazelcast", "protects", "the", "user", "in", "case", "the", "number", "of", "nodes", "in", "a", "cluster", "drops", "below", "the", "specified", "one", "." ]
public class QuorumServiceImpl implements EventPublishingService<QuorumEvent, QuorumListener>, MembershipAwareService, QuorumService, HeartbeatAware, PingAware { public static final String SERVICE_NAME = "hz:impl:quorumService"; /** * Single threaded quorum executor. Quorum updates are executed in order, without concurrency. */ private static final String QUORUM_EXECUTOR = "hz:quorum"; private final NodeEngineImpl nodeEngine; private final EventService eventService; private volatile Map<String, QuorumImpl> quorums; // true when at least one configured quorum implementation is HeartbeatAware private volatile boolean heartbeatAware; // true when at least one configured quorum implementation is PingAware private volatile boolean pingAware; public QuorumServiceImpl(NodeEngineImpl nodeEngine) { this.nodeEngine = nodeEngine; this.eventService = nodeEngine.getEventService(); } public void start() { // before starting, no quorums are used, just QuorumService dependency is provided to services which depend on it // so it's safe to initialize quorums here (and we have ClusterService already constructed) this.quorums = Collections.unmodifiableMap(initializeQuorums()); scanQuorums(); initializeListeners(); if (isInactive()) { return; } InternalExecutionService executionService = nodeEngine.getExecutionService(); // single thread quorum executor executionService.register(QUORUM_EXECUTOR, 1, Integer.MAX_VALUE, ExecutorType.CACHED); long heartbeatInterval = nodeEngine.getProperties().getSeconds(GroupProperty.HEARTBEAT_INTERVAL_SECONDS); executionService.scheduleWithRepetition(QUORUM_EXECUTOR, new UpdateQuorums(), heartbeatInterval, heartbeatInterval, TimeUnit.SECONDS); } private Map<String, QuorumImpl> initializeQuorums() { Map<String, QuorumImpl> quorums = new HashMap<String, QuorumImpl>(); for (QuorumConfig quorumConfig : nodeEngine.getConfig().getQuorumConfigs().values()) { validateQuorumConfig(quorumConfig); QuorumImpl quorum = new QuorumImpl(quorumConfig, nodeEngine); quorums.put(quorumConfig.getName(), quorum); } return quorums; } private void validateQuorumConfig(QuorumConfig quorumConfig) { if (quorumConfig.getQuorumFunctionImplementation() == null) { return; } QuorumFunction quorumFunction = quorumConfig.getQuorumFunctionImplementation(); if (quorumFunction instanceof ProbabilisticQuorumFunction) { validateQuorumParameters(quorumConfig.getName(), ((ProbabilisticQuorumFunction) quorumFunction).getAcceptableHeartbeatPauseMillis(), "acceptable heartbeat pause"); } else if (quorumFunction instanceof RecentlyActiveQuorumFunction) { validateQuorumParameters(quorumConfig.getName(), ((RecentlyActiveQuorumFunction) quorumFunction).getHeartbeatToleranceMillis(), "heartbeat tolerance"); } } private void validateQuorumParameters(String quorumName, long value, String parameterName) { HazelcastProperties nodeProperties = nodeEngine.getProperties(); long maxNoHeartbeatMillis = nodeProperties.getMillis(GroupProperty.MAX_NO_HEARTBEAT_SECONDS); long heartbeatIntervalMillis = nodeProperties.getMillis(GroupProperty.HEARTBEAT_INTERVAL_SECONDS); if (value > maxNoHeartbeatMillis) { throw new InvalidConfigurationException("This member is configured with maximum no-heartbeat duration " + maxNoHeartbeatMillis + " millis. For the quorum '" + quorumName + "' to be effective, set " + parameterName + " to a lower value. Currently configured value is " + value + ", reconfigure to a value lower than " + maxNoHeartbeatMillis + "."); } else if (value < heartbeatIntervalMillis) { throw new InvalidConfigurationException("Quorum '" + quorumName + "' is misconfigured: the value of " + "acceptable heartbeat pause (" + value + ") must be greater than " + "the configured heartbeat interval (" + heartbeatIntervalMillis + "), otherwise quorum " + "will be always absent."); } } private void initializeListeners() { for (Map.Entry<String, QuorumConfig> configEntry : nodeEngine.getConfig().getQuorumConfigs().entrySet()) { QuorumConfig config = configEntry.getValue(); String instanceName = configEntry.getKey(); for (QuorumListenerConfig listenerConfig : config.getListenerConfigs()) { initializeListenerInternal(instanceName, listenerConfig); } } } private void initializeListenerInternal(String instanceName, QuorumListenerConfig listenerConfig) { QuorumListener listener = null; if (listenerConfig.getImplementation() != null) { listener = listenerConfig.getImplementation(); } else if (listenerConfig.getClassName() != null) { try { listener = ClassLoaderUtil .newInstance(nodeEngine.getConfigClassLoader(), listenerConfig.getClassName()); } catch (Exception e) { throw ExceptionUtil.rethrow(e); } } if (listener != null) { addQuorumListener(instanceName, listener); } } // scan quorums for heartbeat-aware and ping-aware implementations and set corresponding flags private void scanQuorums() { for (QuorumImpl quorum : quorums.values()) { if (quorum.isHeartbeatAware()) { this.heartbeatAware = true; } if (quorum.isPingAware()) { this.pingAware = true; } } } private boolean isInactive() { return quorums.isEmpty(); } public void addQuorumListener(String name, QuorumListener listener) { eventService.registerLocalListener(SERVICE_NAME, name, listener); } /** * Ensures that the quorum for the given operation is present. This requires that there is a quorum configured under the * name which is returned by the operation service. * This in turn requires that the operation is named and that the operation service is a {@link QuorumAwareService}. * * @param op the operation for which the quorum should be present * @throws QuorumException if the operation requires a quorum and the quorum is not present */ public void ensureQuorumPresent(Operation op) { if (isInactive()) { return; } QuorumImpl quorum = findQuorum(op); if (quorum == null) { return; } quorum.ensureQuorumPresent(op); } public void ensureQuorumPresent(String quorumName, QuorumType requiredQuorumPermissionType) { if (isInactive() || quorumName == null) { return; } QuorumImpl definedQuorum = quorums.get(quorumName); QuorumType definedQuorumType = definedQuorum.getConfig().getType(); switch (requiredQuorumPermissionType) { case WRITE: if (definedQuorumType.equals(WRITE) || definedQuorumType.equals(READ_WRITE)) { definedQuorum.ensureQuorumPresent(); } break; case READ: if (definedQuorumType.equals(READ) || definedQuorumType.equals(READ_WRITE)) { definedQuorum.ensureQuorumPresent(); } break; case READ_WRITE: if (definedQuorumType.equals(READ_WRITE)) { definedQuorum.ensureQuorumPresent(); } break; default: throw new IllegalStateException("Unhandled quorum type: " + requiredQuorumPermissionType); } } /** * Returns a {@link QuorumImpl} for the given operation. The operation should be named and the operation service should * be a {@link QuorumAwareService}. This service will then return the quorum configured under the name returned by the * operation service. * * @param op the operation for which the Quorum should be returned * @return the quorum */ private QuorumImpl findQuorum(Operation op) { if (!isNamedOperation(op) || !isQuorumAware(op)) { return null; } String quorumName = getQuorumName(op); if (quorumName == null) { return null; } return quorums.get(quorumName); } private String getQuorumName(Operation op) { QuorumAwareService service; if (op instanceof ServiceNamespaceAware) { ServiceNamespace serviceNamespace = ((ServiceNamespaceAware) op).getServiceNamespace(); service = nodeEngine.getService(serviceNamespace.getServiceName()); } else { service = op.getService(); } String name = ((NamedOperation) op).getName(); return service.getQuorumName(name); } private boolean isQuorumAware(Operation op) { return op.getService() instanceof QuorumAwareService; } private boolean isNamedOperation(Operation op) { return op instanceof NamedOperation; } @Override public void dispatchEvent(QuorumEvent event, QuorumListener listener) { listener.onChange(event); } @Override public void memberAdded(MembershipServiceEvent event) { if (isInactive()) { return; } nodeEngine.getExecutionService().execute(QUORUM_EXECUTOR, new UpdateQuorums(event)); } @Override public void memberRemoved(MembershipServiceEvent event) { if (isInactive()) { return; } nodeEngine.getExecutionService().execute(QUORUM_EXECUTOR, new UpdateQuorums(event)); } @Override public void memberAttributeChanged(MemberAttributeServiceEvent event) { // nop // MemberAttributeServiceEvent does NOT contain set of members // They cannot change quorum state } @Override public Quorum getQuorum(String quorumName) { checkNotNull(quorumName, "quorumName cannot be null!"); Quorum quorum = quorums.get(quorumName); if (quorum == null) { throw new IllegalArgumentException("No quorum configuration named [ " + quorumName + " ] is found!"); } return quorum; } @Override public void onHeartbeat(Member member, long timestamp) { if (isInactive() || !heartbeatAware) { return; } nodeEngine.getExecutionService().execute(QUORUM_EXECUTOR, new OnHeartbeat(member, timestamp)); } @Override public void onPingLost(Member member) { if (isInactive() || !pingAware) { return; } nodeEngine.getExecutionService().execute(QUORUM_EXECUTOR, new OnPing(member, false)); } @Override public void onPingRestored(Member member) { if (isInactive() || !pingAware) { return; } nodeEngine.getExecutionService().execute(QUORUM_EXECUTOR, new OnPing(member, true)); } private class UpdateQuorums implements Runnable { private final MembershipEvent event; UpdateQuorums() { this.event = null; } UpdateQuorums(MembershipEvent event) { this.event = event; } @Override public void run() { ClusterService clusterService = nodeEngine.getClusterService(); Collection<Member> members = clusterService.getMembers(MemberSelectors.DATA_MEMBER_SELECTOR); for (QuorumImpl quorum : quorums.values()) { if (event != null) { switch (event.getEventType()) { case MembershipEvent.MEMBER_ADDED: quorum.onMemberAdded(event); break; case MembershipEvent.MEMBER_REMOVED: quorum.onMemberRemoved(event); break; default: // nop break; } } quorum.update(members); } } } private class OnHeartbeat implements Runnable { private final Member member; private final long timestamp; OnHeartbeat(Member member, long timestamp) { this.member = member; this.timestamp = timestamp; } @Override public void run() { ClusterService clusterService = nodeEngine.getClusterService(); Collection<Member> members = clusterService.getMembers(MemberSelectors.DATA_MEMBER_SELECTOR); for (QuorumImpl quorum : quorums.values()) { quorum.onHeartbeat(member, timestamp); quorum.update(members); } } } private class OnPing implements Runnable { private final Member member; private final boolean successful; OnPing(Member member, boolean successful) { this.member = member; this.successful = successful; } @Override public void run() { ClusterService clusterService = nodeEngine.getClusterService(); Collection<Member> members = clusterService.getMembers(MemberSelectors.DATA_MEMBER_SELECTOR); for (QuorumImpl quorum : quorums.values()) { quorum.onPing(member, successful); quorum.update(members); } } } }
[ "public", "class", "QuorumServiceImpl", "implements", "EventPublishingService", "<", "QuorumEvent", ",", "QuorumListener", ">", ",", "MembershipAwareService", ",", "QuorumService", ",", "HeartbeatAware", ",", "PingAware", "{", "public", "static", "final", "String", "SERVICE_NAME", "=", "\"", "hz:impl:quorumService", "\"", ";", "/**\n * Single threaded quorum executor. Quorum updates are executed in order, without concurrency.\n */", "private", "static", "final", "String", "QUORUM_EXECUTOR", "=", "\"", "hz:quorum", "\"", ";", "private", "final", "NodeEngineImpl", "nodeEngine", ";", "private", "final", "EventService", "eventService", ";", "private", "volatile", "Map", "<", "String", ",", "QuorumImpl", ">", "quorums", ";", "private", "volatile", "boolean", "heartbeatAware", ";", "private", "volatile", "boolean", "pingAware", ";", "public", "QuorumServiceImpl", "(", "NodeEngineImpl", "nodeEngine", ")", "{", "this", ".", "nodeEngine", "=", "nodeEngine", ";", "this", ".", "eventService", "=", "nodeEngine", ".", "getEventService", "(", ")", ";", "}", "public", "void", "start", "(", ")", "{", "this", ".", "quorums", "=", "Collections", ".", "unmodifiableMap", "(", "initializeQuorums", "(", ")", ")", ";", "scanQuorums", "(", ")", ";", "initializeListeners", "(", ")", ";", "if", "(", "isInactive", "(", ")", ")", "{", "return", ";", "}", "InternalExecutionService", "executionService", "=", "nodeEngine", ".", "getExecutionService", "(", ")", ";", "executionService", ".", "register", "(", "QUORUM_EXECUTOR", ",", "1", ",", "Integer", ".", "MAX_VALUE", ",", "ExecutorType", ".", "CACHED", ")", ";", "long", "heartbeatInterval", "=", "nodeEngine", ".", "getProperties", "(", ")", ".", "getSeconds", "(", "GroupProperty", ".", "HEARTBEAT_INTERVAL_SECONDS", ")", ";", "executionService", ".", "scheduleWithRepetition", "(", "QUORUM_EXECUTOR", ",", "new", "UpdateQuorums", "(", ")", ",", "heartbeatInterval", ",", "heartbeatInterval", ",", "TimeUnit", ".", "SECONDS", ")", ";", "}", "private", "Map", "<", "String", ",", "QuorumImpl", ">", "initializeQuorums", "(", ")", "{", "Map", "<", "String", ",", "QuorumImpl", ">", "quorums", "=", "new", "HashMap", "<", "String", ",", "QuorumImpl", ">", "(", ")", ";", "for", "(", "QuorumConfig", "quorumConfig", ":", "nodeEngine", ".", "getConfig", "(", ")", ".", "getQuorumConfigs", "(", ")", ".", "values", "(", ")", ")", "{", "validateQuorumConfig", "(", "quorumConfig", ")", ";", "QuorumImpl", "quorum", "=", "new", "QuorumImpl", "(", "quorumConfig", ",", "nodeEngine", ")", ";", "quorums", ".", "put", "(", "quorumConfig", ".", "getName", "(", ")", ",", "quorum", ")", ";", "}", "return", "quorums", ";", "}", "private", "void", "validateQuorumConfig", "(", "QuorumConfig", "quorumConfig", ")", "{", "if", "(", "quorumConfig", ".", "getQuorumFunctionImplementation", "(", ")", "==", "null", ")", "{", "return", ";", "}", "QuorumFunction", "quorumFunction", "=", "quorumConfig", ".", "getQuorumFunctionImplementation", "(", ")", ";", "if", "(", "quorumFunction", "instanceof", "ProbabilisticQuorumFunction", ")", "{", "validateQuorumParameters", "(", "quorumConfig", ".", "getName", "(", ")", ",", "(", "(", "ProbabilisticQuorumFunction", ")", "quorumFunction", ")", ".", "getAcceptableHeartbeatPauseMillis", "(", ")", ",", "\"", "acceptable heartbeat pause", "\"", ")", ";", "}", "else", "if", "(", "quorumFunction", "instanceof", "RecentlyActiveQuorumFunction", ")", "{", "validateQuorumParameters", "(", "quorumConfig", ".", "getName", "(", ")", ",", "(", "(", "RecentlyActiveQuorumFunction", ")", "quorumFunction", ")", ".", "getHeartbeatToleranceMillis", "(", ")", ",", "\"", "heartbeat tolerance", "\"", ")", ";", "}", "}", "private", "void", "validateQuorumParameters", "(", "String", "quorumName", ",", "long", "value", ",", "String", "parameterName", ")", "{", "HazelcastProperties", "nodeProperties", "=", "nodeEngine", ".", "getProperties", "(", ")", ";", "long", "maxNoHeartbeatMillis", "=", "nodeProperties", ".", "getMillis", "(", "GroupProperty", ".", "MAX_NO_HEARTBEAT_SECONDS", ")", ";", "long", "heartbeatIntervalMillis", "=", "nodeProperties", ".", "getMillis", "(", "GroupProperty", ".", "HEARTBEAT_INTERVAL_SECONDS", ")", ";", "if", "(", "value", ">", "maxNoHeartbeatMillis", ")", "{", "throw", "new", "InvalidConfigurationException", "(", "\"", "This member is configured with maximum no-heartbeat duration ", "\"", "+", "maxNoHeartbeatMillis", "+", "\"", " millis. For the quorum '", "\"", "+", "quorumName", "+", "\"", "' to be effective, set ", "\"", "+", "parameterName", "+", "\"", " to a lower value. Currently configured value is ", "\"", "+", "value", "+", "\"", ", reconfigure to a value lower than ", "\"", "+", "maxNoHeartbeatMillis", "+", "\"", ".", "\"", ")", ";", "}", "else", "if", "(", "value", "<", "heartbeatIntervalMillis", ")", "{", "throw", "new", "InvalidConfigurationException", "(", "\"", "Quorum '", "\"", "+", "quorumName", "+", "\"", "' is misconfigured: the value of ", "\"", "+", "\"", "acceptable heartbeat pause (", "\"", "+", "value", "+", "\"", ") must be greater than ", "\"", "+", "\"", "the configured heartbeat interval (", "\"", "+", "heartbeatIntervalMillis", "+", "\"", "), otherwise quorum ", "\"", "+", "\"", "will be always absent.", "\"", ")", ";", "}", "}", "private", "void", "initializeListeners", "(", ")", "{", "for", "(", "Map", ".", "Entry", "<", "String", ",", "QuorumConfig", ">", "configEntry", ":", "nodeEngine", ".", "getConfig", "(", ")", ".", "getQuorumConfigs", "(", ")", ".", "entrySet", "(", ")", ")", "{", "QuorumConfig", "config", "=", "configEntry", ".", "getValue", "(", ")", ";", "String", "instanceName", "=", "configEntry", ".", "getKey", "(", ")", ";", "for", "(", "QuorumListenerConfig", "listenerConfig", ":", "config", ".", "getListenerConfigs", "(", ")", ")", "{", "initializeListenerInternal", "(", "instanceName", ",", "listenerConfig", ")", ";", "}", "}", "}", "private", "void", "initializeListenerInternal", "(", "String", "instanceName", ",", "QuorumListenerConfig", "listenerConfig", ")", "{", "QuorumListener", "listener", "=", "null", ";", "if", "(", "listenerConfig", ".", "getImplementation", "(", ")", "!=", "null", ")", "{", "listener", "=", "listenerConfig", ".", "getImplementation", "(", ")", ";", "}", "else", "if", "(", "listenerConfig", ".", "getClassName", "(", ")", "!=", "null", ")", "{", "try", "{", "listener", "=", "ClassLoaderUtil", ".", "newInstance", "(", "nodeEngine", ".", "getConfigClassLoader", "(", ")", ",", "listenerConfig", ".", "getClassName", "(", ")", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "ExceptionUtil", ".", "rethrow", "(", "e", ")", ";", "}", "}", "if", "(", "listener", "!=", "null", ")", "{", "addQuorumListener", "(", "instanceName", ",", "listener", ")", ";", "}", "}", "private", "void", "scanQuorums", "(", ")", "{", "for", "(", "QuorumImpl", "quorum", ":", "quorums", ".", "values", "(", ")", ")", "{", "if", "(", "quorum", ".", "isHeartbeatAware", "(", ")", ")", "{", "this", ".", "heartbeatAware", "=", "true", ";", "}", "if", "(", "quorum", ".", "isPingAware", "(", ")", ")", "{", "this", ".", "pingAware", "=", "true", ";", "}", "}", "}", "private", "boolean", "isInactive", "(", ")", "{", "return", "quorums", ".", "isEmpty", "(", ")", ";", "}", "public", "void", "addQuorumListener", "(", "String", "name", ",", "QuorumListener", "listener", ")", "{", "eventService", ".", "registerLocalListener", "(", "SERVICE_NAME", ",", "name", ",", "listener", ")", ";", "}", "/**\n * Ensures that the quorum for the given operation is present. This requires that there is a quorum configured under the\n * name which is returned by the operation service.\n * This in turn requires that the operation is named and that the operation service is a {@link QuorumAwareService}.\n *\n * @param op the operation for which the quorum should be present\n * @throws QuorumException if the operation requires a quorum and the quorum is not present\n */", "public", "void", "ensureQuorumPresent", "(", "Operation", "op", ")", "{", "if", "(", "isInactive", "(", ")", ")", "{", "return", ";", "}", "QuorumImpl", "quorum", "=", "findQuorum", "(", "op", ")", ";", "if", "(", "quorum", "==", "null", ")", "{", "return", ";", "}", "quorum", ".", "ensureQuorumPresent", "(", "op", ")", ";", "}", "public", "void", "ensureQuorumPresent", "(", "String", "quorumName", ",", "QuorumType", "requiredQuorumPermissionType", ")", "{", "if", "(", "isInactive", "(", ")", "||", "quorumName", "==", "null", ")", "{", "return", ";", "}", "QuorumImpl", "definedQuorum", "=", "quorums", ".", "get", "(", "quorumName", ")", ";", "QuorumType", "definedQuorumType", "=", "definedQuorum", ".", "getConfig", "(", ")", ".", "getType", "(", ")", ";", "switch", "(", "requiredQuorumPermissionType", ")", "{", "case", "WRITE", ":", "if", "(", "definedQuorumType", ".", "equals", "(", "WRITE", ")", "||", "definedQuorumType", ".", "equals", "(", "READ_WRITE", ")", ")", "{", "definedQuorum", ".", "ensureQuorumPresent", "(", ")", ";", "}", "break", ";", "case", "READ", ":", "if", "(", "definedQuorumType", ".", "equals", "(", "READ", ")", "||", "definedQuorumType", ".", "equals", "(", "READ_WRITE", ")", ")", "{", "definedQuorum", ".", "ensureQuorumPresent", "(", ")", ";", "}", "break", ";", "case", "READ_WRITE", ":", "if", "(", "definedQuorumType", ".", "equals", "(", "READ_WRITE", ")", ")", "{", "definedQuorum", ".", "ensureQuorumPresent", "(", ")", ";", "}", "break", ";", "default", ":", "throw", "new", "IllegalStateException", "(", "\"", "Unhandled quorum type: ", "\"", "+", "requiredQuorumPermissionType", ")", ";", "}", "}", "/**\n * Returns a {@link QuorumImpl} for the given operation. The operation should be named and the operation service should\n * be a {@link QuorumAwareService}. This service will then return the quorum configured under the name returned by the\n * operation service.\n *\n * @param op the operation for which the Quorum should be returned\n * @return the quorum\n */", "private", "QuorumImpl", "findQuorum", "(", "Operation", "op", ")", "{", "if", "(", "!", "isNamedOperation", "(", "op", ")", "||", "!", "isQuorumAware", "(", "op", ")", ")", "{", "return", "null", ";", "}", "String", "quorumName", "=", "getQuorumName", "(", "op", ")", ";", "if", "(", "quorumName", "==", "null", ")", "{", "return", "null", ";", "}", "return", "quorums", ".", "get", "(", "quorumName", ")", ";", "}", "private", "String", "getQuorumName", "(", "Operation", "op", ")", "{", "QuorumAwareService", "service", ";", "if", "(", "op", "instanceof", "ServiceNamespaceAware", ")", "{", "ServiceNamespace", "serviceNamespace", "=", "(", "(", "ServiceNamespaceAware", ")", "op", ")", ".", "getServiceNamespace", "(", ")", ";", "service", "=", "nodeEngine", ".", "getService", "(", "serviceNamespace", ".", "getServiceName", "(", ")", ")", ";", "}", "else", "{", "service", "=", "op", ".", "getService", "(", ")", ";", "}", "String", "name", "=", "(", "(", "NamedOperation", ")", "op", ")", ".", "getName", "(", ")", ";", "return", "service", ".", "getQuorumName", "(", "name", ")", ";", "}", "private", "boolean", "isQuorumAware", "(", "Operation", "op", ")", "{", "return", "op", ".", "getService", "(", ")", "instanceof", "QuorumAwareService", ";", "}", "private", "boolean", "isNamedOperation", "(", "Operation", "op", ")", "{", "return", "op", "instanceof", "NamedOperation", ";", "}", "@", "Override", "public", "void", "dispatchEvent", "(", "QuorumEvent", "event", ",", "QuorumListener", "listener", ")", "{", "listener", ".", "onChange", "(", "event", ")", ";", "}", "@", "Override", "public", "void", "memberAdded", "(", "MembershipServiceEvent", "event", ")", "{", "if", "(", "isInactive", "(", ")", ")", "{", "return", ";", "}", "nodeEngine", ".", "getExecutionService", "(", ")", ".", "execute", "(", "QUORUM_EXECUTOR", ",", "new", "UpdateQuorums", "(", "event", ")", ")", ";", "}", "@", "Override", "public", "void", "memberRemoved", "(", "MembershipServiceEvent", "event", ")", "{", "if", "(", "isInactive", "(", ")", ")", "{", "return", ";", "}", "nodeEngine", ".", "getExecutionService", "(", ")", ".", "execute", "(", "QUORUM_EXECUTOR", ",", "new", "UpdateQuorums", "(", "event", ")", ")", ";", "}", "@", "Override", "public", "void", "memberAttributeChanged", "(", "MemberAttributeServiceEvent", "event", ")", "{", "}", "@", "Override", "public", "Quorum", "getQuorum", "(", "String", "quorumName", ")", "{", "checkNotNull", "(", "quorumName", ",", "\"", "quorumName cannot be null!", "\"", ")", ";", "Quorum", "quorum", "=", "quorums", ".", "get", "(", "quorumName", ")", ";", "if", "(", "quorum", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"", "No quorum configuration named [ ", "\"", "+", "quorumName", "+", "\"", " ] is found!", "\"", ")", ";", "}", "return", "quorum", ";", "}", "@", "Override", "public", "void", "onHeartbeat", "(", "Member", "member", ",", "long", "timestamp", ")", "{", "if", "(", "isInactive", "(", ")", "||", "!", "heartbeatAware", ")", "{", "return", ";", "}", "nodeEngine", ".", "getExecutionService", "(", ")", ".", "execute", "(", "QUORUM_EXECUTOR", ",", "new", "OnHeartbeat", "(", "member", ",", "timestamp", ")", ")", ";", "}", "@", "Override", "public", "void", "onPingLost", "(", "Member", "member", ")", "{", "if", "(", "isInactive", "(", ")", "||", "!", "pingAware", ")", "{", "return", ";", "}", "nodeEngine", ".", "getExecutionService", "(", ")", ".", "execute", "(", "QUORUM_EXECUTOR", ",", "new", "OnPing", "(", "member", ",", "false", ")", ")", ";", "}", "@", "Override", "public", "void", "onPingRestored", "(", "Member", "member", ")", "{", "if", "(", "isInactive", "(", ")", "||", "!", "pingAware", ")", "{", "return", ";", "}", "nodeEngine", ".", "getExecutionService", "(", ")", ".", "execute", "(", "QUORUM_EXECUTOR", ",", "new", "OnPing", "(", "member", ",", "true", ")", ")", ";", "}", "private", "class", "UpdateQuorums", "implements", "Runnable", "{", "private", "final", "MembershipEvent", "event", ";", "UpdateQuorums", "(", ")", "{", "this", ".", "event", "=", "null", ";", "}", "UpdateQuorums", "(", "MembershipEvent", "event", ")", "{", "this", ".", "event", "=", "event", ";", "}", "@", "Override", "public", "void", "run", "(", ")", "{", "ClusterService", "clusterService", "=", "nodeEngine", ".", "getClusterService", "(", ")", ";", "Collection", "<", "Member", ">", "members", "=", "clusterService", ".", "getMembers", "(", "MemberSelectors", ".", "DATA_MEMBER_SELECTOR", ")", ";", "for", "(", "QuorumImpl", "quorum", ":", "quorums", ".", "values", "(", ")", ")", "{", "if", "(", "event", "!=", "null", ")", "{", "switch", "(", "event", ".", "getEventType", "(", ")", ")", "{", "case", "MembershipEvent", ".", "MEMBER_ADDED", ":", "quorum", ".", "onMemberAdded", "(", "event", ")", ";", "break", ";", "case", "MembershipEvent", ".", "MEMBER_REMOVED", ":", "quorum", ".", "onMemberRemoved", "(", "event", ")", ";", "break", ";", "default", ":", "break", ";", "}", "}", "quorum", ".", "update", "(", "members", ")", ";", "}", "}", "}", "private", "class", "OnHeartbeat", "implements", "Runnable", "{", "private", "final", "Member", "member", ";", "private", "final", "long", "timestamp", ";", "OnHeartbeat", "(", "Member", "member", ",", "long", "timestamp", ")", "{", "this", ".", "member", "=", "member", ";", "this", ".", "timestamp", "=", "timestamp", ";", "}", "@", "Override", "public", "void", "run", "(", ")", "{", "ClusterService", "clusterService", "=", "nodeEngine", ".", "getClusterService", "(", ")", ";", "Collection", "<", "Member", ">", "members", "=", "clusterService", ".", "getMembers", "(", "MemberSelectors", ".", "DATA_MEMBER_SELECTOR", ")", ";", "for", "(", "QuorumImpl", "quorum", ":", "quorums", ".", "values", "(", ")", ")", "{", "quorum", ".", "onHeartbeat", "(", "member", ",", "timestamp", ")", ";", "quorum", ".", "update", "(", "members", ")", ";", "}", "}", "}", "private", "class", "OnPing", "implements", "Runnable", "{", "private", "final", "Member", "member", ";", "private", "final", "boolean", "successful", ";", "OnPing", "(", "Member", "member", ",", "boolean", "successful", ")", "{", "this", ".", "member", "=", "member", ";", "this", ".", "successful", "=", "successful", ";", "}", "@", "Override", "public", "void", "run", "(", ")", "{", "ClusterService", "clusterService", "=", "nodeEngine", ".", "getClusterService", "(", ")", ";", "Collection", "<", "Member", ">", "members", "=", "clusterService", ".", "getMembers", "(", "MemberSelectors", ".", "DATA_MEMBER_SELECTOR", ")", ";", "for", "(", "QuorumImpl", "quorum", ":", "quorums", ".", "values", "(", ")", ")", "{", "quorum", ".", "onPing", "(", "member", ",", "successful", ")", ";", "quorum", ".", "update", "(", "members", ")", ";", "}", "}", "}", "}" ]
Service containing logic for cluster quorum.
[ "Service", "containing", "logic", "for", "cluster", "quorum", "." ]
[ "// true when at least one configured quorum implementation is HeartbeatAware", "// true when at least one configured quorum implementation is PingAware", "// before starting, no quorums are used, just QuorumService dependency is provided to services which depend on it", "// so it's safe to initialize quorums here (and we have ClusterService already constructed)", "// single thread quorum executor", "// scan quorums for heartbeat-aware and ping-aware implementations and set corresponding flags", "// nop", "// MemberAttributeServiceEvent does NOT contain set of members", "// They cannot change quorum state", "// nop" ]
[ { "param": "EventPublishingService<QuorumEvent, QuorumListener>, MembershipAwareService,\n QuorumService, HeartbeatAware, PingAware", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "EventPublishingService<QuorumEvent, QuorumListener>, MembershipAwareService,\n QuorumService, HeartbeatAware, PingAware", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
21
2,794
91
e6e8cdb07b03810e2e3e03374a0144d450f5a672
guillermo20/fermat
P2P/library/api/fermat-p2p-api/src/main/java/com/bitdubai/fermat_p2p_api/layer/all_definition/common/network_services/template/structure/AbstractCommunicationRegistrationProcessNetworkServiceAgent.java
[ "MIT" ]
Java
AbstractCommunicationRegistrationProcessNetworkServiceAgent
/** * The Class <code>com.bitdubai.fermat_p2p_api.layer.all_definition.common.network_services.template.structure.AbstractCommunicationRegistrationProcessNetworkServiceAgent</code> * contains all the basic functionality of a CommunicationRegistrationProcessNetworkServiceAgent. * * The method <code>registrationProcess</code> can be override to modify its behavior. * * Created by lnacosta - ([email protected]) on 30/10/15. * * @version 1.0 * @since Java JDK 1.7 */
The method registrationProcess can be override to modify its behavior.
[ "The", "method", "registrationProcess", "can", "be", "override", "to", "modify", "its", "behavior", "." ]
public abstract class AbstractCommunicationRegistrationProcessNetworkServiceAgent extends FermatAgent { /* * Represent the sleep time for the read or send (5000 milliseconds) */ private static final long SLEEP_TIME = 5000; private static final long MAX_SLEEP_TIME = 20000; private final Thread agentThread; private final AbstractNetworkService networkServicePluginRoot ; private final CommunicationsClientConnection communicationsClientConnection; /** * Constructor with parameters. * * @param networkServicePluginRoot pluginRoot of the network service. * @param communicationsClientConnection communication client connection instance. */ public AbstractCommunicationRegistrationProcessNetworkServiceAgent(final AbstractNetworkService networkServicePluginRoot , final CommunicationsClientConnection communicationsClientConnection) { this.networkServicePluginRoot = networkServicePluginRoot ; this.communicationsClientConnection = communicationsClientConnection; this.status = AgentStatus.CREATED; this.agentThread = new Thread(new Runnable() { @Override public void run() { while (isRunning()) registrationProcess(); } }); } @Override public final synchronized void start() { this.agentThread.start(); this.status = AgentStatus.STARTED; } @Override public final void stop() { this.agentThread.interrupt(); this.status = AgentStatus.STOPPED; } protected void registrationProcess() { try { if (communicationsClientConnection.isRegister() && !networkServicePluginRoot.isRegister()){ //Construct my profile and register me PlatformComponentProfile platformComponentProfile = communicationsClientConnection.constructPlatformComponentProfileFactory( networkServicePluginRoot.getIdentityPublicKey(), networkServicePluginRoot.getAlias().toLowerCase(), networkServicePluginRoot.getName(), networkServicePluginRoot.getNetworkServiceType(), networkServicePluginRoot.getPlatformComponentType(), networkServicePluginRoot.getExtraData() ); // Register me communicationsClientConnection.registerComponentForCommunication(networkServicePluginRoot.getNetworkServiceType(), platformComponentProfile); // Configure my new profile networkServicePluginRoot.setPlatformComponentProfilePluginRoot(platformComponentProfile); //Initialize the connection manager networkServicePluginRoot.initializeCommunicationNetworkServiceConnectionManager(); // Stop the agent this.status = AgentStatus.STOPPED; } else if (!networkServicePluginRoot.isRegister()){ try { Thread.sleep(AbstractCommunicationRegistrationProcessNetworkServiceAgent.SLEEP_TIME); } catch (InterruptedException e) { e.printStackTrace(); this.status = AgentStatus.STOPPED; } } // TODO add better exception control here. } catch (Exception e) { try { e.printStackTrace(); Thread.sleep(AbstractCommunicationRegistrationProcessNetworkServiceAgent.MAX_SLEEP_TIME); } catch (InterruptedException e1) { e1.printStackTrace(); this.status = AgentStatus.STOPPED; } } } }
[ "public", "abstract", "class", "AbstractCommunicationRegistrationProcessNetworkServiceAgent", "extends", "FermatAgent", "{", "/*\n * Represent the sleep time for the read or send (5000 milliseconds)\n */", "private", "static", "final", "long", "SLEEP_TIME", "=", "5000", ";", "private", "static", "final", "long", "MAX_SLEEP_TIME", "=", "20000", ";", "private", "final", "Thread", "agentThread", ";", "private", "final", "AbstractNetworkService", "networkServicePluginRoot", ";", "private", "final", "CommunicationsClientConnection", "communicationsClientConnection", ";", "/**\n * Constructor with parameters.\n *\n * @param networkServicePluginRoot pluginRoot of the network service.\n * @param communicationsClientConnection communication client connection instance.\n */", "public", "AbstractCommunicationRegistrationProcessNetworkServiceAgent", "(", "final", "AbstractNetworkService", "networkServicePluginRoot", ",", "final", "CommunicationsClientConnection", "communicationsClientConnection", ")", "{", "this", ".", "networkServicePluginRoot", "=", "networkServicePluginRoot", ";", "this", ".", "communicationsClientConnection", "=", "communicationsClientConnection", ";", "this", ".", "status", "=", "AgentStatus", ".", "CREATED", ";", "this", ".", "agentThread", "=", "new", "Thread", "(", "new", "Runnable", "(", ")", "{", "@", "Override", "public", "void", "run", "(", ")", "{", "while", "(", "isRunning", "(", ")", ")", "registrationProcess", "(", ")", ";", "}", "}", ")", ";", "}", "@", "Override", "public", "final", "synchronized", "void", "start", "(", ")", "{", "this", ".", "agentThread", ".", "start", "(", ")", ";", "this", ".", "status", "=", "AgentStatus", ".", "STARTED", ";", "}", "@", "Override", "public", "final", "void", "stop", "(", ")", "{", "this", ".", "agentThread", ".", "interrupt", "(", ")", ";", "this", ".", "status", "=", "AgentStatus", ".", "STOPPED", ";", "}", "protected", "void", "registrationProcess", "(", ")", "{", "try", "{", "if", "(", "communicationsClientConnection", ".", "isRegister", "(", ")", "&&", "!", "networkServicePluginRoot", ".", "isRegister", "(", ")", ")", "{", "PlatformComponentProfile", "platformComponentProfile", "=", "communicationsClientConnection", ".", "constructPlatformComponentProfileFactory", "(", "networkServicePluginRoot", ".", "getIdentityPublicKey", "(", ")", ",", "networkServicePluginRoot", ".", "getAlias", "(", ")", ".", "toLowerCase", "(", ")", ",", "networkServicePluginRoot", ".", "getName", "(", ")", ",", "networkServicePluginRoot", ".", "getNetworkServiceType", "(", ")", ",", "networkServicePluginRoot", ".", "getPlatformComponentType", "(", ")", ",", "networkServicePluginRoot", ".", "getExtraData", "(", ")", ")", ";", "communicationsClientConnection", ".", "registerComponentForCommunication", "(", "networkServicePluginRoot", ".", "getNetworkServiceType", "(", ")", ",", "platformComponentProfile", ")", ";", "networkServicePluginRoot", ".", "setPlatformComponentProfilePluginRoot", "(", "platformComponentProfile", ")", ";", "networkServicePluginRoot", ".", "initializeCommunicationNetworkServiceConnectionManager", "(", ")", ";", "this", ".", "status", "=", "AgentStatus", ".", "STOPPED", ";", "}", "else", "if", "(", "!", "networkServicePluginRoot", ".", "isRegister", "(", ")", ")", "{", "try", "{", "Thread", ".", "sleep", "(", "AbstractCommunicationRegistrationProcessNetworkServiceAgent", ".", "SLEEP_TIME", ")", ";", "}", "catch", "(", "InterruptedException", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "this", ".", "status", "=", "AgentStatus", ".", "STOPPED", ";", "}", "}", "}", "catch", "(", "Exception", "e", ")", "{", "try", "{", "e", ".", "printStackTrace", "(", ")", ";", "Thread", ".", "sleep", "(", "AbstractCommunicationRegistrationProcessNetworkServiceAgent", ".", "MAX_SLEEP_TIME", ")", ";", "}", "catch", "(", "InterruptedException", "e1", ")", "{", "e1", ".", "printStackTrace", "(", ")", ";", "this", ".", "status", "=", "AgentStatus", ".", "STOPPED", ";", "}", "}", "}", "}" ]
The Class <code>com.bitdubai.fermat_p2p_api.layer.all_definition.common.network_services.template.structure.AbstractCommunicationRegistrationProcessNetworkServiceAgent</code> contains all the basic functionality of a CommunicationRegistrationProcessNetworkServiceAgent.
[ "The", "Class", "<code", ">", "com", ".", "bitdubai", ".", "fermat_p2p_api", ".", "layer", ".", "all_definition", ".", "common", ".", "network_services", ".", "template", ".", "structure", ".", "AbstractCommunicationRegistrationProcessNetworkServiceAgent<", "/", "code", ">", "contains", "all", "the", "basic", "functionality", "of", "a", "CommunicationRegistrationProcessNetworkServiceAgent", "." ]
[ "//Construct my profile and register me", "// Register me", "// Configure my new profile", "//Initialize the connection manager", "// Stop the agent", "// TODO add better exception control here." ]
[ { "param": "FermatAgent", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "FermatAgent", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
17
620
121
a8dc1118a3e00931faa6db226fdaf2f5f346eb5d
curiosity-ai/tesserae
Tesserae/src/Helpers/ReadOnlyObservable`1.cs
[ "MIT" ]
C#
ReadOnlyObservable
/// <summary> /// Enables monitoring of changes for a variable of type T (this class is for listeners only, if updating the value is required then the SettableObserver should be used) /// </summary> /// <typeparam name="T">An immutable type to be observed. Be careful with non-imutable types, as they may be changed in ways that will not be repoted here</typeparam>
Enables monitoring of changes for a variable of type T (this class is for listeners only, if updating the value is required then the SettableObserver should be used)
[ "Enables", "monitoring", "of", "changes", "for", "a", "variable", "of", "type", "T", "(", "this", "class", "is", "for", "listeners", "only", "if", "updating", "the", "value", "is", "required", "then", "the", "SettableObserver", "should", "be", "used", ")" ]
public abstract class ReadOnlyObservable<T> : IObservable<T> { private T _value; private IEqualityComparer<T> _comparer; private double _refreshTimeout; private double _refreshDelay = 1; public double Delay { get => _refreshDelay; set => _refreshDelay = value; } protected ReadOnlyObservable(T value = default, IEqualityComparer<T> comparer = null) { _value = value; _comparer = comparer ?? EqualityComparer<T>.Default; } private event ObservableEvent.ValueChanged<T> ValueChanged; public void Observe(ObservableEvent.ValueChanged<T> valueGetter) => Observe(valueGetter, callbackImmediately: true); public void ObserveFutureChanges(ObservableEvent.ValueChanged<T> valueGetter) => Observe(valueGetter, callbackImmediately: false); private void Observe(ObservableEvent.ValueChanged<T> valueGetter, bool callbackImmediately) { ValueChanged += valueGetter; if (callbackImmediately) { valueGetter(Value); } } public void StopObserving(ObservableEvent.ValueChanged<T> valueGetter) => ValueChanged -= valueGetter; public T Value { get => _value; protected set { if (!_comparer.Equals(_value, value)) { _value = value; RaiseOnValueChanged(); } } } protected void RaiseOnValueChanged() { window.clearTimeout(_refreshTimeout); _refreshTimeout = window.setTimeout((_) => { ValueChanged?.Invoke(_value); }, _refreshDelay); } }
[ "public", "abstract", "class", "ReadOnlyObservable", "<", "T", ">", ":", "IObservable", "<", "T", ">", "{", "private", "T", "_value", ";", "private", "IEqualityComparer", "<", "T", ">", "_comparer", ";", "private", "double", "_refreshTimeout", ";", "private", "double", "_refreshDelay", "=", "1", ";", "public", "double", "Delay", "{", "get", "=>", "_refreshDelay", ";", "set", "=>", "_refreshDelay", "=", "value", ";", "}", "protected", "ReadOnlyObservable", "(", "T", "value", "=", "default", ",", "IEqualityComparer", "<", "T", ">", "comparer", "=", "null", ")", "{", "_value", "=", "value", ";", "_comparer", "=", "comparer", "??", "EqualityComparer", "<", "T", ">", ".", "Default", ";", "}", "private", "event", "ObservableEvent", ".", "ValueChanged", "<", "T", ">", "ValueChanged", ";", "public", "void", "Observe", "(", "ObservableEvent", ".", "ValueChanged", "<", "T", ">", "valueGetter", ")", "=>", "Observe", "(", "valueGetter", ",", "callbackImmediately", ":", "true", ")", ";", "public", "void", "ObserveFutureChanges", "(", "ObservableEvent", ".", "ValueChanged", "<", "T", ">", "valueGetter", ")", "=>", "Observe", "(", "valueGetter", ",", "callbackImmediately", ":", "false", ")", ";", "private", "void", "Observe", "(", "ObservableEvent", ".", "ValueChanged", "<", "T", ">", "valueGetter", ",", "bool", "callbackImmediately", ")", "{", "ValueChanged", "+=", "valueGetter", ";", "if", "(", "callbackImmediately", ")", "{", "valueGetter", "(", "Value", ")", ";", "}", "}", "public", "void", "StopObserving", "(", "ObservableEvent", ".", "ValueChanged", "<", "T", ">", "valueGetter", ")", "=>", "ValueChanged", "-=", "valueGetter", ";", "public", "T", "Value", "{", "get", "=>", "_value", ";", "protected", "set", "{", "if", "(", "!", "_comparer", ".", "Equals", "(", "_value", ",", "value", ")", ")", "{", "_value", "=", "value", ";", "RaiseOnValueChanged", "(", ")", ";", "}", "}", "}", "protected", "void", "RaiseOnValueChanged", "(", ")", "{", "window", ".", "clearTimeout", "(", "_refreshTimeout", ")", ";", "_refreshTimeout", "=", "window", ".", "setTimeout", "(", "(", "_", ")", "=>", "{", "ValueChanged", "?", ".", "Invoke", "(", "_value", ")", ";", "}", ",", "_refreshDelay", ")", ";", "}", "}" ]
Enables monitoring of changes for a variable of type T (this class is for listeners only, if updating the value is required then the SettableObserver should be used)
[ "Enables", "monitoring", "of", "changes", "for", "a", "variable", "of", "type", "T", "(", "this", "class", "is", "for", "listeners", "only", "if", "updating", "the", "value", "is", "required", "then", "the", "SettableObserver", "should", "be", "used", ")" ]
[ "// 2020-07-01 DWR: This is an abstract class because it doesn't make sense to have an Observable that can never be updated, so it should always be derived from in order to be useful" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [ { "identifier": "typeparam", "docstring": "An immutable type to be observed. Be careful with non-imutable types, as they may be changed in ways that will not be repoted here", "docstring_tokens": [ "An", "immutable", "type", "to", "be", "observed", ".", "Be", "careful", "with", "non", "-", "imutable", "types", "as", "they", "may", "be", "changed", "in", "ways", "that", "will", "not", "be", "repoted", "here" ] } ] }
false
16
338
81
ad6bf47e3cd19c2f5974499cc9526578731abcc0
FTCTeam4592/Programming_2020
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/ConceptChangePIDController.java
[ "MIT" ]
Java
ConceptChangePIDController
/** * Created by tom on 9/26/17. * This assumes that you are using a REV Robotics Expansion Hub * as your DC motor controller. This op mode uses the extended/enhanced * PID-related functions of the DcMotorControllerEx class. * The REV Robotics Expansion Hub supports the extended motor controller * functions, but other controllers (such as the Modern Robotics and * Hitechnic DC Motor Controllers) do not. */
Created by tom on 9/26/17. This assumes that you are using a REV Robotics Expansion Hub as your DC motor controller. This op mode uses the extended/enhanced PID-related functions of the DcMotorControllerEx class. The REV Robotics Expansion Hub supports the extended motor controller functions, but other controllers (such as the Modern Robotics and Hitechnic DC Motor Controllers) do not.
[ "Created", "by", "tom", "on", "9", "/", "26", "/", "17", ".", "This", "assumes", "that", "you", "are", "using", "a", "REV", "Robotics", "Expansion", "Hub", "as", "your", "DC", "motor", "controller", ".", "This", "op", "mode", "uses", "the", "extended", "/", "enhanced", "PID", "-", "related", "functions", "of", "the", "DcMotorControllerEx", "class", ".", "The", "REV", "Robotics", "Expansion", "Hub", "supports", "the", "extended", "motor", "controller", "functions", "but", "other", "controllers", "(", "such", "as", "the", "Modern", "Robotics", "and", "Hitechnic", "DC", "Motor", "Controllers", ")", "do", "not", "." ]
@Autonomous(name="Concept: Change PID Controller", group = "Examples") public class ConceptChangePIDController extends LinearOpMode { // our DC motor. Robot3939 robot = new Robot3939(); public static final double NEW_P = 2.5; public static final double NEW_I = 0.1; public static final double NEW_D = 0.2; public static final double NEW_F = 0.0; public void runOpMode() { // get reference to DC motor. robot.initMotors(hardwareMap); // wait for start command. waitForStart(); // get a reference to the motor controller and cast it as an extended functionality controller. // we assume it's a REV Robotics Expansion Hub (which supports the extended controller functions). DcMotorControllerEx ExRL = (DcMotorControllerEx)robot.RL.getController(); DcMotorControllerEx ExRR = (DcMotorControllerEx)robot.RR.getController(); DcMotorControllerEx ExFL = (DcMotorControllerEx)robot.FL.getController(); DcMotorControllerEx ExFR = (DcMotorControllerEx)robot.FR.getController(); // get the port number of our configured motor. int indexRL = ((DcMotorEx)robot.RL).getPortNumber(); int indexRR = ((DcMotorEx)robot.RR).getPortNumber(); int indexFR = ((DcMotorEx)robot.FR).getPortNumber(); int indexFL = ((DcMotorEx)robot.FL).getPortNumber(); // // // get the PID coefficients for the RUN_USING_ENCODER modes. // PIDFCoefficients pidOrig = ExRL.getPIDFCoefficients(motorIndex, DcMotor.RunMode.RUN_USING_ENCODER); // change coefficients. PIDFCoefficients pidNew = new PIDFCoefficients(NEW_P, NEW_I, NEW_D, NEW_F); ExRL.setPIDFCoefficients(indexRL, DcMotor.RunMode.RUN_USING_ENCODER, pidNew); ExRR.setPIDFCoefficients(indexRR, DcMotor.RunMode.RUN_USING_ENCODER, pidNew); ExFR.setPIDFCoefficients(indexFR, DcMotor.RunMode.RUN_USING_ENCODER, pidNew); ExFL.setPIDFCoefficients(indexFL, DcMotor.RunMode.RUN_USING_ENCODER, pidNew); // // // re-read coefficients and verify change. PIDFCoefficients modRL = ExRL.getPIDFCoefficients(indexRL, DcMotor.RunMode.RUN_USING_ENCODER); PIDFCoefficients modRR = ExRR.getPIDFCoefficients(indexRR, DcMotor.RunMode.RUN_USING_ENCODER); PIDFCoefficients modFR = ExFR.getPIDFCoefficients(indexFR, DcMotor.RunMode.RUN_USING_ENCODER); PIDFCoefficients modFL = ExFL.getPIDFCoefficients(indexFL, DcMotor.RunMode.RUN_USING_ENCODER); telemetry.addData("Runtime", "%.03f", getRuntime()); telemetry.addData("P,I,D (modified)", "%.04f, %.04f, %.04f", modRL.p, modRL.i, modRL.d); telemetry.update(); // display info to user. if(opModeIsActive()) { ExRL.setMotorMode(indexRL, DcMotor.RunMode.RUN_USING_ENCODER); ExRR.setMotorMode(indexRR, DcMotor.RunMode.RUN_USING_ENCODER); ExFL.setMotorMode(indexFL, DcMotor.RunMode.RUN_USING_ENCODER); ExFR.setMotorMode(indexFR, DcMotor.RunMode.RUN_USING_ENCODER); ExRL.setMotorTargetPosition(indexRL, 1000); ExRR.setMotorTargetPosition(indexRR, 1000); ExFL.setMotorTargetPosition(indexFL, 1000); ExFR.setMotorTargetPosition(indexFR, 1000); ExRL.setMotorMode(indexRL, DcMotor.RunMode.RUN_TO_POSITION); ExRR.setMotorMode(indexRR, DcMotor.RunMode.RUN_TO_POSITION); ExFL.setMotorMode(indexFL, DcMotor.RunMode.RUN_TO_POSITION); ExFR.setMotorMode(indexFR, DcMotor.RunMode.RUN_TO_POSITION); ExRL.setMotorPower(indexRL, 1); ExRR.setMotorPower(indexRR, 1); ExFL.setMotorPower(indexFL, 1); ExFR.setMotorPower(indexFR, 1); while(ExRL.isBusy(indexRL) || ExRR.isMotorEnabled(indexRR) || ExFL.isBusy(indexFL) || ExFR.isMotorEnabled(indexFR)) { } telemetry.addData("Runtime", "%.03f", getRuntime()); telemetry.addData("P,I,D (modified)", "%.04f, %.04f, %.04f", modRL.p, modRL.i, modRL.d); telemetry.update(); } } }
[ "@", "Autonomous", "(", "name", "=", "\"", "Concept: Change PID Controller", "\"", ",", "group", "=", "\"", "Examples", "\"", ")", "public", "class", "ConceptChangePIDController", "extends", "LinearOpMode", "{", "Robot3939", "robot", "=", "new", "Robot3939", "(", ")", ";", "public", "static", "final", "double", "NEW_P", "=", "2.5", ";", "public", "static", "final", "double", "NEW_I", "=", "0.1", ";", "public", "static", "final", "double", "NEW_D", "=", "0.2", ";", "public", "static", "final", "double", "NEW_F", "=", "0.0", ";", "public", "void", "runOpMode", "(", ")", "{", "robot", ".", "initMotors", "(", "hardwareMap", ")", ";", "waitForStart", "(", ")", ";", "DcMotorControllerEx", "ExRL", "=", "(", "DcMotorControllerEx", ")", "robot", ".", "RL", ".", "getController", "(", ")", ";", "DcMotorControllerEx", "ExRR", "=", "(", "DcMotorControllerEx", ")", "robot", ".", "RR", ".", "getController", "(", ")", ";", "DcMotorControllerEx", "ExFL", "=", "(", "DcMotorControllerEx", ")", "robot", ".", "FL", ".", "getController", "(", ")", ";", "DcMotorControllerEx", "ExFR", "=", "(", "DcMotorControllerEx", ")", "robot", ".", "FR", ".", "getController", "(", ")", ";", "int", "indexRL", "=", "(", "(", "DcMotorEx", ")", "robot", ".", "RL", ")", ".", "getPortNumber", "(", ")", ";", "int", "indexRR", "=", "(", "(", "DcMotorEx", ")", "robot", ".", "RR", ")", ".", "getPortNumber", "(", ")", ";", "int", "indexFR", "=", "(", "(", "DcMotorEx", ")", "robot", ".", "FR", ")", ".", "getPortNumber", "(", ")", ";", "int", "indexFL", "=", "(", "(", "DcMotorEx", ")", "robot", ".", "FL", ")", ".", "getPortNumber", "(", ")", ";", "PIDFCoefficients", "pidNew", "=", "new", "PIDFCoefficients", "(", "NEW_P", ",", "NEW_I", ",", "NEW_D", ",", "NEW_F", ")", ";", "ExRL", ".", "setPIDFCoefficients", "(", "indexRL", ",", "DcMotor", ".", "RunMode", ".", "RUN_USING_ENCODER", ",", "pidNew", ")", ";", "ExRR", ".", "setPIDFCoefficients", "(", "indexRR", ",", "DcMotor", ".", "RunMode", ".", "RUN_USING_ENCODER", ",", "pidNew", ")", ";", "ExFR", ".", "setPIDFCoefficients", "(", "indexFR", ",", "DcMotor", ".", "RunMode", ".", "RUN_USING_ENCODER", ",", "pidNew", ")", ";", "ExFL", ".", "setPIDFCoefficients", "(", "indexFL", ",", "DcMotor", ".", "RunMode", ".", "RUN_USING_ENCODER", ",", "pidNew", ")", ";", "PIDFCoefficients", "modRL", "=", "ExRL", ".", "getPIDFCoefficients", "(", "indexRL", ",", "DcMotor", ".", "RunMode", ".", "RUN_USING_ENCODER", ")", ";", "PIDFCoefficients", "modRR", "=", "ExRR", ".", "getPIDFCoefficients", "(", "indexRR", ",", "DcMotor", ".", "RunMode", ".", "RUN_USING_ENCODER", ")", ";", "PIDFCoefficients", "modFR", "=", "ExFR", ".", "getPIDFCoefficients", "(", "indexFR", ",", "DcMotor", ".", "RunMode", ".", "RUN_USING_ENCODER", ")", ";", "PIDFCoefficients", "modFL", "=", "ExFL", ".", "getPIDFCoefficients", "(", "indexFL", ",", "DcMotor", ".", "RunMode", ".", "RUN_USING_ENCODER", ")", ";", "telemetry", ".", "addData", "(", "\"", "Runtime", "\"", ",", "\"", "%.03f", "\"", ",", "getRuntime", "(", ")", ")", ";", "telemetry", ".", "addData", "(", "\"", "P,I,D (modified)", "\"", ",", "\"", "%.04f, %.04f, %.04f", "\"", ",", "modRL", ".", "p", ",", "modRL", ".", "i", ",", "modRL", ".", "d", ")", ";", "telemetry", ".", "update", "(", ")", ";", "if", "(", "opModeIsActive", "(", ")", ")", "{", "ExRL", ".", "setMotorMode", "(", "indexRL", ",", "DcMotor", ".", "RunMode", ".", "RUN_USING_ENCODER", ")", ";", "ExRR", ".", "setMotorMode", "(", "indexRR", ",", "DcMotor", ".", "RunMode", ".", "RUN_USING_ENCODER", ")", ";", "ExFL", ".", "setMotorMode", "(", "indexFL", ",", "DcMotor", ".", "RunMode", ".", "RUN_USING_ENCODER", ")", ";", "ExFR", ".", "setMotorMode", "(", "indexFR", ",", "DcMotor", ".", "RunMode", ".", "RUN_USING_ENCODER", ")", ";", "ExRL", ".", "setMotorTargetPosition", "(", "indexRL", ",", "1000", ")", ";", "ExRR", ".", "setMotorTargetPosition", "(", "indexRR", ",", "1000", ")", ";", "ExFL", ".", "setMotorTargetPosition", "(", "indexFL", ",", "1000", ")", ";", "ExFR", ".", "setMotorTargetPosition", "(", "indexFR", ",", "1000", ")", ";", "ExRL", ".", "setMotorMode", "(", "indexRL", ",", "DcMotor", ".", "RunMode", ".", "RUN_TO_POSITION", ")", ";", "ExRR", ".", "setMotorMode", "(", "indexRR", ",", "DcMotor", ".", "RunMode", ".", "RUN_TO_POSITION", ")", ";", "ExFL", ".", "setMotorMode", "(", "indexFL", ",", "DcMotor", ".", "RunMode", ".", "RUN_TO_POSITION", ")", ";", "ExFR", ".", "setMotorMode", "(", "indexFR", ",", "DcMotor", ".", "RunMode", ".", "RUN_TO_POSITION", ")", ";", "ExRL", ".", "setMotorPower", "(", "indexRL", ",", "1", ")", ";", "ExRR", ".", "setMotorPower", "(", "indexRR", ",", "1", ")", ";", "ExFL", ".", "setMotorPower", "(", "indexFL", ",", "1", ")", ";", "ExFR", ".", "setMotorPower", "(", "indexFR", ",", "1", ")", ";", "while", "(", "ExRL", ".", "isBusy", "(", "indexRL", ")", "||", "ExRR", ".", "isMotorEnabled", "(", "indexRR", ")", "||", "ExFL", ".", "isBusy", "(", "indexFL", ")", "||", "ExFR", ".", "isMotorEnabled", "(", "indexFR", ")", ")", "{", "}", "telemetry", ".", "addData", "(", "\"", "Runtime", "\"", ",", "\"", "%.03f", "\"", ",", "getRuntime", "(", ")", ")", ";", "telemetry", ".", "addData", "(", "\"", "P,I,D (modified)", "\"", ",", "\"", "%.04f, %.04f, %.04f", "\"", ",", "modRL", ".", "p", ",", "modRL", ".", "i", ",", "modRL", ".", "d", ")", ";", "telemetry", ".", "update", "(", ")", ";", "}", "}", "}" ]
Created by tom on 9/26/17.
[ "Created", "by", "tom", "on", "9", "/", "26", "/", "17", "." ]
[ "// our DC motor.", "// get reference to DC motor.", "// wait for start command.", "// get a reference to the motor controller and cast it as an extended functionality controller.", "// we assume it's a REV Robotics Expansion Hub (which supports the extended controller functions).", "// get the port number of our configured motor.", "//", "// // get the PID coefficients for the RUN_USING_ENCODER modes.", "// PIDFCoefficients pidOrig = ExRL.getPIDFCoefficients(motorIndex, DcMotor.RunMode.RUN_USING_ENCODER);", "// change coefficients.", "//", "// // re-read coefficients and verify change.", "// display info to user." ]
[ { "param": "LinearOpMode", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "LinearOpMode", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
14
1,087
97
4b4bfe5775ed11328dca2648f0d0dc947ec2a51a
d4l3k/torchx
torchx/specs/api.py
[ "BSD-3-Clause" ]
Python
macros
Defines macros that can be used with ``Role.entrypoint`` and ``Role.args``. The macros will be substituted at runtime to their actual values. Available macros: 1. ``img_root`` - root directory of the pulled conatiner.image 2. ``base_img_root`` - root directory of the pulled container.base_image (resolves to "<NONE>" if no base_image set) 3. ``app_id`` - application id as assigned by the scheduler 4. ``replica_id`` - unique id for each instance of a replica of a Role, for instance a role with 3 replicas could have the 0, 1, 2 as replica ids. Note that when the container fails and is replaced, the new container will have the same ``replica_id`` as the one it is replacing. For instance if node 1 failed and was replaced by the scheduler the replacing node will also have ``replica_id=1``. Example: :: # runs: hello_world.py --app_id ${app_id} trainer = Role(name="trainer").runs("hello_world.py", "--app_id", macros.app_id) app = Application("train_app").of(trainer) app_handle = session.run(app, scheduler="local", cfg=RunConfig())
Available macros. 1. ``img_root`` - root directory of the pulled conatiner.image 2. ``base_img_root`` - root directory of the pulled container.base_image (resolves to "" if no base_image set) 3. ``app_id`` - application id as assigned by the scheduler 4. ``replica_id`` - unique id for each instance of a replica of a Role, for instance a role with 3 replicas could have the 0, 1, 2 as replica ids. Note that when the container fails and is replaced, the new container will have the same ``replica_id`` as the one it is replacing. For instance if node 1 failed and was replaced by the scheduler the replacing node will also have ``replica_id=1``.
[ "Available", "macros", ".", "1", ".", "`", "`", "img_root", "`", "`", "-", "root", "directory", "of", "the", "pulled", "conatiner", ".", "image", "2", ".", "`", "`", "base_img_root", "`", "`", "-", "root", "directory", "of", "the", "pulled", "container", ".", "base_image", "(", "resolves", "to", "\"", "\"", "if", "no", "base_image", "set", ")", "3", ".", "`", "`", "app_id", "`", "`", "-", "application", "id", "as", "assigned", "by", "the", "scheduler", "4", ".", "`", "`", "replica_id", "`", "`", "-", "unique", "id", "for", "each", "instance", "of", "a", "replica", "of", "a", "Role", "for", "instance", "a", "role", "with", "3", "replicas", "could", "have", "the", "0", "1", "2", "as", "replica", "ids", ".", "Note", "that", "when", "the", "container", "fails", "and", "is", "replaced", "the", "new", "container", "will", "have", "the", "same", "`", "`", "replica_id", "`", "`", "as", "the", "one", "it", "is", "replacing", ".", "For", "instance", "if", "node", "1", "failed", "and", "was", "replaced", "by", "the", "scheduler", "the", "replacing", "node", "will", "also", "have", "`", "`", "replica_id", "=", "1", "`", "`", "." ]
class macros: """ Defines macros that can be used with ``Role.entrypoint`` and ``Role.args``. The macros will be substituted at runtime to their actual values. Available macros: 1. ``img_root`` - root directory of the pulled conatiner.image 2. ``base_img_root`` - root directory of the pulled container.base_image (resolves to "<NONE>" if no base_image set) 3. ``app_id`` - application id as assigned by the scheduler 4. ``replica_id`` - unique id for each instance of a replica of a Role, for instance a role with 3 replicas could have the 0, 1, 2 as replica ids. Note that when the container fails and is replaced, the new container will have the same ``replica_id`` as the one it is replacing. For instance if node 1 failed and was replaced by the scheduler the replacing node will also have ``replica_id=1``. Example: :: # runs: hello_world.py --app_id ${app_id} trainer = Role(name="trainer").runs("hello_world.py", "--app_id", macros.app_id) app = Application("train_app").of(trainer) app_handle = session.run(app, scheduler="local", cfg=RunConfig()) """ img_root = "${img_root}" base_img_root = "${base_img_root}" app_id = "${app_id}" replica_id = "${replica_id}" @dataclass class Values: img_root: str app_id: str replica_id: str base_img_root: str = NONE def apply(self, role: "Role") -> "Role": """ apply applies the values to a copy the specified role and returns it. """ role = copy.deepcopy(role) role.args = [self.substitute(arg) for arg in role.args] role.env = {key: self.substitute(arg) for key, arg in role.env.items()} return role def substitute(self, arg: str) -> str: """ substitute applies the values to the template arg. """ return Template(arg).safe_substitute(**asdict(self))
[ "class", "macros", ":", "img_root", "=", "\"${img_root}\"", "base_img_root", "=", "\"${base_img_root}\"", "app_id", "=", "\"${app_id}\"", "replica_id", "=", "\"${replica_id}\"", "@", "dataclass", "class", "Values", ":", "img_root", ":", "str", "app_id", ":", "str", "replica_id", ":", "str", "base_img_root", ":", "str", "=", "NONE", "def", "apply", "(", "self", ",", "role", ":", "\"Role\"", ")", "->", "\"Role\"", ":", "\"\"\"\n apply applies the values to a copy the specified role and returns it.\n \"\"\"", "role", "=", "copy", ".", "deepcopy", "(", "role", ")", "role", ".", "args", "=", "[", "self", ".", "substitute", "(", "arg", ")", "for", "arg", "in", "role", ".", "args", "]", "role", ".", "env", "=", "{", "key", ":", "self", ".", "substitute", "(", "arg", ")", "for", "key", ",", "arg", "in", "role", ".", "env", ".", "items", "(", ")", "}", "return", "role", "def", "substitute", "(", "self", ",", "arg", ":", "str", ")", "->", "str", ":", "\"\"\"\n substitute applies the values to the template arg.\n \"\"\"", "return", "Template", "(", "arg", ")", ".", "safe_substitute", "(", "**", "asdict", "(", "self", ")", ")" ]
Defines macros that can be used with ``Role.entrypoint`` and ``Role.args``.
[ "Defines", "macros", "that", "can", "be", "used", "with", "`", "`", "Role", ".", "entrypoint", "`", "`", "and", "`", "`", "Role", ".", "args", "`", "`", "." ]
[ "\"\"\"\n Defines macros that can be used with ``Role.entrypoint`` and ``Role.args``.\n The macros will be substituted at runtime to their actual values.\n\n Available macros:\n\n 1. ``img_root`` - root directory of the pulled conatiner.image\n 2. ``base_img_root`` - root directory of the pulled container.base_image\n (resolves to \"<NONE>\" if no base_image set)\n 3. ``app_id`` - application id as assigned by the scheduler\n 4. ``replica_id`` - unique id for each instance of a replica of a Role,\n for instance a role with 3 replicas could have the 0, 1, 2\n as replica ids. Note that when the container fails and is\n replaced, the new container will have the same ``replica_id``\n as the one it is replacing. For instance if node 1 failed and\n was replaced by the scheduler the replacing node will also\n have ``replica_id=1``.\n\n Example:\n\n ::\n\n # runs: hello_world.py --app_id ${app_id}\n trainer = Role(name=\"trainer\").runs(\"hello_world.py\", \"--app_id\", macros.app_id)\n app = Application(\"train_app\").of(trainer)\n app_handle = session.run(app, scheduler=\"local\", cfg=RunConfig())\n\n \"\"\"", "\"\"\"\n apply applies the values to a copy the specified role and returns it.\n \"\"\"", "\"\"\"\n substitute applies the values to the template arg.\n \"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [ { "identifier": "#", "docstring": "hello_world.py --app_id ${app_id}\ntrainer = Role(name=\"trainer\").runs(\"hello_world.py\", \"--app_id\", macros.app_id)\napp = Application(\"train_app\").of(trainer)\napp_handle = session.run(app, scheduler=\"local\", cfg=RunConfig())", "docstring_tokens": [ "hello_world", ".", "py", "--", "app_id", "$", "{", "app_id", "}", "trainer", "=", "Role", "(", "name", "=", "\"", "trainer", "\"", ")", ".", "runs", "(", "\"", "hello_world", ".", "py", "\"", "\"", "--", "app_id", "\"", "macros", ".", "app_id", ")", "app", "=", "Application", "(", "\"", "train_app", "\"", ")", ".", "of", "(", "trainer", ")", "app_handle", "=", "session", ".", "run", "(", "app", "scheduler", "=", "\"", "local", "\"", "cfg", "=", "RunConfig", "()", ")" ] } ] }
false
15
485
289
8faa14680453f4cba05f49579c33502f679e5f98
minelytics/django-code-generator
django_genie/models.py
[ "MIT" ]
Python
Model
A class for receiving a model ... Attributes ---------- model : a model Methods ------- name(): returns the name of the model field_names(): returns a string of all forward field names on the model and its parents, excluding ManyToManyFields local_field_names(): returns a string of model field names concrete_field_names(): returns a string of all concrete field names on the model and its parents serializer_field_names(): removes unnecessary field names for serializers admin_field_names(): removes unnecessary field names for admin snake_case_name(): returns model name in snake case __str__(): string representation of Model class
A class for receiving a model Attributes model : a model Methods
[ "A", "class", "for", "receiving", "a", "model", "Attributes", "model", ":", "a", "model", "Methods" ]
class Model: """ A class for receiving a model ... Attributes ---------- model : a model Methods ------- name(): returns the name of the model field_names(): returns a string of all forward field names on the model and its parents, excluding ManyToManyFields local_field_names(): returns a string of model field names concrete_field_names(): returns a string of all concrete field names on the model and its parents serializer_field_names(): removes unnecessary field names for serializers admin_field_names(): removes unnecessary field names for admin snake_case_name(): returns model name in snake case __str__(): string representation of Model class """ def __init__(self, model): """ declares model parameter as self variable :param model: a model object :type model: model """ self.model = model @property def name(self): """ returns the name of the model :return: name :rtype: str """ return self.model._meta.object_name @property def field_names(self): """ returns a string of all forward field names on the model and its parents, excluding ManyToManyFields :return: model field names :rtype: str """ return get_field_names(self.model._meta.fields) @property def local_field_names(self): """ returns a string of model field names :return: model field names :rtype: str """ return get_field_names(self.model._meta.local_fields) @property def concrete_field_names(self): """ returns a string of all concrete field names on the model and its parents :return: model field names :rtype: str """ return get_field_names(self.model._meta.concrete_fields) @property def serializer_field_names(self): """ removes unnecessary field names for serializers :return: model field names :rtype: str """ return ", ".join([ "'{}'".format(x.name) for x in self.model._meta.fields if x.name not in ["created_at", "updated_at", "deleted_at"] ]) @property def admin_field_names(self): """ removes unnecessary field names for admin :return: model field names :rtype: str """ return ", ".join([ "'{}'".format(x.name) for x in self.model._meta.fields if x.name not in ["id", "created_at", "updated_at", "deleted_at", "created_by", "updated_by"] ]) @property def snake_case_name(self): """ returns model name in snake case :return: model field name :rtype: str """ return camel_case_to_spaces(self.name).replace(' ', '_') def __str__(self): """ string representation of Model class :return: model name :rtype: str """ return self.name
[ "class", "Model", ":", "def", "__init__", "(", "self", ",", "model", ")", ":", "\"\"\"\n declares model parameter as self variable\n\n :param model: a model object\n :type model: model\n \"\"\"", "self", ".", "model", "=", "model", "@", "property", "def", "name", "(", "self", ")", ":", "\"\"\"\n returns the name of the model\n\n :return: name\n :rtype: str\n \"\"\"", "return", "self", ".", "model", ".", "_meta", ".", "object_name", "@", "property", "def", "field_names", "(", "self", ")", ":", "\"\"\"\n returns a string of all forward field names on the model and its parents, excluding ManyToManyFields\n\n :return: model field names\n :rtype: str\n \"\"\"", "return", "get_field_names", "(", "self", ".", "model", ".", "_meta", ".", "fields", ")", "@", "property", "def", "local_field_names", "(", "self", ")", ":", "\"\"\"\n returns a string of model field names\n\n :return: model field names\n :rtype: str\n \"\"\"", "return", "get_field_names", "(", "self", ".", "model", ".", "_meta", ".", "local_fields", ")", "@", "property", "def", "concrete_field_names", "(", "self", ")", ":", "\"\"\"\n returns a string of all concrete field names on the model and its parents\n\n :return: model field names\n :rtype: str\n \"\"\"", "return", "get_field_names", "(", "self", ".", "model", ".", "_meta", ".", "concrete_fields", ")", "@", "property", "def", "serializer_field_names", "(", "self", ")", ":", "\"\"\"\n removes unnecessary field names for serializers\n\n :return: model field names\n :rtype: str\n \"\"\"", "return", "\", \"", ".", "join", "(", "[", "\"'{}'\"", ".", "format", "(", "x", ".", "name", ")", "for", "x", "in", "self", ".", "model", ".", "_meta", ".", "fields", "if", "x", ".", "name", "not", "in", "[", "\"created_at\"", ",", "\"updated_at\"", ",", "\"deleted_at\"", "]", "]", ")", "@", "property", "def", "admin_field_names", "(", "self", ")", ":", "\"\"\"\n removes unnecessary field names for admin\n\n :return: model field names\n :rtype: str\n \"\"\"", "return", "\", \"", ".", "join", "(", "[", "\"'{}'\"", ".", "format", "(", "x", ".", "name", ")", "for", "x", "in", "self", ".", "model", ".", "_meta", ".", "fields", "if", "x", ".", "name", "not", "in", "[", "\"id\"", ",", "\"created_at\"", ",", "\"updated_at\"", ",", "\"deleted_at\"", ",", "\"created_by\"", ",", "\"updated_by\"", "]", "]", ")", "@", "property", "def", "snake_case_name", "(", "self", ")", ":", "\"\"\"\n returns model name in snake case\n\n :return: model field name\n :rtype: str\n \"\"\"", "return", "camel_case_to_spaces", "(", "self", ".", "name", ")", ".", "replace", "(", "' '", ",", "'_'", ")", "def", "__str__", "(", "self", ")", ":", "\"\"\"\n string representation of Model class\n\n :return: model name\n :rtype: str\n \"\"\"", "return", "self", ".", "name" ]
A class for receiving a model ...
[ "A", "class", "for", "receiving", "a", "model", "..." ]
[ "\"\"\"\n A class for receiving a model\n\n ...\n\n Attributes\n ----------\n model : a model\n\n Methods\n -------\n name(): returns the name of the model\n field_names(): returns a string of all forward field names on the model and its parents, excluding ManyToManyFields\n local_field_names(): returns a string of model field names\n concrete_field_names(): returns a string of all concrete field names on the model and its parents\n serializer_field_names(): removes unnecessary field names for serializers\n admin_field_names(): removes unnecessary field names for admin\n snake_case_name(): returns model name in snake case\n __str__(): string representation of Model class\n \"\"\"", "\"\"\"\n declares model parameter as self variable\n\n :param model: a model object\n :type model: model\n \"\"\"", "\"\"\"\n returns the name of the model\n\n :return: name\n :rtype: str\n \"\"\"", "\"\"\"\n returns a string of all forward field names on the model and its parents, excluding ManyToManyFields\n\n :return: model field names\n :rtype: str\n \"\"\"", "\"\"\"\n returns a string of model field names\n\n :return: model field names\n :rtype: str\n \"\"\"", "\"\"\"\n returns a string of all concrete field names on the model and its parents\n\n :return: model field names\n :rtype: str\n \"\"\"", "\"\"\"\n removes unnecessary field names for serializers\n\n :return: model field names\n :rtype: str\n \"\"\"", "\"\"\"\n removes unnecessary field names for admin\n\n :return: model field names\n :rtype: str\n \"\"\"", "\"\"\"\n returns model name in snake case\n\n :return: model field name\n :rtype: str\n \"\"\"", "\"\"\"\n string representation of Model class\n\n :return: model name\n :rtype: str\n \"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
14
659
142
8c037d73f76cb0f80f7c6be8e0110a07f9cf59f4
gongchengshi/DotNet-Common.WPF
Common.WPF/DerivedProperty.cs
[ "MIT" ]
C#
Property
/// <summary> /// A generic databindable Property. This class exists for the following reasons: /// * Eliminate string binding of property names. /// * Support derived properties. /// /// Usage: /// Property&lt;int&gt; MyIntProperty = new Property&lt;int&gt;(); /// ... /// MyIntProperty.Value = 5; /// </summary>
A generic databindable Property. This class exists for the following reasons: Eliminate string binding of property names. Support derived properties. Property MyIntProperty = new Property(); MyIntProperty.Value = 5.
[ "A", "generic", "databindable", "Property", ".", "This", "class", "exists", "for", "the", "following", "reasons", ":", "Eliminate", "string", "binding", "of", "property", "names", ".", "Support", "derived", "properties", ".", "Property", "MyIntProperty", "=", "new", "Property", "()", ";", "MyIntProperty", ".", "Value", "=", "5", "." ]
public class Property<T> : IProperty { private static readonly bool _isClass = typeof(T).IsClass; public Property() { PropertyChanged += (s, e) => Changed(); } public Property(T value) : this() { _Value = value; } public T Value { get { return _Value; } set { if (_isClass) { if (ReferenceEquals(_Value, value)) { return; } if (value == null || _Value == null) { _Value = value; RaisePropertyChanged(); return; } } if (!value.Equals(_Value)) { _Value = value; RaisePropertyChanged(); } } } T _Value; public void RaisePropertyChanged() { PropertyChanged(this, new PropertyChangedEventArgs(PropertyConstants.ValueName)); } public event PropertyChangedEventHandler PropertyChanged; public event Action Changed = delegate { }; public override string ToString() { return _Value.ToString(); } }
[ "public", "class", "Property", "<", "T", ">", ":", "IProperty", "{", "private", "static", "readonly", "bool", "_isClass", "=", "typeof", "(", "T", ")", ".", "IsClass", ";", "public", "Property", "(", ")", "{", "PropertyChanged", "+=", "(", "s", ",", "e", ")", "=>", "Changed", "(", ")", ";", "}", "public", "Property", "(", "T", "value", ")", ":", "this", "(", ")", "{", "_Value", "=", "value", ";", "}", "public", "T", "Value", "{", "get", "{", "return", "_Value", ";", "}", "set", "{", "if", "(", "_isClass", ")", "{", "if", "(", "ReferenceEquals", "(", "_Value", ",", "value", ")", ")", "{", "return", ";", "}", "if", "(", "value", "==", "null", "||", "_Value", "==", "null", ")", "{", "_Value", "=", "value", ";", "RaisePropertyChanged", "(", ")", ";", "return", ";", "}", "}", "if", "(", "!", "value", ".", "Equals", "(", "_Value", ")", ")", "{", "_Value", "=", "value", ";", "RaisePropertyChanged", "(", ")", ";", "}", "}", "}", "T", "_Value", ";", "public", "void", "RaisePropertyChanged", "(", ")", "{", "PropertyChanged", "(", "this", ",", "new", "PropertyChangedEventArgs", "(", "PropertyConstants", ".", "ValueName", ")", ")", ";", "}", "public", "event", "PropertyChangedEventHandler", "PropertyChanged", ";", "public", "event", "Action", "Changed", "=", "delegate", "{", "}", ";", "public", "override", "string", "ToString", "(", ")", "{", "return", "_Value", ".", "ToString", "(", ")", ";", "}", "}" ]
A generic databindable Property.
[ "A", "generic", "databindable", "Property", "." ]
[ "// This class does not need to be IDisposable because it does not register for events", "// on outside objects. This is registering for its own event, and will get garbage", "// collected appropriately (because this object add the event will be an island).", "// Avoids boxing when using ReferenceEquals or comparing with null" ]
[ { "param": "IProperty", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "IProperty", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
14
225
81
05554be5eacf4645cadcea7c0aaac1734931080e
jonbleiberg88/mayacal
mayacal/utils/utils.py
[ "MIT" ]
Python
GregorianDate
Basic class to handle (proleptic) Gregorian calendar dates and conversions Note that this class uses the astronomical year convention for years before 1 CE, i.e. 1 BCE = 0, 2 BCE = -1, etc. Attributes: day (int): The day of the Gregorian calendar date month (int): The month number of the Gregorian calendar date year (int): The (astronomical) year number of the Gregorian calendar date
Basic class to handle (proleptic) Gregorian calendar dates and conversions Note that this class uses the astronomical year convention for years before 1 CE, i.e.
[ "Basic", "class", "to", "handle", "(", "proleptic", ")", "Gregorian", "calendar", "dates", "and", "conversions", "Note", "that", "this", "class", "uses", "the", "astronomical", "year", "convention", "for", "years", "before", "1", "CE", "i", ".", "e", "." ]
class GregorianDate: """Basic class to handle (proleptic) Gregorian calendar dates and conversions Note that this class uses the astronomical year convention for years before 1 CE, i.e. 1 BCE = 0, 2 BCE = -1, etc. Attributes: day (int): The day of the Gregorian calendar date month (int): The month number of the Gregorian calendar date year (int): The (astronomical) year number of the Gregorian calendar date """ def __init__(self, day, month, year): """Creates a new GregorianDate object Note that this class uses the astronomical year convention for years before 1 CE, i.e. 1 BCE = 0, 2 BCE = -1, etc. Args: day (int): The day of the Gregorian calendar date month (int): The month number of the Gregorian calendar date year (int): The (astronomical) year number of the Gregorian calendar date """ if day > 31 or day < 1: raise ValueError("Invalid day, must be integer between 1 and 31") self.day = day if month > 12 or month < 1: raise ValueError("Invalid month, must be integer between 1 and 12") self.month = month self.year = year self.__check_month_days() def to_julian_day(self): """Converts the Gregorian calendar date to its Julian Day number equivalent Adapted from: https://www.researchgate.net/publication/316558298_Date_Algorithms#pf5 Returns: (float): The Julian day number corresponding to the Gregorian calendar date. """ if self.month < 3: M = self.month + 12 Y = self.year - 1 else: M = self.month Y = self.year D = self.day return ( D + (153 * M - 457) // 5 + 365 * Y + math.floor(Y / 4) - math.floor(Y / 100) + math.floor(Y / 400) + 1721118.5 ) def to_julian(self): """Converts the Gregorian calendar date to its Julian calendar equivalent Returns: (JulianDate): The Julian calendar date corresponding to the Gregorian calendar date. """ return julian_day_to_julian(math.ceil(self.to_julian_day())) def to_mayadate(self, correlation=584283): """Converts the Gregorian calendar date to its Mayan calendar equivalent Returns: (Mayadate): The Mayan calendar date corresponding to the Gregorian calendar date. """ from .long_count import LongCount, kin_to_long_count from .mayadate import Mayadate num_kin = math.ceil(self.to_julian_day()) - correlation long_count = kin_to_long_count(num_kin) return Mayadate(long_count, None) def to_datetime(self): """Converts the GregorianDate object to a datetime.date object Note that datetime.date objects do not support years before 1 CE. Attempting to convert GregorianDate objects with year before 1 CE will raise a ValueError. Returns: (datetime.date): The datetime.date object corresponding to the Gregorian calendar date. """ if self.year < 1: raise ValueError("datetime.date objects do not support years before 1 CE") return datetime.date(self.year, self.month, self.day) def is_leap_year(self): """Determines whether the year of the GregorianDate object is a leap year Returns: (bool): True if the year is a leap year, False otherwise """ if self.year % 4 == 0: if self.year % 100 == 0 and self.year % 400 != 0: return False else: return True return False def __check_month_days(self): """Raises error if the current configuration of month, day, year is invalid""" max_days = { 1: 31, 2: 28, 3: 31, 4: 30, 5: 31, 6: 30, 7: 31, 8: 31, 9: 30, 10: 31, 11: 30, 12: 31, } if self.is_leap_year(): max_days[2] = 29 if max_days[self.month] < self.day: raise ValueError(f"Invalid day, month combination {self.month}/{self.day}") def __eq__(self, other): return ( self.day == other.day and self.month == other.month and self.year == other.year ) def __repr__(self): return f"({self.day}, {self.month}, {self.year})" def __str__(self): if self.year > 0: return f"{_num_to_month(self.month)} {self.day}, {self.year} CE" elif self.year <= 0: return f"{_num_to_month(self.month)} {self.day}, {abs(self.year) + 1} BCE"
[ "class", "GregorianDate", ":", "def", "__init__", "(", "self", ",", "day", ",", "month", ",", "year", ")", ":", "\"\"\"Creates a new GregorianDate object\n\n Note that this class uses the astronomical year convention for years before 1 CE,\n i.e. 1 BCE = 0, 2 BCE = -1, etc.\n\n Args:\n day (int): The day of the Gregorian calendar date\n month (int): The month number of the Gregorian calendar date\n year (int): The (astronomical) year number of the Gregorian calendar date\n \"\"\"", "if", "day", ">", "31", "or", "day", "<", "1", ":", "raise", "ValueError", "(", "\"Invalid day, must be integer between 1 and 31\"", ")", "self", ".", "day", "=", "day", "if", "month", ">", "12", "or", "month", "<", "1", ":", "raise", "ValueError", "(", "\"Invalid month, must be integer between 1 and 12\"", ")", "self", ".", "month", "=", "month", "self", ".", "year", "=", "year", "self", ".", "__check_month_days", "(", ")", "def", "to_julian_day", "(", "self", ")", ":", "\"\"\"Converts the Gregorian calendar date to its Julian Day number equivalent\n\n Adapted from: https://www.researchgate.net/publication/316558298_Date_Algorithms#pf5\n\n Returns:\n (float): The Julian day number corresponding to the Gregorian calendar\n date.\n\n \"\"\"", "if", "self", ".", "month", "<", "3", ":", "M", "=", "self", ".", "month", "+", "12", "Y", "=", "self", ".", "year", "-", "1", "else", ":", "M", "=", "self", ".", "month", "Y", "=", "self", ".", "year", "D", "=", "self", ".", "day", "return", "(", "D", "+", "(", "153", "*", "M", "-", "457", ")", "//", "5", "+", "365", "*", "Y", "+", "math", ".", "floor", "(", "Y", "/", "4", ")", "-", "math", ".", "floor", "(", "Y", "/", "100", ")", "+", "math", ".", "floor", "(", "Y", "/", "400", ")", "+", "1721118.5", ")", "def", "to_julian", "(", "self", ")", ":", "\"\"\"Converts the Gregorian calendar date to its Julian calendar equivalent\n\n Returns:\n (JulianDate): The Julian calendar date corresponding to the Gregorian\n calendar date.\n\n \"\"\"", "return", "julian_day_to_julian", "(", "math", ".", "ceil", "(", "self", ".", "to_julian_day", "(", ")", ")", ")", "def", "to_mayadate", "(", "self", ",", "correlation", "=", "584283", ")", ":", "\"\"\"Converts the Gregorian calendar date to its Mayan calendar equivalent\n\n Returns:\n (Mayadate): The Mayan calendar date corresponding to the Gregorian\n calendar date.\n\n \"\"\"", "from", ".", "long_count", "import", "LongCount", ",", "kin_to_long_count", "from", ".", "mayadate", "import", "Mayadate", "num_kin", "=", "math", ".", "ceil", "(", "self", ".", "to_julian_day", "(", ")", ")", "-", "correlation", "long_count", "=", "kin_to_long_count", "(", "num_kin", ")", "return", "Mayadate", "(", "long_count", ",", "None", ")", "def", "to_datetime", "(", "self", ")", ":", "\"\"\"Converts the GregorianDate object to a datetime.date object\n\n Note that datetime.date objects do not support years before 1 CE. Attempting\n to convert GregorianDate objects with year before 1 CE will raise a ValueError.\n\n Returns:\n (datetime.date): The datetime.date object corresponding to the Gregorian\n calendar date.\n\n \"\"\"", "if", "self", ".", "year", "<", "1", ":", "raise", "ValueError", "(", "\"datetime.date objects do not support years before 1 CE\"", ")", "return", "datetime", ".", "date", "(", "self", ".", "year", ",", "self", ".", "month", ",", "self", ".", "day", ")", "def", "is_leap_year", "(", "self", ")", ":", "\"\"\"Determines whether the year of the GregorianDate object is a leap year\n\n Returns:\n (bool): True if the year is a leap year, False otherwise\n\n \"\"\"", "if", "self", ".", "year", "%", "4", "==", "0", ":", "if", "self", ".", "year", "%", "100", "==", "0", "and", "self", ".", "year", "%", "400", "!=", "0", ":", "return", "False", "else", ":", "return", "True", "return", "False", "def", "__check_month_days", "(", "self", ")", ":", "\"\"\"Raises error if the current configuration of month, day, year is invalid\"\"\"", "max_days", "=", "{", "1", ":", "31", ",", "2", ":", "28", ",", "3", ":", "31", ",", "4", ":", "30", ",", "5", ":", "31", ",", "6", ":", "30", ",", "7", ":", "31", ",", "8", ":", "31", ",", "9", ":", "30", ",", "10", ":", "31", ",", "11", ":", "30", ",", "12", ":", "31", ",", "}", "if", "self", ".", "is_leap_year", "(", ")", ":", "max_days", "[", "2", "]", "=", "29", "if", "max_days", "[", "self", ".", "month", "]", "<", "self", ".", "day", ":", "raise", "ValueError", "(", "f\"Invalid day, month combination {self.month}/{self.day}\"", ")", "def", "__eq__", "(", "self", ",", "other", ")", ":", "return", "(", "self", ".", "day", "==", "other", ".", "day", "and", "self", ".", "month", "==", "other", ".", "month", "and", "self", ".", "year", "==", "other", ".", "year", ")", "def", "__repr__", "(", "self", ")", ":", "return", "f\"({self.day}, {self.month}, {self.year})\"", "def", "__str__", "(", "self", ")", ":", "if", "self", ".", "year", ">", "0", ":", "return", "f\"{_num_to_month(self.month)} {self.day}, {self.year} CE\"", "elif", "self", ".", "year", "<=", "0", ":", "return", "f\"{_num_to_month(self.month)} {self.day}, {abs(self.year) + 1} BCE\"" ]
Basic class to handle (proleptic) Gregorian calendar dates and conversions Note that this class uses the astronomical year convention for years before 1 CE, i.e.
[ "Basic", "class", "to", "handle", "(", "proleptic", ")", "Gregorian", "calendar", "dates", "and", "conversions", "Note", "that", "this", "class", "uses", "the", "astronomical", "year", "convention", "for", "years", "before", "1", "CE", "i", ".", "e", "." ]
[ "\"\"\"Basic class to handle (proleptic) Gregorian calendar dates and conversions\n\n Note that this class uses the astronomical year convention for years before 1 CE,\n i.e. 1 BCE = 0, 2 BCE = -1, etc.\n\n Attributes:\n day (int): The day of the Gregorian calendar date\n month (int): The month number of the Gregorian calendar date\n year (int): The (astronomical) year number of the Gregorian calendar date\n \"\"\"", "\"\"\"Creates a new GregorianDate object\n\n Note that this class uses the astronomical year convention for years before 1 CE,\n i.e. 1 BCE = 0, 2 BCE = -1, etc.\n\n Args:\n day (int): The day of the Gregorian calendar date\n month (int): The month number of the Gregorian calendar date\n year (int): The (astronomical) year number of the Gregorian calendar date\n \"\"\"", "\"\"\"Converts the Gregorian calendar date to its Julian Day number equivalent\n\n Adapted from: https://www.researchgate.net/publication/316558298_Date_Algorithms#pf5\n\n Returns:\n (float): The Julian day number corresponding to the Gregorian calendar\n date.\n\n \"\"\"", "\"\"\"Converts the Gregorian calendar date to its Julian calendar equivalent\n\n Returns:\n (JulianDate): The Julian calendar date corresponding to the Gregorian\n calendar date.\n\n \"\"\"", "\"\"\"Converts the Gregorian calendar date to its Mayan calendar equivalent\n\n Returns:\n (Mayadate): The Mayan calendar date corresponding to the Gregorian\n calendar date.\n\n \"\"\"", "\"\"\"Converts the GregorianDate object to a datetime.date object\n\n Note that datetime.date objects do not support years before 1 CE. Attempting\n to convert GregorianDate objects with year before 1 CE will raise a ValueError.\n\n Returns:\n (datetime.date): The datetime.date object corresponding to the Gregorian\n calendar date.\n\n \"\"\"", "\"\"\"Determines whether the year of the GregorianDate object is a leap year\n\n Returns:\n (bool): True if the year is a leap year, False otherwise\n\n \"\"\"", "\"\"\"Raises error if the current configuration of month, day, year is invalid\"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [ { "identifier": "day", "type": null, "docstring": "The day of the Gregorian calendar date", "docstring_tokens": [ "The", "day", "of", "the", "Gregorian", "calendar", "date" ], "default": null, "is_optional": false }, { "identifier": "month", "type": null, "docstring": "The month number of the Gregorian calendar date", "docstring_tokens": [ "The", "month", "number", "of", "the", "Gregorian", "calendar", "date" ], "default": null, "is_optional": false }, { "identifier": "year", "type": null, "docstring": "The (astronomical) year number of the Gregorian calendar date", "docstring_tokens": [ "The", "(", "astronomical", ")", "year", "number", "of", "the", "Gregorian", "calendar", "date" ], "default": null, "is_optional": false } ], "others": [] }
false
17
1,235
106
65148d7fa0a7a14353fda3255034bea4e5a02c16
The-Alchemist/at4j
src/AT4J_zip/src/org/at4j/zip/prog/Zip.java
[ "Apache-2.0" ]
Java
Zip
/** * This runnable class emulates the {@code zip} command. It understands a subset * of {@code zip}'s command line arguments. * <p> * * <pre> * Usage: * java -cp [classpath] org.at4j.zip.prog.Zip [options] file file[s] * Where: * classpath - Should include the at4j, bzip, lzma and entityfs-core Jars. * options - Command options. See below. * file - The name and path of the Zip file to create. * file[s] - The files and directories to add to the Zip archive. If the * -r option is used, directories are added recursively. * Options: * -r - Add directories recursively. * --timing - After building the archive, print out how long it took. * </pre> * @author Karl Gustafsson * @since 1.0 */
This runnable class emulates the zip command. It understands a subset of zip's command line arguments. Usage: java -cp [classpath] org.at4j.zip.prog.Zip [options] file file[s] Where: classpath - Should include the at4j, bzip, lzma and entityfs-core Jars. options - Command options. See below. file - The name and path of the Zip file to create. file[s] - The files and directories to add to the Zip archive. If the -r option is used, directories are added recursively. Options: -r - Add directories recursively. timing - After building the archive, print out how long it took. @author Karl Gustafsson @since 1.0
[ "This", "runnable", "class", "emulates", "the", "zip", "command", ".", "It", "understands", "a", "subset", "of", "zip", "'", "s", "command", "line", "arguments", ".", "Usage", ":", "java", "-", "cp", "[", "classpath", "]", "org", ".", "at4j", ".", "zip", ".", "prog", ".", "Zip", "[", "options", "]", "file", "file", "[", "s", "]", "Where", ":", "classpath", "-", "Should", "include", "the", "at4j", "bzip", "lzma", "and", "entityfs", "-", "core", "Jars", ".", "options", "-", "Command", "options", ".", "See", "below", ".", "file", "-", "The", "name", "and", "path", "of", "the", "Zip", "file", "to", "create", ".", "file", "[", "s", "]", "-", "The", "files", "and", "directories", "to", "add", "to", "the", "Zip", "archive", ".", "If", "the", "-", "r", "option", "is", "used", "directories", "are", "added", "recursively", ".", "Options", ":", "-", "r", "-", "Add", "directories", "recursively", ".", "timing", "-", "After", "building", "the", "archive", "print", "out", "how", "long", "it", "took", ".", "@author", "Karl", "Gustafsson", "@since", "1", ".", "0" ]
public final class Zip extends AbstractProgram { private ZipCommandLineArguments parseCommandLine(String[] args) throws CommandErrorException { ZipCommandLineArguments res = new ZipCommandLineArguments(); int pos = 0; String arg = getArg(args, pos++, "Missing files"); while (isFlagArgument(arg)) { if ("-r".equals(arg)) { res.setRecursive(); } else if ("--timing".equals(arg)) { res.setTiming(); } else { throw new CommandErrorException("Unknown argument " + arg); } arg = getArg(args, pos++, "Missing files"); } res.setTargetFile(new File(arg)); res.addFileToZip(new File(getArg(args, pos++, "Missing files to zip"))); while (pos < args.length) { res.addFileToZip(new File(args[pos++])); } return res; } private void run(String[] args) throws CommandErrorException, IOException { ZipCommandLineArguments cla = parseCommandLine(args); long start = System.currentTimeMillis(); File targetFile = cla.getTargetFile(); if (!targetFile.createNewFile()) { throw new CommandErrorException("Could not create target file " + targetFile); } RandomlyAccessibleFile f = new ReadWritableFileAdapter(targetFile); ZipBuilder zb = new ZipBuilder(f); try { for (File ftz : cla.getFilesToZip()) { AbsoluteLocation parentLocation = getParentLocation(ftz); if (cla.isRecursive()) { zb.addRecursively(ftz, parentLocation.getChildLocation(ftz.getName())); } else { zb.add(ftz, parentLocation); } } } finally { zb.close(); } long end = System.currentTimeMillis(); if (cla.isTiming()) { System.out.println("The operation took " + (end - start) + " ms."); System.out.println("The time it took to load Java and start the program is not included."); } } public static void main(String[] args) { try { new Zip().run(args); } catch (CommandErrorException e) { System.err.println(e.getMessage()); System.exit(1); } catch (IOException e) { System.err.println(e.getMessage()); System.exit(1); } catch (WrappedIOException e) { System.err.println(e.getMessage()); System.exit(1); } } }
[ "public", "final", "class", "Zip", "extends", "AbstractProgram", "{", "private", "ZipCommandLineArguments", "parseCommandLine", "(", "String", "[", "]", "args", ")", "throws", "CommandErrorException", "{", "ZipCommandLineArguments", "res", "=", "new", "ZipCommandLineArguments", "(", ")", ";", "int", "pos", "=", "0", ";", "String", "arg", "=", "getArg", "(", "args", ",", "pos", "++", ",", "\"", "Missing files", "\"", ")", ";", "while", "(", "isFlagArgument", "(", "arg", ")", ")", "{", "if", "(", "\"", "-r", "\"", ".", "equals", "(", "arg", ")", ")", "{", "res", ".", "setRecursive", "(", ")", ";", "}", "else", "if", "(", "\"", "--timing", "\"", ".", "equals", "(", "arg", ")", ")", "{", "res", ".", "setTiming", "(", ")", ";", "}", "else", "{", "throw", "new", "CommandErrorException", "(", "\"", "Unknown argument ", "\"", "+", "arg", ")", ";", "}", "arg", "=", "getArg", "(", "args", ",", "pos", "++", ",", "\"", "Missing files", "\"", ")", ";", "}", "res", ".", "setTargetFile", "(", "new", "File", "(", "arg", ")", ")", ";", "res", ".", "addFileToZip", "(", "new", "File", "(", "getArg", "(", "args", ",", "pos", "++", ",", "\"", "Missing files to zip", "\"", ")", ")", ")", ";", "while", "(", "pos", "<", "args", ".", "length", ")", "{", "res", ".", "addFileToZip", "(", "new", "File", "(", "args", "[", "pos", "++", "]", ")", ")", ";", "}", "return", "res", ";", "}", "private", "void", "run", "(", "String", "[", "]", "args", ")", "throws", "CommandErrorException", ",", "IOException", "{", "ZipCommandLineArguments", "cla", "=", "parseCommandLine", "(", "args", ")", ";", "long", "start", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "File", "targetFile", "=", "cla", ".", "getTargetFile", "(", ")", ";", "if", "(", "!", "targetFile", ".", "createNewFile", "(", ")", ")", "{", "throw", "new", "CommandErrorException", "(", "\"", "Could not create target file ", "\"", "+", "targetFile", ")", ";", "}", "RandomlyAccessibleFile", "f", "=", "new", "ReadWritableFileAdapter", "(", "targetFile", ")", ";", "ZipBuilder", "zb", "=", "new", "ZipBuilder", "(", "f", ")", ";", "try", "{", "for", "(", "File", "ftz", ":", "cla", ".", "getFilesToZip", "(", ")", ")", "{", "AbsoluteLocation", "parentLocation", "=", "getParentLocation", "(", "ftz", ")", ";", "if", "(", "cla", ".", "isRecursive", "(", ")", ")", "{", "zb", ".", "addRecursively", "(", "ftz", ",", "parentLocation", ".", "getChildLocation", "(", "ftz", ".", "getName", "(", ")", ")", ")", ";", "}", "else", "{", "zb", ".", "add", "(", "ftz", ",", "parentLocation", ")", ";", "}", "}", "}", "finally", "{", "zb", ".", "close", "(", ")", ";", "}", "long", "end", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "if", "(", "cla", ".", "isTiming", "(", ")", ")", "{", "System", ".", "out", ".", "println", "(", "\"", "The operation took ", "\"", "+", "(", "end", "-", "start", ")", "+", "\"", " ms.", "\"", ")", ";", "System", ".", "out", ".", "println", "(", "\"", "The time it took to load Java and start the program is not included.", "\"", ")", ";", "}", "}", "public", "static", "void", "main", "(", "String", "[", "]", "args", ")", "{", "try", "{", "new", "Zip", "(", ")", ".", "run", "(", "args", ")", ";", "}", "catch", "(", "CommandErrorException", "e", ")", "{", "System", ".", "err", ".", "println", "(", "e", ".", "getMessage", "(", ")", ")", ";", "System", ".", "exit", "(", "1", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "System", ".", "err", ".", "println", "(", "e", ".", "getMessage", "(", ")", ")", ";", "System", ".", "exit", "(", "1", ")", ";", "}", "catch", "(", "WrappedIOException", "e", ")", "{", "System", ".", "err", ".", "println", "(", "e", ".", "getMessage", "(", ")", ")", ";", "System", ".", "exit", "(", "1", ")", ";", "}", "}", "}" ]
This runnable class emulates the {@code zip} command.
[ "This", "runnable", "class", "emulates", "the", "{", "@code", "zip", "}", "command", "." ]
[]
[ { "param": "AbstractProgram", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "AbstractProgram", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
18
575
206
788669c3d176064f1728e69d55c3bd105df0799c
jonilviv/google-api-dotnet-client
Src/Generated/Google.Apis.Logging.v2/Google.Apis.Logging.v2.cs
[ "Apache-2.0" ]
C#
PatchRequest
/// <summary>Updates a bucket. This method replaces the following fields in the existing bucket with /// values from the new bucket: retention_periodIf the retention period is decreased and the bucket is /// locked, FAILED_PRECONDITION will be returned.If the bucket has a LifecycleState of DELETE_REQUESTED, /// FAILED_PRECONDITION will be returned.A buckets region may not be modified after it is /// created.</summary>
Updates a bucket. This method replaces the following fields in the existing bucket with values from the new bucket: retention_periodIf the retention period is decreased and the bucket is locked, FAILED_PRECONDITION will be returned.If the bucket has a LifecycleState of DELETE_REQUESTED, FAILED_PRECONDITION will be returned.A buckets region may not be modified after it is created.
[ "Updates", "a", "bucket", ".", "This", "method", "replaces", "the", "following", "fields", "in", "the", "existing", "bucket", "with", "values", "from", "the", "new", "bucket", ":", "retention_periodIf", "the", "retention", "period", "is", "decreased", "and", "the", "bucket", "is", "locked", "FAILED_PRECONDITION", "will", "be", "returned", ".", "If", "the", "bucket", "has", "a", "LifecycleState", "of", "DELETE_REQUESTED", "FAILED_PRECONDITION", "will", "be", "returned", ".", "A", "buckets", "region", "may", "not", "be", "modified", "after", "it", "is", "created", "." ]
public class PatchRequest : LoggingBaseServiceRequest<Google.Apis.Logging.v2.Data.LogBucket> { public PatchRequest(Google.Apis.Services.IClientService service, Google.Apis.Logging.v2.Data.LogBucket body, string name) : base(service) { Name = name; Body = body; InitParameters(); } [Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)] public virtual string Name { get; private set; } [Google.Apis.Util.RequestParameterAttribute("updateMask", Google.Apis.Util.RequestParameterType.Query)] public virtual object UpdateMask { get; set; } Google.Apis.Logging.v2.Data.LogBucket Body { get; set; } protected override object GetBody() => Body; public override string MethodName => "patch"; public override string HttpMethod => "PATCH"; public override string RestPath => "v2/{+name}"; protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("name", new Google.Apis.Discovery.Parameter { Name = "name", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^projects/[^/]+/locations/[^/]+/buckets/[^/]+$", }); RequestParameters.Add("updateMask", new Google.Apis.Discovery.Parameter { Name = "updateMask", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } }
[ "public", "class", "PatchRequest", ":", "LoggingBaseServiceRequest", "<", "Google", ".", "Apis", ".", "Logging", ".", "v2", ".", "Data", ".", "LogBucket", ">", "{", "public", "PatchRequest", "(", "Google", ".", "Apis", ".", "Services", ".", "IClientService", "service", ",", "Google", ".", "Apis", ".", "Logging", ".", "v2", ".", "Data", ".", "LogBucket", "body", ",", "string", "name", ")", ":", "base", "(", "service", ")", "{", "Name", "=", "name", ";", "Body", "=", "body", ";", "InitParameters", "(", ")", ";", "}", "[", "Google", ".", "Apis", ".", "Util", ".", "RequestParameterAttribute", "(", "\"", "name", "\"", ",", "Google", ".", "Apis", ".", "Util", ".", "RequestParameterType", ".", "Path", ")", "]", "public", "virtual", "string", "Name", "{", "get", ";", "private", "set", ";", "}", "[", "Google", ".", "Apis", ".", "Util", ".", "RequestParameterAttribute", "(", "\"", "updateMask", "\"", ",", "Google", ".", "Apis", ".", "Util", ".", "RequestParameterType", ".", "Query", ")", "]", "public", "virtual", "object", "UpdateMask", "{", "get", ";", "set", ";", "}", "Google", ".", "Apis", ".", "Logging", ".", "v2", ".", "Data", ".", "LogBucket", "Body", "{", "get", ";", "set", ";", "}", "protected", "override", "object", "GetBody", "(", ")", "=>", "Body", ";", "public", "override", "string", "MethodName", "=>", "\"", "patch", "\"", ";", "public", "override", "string", "HttpMethod", "=>", "\"", "PATCH", "\"", ";", "public", "override", "string", "RestPath", "=>", "\"", "v2/{+name}", "\"", ";", "protected", "override", "void", "InitParameters", "(", ")", "{", "base", ".", "InitParameters", "(", ")", ";", "RequestParameters", ".", "Add", "(", "\"", "name", "\"", ",", "new", "Google", ".", "Apis", ".", "Discovery", ".", "Parameter", "{", "Name", "=", "\"", "name", "\"", ",", "IsRequired", "=", "true", ",", "ParameterType", "=", "\"", "path", "\"", ",", "DefaultValue", "=", "null", ",", "Pattern", "=", "@\"^projects/[^/]+/locations/[^/]+/buckets/[^/]+$\"", ",", "}", ")", ";", "RequestParameters", ".", "Add", "(", "\"", "updateMask", "\"", ",", "new", "Google", ".", "Apis", ".", "Discovery", ".", "Parameter", "{", "Name", "=", "\"", "updateMask", "\"", ",", "IsRequired", "=", "false", ",", "ParameterType", "=", "\"", "query", "\"", ",", "DefaultValue", "=", "null", ",", "Pattern", "=", "null", ",", "}", ")", ";", "}", "}" ]
Updates a bucket.
[ "Updates", "a", "bucket", "." ]
[ "/// <summary>Constructs a new Patch request.</summary>", "/// <summary>Required. The full resource name of the bucket to update.", "/// \"projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]\"", "/// \"organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]\"", "/// \"billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]\"", "/// \"folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]\" Example: \"projects/my-project-", "/// id/locations/my-location/buckets/my-bucket-id\". Also requires permission", "/// \"resourcemanager.projects.updateLiens\" to set the locked property</summary>", "/// <summary>Required. Field mask that specifies the fields in bucket that need an update. A bucket", "/// field will be overwritten if, and only if, it is in the update mask. name and output only fields", "/// cannot be updated.For a detailed FieldMask definition, see https://developers.google.com", "/// /protocol-buffers/docs/reference/google.protobuf#google.protobuf.FieldMaskExample:", "/// updateMask=retention_days.</summary>", "/// <summary>Gets or sets the body of this request.</summary>", "/// <summary>Returns the body of the request.</summary>", "/// <summary>Gets the method name.</summary>", "/// <summary>Gets the HTTP method.</summary>", "/// <summary>Gets the REST path.</summary>", "/// <summary>Initializes Patch parameter list.</summary>" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
13
323
84
379c0bcd947a25bd7c5e8d50e0944ba1b23b71b7
cts-randrid/WurmAssistant3
lib/ObjectListView/ObjectListView/ListViewPrinter/RuntimePropertiesObject.cs
[ "MIT" ]
C#
RuntimePropertyObject
/// <summary> /// A RuntimePropertyObject can construct its visible properties at runtime, /// not through reflection. /// </summary> /// <remarks> /// Instances of this class can have their properties constructed at /// runtime in such a way that a PropertyGrid can read and modify its /// properties. A PropertyGrid normally uses reflection to decide /// the properties to be presents, which means the characteristics of /// an object are decided at runtime. In contrast, this object /// properties are determined by the AddProperty() calls that are made /// on it. /// </remarks>
A RuntimePropertyObject can construct its visible properties at runtime, not through reflection.
[ "A", "RuntimePropertyObject", "can", "construct", "its", "visible", "properties", "at", "runtime", "not", "through", "reflection", "." ]
internal class RuntimePropertyObject : CustomTypeDescriptor { #region Property Management public void AddProperty(string name, Type propertyType) { this.propertyDescriptions.Add(new CustomPropertyDescriptor(name, propertyType, this.propertyCategory)); } public void AddProperty(string name, Type propertyType, object defaultValue) { this.AddProperty(name, propertyType); this.valueMap[name] = defaultValue; } public void SetPropertyCategory(string category) { this.propertyCategory = category; } string propertyCategory; List<CustomPropertyDescriptor> propertyDescriptions = new List<CustomPropertyDescriptor>(); #endregion #region Property values public object GetValue(string name) { object value; if (this.valueMap.TryGetValue(name, out value)) return value; else return null; } public void SetValue(string name, object value) { this.valueMap[name] = value; } public void ResetValue(string name) { this.valueMap[name] = null; } Dictionary<string, object> valueMap = new Dictionary<string, object>(); #endregion #region Overrides of CustomTypeDescriptor public override object GetPropertyOwner(PropertyDescriptor pd) { return this; } public override PropertyDescriptorCollection GetProperties(Attribute[] attributes) { return new PropertyDescriptorCollection(propertyDescriptions.ToArray()); } #endregion }
[ "internal", "class", "RuntimePropertyObject", ":", "CustomTypeDescriptor", "{", "region", " Property Management", "public", "void", "AddProperty", "(", "string", "name", ",", "Type", "propertyType", ")", "{", "this", ".", "propertyDescriptions", ".", "Add", "(", "new", "CustomPropertyDescriptor", "(", "name", ",", "propertyType", ",", "this", ".", "propertyCategory", ")", ")", ";", "}", "public", "void", "AddProperty", "(", "string", "name", ",", "Type", "propertyType", ",", "object", "defaultValue", ")", "{", "this", ".", "AddProperty", "(", "name", ",", "propertyType", ")", ";", "this", ".", "valueMap", "[", "name", "]", "=", "defaultValue", ";", "}", "public", "void", "SetPropertyCategory", "(", "string", "category", ")", "{", "this", ".", "propertyCategory", "=", "category", ";", "}", "string", "propertyCategory", ";", "List", "<", "CustomPropertyDescriptor", ">", "propertyDescriptions", "=", "new", "List", "<", "CustomPropertyDescriptor", ">", "(", ")", ";", "endregion", "region", " Property values", "public", "object", "GetValue", "(", "string", "name", ")", "{", "object", "value", ";", "if", "(", "this", ".", "valueMap", ".", "TryGetValue", "(", "name", ",", "out", "value", ")", ")", "return", "value", ";", "else", "return", "null", ";", "}", "public", "void", "SetValue", "(", "string", "name", ",", "object", "value", ")", "{", "this", ".", "valueMap", "[", "name", "]", "=", "value", ";", "}", "public", "void", "ResetValue", "(", "string", "name", ")", "{", "this", ".", "valueMap", "[", "name", "]", "=", "null", ";", "}", "Dictionary", "<", "string", ",", "object", ">", "valueMap", "=", "new", "Dictionary", "<", "string", ",", "object", ">", "(", ")", ";", "endregion", "region", " Overrides of CustomTypeDescriptor", "public", "override", "object", "GetPropertyOwner", "(", "PropertyDescriptor", "pd", ")", "{", "return", "this", ";", "}", "public", "override", "PropertyDescriptorCollection", "GetProperties", "(", "Attribute", "[", "]", "attributes", ")", "{", "return", "new", "PropertyDescriptorCollection", "(", "propertyDescriptions", ".", "ToArray", "(", ")", ")", ";", "}", "endregion", "}" ]
A RuntimePropertyObject can construct its visible properties at runtime, not through reflection.
[ "A", "RuntimePropertyObject", "can", "construct", "its", "visible", "properties", "at", "runtime", "not", "through", "reflection", "." ]
[ "// This is the part that determines what properties are shown by the PropertyGrid", "// The value returned by this method is the 'component' parameter of the ", "// CustomPropertyDescriptor.GetValue, SetValue and ResetValue methods." ]
[ { "param": "CustomTypeDescriptor", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "CustomTypeDescriptor", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [ { "identifier": "remarks", "docstring": "Instances of this class can have their properties constructed at\nruntime in such a way that a PropertyGrid can read and modify its\nproperties. A PropertyGrid normally uses reflection to decide\nthe properties to be presents, which means the characteristics of\nan object are decided at runtime. In contrast, this object\nproperties are determined by the AddProperty() calls that are made\non it.", "docstring_tokens": [ "Instances", "of", "this", "class", "can", "have", "their", "properties", "constructed", "at", "runtime", "in", "such", "a", "way", "that", "a", "PropertyGrid", "can", "read", "and", "modify", "its", "properties", ".", "A", "PropertyGrid", "normally", "uses", "reflection", "to", "decide", "the", "properties", "to", "be", "presents", "which", "means", "the", "characteristics", "of", "an", "object", "are", "decided", "at", "runtime", ".", "In", "contrast", "this", "object", "properties", "are", "determined", "by", "the", "AddProperty", "()", "calls", "that", "are", "made", "on", "it", "." ] } ] }
false
13
298
119
0c85ef6dda7f195b7f9de2e3eac8e637a99748d2
adamenk/preferencex
src/main/java/com/github/adamenko/prefs/FilePreferencesFactory.java
[ "MIT" ]
Java
FilePreferencesFactory
/** * PreferencesFactory implementation that stores the preferences in a user-defined file. To use it, * set the system property <tt>java.util.prefs.PreferencesFactory</tt> to * <tt>FilePreferencesFactory</tt> * <p/> * The file defaults to [user.home]/.fileprefs, but may be overridden with the system property * <tt>FilePreferencesFactory.file</tt> */
PreferencesFactory implementation that stores the preferences in a user-defined file. To use it, set the system property java.util.prefs.PreferencesFactory to FilePreferencesFactory The file defaults to [user.home]/.fileprefs, but may be overridden with the system property FilePreferencesFactory.file
[ "PreferencesFactory", "implementation", "that", "stores", "the", "preferences", "in", "a", "user", "-", "defined", "file", ".", "To", "use", "it", "set", "the", "system", "property", "java", ".", "util", ".", "prefs", ".", "PreferencesFactory", "to", "FilePreferencesFactory", "The", "file", "defaults", "to", "[", "user", ".", "home", "]", "/", ".", "fileprefs", "but", "may", "be", "overridden", "with", "the", "system", "property", "FilePreferencesFactory", ".", "file" ]
public class FilePreferencesFactory implements PreferencesFactory { private static final Logger log = Logger.getLogger(FilePreferencesFactory.class.getName()); private Preferences rootPreferences; public static final String SYSTEM_PROPERTY_FILE = "FilePreferencesFactory.file"; public Preferences systemRoot() { return userRoot(); } public Preferences userRoot() { if (rootPreferences == null) { log.finer("Instantiating root preferences"); rootPreferences = new FilePreferences(null, ""); } return rootPreferences; } private static File preferencesFile; public static File getPreferencesFile() { if (preferencesFile == null) { String prefsFile = System.getProperty(SYSTEM_PROPERTY_FILE); if (prefsFile == null || prefsFile.length() == 0) { prefsFile = System.getProperty("user.home") + File.separator + ".fileprefs"; } preferencesFile = new File(prefsFile).getAbsoluteFile(); log.finer("Preferences file is " + preferencesFile); } return preferencesFile; } }
[ "public", "class", "FilePreferencesFactory", "implements", "PreferencesFactory", "{", "private", "static", "final", "Logger", "log", "=", "Logger", ".", "getLogger", "(", "FilePreferencesFactory", ".", "class", ".", "getName", "(", ")", ")", ";", "private", "Preferences", "rootPreferences", ";", "public", "static", "final", "String", "SYSTEM_PROPERTY_FILE", "=", "\"", "FilePreferencesFactory.file", "\"", ";", "public", "Preferences", "systemRoot", "(", ")", "{", "return", "userRoot", "(", ")", ";", "}", "public", "Preferences", "userRoot", "(", ")", "{", "if", "(", "rootPreferences", "==", "null", ")", "{", "log", ".", "finer", "(", "\"", "Instantiating root preferences", "\"", ")", ";", "rootPreferences", "=", "new", "FilePreferences", "(", "null", ",", "\"", "\"", ")", ";", "}", "return", "rootPreferences", ";", "}", "private", "static", "File", "preferencesFile", ";", "public", "static", "File", "getPreferencesFile", "(", ")", "{", "if", "(", "preferencesFile", "==", "null", ")", "{", "String", "prefsFile", "=", "System", ".", "getProperty", "(", "SYSTEM_PROPERTY_FILE", ")", ";", "if", "(", "prefsFile", "==", "null", "||", "prefsFile", ".", "length", "(", ")", "==", "0", ")", "{", "prefsFile", "=", "System", ".", "getProperty", "(", "\"", "user.home", "\"", ")", "+", "File", ".", "separator", "+", "\"", ".fileprefs", "\"", ";", "}", "preferencesFile", "=", "new", "File", "(", "prefsFile", ")", ".", "getAbsoluteFile", "(", ")", ";", "log", ".", "finer", "(", "\"", "Preferences file is ", "\"", "+", "preferencesFile", ")", ";", "}", "return", "preferencesFile", ";", "}", "}" ]
PreferencesFactory implementation that stores the preferences in a user-defined file.
[ "PreferencesFactory", "implementation", "that", "stores", "the", "preferences", "in", "a", "user", "-", "defined", "file", "." ]
[]
[ { "param": "PreferencesFactory", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "PreferencesFactory", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
16
216
87
342d26678d959a8255f5abb4c85692cffe53dde2
rdwight/smobol
smobol/sparse.py
[ "MIT" ]
Python
SparseComponentRule
A tensor-product rule forming a component of a sparse-grid rule. Exclusively for use in class SparseGrid. Members: dim - dimension of rule - same as SparseGrid dimension delta - False, standard rule U_i(f), True, \Delta = (U_i-U_{i-1})(f) including interpolation (bool) quad - nested quadrature object, e.g. QuadraturePatterson levelidx - quadrature rule level in each dim (list (dim,)) nnodes - number of nodes in each dimension (ndarray (dim,)) i - multi-indices of quadrature points, with reference to the finest tensor-product grid, ndarray (N, dim) - N total points w - weights of the multidimensional rule, corresponding to entries of i, ndarray (N,)
A tensor-product rule forming a component of a sparse-grid rule. Exclusively for use in class SparseGrid.
[ "A", "tensor", "-", "product", "rule", "forming", "a", "component", "of", "a", "sparse", "-", "grid", "rule", ".", "Exclusively", "for", "use", "in", "class", "SparseGrid", "." ]
class SparseComponentRule: """ A tensor-product rule forming a component of a sparse-grid rule. Exclusively for use in class SparseGrid. Members: dim - dimension of rule - same as SparseGrid dimension delta - False, standard rule U_i(f), True, \Delta = (U_i-U_{i-1})(f) including interpolation (bool) quad - nested quadrature object, e.g. QuadraturePatterson levelidx - quadrature rule level in each dim (list (dim,)) nnodes - number of nodes in each dimension (ndarray (dim,)) i - multi-indices of quadrature points, with reference to the finest tensor-product grid, ndarray (N, dim) - N total points w - weights of the multidimensional rule, corresponding to entries of i, ndarray (N,) """ def __init__(self, quad, levelidx, delta=False): i_1d = [quad.idx[l - 1] for l in levelidx] w = quad.dw if delta else quad.w w_1d = [w[l - 1] for l in levelidx] self.delta = delta # Original rule or difference rule self.levelidx = levelidx self.dim = len(self.levelidx) self.quad = quad # 1d quadrature rule self.nnodes = np.array([quad.nnode(l - 1) for l in self.levelidx]) self.i = mylib.meshgrid_flatten(*i_1d) self.w = mylib.meshprod_flatten(*w_1d) def nnodes_total(self): """Total number of nodes in rule (scalar)""" assert self.w.shape[0] == np.prod(self.nnodes) assert len(self.w) == self.i.shape[0] return np.prod(self.nnodes) def global_index_to_x(self, midx): """Convert global-index to x-coordinates""" assert len(midx) == self.i.shape[1] return np.array(self.quad.global_index_to_x(np.array(midx))) def get_x(self): """Return all point coordinates as numpy array""" x = np.zeros((self.nnodes_total(), self.dim)) for j, midx in enumerate(self.i): x[j, :] = self.global_index_to_x(midx) return x def extract_fvec(self, fval): """ Given fval extract the values needed for this rule in a flat array fval - dictionary of function values indexed by tuples, function values are allowed to be scalars or ndarrays (of any rank). Return: fvec - ndarray of function values, ordered according to self.i """ # Detect datatype vex = fval.itervalues().next() # Any entry from dict if type(vex) == np.ndarray: fvec = np.zeros((self.nnodes_total(),) + vex.shape) else: fvec = np.zeros(self.nnodes_total()) # Fill array for j, midx in enumerate(self.i): loc = tuple(midx) assert loc in fval, 'Location not in fval: %s' % (loc,) fvec[j] = fval[loc] return fvec def lagrange(self, x): """ Return all Lagrange polynomials for this rule at single location x, ordering according to self.i """ assert len(x) == self.dim lag = self.quad.lagrange_delta if self.delta else self.quad.lagrange L_1d = [lag(x[j], self.levelidx[j] - 1) for j in range(self.dim)] return mylib.meshprod_flatten(*L_1d) def integrate(self, fval): """ Evaluate integral given data (dot-product of weights and values) fval - Either a) a dictionary of scalars/ndarrays indexed by tuples, storage format of SparseGrid Or b) an fvec - e.g. output of self.extract_fvec(fval) """ fvec = self.extract_fvec(fval) if type(fval) == type({}) else fval return np.einsum('i...,i...', self.w, fvec) def interpolate(self, x, fval): """ Polynomial interpolation based on this tensor-product rule x - location at which to interpolate ndarray (dim,) fval - dictionary of function values indexed by tuples """ return np.einsum('i...,i...', self.lagrange(x), self.extract_fvec(fval)) def dimensionate(self, fvec): """ Return fvec (itself the return value of self.extract_fvec()) viewed as a rank (self.dim) array - i.e. the most natural (unencoded) form of the data. Nf is the size of the vector output in the case of non-scalar f. """ if fvec.ndim == 1: # Scalar-valued f return fvec.reshape(self.nnodes) else: # Tensor-valued f Nf = fvec.shape[1:] # (shape of tensor-part) return fvec.reshape(np.hstack((self.nnodes, Nf))) def undimensionate(self, f): """Inverse of dimensionate - flatten f into fvec""" if f.ndim == self.dim: # Scalar-valued f return f.reshape(self.nnodes_total()) else: # Tensor-valued f Nf = f.shape[self.dim :] # (shape of tensor-part) return f.reshape((self.nnodes_total(),) + Nf) def integrate_partial(self, fval, axes): """ Integrate over a subset of the dimensions of the rule. If axes lists all the axes this is equivalent to integrate(). fval - data evaluated at all support points of the component rule. If f is vector-valued the last dimension is the vector axes - list of axes over which to integrate Return: sc_r - SparseComponentRule object of reduced dimension fval_r - reduced rank version of fval, dictionary indexed by new reduced-dim multi-indices axes_r - list of remaining axes in f_r (those not integrated yet) """ # Full-rank representation of f f = self.dimensionate(self.extract_fvec(fval)) if len(axes) == 0: return f, range(self.dim) # Creative use of einsum() assert f.ndim < 26, ValueError('Implementation limit dim < 26') ijk = np.array(list('abcdefghijklmnopqrstuvwxyz')) # Eg. cmd = 'abcde,b,c' for dim=3, # axis=[1,2], and matrix-valued f. # We avoid the ellipsis '...' because # of non-mature implementation. cmd = ''.join(ijk[: f.ndim]) + ',' + ','.join(ijk[list(axes)]) w = self.quad.dw if self.delta else self.quad.w warg = [w[self.levelidx[ai] - 1] for ai in axes] f_r = np.einsum(cmd, f, *warg) # Partial integral of f # Complement of axes (remaining axes) axes_r = mylib.complement(axes, self.dim) # Remaining level indices, new comp rule levelidx_r = list(np.array(self.levelidx)[axes_r]) sc_r = SparseComponentRule(self.quad, levelidx_r, delta=self.delta) # CHECK TODO: correct ordering? fvec_r = sc_r.undimensionate(f_r) fval_r = dict(zip([tuple(midx) for midx in sc_r.i], fvec_r)) return sc_r, fval_r, axes_r
[ "class", "SparseComponentRule", ":", "def", "__init__", "(", "self", ",", "quad", ",", "levelidx", ",", "delta", "=", "False", ")", ":", "i_1d", "=", "[", "quad", ".", "idx", "[", "l", "-", "1", "]", "for", "l", "in", "levelidx", "]", "w", "=", "quad", ".", "dw", "if", "delta", "else", "quad", ".", "w", "w_1d", "=", "[", "w", "[", "l", "-", "1", "]", "for", "l", "in", "levelidx", "]", "self", ".", "delta", "=", "delta", "self", ".", "levelidx", "=", "levelidx", "self", ".", "dim", "=", "len", "(", "self", ".", "levelidx", ")", "self", ".", "quad", "=", "quad", "self", ".", "nnodes", "=", "np", ".", "array", "(", "[", "quad", ".", "nnode", "(", "l", "-", "1", ")", "for", "l", "in", "self", ".", "levelidx", "]", ")", "self", ".", "i", "=", "mylib", ".", "meshgrid_flatten", "(", "*", "i_1d", ")", "self", ".", "w", "=", "mylib", ".", "meshprod_flatten", "(", "*", "w_1d", ")", "def", "nnodes_total", "(", "self", ")", ":", "\"\"\"Total number of nodes in rule (scalar)\"\"\"", "assert", "self", ".", "w", ".", "shape", "[", "0", "]", "==", "np", ".", "prod", "(", "self", ".", "nnodes", ")", "assert", "len", "(", "self", ".", "w", ")", "==", "self", ".", "i", ".", "shape", "[", "0", "]", "return", "np", ".", "prod", "(", "self", ".", "nnodes", ")", "def", "global_index_to_x", "(", "self", ",", "midx", ")", ":", "\"\"\"Convert global-index to x-coordinates\"\"\"", "assert", "len", "(", "midx", ")", "==", "self", ".", "i", ".", "shape", "[", "1", "]", "return", "np", ".", "array", "(", "self", ".", "quad", ".", "global_index_to_x", "(", "np", ".", "array", "(", "midx", ")", ")", ")", "def", "get_x", "(", "self", ")", ":", "\"\"\"Return all point coordinates as numpy array\"\"\"", "x", "=", "np", ".", "zeros", "(", "(", "self", ".", "nnodes_total", "(", ")", ",", "self", ".", "dim", ")", ")", "for", "j", ",", "midx", "in", "enumerate", "(", "self", ".", "i", ")", ":", "x", "[", "j", ",", ":", "]", "=", "self", ".", "global_index_to_x", "(", "midx", ")", "return", "x", "def", "extract_fvec", "(", "self", ",", "fval", ")", ":", "\"\"\"\n Given fval extract the values needed for this rule in a flat array\n fval - dictionary of function values indexed by tuples, function values\n are allowed to be scalars or ndarrays (of any rank).\n Return:\n fvec - ndarray of function values, ordered according to self.i\n \"\"\"", "vex", "=", "fval", ".", "itervalues", "(", ")", ".", "next", "(", ")", "if", "type", "(", "vex", ")", "==", "np", ".", "ndarray", ":", "fvec", "=", "np", ".", "zeros", "(", "(", "self", ".", "nnodes_total", "(", ")", ",", ")", "+", "vex", ".", "shape", ")", "else", ":", "fvec", "=", "np", ".", "zeros", "(", "self", ".", "nnodes_total", "(", ")", ")", "for", "j", ",", "midx", "in", "enumerate", "(", "self", ".", "i", ")", ":", "loc", "=", "tuple", "(", "midx", ")", "assert", "loc", "in", "fval", ",", "'Location not in fval: %s'", "%", "(", "loc", ",", ")", "fvec", "[", "j", "]", "=", "fval", "[", "loc", "]", "return", "fvec", "def", "lagrange", "(", "self", ",", "x", ")", ":", "\"\"\"\n Return all Lagrange polynomials for this rule at single location x,\n ordering according to self.i\n \"\"\"", "assert", "len", "(", "x", ")", "==", "self", ".", "dim", "lag", "=", "self", ".", "quad", ".", "lagrange_delta", "if", "self", ".", "delta", "else", "self", ".", "quad", ".", "lagrange", "L_1d", "=", "[", "lag", "(", "x", "[", "j", "]", ",", "self", ".", "levelidx", "[", "j", "]", "-", "1", ")", "for", "j", "in", "range", "(", "self", ".", "dim", ")", "]", "return", "mylib", ".", "meshprod_flatten", "(", "*", "L_1d", ")", "def", "integrate", "(", "self", ",", "fval", ")", ":", "\"\"\"\n Evaluate integral given data (dot-product of weights and values)\n fval - Either a) a dictionary of scalars/ndarrays indexed by tuples,\n storage format of SparseGrid\n Or b) an fvec - e.g. output of self.extract_fvec(fval)\n \"\"\"", "fvec", "=", "self", ".", "extract_fvec", "(", "fval", ")", "if", "type", "(", "fval", ")", "==", "type", "(", "{", "}", ")", "else", "fval", "return", "np", ".", "einsum", "(", "'i...,i...'", ",", "self", ".", "w", ",", "fvec", ")", "def", "interpolate", "(", "self", ",", "x", ",", "fval", ")", ":", "\"\"\"\n Polynomial interpolation based on this tensor-product rule\n x - location at which to interpolate ndarray (dim,)\n fval - dictionary of function values indexed by tuples\n \"\"\"", "return", "np", ".", "einsum", "(", "'i...,i...'", ",", "self", ".", "lagrange", "(", "x", ")", ",", "self", ".", "extract_fvec", "(", "fval", ")", ")", "def", "dimensionate", "(", "self", ",", "fvec", ")", ":", "\"\"\"\n Return fvec (itself the return value of self.extract_fvec()) viewed as a\n rank (self.dim) array - i.e. the most natural (unencoded) form of the\n data. Nf is the size of the vector output in the case of non-scalar f.\n \"\"\"", "if", "fvec", ".", "ndim", "==", "1", ":", "return", "fvec", ".", "reshape", "(", "self", ".", "nnodes", ")", "else", ":", "Nf", "=", "fvec", ".", "shape", "[", "1", ":", "]", "return", "fvec", ".", "reshape", "(", "np", ".", "hstack", "(", "(", "self", ".", "nnodes", ",", "Nf", ")", ")", ")", "def", "undimensionate", "(", "self", ",", "f", ")", ":", "\"\"\"Inverse of dimensionate - flatten f into fvec\"\"\"", "if", "f", ".", "ndim", "==", "self", ".", "dim", ":", "return", "f", ".", "reshape", "(", "self", ".", "nnodes_total", "(", ")", ")", "else", ":", "Nf", "=", "f", ".", "shape", "[", "self", ".", "dim", ":", "]", "return", "f", ".", "reshape", "(", "(", "self", ".", "nnodes_total", "(", ")", ",", ")", "+", "Nf", ")", "def", "integrate_partial", "(", "self", ",", "fval", ",", "axes", ")", ":", "\"\"\"\n Integrate over a subset of the dimensions of the rule. If axes lists all\n the axes this is equivalent to integrate().\n fval - data evaluated at all support points of the component rule. \n If f is vector-valued the last dimension is the vector\n axes - list of axes over which to integrate\n Return:\n sc_r - SparseComponentRule object of reduced dimension\n fval_r - reduced rank version of fval, dictionary indexed by new\n reduced-dim multi-indices\n axes_r - list of remaining axes in f_r (those not integrated yet)\n \"\"\"", "f", "=", "self", ".", "dimensionate", "(", "self", ".", "extract_fvec", "(", "fval", ")", ")", "if", "len", "(", "axes", ")", "==", "0", ":", "return", "f", ",", "range", "(", "self", ".", "dim", ")", "assert", "f", ".", "ndim", "<", "26", ",", "ValueError", "(", "'Implementation limit dim < 26'", ")", "ijk", "=", "np", ".", "array", "(", "list", "(", "'abcdefghijklmnopqrstuvwxyz'", ")", ")", "cmd", "=", "''", ".", "join", "(", "ijk", "[", ":", "f", ".", "ndim", "]", ")", "+", "','", "+", "','", ".", "join", "(", "ijk", "[", "list", "(", "axes", ")", "]", ")", "w", "=", "self", ".", "quad", ".", "dw", "if", "self", ".", "delta", "else", "self", ".", "quad", ".", "w", "warg", "=", "[", "w", "[", "self", ".", "levelidx", "[", "ai", "]", "-", "1", "]", "for", "ai", "in", "axes", "]", "f_r", "=", "np", ".", "einsum", "(", "cmd", ",", "f", ",", "*", "warg", ")", "axes_r", "=", "mylib", ".", "complement", "(", "axes", ",", "self", ".", "dim", ")", "levelidx_r", "=", "list", "(", "np", ".", "array", "(", "self", ".", "levelidx", ")", "[", "axes_r", "]", ")", "sc_r", "=", "SparseComponentRule", "(", "self", ".", "quad", ",", "levelidx_r", ",", "delta", "=", "self", ".", "delta", ")", "fvec_r", "=", "sc_r", ".", "undimensionate", "(", "f_r", ")", "fval_r", "=", "dict", "(", "zip", "(", "[", "tuple", "(", "midx", ")", "for", "midx", "in", "sc_r", ".", "i", "]", ",", "fvec_r", ")", ")", "return", "sc_r", ",", "fval_r", ",", "axes_r" ]
A tensor-product rule forming a component of a sparse-grid rule.
[ "A", "tensor", "-", "product", "rule", "forming", "a", "component", "of", "a", "sparse", "-", "grid", "rule", "." ]
[ "\"\"\"\n A tensor-product rule forming a component of a sparse-grid rule.\n Exclusively for use in class SparseGrid.\n Members:\n dim - dimension of rule - same as SparseGrid dimension\n delta - False, standard rule U_i(f), True, \\Delta = (U_i-U_{i-1})(f)\n including interpolation (bool)\n quad - nested quadrature object, e.g. QuadraturePatterson\n levelidx - quadrature rule level in each dim (list (dim,))\n nnodes - number of nodes in each dimension (ndarray (dim,))\n i - multi-indices of quadrature points, with reference to the finest\n tensor-product grid, ndarray (N, dim) - N total points\n w - weights of the multidimensional rule, corresponding to entries\n of i, ndarray (N,)\n \"\"\"", "# Original rule or difference rule", "# 1d quadrature rule", "\"\"\"Total number of nodes in rule (scalar)\"\"\"", "\"\"\"Convert global-index to x-coordinates\"\"\"", "\"\"\"Return all point coordinates as numpy array\"\"\"", "\"\"\"\n Given fval extract the values needed for this rule in a flat array\n fval - dictionary of function values indexed by tuples, function values\n are allowed to be scalars or ndarrays (of any rank).\n Return:\n fvec - ndarray of function values, ordered according to self.i\n \"\"\"", "# Detect datatype", "# Any entry from dict", "# Fill array", "\"\"\"\n Return all Lagrange polynomials for this rule at single location x,\n ordering according to self.i\n \"\"\"", "\"\"\"\n Evaluate integral given data (dot-product of weights and values)\n fval - Either a) a dictionary of scalars/ndarrays indexed by tuples,\n storage format of SparseGrid\n Or b) an fvec - e.g. output of self.extract_fvec(fval)\n \"\"\"", "\"\"\"\n Polynomial interpolation based on this tensor-product rule\n x - location at which to interpolate ndarray (dim,)\n fval - dictionary of function values indexed by tuples\n \"\"\"", "\"\"\"\n Return fvec (itself the return value of self.extract_fvec()) viewed as a\n rank (self.dim) array - i.e. the most natural (unencoded) form of the\n data. Nf is the size of the vector output in the case of non-scalar f.\n \"\"\"", "# Scalar-valued f", "# Tensor-valued f", "# (shape of tensor-part)", "\"\"\"Inverse of dimensionate - flatten f into fvec\"\"\"", "# Scalar-valued f", "# Tensor-valued f", "# (shape of tensor-part)", "\"\"\"\n Integrate over a subset of the dimensions of the rule. If axes lists all\n the axes this is equivalent to integrate().\n fval - data evaluated at all support points of the component rule. \n If f is vector-valued the last dimension is the vector\n axes - list of axes over which to integrate\n Return:\n sc_r - SparseComponentRule object of reduced dimension\n fval_r - reduced rank version of fval, dictionary indexed by new\n reduced-dim multi-indices\n axes_r - list of remaining axes in f_r (those not integrated yet)\n \"\"\"", "# Full-rank representation of f", "# Creative use of einsum()", "# Eg. cmd = 'abcde,b,c' for dim=3,", "# axis=[1,2], and matrix-valued f.", "# We avoid the ellipsis '...' because", "# of non-mature implementation.", "# Partial integral of f", "# Complement of axes (remaining axes)", "# Remaining level indices, new comp rule", "# CHECK TODO: correct ordering?" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
15
1,724
186
7d64c956d65caa436c9b9ac4d20cdc2c9cc374bc
dhermes/bezier
src/python/bezier/hazmat/intersection_helpers.py
[ "Apache-2.0" ]
Python
NewtonSimpleRoot
r"""Callable object that facilitates Newton's method. This is meant to be used to compute the Newton update via: .. math:: DF(s, t) \left[\begin{array}{c} \Delta s \\ \Delta t \end{array}\right] = -F(s, t). Args: nodes1 (numpy.ndarray): Control points of the first curve. first_deriv1 (numpy.ndarray): Control points of the curve :math:`B_1'(s)`. nodes2 (numpy.ndarray): Control points of the second curve. first_deriv2 (numpy.ndarray): Control points of the curve :math:`B_2'(t)`.
r"""Callable object that facilitates Newton's method. This is meant to be used to compute the Newton update via.
[ "r", "\"", "\"", "\"", "Callable", "object", "that", "facilitates", "Newton", "'", "s", "method", ".", "This", "is", "meant", "to", "be", "used", "to", "compute", "the", "Newton", "update", "via", "." ]
class NewtonSimpleRoot: # pylint: disable=too-few-public-methods r"""Callable object that facilitates Newton's method. This is meant to be used to compute the Newton update via: .. math:: DF(s, t) \left[\begin{array}{c} \Delta s \\ \Delta t \end{array}\right] = -F(s, t). Args: nodes1 (numpy.ndarray): Control points of the first curve. first_deriv1 (numpy.ndarray): Control points of the curve :math:`B_1'(s)`. nodes2 (numpy.ndarray): Control points of the second curve. first_deriv2 (numpy.ndarray): Control points of the curve :math:`B_2'(t)`. """ def __init__(self, nodes1, first_deriv1, nodes2, first_deriv2): self.nodes1 = nodes1 self.first_deriv1 = first_deriv1 self.nodes2 = nodes2 self.first_deriv2 = first_deriv2 def __call__(self, s, t): r"""This computes :math:`F = B_1(s) - B_2(t)` and :math:`DF(s, t)`. .. note:: There is **almost** identical code in :func:`.newton_refine`, but that code can avoid computing the ``first_deriv1`` and ``first_deriv2`` nodes in cases that :math:`F(s, t) = 0` whereas this function assumes they have been given. In the case that :math:`DF(s, t)` is singular, the assumption is that the intersection has a multiplicity higher than one (i.e. the root is non-simple). **Near** a simple root, it must be the case that :math:`DF(s, t)` has non-zero determinant, so due to continuity, we assume the Jacobian will be invertible nearby. Args: s (float): The parameter where we'll compute :math:`B_1(s)` and :math:`DF(s, t)`. t (float): The parameter where we'll compute :math:`B_2(t)` and :math:`DF(s, t)`. Returns: Tuple[Optional[numpy.ndarray], numpy.ndarray]: Pair of * The LHS matrix ``DF``, a ``2 x 2`` array. If ``F == 0`` then this matrix won't be computed and :data:`None` will be returned. * The RHS vector ``F``, a ``2 x 1`` array. """ s_vals = np.asfortranarray([s]) b1_s = curve_helpers.evaluate_multi(self.nodes1, s_vals) t_vals = np.asfortranarray([t]) b2_t = curve_helpers.evaluate_multi(self.nodes2, t_vals) func_val = b1_s - b2_t if np.all(func_val == 0.0): return None, func_val else: jacobian = np.empty((2, 2), order="F") jacobian[:, :1] = curve_helpers.evaluate_multi( self.first_deriv1, s_vals ) jacobian[:, 1:] = -curve_helpers.evaluate_multi( self.first_deriv2, t_vals ) return jacobian, func_val
[ "class", "NewtonSimpleRoot", ":", "def", "__init__", "(", "self", ",", "nodes1", ",", "first_deriv1", ",", "nodes2", ",", "first_deriv2", ")", ":", "self", ".", "nodes1", "=", "nodes1", "self", ".", "first_deriv1", "=", "first_deriv1", "self", ".", "nodes2", "=", "nodes2", "self", ".", "first_deriv2", "=", "first_deriv2", "def", "__call__", "(", "self", ",", "s", ",", "t", ")", ":", "r\"\"\"This computes :math:`F = B_1(s) - B_2(t)` and :math:`DF(s, t)`.\n\n .. note::\n\n There is **almost** identical code in :func:`.newton_refine`, but\n that code can avoid computing the ``first_deriv1`` and\n ``first_deriv2`` nodes in cases that :math:`F(s, t) = 0` whereas\n this function assumes they have been given.\n\n In the case that :math:`DF(s, t)` is singular, the assumption is that\n the intersection has a multiplicity higher than one (i.e. the root is\n non-simple). **Near** a simple root, it must be the case that\n :math:`DF(s, t)` has non-zero determinant, so due to continuity, we\n assume the Jacobian will be invertible nearby.\n\n Args:\n s (float): The parameter where we'll compute :math:`B_1(s)` and\n :math:`DF(s, t)`.\n t (float): The parameter where we'll compute :math:`B_2(t)` and\n :math:`DF(s, t)`.\n\n Returns:\n Tuple[Optional[numpy.ndarray], numpy.ndarray]: Pair of\n\n * The LHS matrix ``DF``, a ``2 x 2`` array. If ``F == 0`` then\n this matrix won't be computed and :data:`None` will be returned.\n * The RHS vector ``F``, a ``2 x 1`` array.\n \"\"\"", "s_vals", "=", "np", ".", "asfortranarray", "(", "[", "s", "]", ")", "b1_s", "=", "curve_helpers", ".", "evaluate_multi", "(", "self", ".", "nodes1", ",", "s_vals", ")", "t_vals", "=", "np", ".", "asfortranarray", "(", "[", "t", "]", ")", "b2_t", "=", "curve_helpers", ".", "evaluate_multi", "(", "self", ".", "nodes2", ",", "t_vals", ")", "func_val", "=", "b1_s", "-", "b2_t", "if", "np", ".", "all", "(", "func_val", "==", "0.0", ")", ":", "return", "None", ",", "func_val", "else", ":", "jacobian", "=", "np", ".", "empty", "(", "(", "2", ",", "2", ")", ",", "order", "=", "\"F\"", ")", "jacobian", "[", ":", ",", ":", "1", "]", "=", "curve_helpers", ".", "evaluate_multi", "(", "self", ".", "first_deriv1", ",", "s_vals", ")", "jacobian", "[", ":", ",", "1", ":", "]", "=", "-", "curve_helpers", ".", "evaluate_multi", "(", "self", ".", "first_deriv2", ",", "t_vals", ")", "return", "jacobian", ",", "func_val" ]
r"""Callable object that facilitates Newton's method.
[ "r", "\"", "\"", "\"", "Callable", "object", "that", "facilitates", "Newton", "'", "s", "method", "." ]
[ "# pylint: disable=too-few-public-methods", "r\"\"\"Callable object that facilitates Newton's method.\n\n This is meant to be used to compute the Newton update via:\n\n .. math::\n\n DF(s, t) \\left[\\begin{array}{c}\n \\Delta s \\\\ \\Delta t \\end{array}\\right] = -F(s, t).\n\n Args:\n nodes1 (numpy.ndarray): Control points of the first curve.\n first_deriv1 (numpy.ndarray): Control points of the curve\n :math:`B_1'(s)`.\n nodes2 (numpy.ndarray): Control points of the second curve.\n first_deriv2 (numpy.ndarray): Control points of the curve\n :math:`B_2'(t)`.\n \"\"\"", "r\"\"\"This computes :math:`F = B_1(s) - B_2(t)` and :math:`DF(s, t)`.\n\n .. note::\n\n There is **almost** identical code in :func:`.newton_refine`, but\n that code can avoid computing the ``first_deriv1`` and\n ``first_deriv2`` nodes in cases that :math:`F(s, t) = 0` whereas\n this function assumes they have been given.\n\n In the case that :math:`DF(s, t)` is singular, the assumption is that\n the intersection has a multiplicity higher than one (i.e. the root is\n non-simple). **Near** a simple root, it must be the case that\n :math:`DF(s, t)` has non-zero determinant, so due to continuity, we\n assume the Jacobian will be invertible nearby.\n\n Args:\n s (float): The parameter where we'll compute :math:`B_1(s)` and\n :math:`DF(s, t)`.\n t (float): The parameter where we'll compute :math:`B_2(t)` and\n :math:`DF(s, t)`.\n\n Returns:\n Tuple[Optional[numpy.ndarray], numpy.ndarray]: Pair of\n\n * The LHS matrix ``DF``, a ``2 x 2`` array. If ``F == 0`` then\n this matrix won't be computed and :data:`None` will be returned.\n * The RHS vector ``F``, a ``2 x 1`` array.\n \"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [ { "identifier": "nodes1", "type": null, "docstring": "Control points of the first curve.", "docstring_tokens": [ "Control", "points", "of", "the", "first", "curve", "." ], "default": null, "is_optional": false }, { "identifier": "first_deriv1", "type": null, "docstring": "Control points of the curve\n:math:`B_1'(s)`.", "docstring_tokens": [ "Control", "points", "of", "the", "curve", ":", "math", ":", "`", "B_1", "'", "(", "s", ")", "`", "." ], "default": null, "is_optional": false }, { "identifier": "nodes2", "type": null, "docstring": "Control points of the second curve.", "docstring_tokens": [ "Control", "points", "of", "the", "second", "curve", "." ], "default": null, "is_optional": false }, { "identifier": "first_deriv2", "type": null, "docstring": "Control points of the curve\n:math:`B_2'(t)`.", "docstring_tokens": [ "Control", "points", "of", "the", "curve", ":", "math", ":", "`", "B_2", "'", "(", "t", ")", "`", "." ], "default": null, "is_optional": false } ], "others": [] }
false
14
733
147
3fea251ad96e4dbfd3fab698b559ce7976fa6374
0xDEC0DE/spinach
spinach/queuey.py
[ "BSD-2-Clause" ]
Python
Queuey
Hybrid queue allowing to interface sync and async(io) code. It is widely inspired by a talk by David Beazley on the subject: https://www.youtube.com/watch?v=x1ndXuw7S0s One big difference with a normal queue is that even with a maxsize set to a fixed number, this queue can still end up taking an infinite amount of memory since pending get/put operation are kept as futures. It is an alternative to the 3rd-party Janus library which had shortcomings when used in Spinach: - Janus queues have to be created in an asyncio coroutine, turning the creation of the queue in the Workers class into a strange dance. - It was not obvious to me how to implement showing the queue as full if there are unfinished tasks. - It adds a few dependencies only needed by a fractions of users, adds a ton of code for something that should be simple.
Hybrid queue allowing to interface sync and async(io) code. One big difference with a normal queue is that even with a maxsize set to a fixed number, this queue can still end up taking an infinite amount of memory since pending get/put operation are kept as futures. It is an alternative to the 3rd-party Janus library which had shortcomings when used in Spinach: Janus queues have to be created in an asyncio coroutine, turning the creation of the queue in the Workers class into a strange dance. It was not obvious to me how to implement showing the queue as full if there are unfinished tasks. It adds a few dependencies only needed by a fractions of users, adds a ton of code for something that should be simple.
[ "Hybrid", "queue", "allowing", "to", "interface", "sync", "and", "async", "(", "io", ")", "code", ".", "One", "big", "difference", "with", "a", "normal", "queue", "is", "that", "even", "with", "a", "maxsize", "set", "to", "a", "fixed", "number", "this", "queue", "can", "still", "end", "up", "taking", "an", "infinite", "amount", "of", "memory", "since", "pending", "get", "/", "put", "operation", "are", "kept", "as", "futures", ".", "It", "is", "an", "alternative", "to", "the", "3rd", "-", "party", "Janus", "library", "which", "had", "shortcomings", "when", "used", "in", "Spinach", ":", "Janus", "queues", "have", "to", "be", "created", "in", "an", "asyncio", "coroutine", "turning", "the", "creation", "of", "the", "queue", "in", "the", "Workers", "class", "into", "a", "strange", "dance", ".", "It", "was", "not", "obvious", "to", "me", "how", "to", "implement", "showing", "the", "queue", "as", "full", "if", "there", "are", "unfinished", "tasks", ".", "It", "adds", "a", "few", "dependencies", "only", "needed", "by", "a", "fractions", "of", "users", "adds", "a", "ton", "of", "code", "for", "something", "that", "should", "be", "simple", "." ]
class Queuey: """Hybrid queue allowing to interface sync and async(io) code. It is widely inspired by a talk by David Beazley on the subject: https://www.youtube.com/watch?v=x1ndXuw7S0s One big difference with a normal queue is that even with a maxsize set to a fixed number, this queue can still end up taking an infinite amount of memory since pending get/put operation are kept as futures. It is an alternative to the 3rd-party Janus library which had shortcomings when used in Spinach: - Janus queues have to be created in an asyncio coroutine, turning the creation of the queue in the Workers class into a strange dance. - It was not obvious to me how to implement showing the queue as full if there are unfinished tasks. - It adds a few dependencies only needed by a fractions of users, adds a ton of code for something that should be simple. """ def __init__(self, maxsize: int): self.maxsize = maxsize self._mutex = threading.Lock() self._items: Deque[Any] = deque() self._getters: Deque[Future] = deque() self._putters: Deque[Tuple[Any, Future]] = deque() self._unfinished_tasks = 0 def _get_noblock(self) -> Tuple[Optional[Any], Optional[Future]]: with self._mutex: if self._items: if self._putters: # About to remove one item from the queue which means # that a new spot will be available. Since there are # putters waiting, wake up one and take its item. item, put_fut = self._putters.popleft() self._items.append(item) put_fut.set_result(True) return self._items.popleft(), None else: fut = Future() self._getters.append(fut) return None, fut def _put_noblock(self, item: Any) -> Optional[Future]: with self._mutex: if len(self._items) < self.maxsize: self._items.append(item) self._unfinished_tasks += 1 if self._getters: self._getters.popleft().set_result(self._items.popleft()) else: fut = Future() self._putters.append((item, fut)) return fut def get_sync(self) -> Any: item, fut = self._get_noblock() if fut: item = fut.result() return item def put_sync(self, item: Any) -> None: fut = self._put_noblock(item) if fut is None: return fut.result() async def get_async(self) -> Any: item, fut = self._get_noblock() if fut: item = await asyncio.wait_for(asyncio.wrap_future(fut), None) return item async def put_async(self, item: Any) -> None: fut = self._put_noblock(item) if fut is None: return await asyncio.wait_for(asyncio.wrap_future(fut), None) def task_done(self) -> None: """Indicate that a formerly enqueued task is complete. Raises a ValueError if called more times than there were items placed in the queue. """ with self._mutex: unfinished = self._unfinished_tasks - 1 if unfinished < 0: raise ValueError('task_done() called too many times') self._unfinished_tasks = unfinished def empty(self) -> bool: with self._mutex: return self._unfinished_tasks == 0 def full(self) -> bool: with self._mutex: return self.maxsize <= self._unfinished_tasks def available_slots(self) -> int: with self._mutex: return self.maxsize - self._unfinished_tasks
[ "class", "Queuey", ":", "def", "__init__", "(", "self", ",", "maxsize", ":", "int", ")", ":", "self", ".", "maxsize", "=", "maxsize", "self", ".", "_mutex", "=", "threading", ".", "Lock", "(", ")", "self", ".", "_items", ":", "Deque", "[", "Any", "]", "=", "deque", "(", ")", "self", ".", "_getters", ":", "Deque", "[", "Future", "]", "=", "deque", "(", ")", "self", ".", "_putters", ":", "Deque", "[", "Tuple", "[", "Any", ",", "Future", "]", "]", "=", "deque", "(", ")", "self", ".", "_unfinished_tasks", "=", "0", "def", "_get_noblock", "(", "self", ")", "->", "Tuple", "[", "Optional", "[", "Any", "]", ",", "Optional", "[", "Future", "]", "]", ":", "with", "self", ".", "_mutex", ":", "if", "self", ".", "_items", ":", "if", "self", ".", "_putters", ":", "item", ",", "put_fut", "=", "self", ".", "_putters", ".", "popleft", "(", ")", "self", ".", "_items", ".", "append", "(", "item", ")", "put_fut", ".", "set_result", "(", "True", ")", "return", "self", ".", "_items", ".", "popleft", "(", ")", ",", "None", "else", ":", "fut", "=", "Future", "(", ")", "self", ".", "_getters", ".", "append", "(", "fut", ")", "return", "None", ",", "fut", "def", "_put_noblock", "(", "self", ",", "item", ":", "Any", ")", "->", "Optional", "[", "Future", "]", ":", "with", "self", ".", "_mutex", ":", "if", "len", "(", "self", ".", "_items", ")", "<", "self", ".", "maxsize", ":", "self", ".", "_items", ".", "append", "(", "item", ")", "self", ".", "_unfinished_tasks", "+=", "1", "if", "self", ".", "_getters", ":", "self", ".", "_getters", ".", "popleft", "(", ")", ".", "set_result", "(", "self", ".", "_items", ".", "popleft", "(", ")", ")", "else", ":", "fut", "=", "Future", "(", ")", "self", ".", "_putters", ".", "append", "(", "(", "item", ",", "fut", ")", ")", "return", "fut", "def", "get_sync", "(", "self", ")", "->", "Any", ":", "item", ",", "fut", "=", "self", ".", "_get_noblock", "(", ")", "if", "fut", ":", "item", "=", "fut", ".", "result", "(", ")", "return", "item", "def", "put_sync", "(", "self", ",", "item", ":", "Any", ")", "->", "None", ":", "fut", "=", "self", ".", "_put_noblock", "(", "item", ")", "if", "fut", "is", "None", ":", "return", "fut", ".", "result", "(", ")", "async", "def", "get_async", "(", "self", ")", "->", "Any", ":", "item", ",", "fut", "=", "self", ".", "_get_noblock", "(", ")", "if", "fut", ":", "item", "=", "await", "asyncio", ".", "wait_for", "(", "asyncio", ".", "wrap_future", "(", "fut", ")", ",", "None", ")", "return", "item", "async", "def", "put_async", "(", "self", ",", "item", ":", "Any", ")", "->", "None", ":", "fut", "=", "self", ".", "_put_noblock", "(", "item", ")", "if", "fut", "is", "None", ":", "return", "await", "asyncio", ".", "wait_for", "(", "asyncio", ".", "wrap_future", "(", "fut", ")", ",", "None", ")", "def", "task_done", "(", "self", ")", "->", "None", ":", "\"\"\"Indicate that a formerly enqueued task is complete.\n\n Raises a ValueError if called more times than there were items\n placed in the queue.\n \"\"\"", "with", "self", ".", "_mutex", ":", "unfinished", "=", "self", ".", "_unfinished_tasks", "-", "1", "if", "unfinished", "<", "0", ":", "raise", "ValueError", "(", "'task_done() called too many times'", ")", "self", ".", "_unfinished_tasks", "=", "unfinished", "def", "empty", "(", "self", ")", "->", "bool", ":", "with", "self", ".", "_mutex", ":", "return", "self", ".", "_unfinished_tasks", "==", "0", "def", "full", "(", "self", ")", "->", "bool", ":", "with", "self", ".", "_mutex", ":", "return", "self", ".", "maxsize", "<=", "self", ".", "_unfinished_tasks", "def", "available_slots", "(", "self", ")", "->", "int", ":", "with", "self", ".", "_mutex", ":", "return", "self", ".", "maxsize", "-", "self", ".", "_unfinished_tasks" ]
Hybrid queue allowing to interface sync and async(io) code.
[ "Hybrid", "queue", "allowing", "to", "interface", "sync", "and", "async", "(", "io", ")", "code", "." ]
[ "\"\"\"Hybrid queue allowing to interface sync and async(io) code.\n\n It is widely inspired by a talk by David Beazley on the subject:\n https://www.youtube.com/watch?v=x1ndXuw7S0s\n\n One big difference with a normal queue is that even with a maxsize\n set to a fixed number, this queue can still end up taking an\n infinite amount of memory since pending get/put operation are kept\n as futures.\n\n It is an alternative to the 3rd-party Janus library which had\n shortcomings when used in Spinach:\n - Janus queues have to be created in an asyncio coroutine, turning\n the creation of the queue in the Workers class into a strange dance.\n - It was not obvious to me how to implement showing the queue as full\n if there are unfinished tasks.\n - It adds a few dependencies only needed by a fractions of users, adds a\n ton of code for something that should be simple.\n \"\"\"", "# About to remove one item from the queue which means", "# that a new spot will be available. Since there are", "# putters waiting, wake up one and take its item.", "\"\"\"Indicate that a formerly enqueued task is complete.\n\n Raises a ValueError if called more times than there were items\n placed in the queue.\n \"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
17
861
208
65129fbe877767638375802ef08a6722dce0852d
Tall-Paul/PrimePenguin.WixSharp
WixSharp/Infrastructure/Policies/SmartRetryExecutionPolicy.cs
[ "MIT" ]
C#
SmartRetryExecutionPolicy
/// <summary> /// A retry policy that attemps to pro-actively limit the number of requests that will result in a WixRateLimitException /// by implementing the leaky bucket algorithm. /// For example: if 100 requests are created in parallel, only 40 should be immediately sent, and the subsequent 60 requests /// should be throttled at 1 per 500ms. /// </summary> /// <remarks> /// In comparison, the naive retry policy will issue the 100 requests immediately: /// 60 requests will fail and be retried after 500ms, /// 59 requests will fail and be retried after 500ms, /// 58 requests will fail and be retried after 500ms. /// See https://help.Wix.com/api/guides/api-call-limit /// https://en.wikipedia.org/wiki/Leaky_bucket /// </remarks>
A retry policy that attemps to pro-actively limit the number of requests that will result in a WixRateLimitException by implementing the leaky bucket algorithm. For example: if 100 requests are created in parallel, only 40 should be immediately sent, and the subsequent 60 requests should be throttled at 1 per 500ms.
[ "A", "retry", "policy", "that", "attemps", "to", "pro", "-", "actively", "limit", "the", "number", "of", "requests", "that", "will", "result", "in", "a", "WixRateLimitException", "by", "implementing", "the", "leaky", "bucket", "algorithm", ".", "For", "example", ":", "if", "100", "requests", "are", "created", "in", "parallel", "only", "40", "should", "be", "immediately", "sent", "and", "the", "subsequent", "60", "requests", "should", "be", "throttled", "at", "1", "per", "500ms", "." ]
public partial class SmartRetryExecutionPolicy : IRequestExecutionPolicy { private const string RESPONSE_HEADER_API_CALL_LIMIT = "X-Wix-Shop-Api-Call-Limit"; private const string REQUEST_HEADER_ACCESS_TOKEN = "X-Wix-Access-Token"; private static readonly TimeSpan THROTTLE_DELAY = TimeSpan.FromMilliseconds(500); private static ConcurrentDictionary<string, LeakyBucket> _shopAccessTokenToLeakyBucket = new ConcurrentDictionary<string, LeakyBucket>(); public async Task<T> Run<T>(CloneableRequestMessage baseRequest, ExecuteRequestAsync<T> executeRequestAsync) { var accessToken = GetAccessToken(baseRequest); LeakyBucket bucket = null; if (accessToken != null) { bucket = _shopAccessTokenToLeakyBucket.GetOrAdd(accessToken, _ => new LeakyBucket()); } while (true) { var request = baseRequest.Clone(); if (accessToken != null) { await bucket.GrantAsync(); } try { var fullResult = await executeRequestAsync(request); var bucketState = GetBucketState(fullResult.Response); if (bucketState != null) { bucket?.SetState(bucketState); } return fullResult.Result; } catch (WixRateLimitException) { await Task.Delay(THROTTLE_DELAY); } } } private string GetAccessToken(HttpRequestMessage client) { IEnumerable<string> values = new List<string>(); return client.Headers.TryGetValues(REQUEST_HEADER_ACCESS_TOKEN, out values) ? values.FirstOrDefault() : null; } private LeakyBucketState GetBucketState(HttpResponseMessage response) { var headers = response.Headers.FirstOrDefault(kvp => kvp.Key == RESPONSE_HEADER_API_CALL_LIMIT); var apiCallLimitHeaderValue = headers.Value?.FirstOrDefault(); if (apiCallLimitHeaderValue != null) { var split = apiCallLimitHeaderValue.Split('/'); if (split.Length == 2 && int.TryParse(split[0], out int currentFillLevel) && int.TryParse(split[1], out int capacity)) { return new LeakyBucketState(capacity, currentFillLevel); } } return null; } }
[ "public", "partial", "class", "SmartRetryExecutionPolicy", ":", "IRequestExecutionPolicy", "{", "private", "const", "string", "RESPONSE_HEADER_API_CALL_LIMIT", "=", "\"", "X-Wix-Shop-Api-Call-Limit", "\"", ";", "private", "const", "string", "REQUEST_HEADER_ACCESS_TOKEN", "=", "\"", "X-Wix-Access-Token", "\"", ";", "private", "static", "readonly", "TimeSpan", "THROTTLE_DELAY", "=", "TimeSpan", ".", "FromMilliseconds", "(", "500", ")", ";", "private", "static", "ConcurrentDictionary", "<", "string", ",", "LeakyBucket", ">", "_shopAccessTokenToLeakyBucket", "=", "new", "ConcurrentDictionary", "<", "string", ",", "LeakyBucket", ">", "(", ")", ";", "public", "async", "Task", "<", "T", ">", "Run", "<", "T", ">", "(", "CloneableRequestMessage", "baseRequest", ",", "ExecuteRequestAsync", "<", "T", ">", "executeRequestAsync", ")", "{", "var", "accessToken", "=", "GetAccessToken", "(", "baseRequest", ")", ";", "LeakyBucket", "bucket", "=", "null", ";", "if", "(", "accessToken", "!=", "null", ")", "{", "bucket", "=", "_shopAccessTokenToLeakyBucket", ".", "GetOrAdd", "(", "accessToken", ",", "_", "=>", "new", "LeakyBucket", "(", ")", ")", ";", "}", "while", "(", "true", ")", "{", "var", "request", "=", "baseRequest", ".", "Clone", "(", ")", ";", "if", "(", "accessToken", "!=", "null", ")", "{", "await", "bucket", ".", "GrantAsync", "(", ")", ";", "}", "try", "{", "var", "fullResult", "=", "await", "executeRequestAsync", "(", "request", ")", ";", "var", "bucketState", "=", "GetBucketState", "(", "fullResult", ".", "Response", ")", ";", "if", "(", "bucketState", "!=", "null", ")", "{", "bucket", "?", ".", "SetState", "(", "bucketState", ")", ";", "}", "return", "fullResult", ".", "Result", ";", "}", "catch", "(", "WixRateLimitException", ")", "{", "await", "Task", ".", "Delay", "(", "THROTTLE_DELAY", ")", ";", "}", "}", "}", "private", "string", "GetAccessToken", "(", "HttpRequestMessage", "client", ")", "{", "IEnumerable", "<", "string", ">", "values", "=", "new", "List", "<", "string", ">", "(", ")", ";", "return", "client", ".", "Headers", ".", "TryGetValues", "(", "REQUEST_HEADER_ACCESS_TOKEN", ",", "out", "values", ")", "?", "values", ".", "FirstOrDefault", "(", ")", ":", "null", ";", "}", "private", "LeakyBucketState", "GetBucketState", "(", "HttpResponseMessage", "response", ")", "{", "var", "headers", "=", "response", ".", "Headers", ".", "FirstOrDefault", "(", "kvp", "=>", "kvp", ".", "Key", "==", "RESPONSE_HEADER_API_CALL_LIMIT", ")", ";", "var", "apiCallLimitHeaderValue", "=", "headers", ".", "Value", "?", ".", "FirstOrDefault", "(", ")", ";", "if", "(", "apiCallLimitHeaderValue", "!=", "null", ")", "{", "var", "split", "=", "apiCallLimitHeaderValue", ".", "Split", "(", "'", "/", "'", ")", ";", "if", "(", "split", ".", "Length", "==", "2", "&&", "int", ".", "TryParse", "(", "split", "[", "0", "]", ",", "out", "int", "currentFillLevel", ")", "&&", "int", ".", "TryParse", "(", "split", "[", "1", "]", ",", "out", "int", "capacity", ")", ")", "{", "return", "new", "LeakyBucketState", "(", "capacity", ",", "currentFillLevel", ")", ";", "}", "}", "return", "null", ";", "}", "}" ]
A retry policy that attemps to pro-actively limit the number of requests that will result in a WixRateLimitException by implementing the leaky bucket algorithm.
[ "A", "retry", "policy", "that", "attemps", "to", "pro", "-", "actively", "limit", "the", "number", "of", "requests", "that", "will", "result", "in", "a", "WixRateLimitException", "by", "implementing", "the", "leaky", "bucket", "algorithm", "." ]
[ "//An exception may still occur:", "//-Wix may have a slightly different algorithm", "//-Wix may change to a different algorithm in the future", "//-There may be timing and latency delays", "//-Multiple programs may use the same access token", "//-Multiple instances of the same program may use the same access token" ]
[ { "param": "IRequestExecutionPolicy", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "IRequestExecutionPolicy", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [ { "identifier": "remarks", "docstring": "In comparison, the naive retry policy will issue the 100 requests immediately:\n60 requests will fail and be retried after 500ms,\n59 requests will fail and be retried after 500ms,\n58 requests will fail and be retried after 500ms.", "docstring_tokens": [ "In", "comparison", "the", "naive", "retry", "policy", "will", "issue", "the", "100", "requests", "immediately", ":", "60", "requests", "will", "fail", "and", "be", "retried", "after", "500ms", "59", "requests", "will", "fail", "and", "be", "retried", "after", "500ms", "58", "requests", "will", "fail", "and", "be", "retried", "after", "500ms", "." ] } ] }
false
16
476
199
49e40a59a1b4ee6c1993a6c4d5de6add4724614a
Scarjit/PUBGSDK
PUBGSDK/URL.Designer.cs
[ "MIT" ]
C#
URL
/// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project.
A strongly-typed resource class, for looking up localized strings, etc.
[ "A", "strongly", "-", "typed", "resource", "class", "for", "looking", "up", "localized", "strings", "etc", "." ]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class URL { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal URL() { } [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("PUBGSDK.URL", typeof(URL).Assembly); resourceMan = temp; } return resourceMan; } } [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } internal static string base_extension { get { return ResourceManager.GetString("base_extension", resourceCulture); } } internal static string base_url { get { return ResourceManager.GetString("base_url", resourceCulture); } } internal static string match { get { return ResourceManager.GetString("match", resourceCulture); } } internal static string player { get { return ResourceManager.GetString("player", resourceCulture); } } internal static string player_ids { get { return ResourceManager.GetString("player_ids", resourceCulture); } } internal static string player_names { get { return ResourceManager.GetString("player_names", resourceCulture); } } internal static string status { get { return ResourceManager.GetString("status", resourceCulture); } } }
[ "[", "global", "::", "System", ".", "CodeDom", ".", "Compiler", ".", "GeneratedCodeAttribute", "(", "\"", "System.Resources.Tools.StronglyTypedResourceBuilder", "\"", ",", "\"", "15.0.0.0", "\"", ")", "]", "[", "global", "::", "System", ".", "Diagnostics", ".", "DebuggerNonUserCodeAttribute", "(", ")", "]", "[", "global", "::", "System", ".", "Runtime", ".", "CompilerServices", ".", "CompilerGeneratedAttribute", "(", ")", "]", "internal", "class", "URL", "{", "private", "static", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "resourceMan", ";", "private", "static", "global", "::", "System", ".", "Globalization", ".", "CultureInfo", "resourceCulture", ";", "[", "global", "::", "System", ".", "Diagnostics", ".", "CodeAnalysis", ".", "SuppressMessageAttribute", "(", "\"", "Microsoft.Performance", "\"", ",", "\"", "CA1811:AvoidUncalledPrivateCode", "\"", ")", "]", "internal", "URL", "(", ")", "{", "}", "[", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableAttribute", "(", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableState", ".", "Advanced", ")", "]", "internal", "static", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "ResourceManager", "{", "get", "{", "if", "(", "object", ".", "ReferenceEquals", "(", "resourceMan", ",", "null", ")", ")", "{", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "temp", "=", "new", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "(", "\"", "PUBGSDK.URL", "\"", ",", "typeof", "(", "URL", ")", ".", "Assembly", ")", ";", "resourceMan", "=", "temp", ";", "}", "return", "resourceMan", ";", "}", "}", "[", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableAttribute", "(", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableState", ".", "Advanced", ")", "]", "internal", "static", "global", "::", "System", ".", "Globalization", ".", "CultureInfo", "Culture", "{", "get", "{", "return", "resourceCulture", ";", "}", "set", "{", "resourceCulture", "=", "value", ";", "}", "}", "internal", "static", "string", "base_extension", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "base_extension", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "base_url", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "base_url", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "match", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "match", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "player", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "player", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "player_ids", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "player_ids", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "player_names", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "player_names", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "status", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "status", "\"", ",", "resourceCulture", ")", ";", "}", "}", "}" ]
A strongly-typed resource class, for looking up localized strings, etc.
[ "A", "strongly", "-", "typed", "resource", "class", "for", "looking", "up", "localized", "strings", "etc", "." ]
[ "/// <summary>", "/// Returns the cached ResourceManager instance used by this class.", "/// </summary>", "/// <summary>", "/// Overrides the current thread's CurrentUICulture property for all", "/// resource lookups using this strongly typed resource class.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to shards/.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to https://api.playbattlegrounds.com/.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to matches/.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to players/.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to players?filter[playerIds]=.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to players?filter[playerNames]=.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to status.", "/// </summary>" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
17
431
84
3487bd4b5a2b740631899d464eb7092a1a710c32
Contrast-Security-OSS/redmine-plugin
lib/contrast_util.rb
[ "MIT" ]
Ruby
ContrastUtil
# MIT License # Copyright (c) 2020 Contrast Security Japan G.K. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE.
MIT License Copyright (c) 2020 Contrast Security Japan G.K. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
[ "MIT", "License", "Copyright", "(", "c", ")", "2020", "Contrast", "Security", "Japan", "G", ".", "K", ".", "Permission", "is", "hereby", "granted", "free", "of", "charge", "to", "any", "person", "obtaining", "a", "copy", "of", "this", "software", "and", "associated", "documentation", "files", "(", "the", "\"", "Software", "\"", ")", "to", "deal", "in", "the", "Software", "without", "restriction", "including", "without", "limitation", "the", "rights", "to", "use", "copy", "modify", "merge", "publish", "distribute", "sublicense", "and", "/", "or", "sell", "copies", "of", "the", "Software", "and", "to", "permit", "persons", "to", "whom", "the", "Software", "is", "furnished", "to", "do", "so", "subject", "to", "the", "following", "conditions", ".", "The", "above", "copyright", "notice", "and", "this", "permission", "notice", "shall", "be", "included", "in", "all", "copies", "or", "substantial", "portions", "of", "the", "Software", "." ]
module ContrastUtil include Redmine::I18n def self.get_priority_by_severity(severity) case severity when "Critical" priority_str = Setting.plugin_contrastsecurity['pri_critical'] when "High" priority_str = Setting.plugin_contrastsecurity['pri_high'] when "Medium" priority_str = Setting.plugin_contrastsecurity['pri_medium'] when "Low" priority_str = Setting.plugin_contrastsecurity['pri_low'] when "Note" priority_str = Setting.plugin_contrastsecurity['pri_note'] end priority = IssuePriority.find_by_name(priority_str) return priority end def self.get_redmine_status(contrast_status) case contrast_status when "Reported", "報告済" rm_status = Setting.plugin_contrastsecurity['sts_reported'] when "Suspicious", "疑わしい" rm_status = Setting.plugin_contrastsecurity['sts_suspicious'] when "Confirmed", "確認済" rm_status = Setting.plugin_contrastsecurity['sts_confirmed'] when "NotAProblem", "Not a Problem", "問題無し" rm_status = Setting.plugin_contrastsecurity['sts_notaproblem'] when "Remediated", "修復済" rm_status = Setting.plugin_contrastsecurity['sts_remediated'] when "Fixed", "修正完了" rm_status = Setting.plugin_contrastsecurity['sts_fixed'] end status = IssueStatus.find_by_name(rm_status) return status end def self.get_contrast_status(redmine_status) sts_reported_array = [Setting.plugin_contrastsecurity['sts_reported']] sts_suspicious_array = [Setting.plugin_contrastsecurity['sts_suspicious']] sts_confirmed_array = [Setting.plugin_contrastsecurity['sts_confirmed']] sts_notaproblem_array = [Setting.plugin_contrastsecurity['sts_notaproblem']] sts_remediated_array = [Setting.plugin_contrastsecurity['sts_remediated']] sts_fixed_array = [Setting.plugin_contrastsecurity['sts_fixed']] status = nil if sts_reported_array.include?(redmine_status) status = "Reported" elsif sts_suspicious_array.include?(redmine_status) status = "Suspicious" elsif sts_confirmed_array.include?(redmine_status) status = "Confirmed" elsif sts_notaproblem_array.include?(redmine_status) status = "NotAProblem" elsif sts_remediated_array.include?(redmine_status) status = "Remediated" elsif sts_fixed_array.include?(redmine_status) status = "Fixed" end return status end def callAPI(url: , method: "GET", data: nil, api_key: nil, username: nil, service_key: nil, proxy_host: nil, proxy_port: nil, proxy_user: nil, proxy_pass: nil) uri = URI.parse(url) http = nil proxy_host ||= Setting.plugin_contrastsecurity['proxy_host'] proxy_port ||= Setting.plugin_contrastsecurity['proxy_port'] proxy_user ||= Setting.plugin_contrastsecurity['proxy_user'] proxy_pass ||= Setting.plugin_contrastsecurity['proxy_pass'] proxy_uri = "" if proxy_host.present? && proxy_port.present? proxy_uri = URI.parse(sprintf('http://%s:%d', proxy_host, proxy_port)) if proxy_user.present? && proxy_pass.present? http = Net::HTTP.new(uri.host, uri.port, proxy_uri.host, proxy_uri.port, proxy_user, proxy_pass) else http = Net::HTTP.new(uri.host, uri.port, proxy_uri.host, proxy_uri.port) end else http = Net::HTTP.new(uri.host, uri.port) end http.use_ssl = false if uri.scheme === "https" http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_NONE end case method when "GET" req = Net::HTTP::Get.new(uri.request_uri) when "POST" req = Net::HTTP::Post.new(uri.request_uri) req.body = data when "PUT" req = Net::HTTP::Put.new(uri.request_uri) req.body = data when "DELETE" req = Net::HTTP::Delete.new(uri.request_uri) else return end # TeamServer接続設定のみparamから渡されたものを使う。なければ設定から取得 api_key ||= Setting.plugin_contrastsecurity['api_key'] username ||= Setting.plugin_contrastsecurity['username'] service_key ||= Setting.plugin_contrastsecurity['service_key'] auth_header = Base64.strict_encode64(username + ":" + service_key) req["Authorization"] = auth_header req["API-Key"] = api_key req['Content-Type'] = req['Accept'] = 'application/json' begin res = http.request(req) return res, nil rescue => e puts [uri.to_s, e.class, e].join(" : ") return nil, e.to_s end end module_function :callAPI def syncComment(org_id, app_id, vul_id, issue) teamserver_url = Setting.plugin_contrastsecurity['teamserver_url'] url = sprintf('%s/api/ng/%s/applications/%s/traces/%s/notes?expand=skip_links', teamserver_url, org_id, app_id, vul_id) res, msg = callAPI(url: url) if res.present? && res.code != "200" return false end notes_json = JSON.parse(res.body) issue.journals.each do |c_journal| if not c_journal.private_notes c_journal.destroy end end notes_json['notes'].reverse.each do |c_note| old_status_str = "" new_status_str = "" status_change_reason_str = "" if c_note.has_key?("properties") c_note['properties'].each do |c_prop| if c_prop['name'] == "status.change.previous.status" status_obj = ContrastUtil.get_redmine_status(c_prop['value']) unless status_obj.nil? old_status_str = status_obj.name end elsif c_prop['name'] == "status.change.status" status_obj = ContrastUtil.get_redmine_status(c_prop['value']) unless status_obj.nil? new_status_str = status_obj.name end elsif c_prop['name'] == "status.change.substatus" && c_prop['value'].present? status_change_reason_str = l(:notaproblem_reason, :reason => c_prop['value']) + "\n" end end end note_str = CGI.unescapeHTML(status_change_reason_str + c_note['note']) if old_status_str.present? && new_status_str.present? cmt_chg_msg = l(:status_changed_comment, :old => old_status_str, :new => new_status_str) note_str = "(" + cmt_chg_msg + ")\n" + CGI.unescapeHTML(status_change_reason_str + c_note['note']) end journal = Journal.new journal.journalized = issue journal.user = User.current journal.notes = note_str journal.created_on = Time.at(c_note['last_modification']/1000.0) journal.details << JournalDetail.new(property: "cf", prop_key: "contrast_note_id", value: c_note['id']) journal.details << JournalDetail.new(property: "cf", prop_key: "contrast_last_updater_uid", value: c_note['last_updater_uid']) journal.details << JournalDetail.new(property: "cf", prop_key: "contrast_last_updater", value: c_note['last_updater']) journal.save() end return true end module_function :syncComment end
[ "module", "ContrastUtil", "include", "Redmine", "::", "I18n", "def", "self", ".", "get_priority_by_severity", "(", "severity", ")", "case", "severity", "when", "\"Critical\"", "priority_str", "=", "Setting", ".", "plugin_contrastsecurity", "[", "'pri_critical'", "]", "when", "\"High\"", "priority_str", "=", "Setting", ".", "plugin_contrastsecurity", "[", "'pri_high'", "]", "when", "\"Medium\"", "priority_str", "=", "Setting", ".", "plugin_contrastsecurity", "[", "'pri_medium'", "]", "when", "\"Low\"", "priority_str", "=", "Setting", ".", "plugin_contrastsecurity", "[", "'pri_low'", "]", "when", "\"Note\"", "priority_str", "=", "Setting", ".", "plugin_contrastsecurity", "[", "'pri_note'", "]", "end", "priority", "=", "IssuePriority", ".", "find_by_name", "(", "priority_str", ")", "return", "priority", "end", "def", "self", ".", "get_redmine_status", "(", "contrast_status", ")", "case", "contrast_status", "when", "\"Reported\"", ",", "\"報告済\"", "rm_status", "=", "Setting", ".", "plugin_contrastsecurity", "[", "'sts_reported'", "]", "when", "\"Suspicious\"", ",", "\"疑わしい\"", "rm_status", "=", "Setting", ".", "plugin_contrastsecurity", "[", "'sts_suspicious'", "]", "when", "\"Confirmed\"", ",", "\"確認済\"", "rm_status", "=", "Setting", ".", "plugin_contrastsecurity", "[", "'sts_confirmed'", "]", "when", "\"NotAProblem\"", ",", "\"Not a Problem\"", ",", "\"問題無し\"", "rm_status", "=", "Setting", ".", "plugin_contrastsecurity", "[", "'sts_notaproblem'", "]", "when", "\"Remediated\"", ",", "\"修復済\"", "rm_status", "=", "Setting", ".", "plugin_contrastsecurity", "[", "'sts_remediated'", "]", "when", "\"Fixed\"", ",", "\"修正完了\"", "rm_status", "=", "Setting", ".", "plugin_contrastsecurity", "[", "'sts_fixed'", "]", "end", "status", "=", "IssueStatus", ".", "find_by_name", "(", "rm_status", ")", "return", "status", "end", "def", "self", ".", "get_contrast_status", "(", "redmine_status", ")", "sts_reported_array", "=", "[", "Setting", ".", "plugin_contrastsecurity", "[", "'sts_reported'", "]", "]", "sts_suspicious_array", "=", "[", "Setting", ".", "plugin_contrastsecurity", "[", "'sts_suspicious'", "]", "]", "sts_confirmed_array", "=", "[", "Setting", ".", "plugin_contrastsecurity", "[", "'sts_confirmed'", "]", "]", "sts_notaproblem_array", "=", "[", "Setting", ".", "plugin_contrastsecurity", "[", "'sts_notaproblem'", "]", "]", "sts_remediated_array", "=", "[", "Setting", ".", "plugin_contrastsecurity", "[", "'sts_remediated'", "]", "]", "sts_fixed_array", "=", "[", "Setting", ".", "plugin_contrastsecurity", "[", "'sts_fixed'", "]", "]", "status", "=", "nil", "if", "sts_reported_array", ".", "include?", "(", "redmine_status", ")", "status", "=", "\"Reported\"", "elsif", "sts_suspicious_array", ".", "include?", "(", "redmine_status", ")", "status", "=", "\"Suspicious\"", "elsif", "sts_confirmed_array", ".", "include?", "(", "redmine_status", ")", "status", "=", "\"Confirmed\"", "elsif", "sts_notaproblem_array", ".", "include?", "(", "redmine_status", ")", "status", "=", "\"NotAProblem\"", "elsif", "sts_remediated_array", ".", "include?", "(", "redmine_status", ")", "status", "=", "\"Remediated\"", "elsif", "sts_fixed_array", ".", "include?", "(", "redmine_status", ")", "status", "=", "\"Fixed\"", "end", "return", "status", "end", "def", "callAPI", "(", "url", ":", ",", "method", ":", "\"GET\"", ",", "data", ":", "nil", ",", "api_key", ":", "nil", ",", "username", ":", "nil", ",", "service_key", ":", "nil", ",", "proxy_host", ":", "nil", ",", "proxy_port", ":", "nil", ",", "proxy_user", ":", "nil", ",", "proxy_pass", ":", "nil", ")", "uri", "=", "URI", ".", "parse", "(", "url", ")", "http", "=", "nil", "proxy_host", "||=", "Setting", ".", "plugin_contrastsecurity", "[", "'proxy_host'", "]", "proxy_port", "||=", "Setting", ".", "plugin_contrastsecurity", "[", "'proxy_port'", "]", "proxy_user", "||=", "Setting", ".", "plugin_contrastsecurity", "[", "'proxy_user'", "]", "proxy_pass", "||=", "Setting", ".", "plugin_contrastsecurity", "[", "'proxy_pass'", "]", "proxy_uri", "=", "\"\"", "if", "proxy_host", ".", "present?", "&&", "proxy_port", ".", "present?", "proxy_uri", "=", "URI", ".", "parse", "(", "sprintf", "(", "'http://%s:%d'", ",", "proxy_host", ",", "proxy_port", ")", ")", "if", "proxy_user", ".", "present?", "&&", "proxy_pass", ".", "present?", "http", "=", "Net", "::", "HTTP", ".", "new", "(", "uri", ".", "host", ",", "uri", ".", "port", ",", "proxy_uri", ".", "host", ",", "proxy_uri", ".", "port", ",", "proxy_user", ",", "proxy_pass", ")", "else", "http", "=", "Net", "::", "HTTP", ".", "new", "(", "uri", ".", "host", ",", "uri", ".", "port", ",", "proxy_uri", ".", "host", ",", "proxy_uri", ".", "port", ")", "end", "else", "http", "=", "Net", "::", "HTTP", ".", "new", "(", "uri", ".", "host", ",", "uri", ".", "port", ")", "end", "http", ".", "use_ssl", "=", "false", "if", "uri", ".", "scheme", "===", "\"https\"", "http", ".", "use_ssl", "=", "true", "http", ".", "verify_mode", "=", "OpenSSL", "::", "SSL", "::", "VERIFY_NONE", "end", "case", "method", "when", "\"GET\"", "req", "=", "Net", "::", "HTTP", "::", "Get", ".", "new", "(", "uri", ".", "request_uri", ")", "when", "\"POST\"", "req", "=", "Net", "::", "HTTP", "::", "Post", ".", "new", "(", "uri", ".", "request_uri", ")", "req", ".", "body", "=", "data", "when", "\"PUT\"", "req", "=", "Net", "::", "HTTP", "::", "Put", ".", "new", "(", "uri", ".", "request_uri", ")", "req", ".", "body", "=", "data", "when", "\"DELETE\"", "req", "=", "Net", "::", "HTTP", "::", "Delete", ".", "new", "(", "uri", ".", "request_uri", ")", "else", "return", "end", "api_key", "||=", "Setting", ".", "plugin_contrastsecurity", "[", "'api_key'", "]", "username", "||=", "Setting", ".", "plugin_contrastsecurity", "[", "'username'", "]", "service_key", "||=", "Setting", ".", "plugin_contrastsecurity", "[", "'service_key'", "]", "auth_header", "=", "Base64", ".", "strict_encode64", "(", "username", "+", "\":\"", "+", "service_key", ")", "req", "[", "\"Authorization\"", "]", "=", "auth_header", "req", "[", "\"API-Key\"", "]", "=", "api_key", "req", "[", "'Content-Type'", "]", "=", "req", "[", "'Accept'", "]", "=", "'application/json'", "begin", "res", "=", "http", ".", "request", "(", "req", ")", "return", "res", ",", "nil", "rescue", "=>", "e", "puts", "[", "uri", ".", "to_s", ",", "e", ".", "class", ",", "e", "]", ".", "join", "(", "\" : \"", ")", "return", "nil", ",", "e", ".", "to_s", "end", "end", "module_function", ":callAPI", "def", "syncComment", "(", "org_id", ",", "app_id", ",", "vul_id", ",", "issue", ")", "teamserver_url", "=", "Setting", ".", "plugin_contrastsecurity", "[", "'teamserver_url'", "]", "url", "=", "sprintf", "(", "'%s/api/ng/%s/applications/%s/traces/%s/notes?expand=skip_links'", ",", "teamserver_url", ",", "org_id", ",", "app_id", ",", "vul_id", ")", "res", ",", "msg", "=", "callAPI", "(", "url", ":", "url", ")", "if", "res", ".", "present?", "&&", "res", ".", "code", "!=", "\"200\"", "return", "false", "end", "notes_json", "=", "JSON", ".", "parse", "(", "res", ".", "body", ")", "issue", ".", "journals", ".", "each", "do", "|", "c_journal", "|", "if", "not", "c_journal", ".", "private_notes", "c_journal", ".", "destroy", "end", "end", "notes_json", "[", "'notes'", "]", ".", "reverse", ".", "each", "do", "|", "c_note", "|", "old_status_str", "=", "\"\"", "new_status_str", "=", "\"\"", "status_change_reason_str", "=", "\"\"", "if", "c_note", ".", "has_key?", "(", "\"properties\"", ")", "c_note", "[", "'properties'", "]", ".", "each", "do", "|", "c_prop", "|", "if", "c_prop", "[", "'name'", "]", "==", "\"status.change.previous.status\"", "status_obj", "=", "ContrastUtil", ".", "get_redmine_status", "(", "c_prop", "[", "'value'", "]", ")", "unless", "status_obj", ".", "nil?", "old_status_str", "=", "status_obj", ".", "name", "end", "elsif", "c_prop", "[", "'name'", "]", "==", "\"status.change.status\"", "status_obj", "=", "ContrastUtil", ".", "get_redmine_status", "(", "c_prop", "[", "'value'", "]", ")", "unless", "status_obj", ".", "nil?", "new_status_str", "=", "status_obj", ".", "name", "end", "elsif", "c_prop", "[", "'name'", "]", "==", "\"status.change.substatus\"", "&&", "c_prop", "[", "'value'", "]", ".", "present?", "status_change_reason_str", "=", "l", "(", ":notaproblem_reason", ",", ":reason", "=>", "c_prop", "[", "'value'", "]", ")", "+", "\"\\n\"", "end", "end", "end", "note_str", "=", "CGI", ".", "unescapeHTML", "(", "status_change_reason_str", "+", "c_note", "[", "'note'", "]", ")", "if", "old_status_str", ".", "present?", "&&", "new_status_str", ".", "present?", "cmt_chg_msg", "=", "l", "(", ":status_changed_comment", ",", ":old", "=>", "old_status_str", ",", ":new", "=>", "new_status_str", ")", "note_str", "=", "\"(\"", "+", "cmt_chg_msg", "+", "\")\\n\"", "+", "CGI", ".", "unescapeHTML", "(", "status_change_reason_str", "+", "c_note", "[", "'note'", "]", ")", "end", "journal", "=", "Journal", ".", "new", "journal", ".", "journalized", "=", "issue", "journal", ".", "user", "=", "User", ".", "current", "journal", ".", "notes", "=", "note_str", "journal", ".", "created_on", "=", "Time", ".", "at", "(", "c_note", "[", "'last_modification'", "]", "/", "1000.0", ")", "journal", ".", "details", "<<", "JournalDetail", ".", "new", "(", "property", ":", "\"cf\"", ",", "prop_key", ":", "\"contrast_note_id\"", ",", "value", ":", "c_note", "[", "'id'", "]", ")", "journal", ".", "details", "<<", "JournalDetail", ".", "new", "(", "property", ":", "\"cf\"", ",", "prop_key", ":", "\"contrast_last_updater_uid\"", ",", "value", ":", "c_note", "[", "'last_updater_uid'", "]", ")", "journal", ".", "details", "<<", "JournalDetail", ".", "new", "(", "property", ":", "\"cf\"", ",", "prop_key", ":", "\"contrast_last_updater\"", ",", "value", ":", "c_note", "[", "'last_updater'", "]", ")", "journal", ".", "save", "(", ")", "end", "return", "true", "end", "module_function", ":syncComment", "end" ]
MIT License Copyright (c) 2020 Contrast Security Japan G.K.
[ "MIT", "License", "Copyright", "(", "c", ")", "2020", "Contrast", "Security", "Japan", "G", ".", "K", "." ]
[ "# TeamServer接続設定のみparamから渡されたものを使う。なければ設定から取得" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
24
1,710
240
a56b982f83b62ccf07e8e1cd7ed5f8cdb51cf131
wbknez/evored-warrior
evored/lang.py
[ "Apache-2.0" ]
Python
Instruction
Represents a collection of symbols that together form a single instruction in Redcode. Please note that in Redcode arguments are evaluated regardless of use. This means that the addressing mode of an argument will always be applied to its value even if the operation code does not make use of it. This has important implications for argument mutation as well as overall program construction.
Represents a collection of symbols that together form a single instruction in Redcode. Please note that in Redcode arguments are evaluated regardless of use. This means that the addressing mode of an argument will always be applied to its value even if the operation code does not make use of it. This has important implications for argument mutation as well as overall program construction.
[ "Represents", "a", "collection", "of", "symbols", "that", "together", "form", "a", "single", "instruction", "in", "Redcode", ".", "Please", "note", "that", "in", "Redcode", "arguments", "are", "evaluated", "regardless", "of", "use", ".", "This", "means", "that", "the", "addressing", "mode", "of", "an", "argument", "will", "always", "be", "applied", "to", "its", "value", "even", "if", "the", "operation", "code", "does", "not", "make", "use", "of", "it", ".", "This", "has", "important", "implications", "for", "argument", "mutation", "as", "well", "as", "overall", "program", "construction", "." ]
class Instruction: """ Represents a collection of symbols that together form a single instruction in Redcode. Please note that in Redcode arguments are evaluated regardless of use. This means that the addressing mode of an argument will always be applied to its value even if the operation code does not make use of it. This has important implications for argument mutation as well as overall program construction. """ def __init__(self, opcode, modifier, arg_a, arg_b): self.opcode = opcode self.modifier = modifier self.arg_a = arg_a self.arg_b = arg_b def __copy__(self): return Instruction(self.opcode, self.modifier, self.arg_a, self.arg_b) def __eq__(self, other): if isinstance(other, Instruction): return self.opcode == other.opcode and \ self.modifier == other.modifier and \ self.arg_a == other.arg_a and self.arg_b == other.arg_b return NotImplemented def __hash__(self): return hash((self.opcode, self.modifier, self.arg_a, self.arg_b)) def __ne__(self, other): return not self == other def __str__(self): ins_str = self.opcode.value if self.modifier: ins_str += ".%s" % self.modifier.value ins_str += " %s %s " % (self.arg_a, self.arg_b) return ins_str
[ "class", "Instruction", ":", "def", "__init__", "(", "self", ",", "opcode", ",", "modifier", ",", "arg_a", ",", "arg_b", ")", ":", "self", ".", "opcode", "=", "opcode", "self", ".", "modifier", "=", "modifier", "self", ".", "arg_a", "=", "arg_a", "self", ".", "arg_b", "=", "arg_b", "def", "__copy__", "(", "self", ")", ":", "return", "Instruction", "(", "self", ".", "opcode", ",", "self", ".", "modifier", ",", "self", ".", "arg_a", ",", "self", ".", "arg_b", ")", "def", "__eq__", "(", "self", ",", "other", ")", ":", "if", "isinstance", "(", "other", ",", "Instruction", ")", ":", "return", "self", ".", "opcode", "==", "other", ".", "opcode", "and", "self", ".", "modifier", "==", "other", ".", "modifier", "and", "self", ".", "arg_a", "==", "other", ".", "arg_a", "and", "self", ".", "arg_b", "==", "other", ".", "arg_b", "return", "NotImplemented", "def", "__hash__", "(", "self", ")", ":", "return", "hash", "(", "(", "self", ".", "opcode", ",", "self", ".", "modifier", ",", "self", ".", "arg_a", ",", "self", ".", "arg_b", ")", ")", "def", "__ne__", "(", "self", ",", "other", ")", ":", "return", "not", "self", "==", "other", "def", "__str__", "(", "self", ")", ":", "ins_str", "=", "self", ".", "opcode", ".", "value", "if", "self", ".", "modifier", ":", "ins_str", "+=", "\".%s\"", "%", "self", ".", "modifier", ".", "value", "ins_str", "+=", "\" %s %s \"", "%", "(", "self", ".", "arg_a", ",", "self", ".", "arg_b", ")", "return", "ins_str" ]
Represents a collection of symbols that together form a single instruction in Redcode.
[ "Represents", "a", "collection", "of", "symbols", "that", "together", "form", "a", "single", "instruction", "in", "Redcode", "." ]
[ "\"\"\"\n Represents a collection of symbols that together form a single\n instruction in Redcode.\n\n Please note that in Redcode arguments are evaluated regardless of use.\n This means that the addressing mode of an argument will always be applied\n to its value even if the operation code does not make use of it. This\n has important implications for argument mutation as well as overall\n program construction.\n \"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
13
323
84
1058ad67a67891a8ab35d47a1f5b5218218d36fe
sandialabs/sibl
cli/src/xyfigure/three_points_angular_velocity.py
[ "MIT" ]
Python
ThreePointsAngularVelocity
Given a time-series of three points' current position and velocity, both three-dimensional, calculates the rigid body angular velocity using a least-squares methodology. : params : : rP Position vector to point P, shape (m, 3) in E3 as (x, y, z). : rQ Position vector to point Q, same shape as rP. : rR Position vector to point R, same shape as rP. All position vectors measured from the origin O. : vP Velocity vector of point P in inertial frame F, same shape as rP. : vQ Velocity vector of point Q in inertial frame F, same shape as rQ. : vR Velocity vector of point R in inertial frame F, same shape as rR. : returns : : wB Angular velocity vector of rigid body B i frame F, with shape (m, 3). : reference : : Laflin, J. (2019) compute_omega_test.py.
Given a time-series of three points' current position and velocity, both three-dimensional, calculates the rigid body angular velocity using a least-squares methodology.
[ "Given", "a", "time", "-", "series", "of", "three", "points", "'", "current", "position", "and", "velocity", "both", "three", "-", "dimensional", "calculates", "the", "rigid", "body", "angular", "velocity", "using", "a", "least", "-", "squares", "methodology", "." ]
class ThreePointsAngularVelocity: """ Given a time-series of three points' current position and velocity, both three-dimensional, calculates the rigid body angular velocity using a least-squares methodology. : params : : rP Position vector to point P, shape (m, 3) in E3 as (x, y, z). : rQ Position vector to point Q, same shape as rP. : rR Position vector to point R, same shape as rP. All position vectors measured from the origin O. : vP Velocity vector of point P in inertial frame F, same shape as rP. : vQ Velocity vector of point Q in inertial frame F, same shape as rQ. : vR Velocity vector of point R in inertial frame F, same shape as rR. : returns : : wB Angular velocity vector of rigid body B i frame F, with shape (m, 3). : reference : : Laflin, J. (2019) compute_omega_test.py. """ def __init__(self, rP, rQ, rR, vP, vQ, vR, verbose=0): self.verbose = verbose if self.verbose: # pragma: no cover print("-------------------------------------------") print("Three Points Angular Velocity server start.") nts, _ = rP.shape # number of time steps, number of space dimensions # position vector r from point P to point Q rPQ = rQ - rP # position vector r from point P to point R rPR = rR - rP # cross_rPQ = self.cross_matrix(rPQ) # cross_rPR = self.cross_matrix(rPR) cross_rPQ = cross_matrix(rPQ) cross_rPR = cross_matrix(rPR) # self.A = np.vstack((-cross_rPQ, -cross_rPR)) self.A = [ np.vstack((-cross_rPQ[i], -cross_rPR[i])).tolist() for i in range(nts) ] # self.b = np.vstack(((vQ - vP).reshape(3, 1), (vR - vP).reshape(3, 1))) self.b = [ np.vstack( ((vQ[i] - vP[i]).reshape(3, 1), (vR[i] - vP[i]).reshape(3, 1)) ).tolist() for i in range(nts) ] # self.wB = np.linalg.solve(np.transpose(self.A) @ self.A, np.transpose(self.A) @ self.b) # self.wB = [np.linalg.solve(np.transpose(self.A[i]) @ self.A[i], np.transpose(self.A[i]) @ self.b[i]) for i in range(nts)] self.wB = [ np.linalg.solve( np.transpose(self.A[i]) @ self.A[i], np.transpose(self.A[i]) @ self.b[i] ).tolist() for i in range(nts) ] self.wB = [ np.squeeze(np.reshape(self.wB[i], (1, 3))).tolist() for i in range(nts) ] if self.verbose: # pragma: no cover print(f"rP = {rP}") print(f"rQ = {rQ}") print(f"rR = {rR}") print("") print(f"vP = {vP}") print(f"vQ = {vQ}") print(f"vR = {vR}") print("") print(f"rPQ = {rPQ}") print(f"rPR = {rPR}") print("") rPQ_length = [np.linalg.norm(rPQ[i]) for i in range(nts)] rPR_length = [np.linalg.norm(rPR[i]) for i in range(nts)] if rPQ_length[0] > 0 and rPR_length[0] > 0: rPQ_hat = [np.array(rPQ[i]) / rPQ_length[i] for i in range(nts)] rPR_hat = [np.array(rPR[i]) / rPR_length[i] for i in range(nts)] print(f"rPQ_hat = {rPQ_hat}") print(f"rPR_hat = {rPR_hat}") print("Dot product between unit vectors rPQ_hat and rPR_hat [0, 1]:") print(" 0 is best, vectors are perpendicular, adds rank") print(" 1 is worst, vectors are parallel, fails to add rank") dot_product = [np.dot(rPQ_hat[i], rPR_hat[i]) for i in range(nts)] print(f" (rPQ_hat . rPR_hat) = {dot_product}") AtransposeA = [np.transpose(self.A[i]) @ self.A[i] for i in range(nts)] print("[A^T A] matrix =") print(f"{AtransposeA}") print("") rank = [np.linalg.matrix_rank(AtransposeA[i]) for i in range(nts)] print(f"Rank of [A^T A] matrix = {rank}") print("") print(f"A = {self.A}") print("") print(f"wB = {self.wB}") print("") print(f"b = {self.b}") print("") print("Three Points Angular Velocity server stop.") print("------------------------------------------") def angular_velocity(self): """ Computes the estimates angular velocity of rigid body B in frame F. """ if self.verbose: # pragma: no cover print(f"calculated angular velocity = {self.wB}") return self.wB def A_matrix(self): """ Computes the least-squares matrix A, in A w = b, used to compute the angular velocity w. """ return self.A def b_vector(self): """ Computes the vector right-hand-side, in A w = b, used to compute the angular velocity w. """ return self.b
[ "class", "ThreePointsAngularVelocity", ":", "def", "__init__", "(", "self", ",", "rP", ",", "rQ", ",", "rR", ",", "vP", ",", "vQ", ",", "vR", ",", "verbose", "=", "0", ")", ":", "self", ".", "verbose", "=", "verbose", "if", "self", ".", "verbose", ":", "print", "(", "\"-------------------------------------------\"", ")", "print", "(", "\"Three Points Angular Velocity server start.\"", ")", "nts", ",", "_", "=", "rP", ".", "shape", "rPQ", "=", "rQ", "-", "rP", "rPR", "=", "rR", "-", "rP", "cross_rPQ", "=", "cross_matrix", "(", "rPQ", ")", "cross_rPR", "=", "cross_matrix", "(", "rPR", ")", "self", ".", "A", "=", "[", "np", ".", "vstack", "(", "(", "-", "cross_rPQ", "[", "i", "]", ",", "-", "cross_rPR", "[", "i", "]", ")", ")", ".", "tolist", "(", ")", "for", "i", "in", "range", "(", "nts", ")", "]", "self", ".", "b", "=", "[", "np", ".", "vstack", "(", "(", "(", "vQ", "[", "i", "]", "-", "vP", "[", "i", "]", ")", ".", "reshape", "(", "3", ",", "1", ")", ",", "(", "vR", "[", "i", "]", "-", "vP", "[", "i", "]", ")", ".", "reshape", "(", "3", ",", "1", ")", ")", ")", ".", "tolist", "(", ")", "for", "i", "in", "range", "(", "nts", ")", "]", "self", ".", "wB", "=", "[", "np", ".", "linalg", ".", "solve", "(", "np", ".", "transpose", "(", "self", ".", "A", "[", "i", "]", ")", "@", "self", ".", "A", "[", "i", "]", ",", "np", ".", "transpose", "(", "self", ".", "A", "[", "i", "]", ")", "@", "self", ".", "b", "[", "i", "]", ")", ".", "tolist", "(", ")", "for", "i", "in", "range", "(", "nts", ")", "]", "self", ".", "wB", "=", "[", "np", ".", "squeeze", "(", "np", ".", "reshape", "(", "self", ".", "wB", "[", "i", "]", ",", "(", "1", ",", "3", ")", ")", ")", ".", "tolist", "(", ")", "for", "i", "in", "range", "(", "nts", ")", "]", "if", "self", ".", "verbose", ":", "print", "(", "f\"rP = {rP}\"", ")", "print", "(", "f\"rQ = {rQ}\"", ")", "print", "(", "f\"rR = {rR}\"", ")", "print", "(", "\"\"", ")", "print", "(", "f\"vP = {vP}\"", ")", "print", "(", "f\"vQ = {vQ}\"", ")", "print", "(", "f\"vR = {vR}\"", ")", "print", "(", "\"\"", ")", "print", "(", "f\"rPQ = {rPQ}\"", ")", "print", "(", "f\"rPR = {rPR}\"", ")", "print", "(", "\"\"", ")", "rPQ_length", "=", "[", "np", ".", "linalg", ".", "norm", "(", "rPQ", "[", "i", "]", ")", "for", "i", "in", "range", "(", "nts", ")", "]", "rPR_length", "=", "[", "np", ".", "linalg", ".", "norm", "(", "rPR", "[", "i", "]", ")", "for", "i", "in", "range", "(", "nts", ")", "]", "if", "rPQ_length", "[", "0", "]", ">", "0", "and", "rPR_length", "[", "0", "]", ">", "0", ":", "rPQ_hat", "=", "[", "np", ".", "array", "(", "rPQ", "[", "i", "]", ")", "/", "rPQ_length", "[", "i", "]", "for", "i", "in", "range", "(", "nts", ")", "]", "rPR_hat", "=", "[", "np", ".", "array", "(", "rPR", "[", "i", "]", ")", "/", "rPR_length", "[", "i", "]", "for", "i", "in", "range", "(", "nts", ")", "]", "print", "(", "f\"rPQ_hat = {rPQ_hat}\"", ")", "print", "(", "f\"rPR_hat = {rPR_hat}\"", ")", "print", "(", "\"Dot product between unit vectors rPQ_hat and rPR_hat [0, 1]:\"", ")", "print", "(", "\" 0 is best, vectors are perpendicular, adds rank\"", ")", "print", "(", "\" 1 is worst, vectors are parallel, fails to add rank\"", ")", "dot_product", "=", "[", "np", ".", "dot", "(", "rPQ_hat", "[", "i", "]", ",", "rPR_hat", "[", "i", "]", ")", "for", "i", "in", "range", "(", "nts", ")", "]", "print", "(", "f\" (rPQ_hat . rPR_hat) = {dot_product}\"", ")", "AtransposeA", "=", "[", "np", ".", "transpose", "(", "self", ".", "A", "[", "i", "]", ")", "@", "self", ".", "A", "[", "i", "]", "for", "i", "in", "range", "(", "nts", ")", "]", "print", "(", "\"[A^T A] matrix =\"", ")", "print", "(", "f\"{AtransposeA}\"", ")", "print", "(", "\"\"", ")", "rank", "=", "[", "np", ".", "linalg", ".", "matrix_rank", "(", "AtransposeA", "[", "i", "]", ")", "for", "i", "in", "range", "(", "nts", ")", "]", "print", "(", "f\"Rank of [A^T A] matrix = {rank}\"", ")", "print", "(", "\"\"", ")", "print", "(", "f\"A = {self.A}\"", ")", "print", "(", "\"\"", ")", "print", "(", "f\"wB = {self.wB}\"", ")", "print", "(", "\"\"", ")", "print", "(", "f\"b = {self.b}\"", ")", "print", "(", "\"\"", ")", "print", "(", "\"Three Points Angular Velocity server stop.\"", ")", "print", "(", "\"------------------------------------------\"", ")", "def", "angular_velocity", "(", "self", ")", ":", "\"\"\"\n Computes the estimates angular velocity of rigid body B in frame F.\n \"\"\"", "if", "self", ".", "verbose", ":", "print", "(", "f\"calculated angular velocity = {self.wB}\"", ")", "return", "self", ".", "wB", "def", "A_matrix", "(", "self", ")", ":", "\"\"\"\n Computes the least-squares matrix A, in A w = b, used to compute\n the angular velocity w.\n \"\"\"", "return", "self", ".", "A", "def", "b_vector", "(", "self", ")", ":", "\"\"\"\n Computes the vector right-hand-side, in A w = b, used to compute\n the angular velocity w.\n \"\"\"", "return", "self", ".", "b" ]
Given a time-series of three points' current position and velocity, both three-dimensional, calculates the rigid body angular velocity using a least-squares methodology.
[ "Given", "a", "time", "-", "series", "of", "three", "points", "'", "current", "position", "and", "velocity", "both", "three", "-", "dimensional", "calculates", "the", "rigid", "body", "angular", "velocity", "using", "a", "least", "-", "squares", "methodology", "." ]
[ "\"\"\"\n Given a time-series of three points' current position and velocity,\n both three-dimensional, calculates the rigid body angular velocity\n using a least-squares methodology.\n\n : params :\n : rP Position vector to point P, shape (m, 3) in E3 as (x, y, z).\n : rQ Position vector to point Q, same shape as rP.\n : rR Position vector to point R, same shape as rP.\n All position vectors measured from the origin O.\n : vP Velocity vector of point P in inertial frame F, same shape as rP.\n : vQ Velocity vector of point Q in inertial frame F, same shape as rQ.\n : vR Velocity vector of point R in inertial frame F, same shape as rR.\n\n : returns :\n : wB Angular velocity vector of rigid body B i frame F, with\n shape (m, 3).\n\n : reference :\n : Laflin, J. (2019) compute_omega_test.py.\n \"\"\"", "# pragma: no cover", "# number of time steps, number of space dimensions", "# position vector r from point P to point Q", "# position vector r from point P to point R", "# cross_rPQ = self.cross_matrix(rPQ)", "# cross_rPR = self.cross_matrix(rPR)", "# self.A = np.vstack((-cross_rPQ, -cross_rPR))", "# self.b = np.vstack(((vQ - vP).reshape(3, 1), (vR - vP).reshape(3, 1)))", "# self.wB = np.linalg.solve(np.transpose(self.A) @ self.A, np.transpose(self.A) @ self.b)", "# self.wB = [np.linalg.solve(np.transpose(self.A[i]) @ self.A[i], np.transpose(self.A[i]) @ self.b[i]) for i in range(nts)]", "# pragma: no cover", "\"\"\"\n Computes the estimates angular velocity of rigid body B in frame F.\n \"\"\"", "# pragma: no cover", "\"\"\"\n Computes the least-squares matrix A, in A w = b, used to compute\n the angular velocity w.\n \"\"\"", "\"\"\"\n Computes the vector right-hand-side, in A w = b, used to compute\n the angular velocity w.\n \"\"\"" ]
[]
{ "returns": [ { "docstring": ": wB Angular velocity vector of rigid body B i frame F, with\nshape (m, 3).", "docstring_tokens": [ ":", "wB", "Angular", "velocity", "vector", "of", "rigid", "body", "B", "i", "frame", "F", "with", "shape", "(", "m", "3", ")", "." ], "type": null } ], "raises": [], "params": [], "outlier_params": [], "others": [ { "identifier": "params", "docstring": ": rP Position vector to point P, shape (m, 3) in E3 as (x, y, z).\n: rQ Position vector to point Q, same shape as rP.\n: rR Position vector to point R, same shape as rP.\nAll position vectors measured from the origin O.\n: vP Velocity vector of point P in inertial frame F, same shape as rP.\n: vQ Velocity vector of point Q in inertial frame F, same shape as rQ.\n: vR Velocity vector of point R in inertial frame F, same shape as rR.", "docstring_tokens": [ ":", "rP", "Position", "vector", "to", "point", "P", "shape", "(", "m", "3", ")", "in", "E3", "as", "(", "x", "y", "z", ")", ".", ":", "rQ", "Position", "vector", "to", "point", "Q", "same", "shape", "as", "rP", ".", ":", "rR", "Position", "vector", "to", "point", "R", "same", "shape", "as", "rP", ".", "All", "position", "vectors", "measured", "from", "the", "origin", "O", ".", ":", "vP", "Velocity", "vector", "of", "point", "P", "in", "inertial", "frame", "F", "same", "shape", "as", "rP", ".", ":", "vQ", "Velocity", "vector", "of", "point", "Q", "in", "inertial", "frame", "F", "same", "shape", "as", "rQ", ".", ":", "vR", "Velocity", "vector", "of", "point", "R", "in", "inertial", "frame", "F", "same", "shape", "as", "rR", "." ] }, { "identifier": "reference", "docstring": ": Laflin, J.", "docstring_tokens": [ ":", "Laflin", "J", "." ] } ] }
false
18
1,343
233
a447c4e36c5a92a3f14f4028bc6fa7822d70e016
RoboticCheese/hephaestoss
lib/hephaestoss/services.rb
[ "Apache-2.0" ]
Ruby
Services
# A singleton class used to store and lookup information about services and # their port mappings. The Services class needs to be configured with a # `path` attribute, pointing to a JSON file that defines recognized services # and their port configurations, e.g.: # # { # "ssh": { # "tcp": [22] # }, # "consul": { # "tcp": [8301, 8400, 8500, 8600], # "udp": [8301, 8600] # } # } # # @author Jonathan Hartman <[email protected]>
A singleton class used to store and lookup information about services and their port mappings. The Services class needs to be configured with a `path` attribute, pointing to a JSON file that defines recognized services and their port configurations, e.g..
[ "A", "singleton", "class", "used", "to", "store", "and", "lookup", "information", "about", "services", "and", "their", "port", "mappings", ".", "The", "Services", "class", "needs", "to", "be", "configured", "with", "a", "`", "path", "`", "attribute", "pointing", "to", "a", "JSON", "file", "that", "defines", "recognized", "services", "and", "their", "port", "configurations", "e", ".", "g", ".." ]
class Services include Configurable default_config :path, File.expand_path('../../../data/services.json', __FILE__) required_config :path class << self # # Provide service lookups as index calls on the class. # # @param [String] the service name to look up # @param [Symbol] the service name to look up # # @return [Hash] the protocol and port attributes for that service # def [](service) to_h[service.to_sym] end # # Return a hash representation of the loaded services. # # @return [Hash] the class' service and port mappings # def to_h mapping end # # Read in and save the JSON file after completing all other configuration. # # (see Hephaestoss::Configurable.configure!) # @return [Hash] the class' service and port mappings # def configure!(config = {}) super @mapping ||= JSON.parse(File.open(@config[:path]).read, symbolize_names: true) end private attr_reader :mapping end end
[ "class", "Services", "include", "Configurable", "default_config", ":path", ",", "File", ".", "expand_path", "(", "'../../../data/services.json'", ",", "__FILE__", ")", "required_config", ":path", "class", "<<", "self", "def", "[]", "(", "service", ")", "to_h", "[", "service", ".", "to_sym", "]", "end", "def", "to_h", "mapping", "end", "def", "configure!", "(", "config", "=", "{", "}", ")", "super", "@mapping", "||=", "JSON", ".", "parse", "(", "File", ".", "open", "(", "@config", "[", ":path", "]", ")", ".", "read", ",", "symbolize_names", ":", "true", ")", "end", "private", "attr_reader", ":mapping", "end", "end" ]
A singleton class used to store and lookup information about services and their port mappings.
[ "A", "singleton", "class", "used", "to", "store", "and", "lookup", "information", "about", "services", "and", "their", "port", "mappings", "." ]
[ "#", "# Provide service lookups as index calls on the class.", "#", "# @param [String] the service name to look up", "# @param [Symbol] the service name to look up", "#", "# @return [Hash] the protocol and port attributes for that service", "#", "#", "# Return a hash representation of the loaded services.", "#", "# @return [Hash] the class' service and port mappings", "#", "#", "# Read in and save the JSON file after completing all other configuration.", "#", "# (see Hephaestoss::Configurable.configure!)", "# @return [Hash] the class' service and port mappings", "#" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [ { "identifier": "author", "docstring": null, "docstring_tokens": [ "None" ] } ] }
false
14
259
154
625c468da1e120e75e4e55bdce768062e748c08b
rnacher/commons-jcs
auxiliary-builds/jdk14/src/java/org/apache/commons/jcs/auxiliary/lateral/javagroups/LateralJGCacheFactory.java
[ "Apache-2.0" ]
Java
LateralJGCacheFactory
/** * Constructs a LateralCacheNoWaitFacade for the given configuration. Each * lateral service / local relationship is managed by one manager. This manager * canl have multiple caches. The remote relationships are consolidated and * restored via these managers. The facade provides a front to the composite * cache so the implmenetation is transparent. * * @deprecated use the new TYPE specific lateral factories. */
Constructs a LateralCacheNoWaitFacade for the given configuration. Each lateral service / local relationship is managed by one manager. This manager canl have multiple caches. The remote relationships are consolidated and restored via these managers. The facade provides a front to the composite cache so the implmenetation is transparent. @deprecated use the new TYPE specific lateral factories.
[ "Constructs", "a", "LateralCacheNoWaitFacade", "for", "the", "given", "configuration", ".", "Each", "lateral", "service", "/", "local", "relationship", "is", "managed", "by", "one", "manager", ".", "This", "manager", "canl", "have", "multiple", "caches", ".", "The", "remote", "relationships", "are", "consolidated", "and", "restored", "via", "these", "managers", ".", "The", "facade", "provides", "a", "front", "to", "the", "composite", "cache", "so", "the", "implmenetation", "is", "transparent", ".", "@deprecated", "use", "the", "new", "TYPE", "specific", "lateral", "factories", "." ]
public class LateralJGCacheFactory extends LateralCacheAbstractFactory { private static final Log log = LogFactory.getLog( LateralJGCacheFactory.class ); /* * (non-Javadoc) * * @see org.apache.commons.jcs.auxiliary.AuxiliaryCacheFactory#createCache(org.apache.commons.jcs.auxiliary.AuxiliaryCacheAttributes, * org.apache.commons.jcs.engine.behavior.ICompositeCacheManager) */ public AuxiliaryCache createCache( AuxiliaryCacheAttributes iaca, ICompositeCacheManager cacheMgr ) { LateralCacheAttributes lac = (LateralCacheAttributes) iaca; ArrayList noWaits = new ArrayList(); LateralJGCacheManager lcm = LateralJGCacheManager.getInstance( lac, cacheMgr ); ICache ic = lcm.getCache( lac.getCacheName() ); if ( ic != null ) { noWaits.add( ic ); } createListener( lac, cacheMgr ); // create the no wait facade. LateralCacheNoWaitFacade lcnwf = new LateralCacheNoWaitFacade( (LateralCacheNoWait[]) noWaits .toArray( new LateralCacheNoWait[0] ), iaca.getCacheName() ); return lcnwf; } /* * (non-Javadoc) * * @see org.apache.commons.jcs.auxiliary.lateral.LateralCacheAbstractFactory#createListener(org.apache.commons.jcs.auxiliary.lateral.LateralCacheAttributes, * org.apache.commons.jcs.engine.behavior.ICompositeCacheManager) */ public void createListener( LateralCacheAttributes lac, ICompositeCacheManager cacheMgr ) { // don't create a listener if we are not receiving. if ( lac.isReceive() ) { if ( log.isInfoEnabled() ) { log.info( "Creating listener for " + lac ); } try { LateralCacheJGListener.getInstance( lac, cacheMgr ); } catch ( Exception e ) { log.error( "Problem creating lateral listener", e ); } } else { if ( log.isDebugEnabled() ) { log.debug( "Not creating a listener since we are not receiving." ); } } } }
[ "public", "class", "LateralJGCacheFactory", "extends", "LateralCacheAbstractFactory", "{", "private", "static", "final", "Log", "log", "=", "LogFactory", ".", "getLog", "(", "LateralJGCacheFactory", ".", "class", ")", ";", "/*\n * (non-Javadoc)\n *\n * @see org.apache.commons.jcs.auxiliary.AuxiliaryCacheFactory#createCache(org.apache.commons.jcs.auxiliary.AuxiliaryCacheAttributes,\n * org.apache.commons.jcs.engine.behavior.ICompositeCacheManager)\n */", "public", "AuxiliaryCache", "createCache", "(", "AuxiliaryCacheAttributes", "iaca", ",", "ICompositeCacheManager", "cacheMgr", ")", "{", "LateralCacheAttributes", "lac", "=", "(", "LateralCacheAttributes", ")", "iaca", ";", "ArrayList", "noWaits", "=", "new", "ArrayList", "(", ")", ";", "LateralJGCacheManager", "lcm", "=", "LateralJGCacheManager", ".", "getInstance", "(", "lac", ",", "cacheMgr", ")", ";", "ICache", "ic", "=", "lcm", ".", "getCache", "(", "lac", ".", "getCacheName", "(", ")", ")", ";", "if", "(", "ic", "!=", "null", ")", "{", "noWaits", ".", "add", "(", "ic", ")", ";", "}", "createListener", "(", "lac", ",", "cacheMgr", ")", ";", "LateralCacheNoWaitFacade", "lcnwf", "=", "new", "LateralCacheNoWaitFacade", "(", "(", "LateralCacheNoWait", "[", "]", ")", "noWaits", ".", "toArray", "(", "new", "LateralCacheNoWait", "[", "0", "]", ")", ",", "iaca", ".", "getCacheName", "(", ")", ")", ";", "return", "lcnwf", ";", "}", "/*\n * (non-Javadoc)\n *\n * @see org.apache.commons.jcs.auxiliary.lateral.LateralCacheAbstractFactory#createListener(org.apache.commons.jcs.auxiliary.lateral.LateralCacheAttributes,\n * org.apache.commons.jcs.engine.behavior.ICompositeCacheManager)\n */", "public", "void", "createListener", "(", "LateralCacheAttributes", "lac", ",", "ICompositeCacheManager", "cacheMgr", ")", "{", "if", "(", "lac", ".", "isReceive", "(", ")", ")", "{", "if", "(", "log", ".", "isInfoEnabled", "(", ")", ")", "{", "log", ".", "info", "(", "\"", "Creating listener for ", "\"", "+", "lac", ")", ";", "}", "try", "{", "LateralCacheJGListener", ".", "getInstance", "(", "lac", ",", "cacheMgr", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "log", ".", "error", "(", "\"", "Problem creating lateral listener", "\"", ",", "e", ")", ";", "}", "}", "else", "{", "if", "(", "log", ".", "isDebugEnabled", "(", ")", ")", "{", "log", ".", "debug", "(", "\"", "Not creating a listener since we are not receiving.", "\"", ")", ";", "}", "}", "}", "}" ]
Constructs a LateralCacheNoWaitFacade for the given configuration.
[ "Constructs", "a", "LateralCacheNoWaitFacade", "for", "the", "given", "configuration", "." ]
[ "// create the no wait facade.", "// don't create a listener if we are not receiving." ]
[ { "param": "LateralCacheAbstractFactory", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "LateralCacheAbstractFactory", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
14
492
85
218d7faff1ea838fd1f6add7ed9393dbfae58ab7
duongphuhiep/ToolsPack.Net
ToolsPack.Collection/UniqueLinkedList.cs
[ "MIT" ]
C#
UniqueLinkedList
/// <summary> /// The unique liked list is implemented with a linked list, /// thus providing very good performances with Add/AddRange. /// /// It has better performance than UniqueList because the Add: /// - do not reallocate memory (linked-list) /// - do not store anything in a dictionnary. /// /// Uniqueness is ensured at reading time. /// The 'this.hashtable' is build just on the first reads (GetEnumerator implementation and in the Contains). /// </summary> /// <remarks> /// Avoid: /// foreach(Node n in xxx) /// { /// if(!uniqueLinkedList.Contains(n)) /// { /// uniqueLinkedList.Add(n); /// } /// } /// Because it destroy and reconstructs all the hastable at each iteration. /// </remarks>
The unique liked list is implemented with a linked list, thus providing very good performances with Add/AddRange. It has better performance than UniqueList because the Add: do not reallocate memory (linked-list) do not store anything in a dictionnary. Uniqueness is ensured at reading time. The 'this.hashtable' is build just on the first reads (GetEnumerator implementation and in the Contains).
[ "The", "unique", "liked", "list", "is", "implemented", "with", "a", "linked", "list", "thus", "providing", "very", "good", "performances", "with", "Add", "/", "AddRange", ".", "It", "has", "better", "performance", "than", "UniqueList", "because", "the", "Add", ":", "do", "not", "reallocate", "memory", "(", "linked", "-", "list", ")", "do", "not", "store", "anything", "in", "a", "dictionnary", ".", "Uniqueness", "is", "ensured", "at", "reading", "time", ".", "The", "'", "this", ".", "hashtable", "'", "is", "build", "just", "on", "the", "first", "reads", "(", "GetEnumerator", "implementation", "and", "in", "the", "Contains", ")", "." ]
[DebuggerDisplay("this.Count = {this.Count}")] public class UniqueLinkedList<T> : ICollection<T>, IDisposable { #region UniqueLinkedListNode class (linked element) private class UniqueLinkedListNode { public T Value; public UniqueLinkedListNode Previous; public UniqueLinkedListNode Next; } #endregion UniqueLinkedListNode<T> class #region UniqueLinkedListEnum class private class UniqueLinkedListEnum : IEnumerator<T> { public UniqueLinkedList<T> list; private UniqueLinkedListNode current; public UniqueLinkedListEnum(UniqueLinkedList<T> list) { this.current = null; this.list = list; } T IEnumerator<T>.Current { get { return this.getCurrent(); } } object System.Collections.IEnumerator.Current { get { return this.getCurrent(); } } private T getCurrent() { if (this.current != null) { return this.current.Value; } else { return default(T); } } bool System.Collections.IEnumerator.MoveNext() { if (this.list.reverse) { return this.getPrevious(); } else { return this.getNext(); } } private bool getNext() { if (this.current == null) { this.current = this.list.first; } else { this.current = this.current.Next; } if (this.current == null) { this.list.hashtableOk = true; return false; } else { if (this.list.hashtableOk) { return true; } else { bool alreadyFound; if (this.current.Value == null) { alreadyFound = this.list.containsNull; } else { alreadyFound = this.list.hashtable.ContainsKey(this.current.Value); } if (alreadyFound) { UniqueLinkedListNode toRemove = this.current; if (toRemove.Previous != null) { toRemove.Previous.Next = toRemove.Next; } if (toRemove.Next != null) { toRemove.Next.Previous = toRemove.Previous; } if (toRemove == this.list.first) { this.list.first = toRemove.Next; } if (toRemove == this.list.last) { this.list.last = toRemove.Previous; } this.current = toRemove.Previous; return this.getNext(); } else { if (this.current.Value == null) { this.list.containsNull = true; } else { this.list.hashtable.Add(this.current.Value, null); } return true; } } } } private bool getPrevious() { if (this.current == null) { this.current = this.list.last; } else { this.current = this.current.Previous; } if (this.current == null) { this.list.hashtableOk = true; return false; } else { if (this.list.hashtableOk) { return true; } else if (this.list.hashtable.ContainsKey(this.current.Value)) { UniqueLinkedListNode toRemove = this.current; if (toRemove.Previous != null) { toRemove.Previous.Next = toRemove.Next; } if (toRemove.Next != null) { toRemove.Next.Previous = toRemove.Previous; } if (toRemove == this.list.first) { this.list.first = toRemove.Next; } if (toRemove == this.list.last) { this.list.last = toRemove.Previous; } this.current = toRemove.Next; return this.getPrevious(); } else { this.list.hashtable.Add(this.current.Value, null); return true; } } } void System.Collections.IEnumerator.Reset() { this.current = null; } public bool Remove(T item) { this.current = null; UniqueLinkedListNode toRemove = null; while (this.getNext()) { bool match = false; if (item == null) { match = (this.current.Value == null); } else { match = this.current.Value.Equals(item); } if (match) { toRemove = this.current; if (this.list.hashtableOk) { break; } } } this.current = null; if (toRemove == null) { return false; } else { if (toRemove.Previous != null) { toRemove.Previous.Next = toRemove.Next; } if (toRemove.Next != null) { toRemove.Next.Previous = toRemove.Previous; } if (toRemove == this.list.first) { this.list.first = toRemove.Next; } if (toRemove == this.list.last) { this.list.last = toRemove.Previous; } if (item == null) { this.list.containsNull = false; } else { this.list.hashtable.Remove(toRemove.Value); } return true; } } public void Dispose() { this.list = null; this.current = null; } } #endregion UniqueLinkedListEnum class #region Fields private bool containsNull; private UniqueLinkedListNode first; private UniqueLinkedListNode last; private Dictionary<T, object> hashtable; private bool hashtableOk; private bool reverse; public bool Reverse { get { return this.reverse; } set { this.reverse = value; } } #endregion Fields #region Constructors public UniqueLinkedList() { this.first = null; this.last = null; this.hashtable = new Dictionary<T, object>(); this.hashtableOk = true; this.reverse = false; this.containsNull = false; } public UniqueLinkedList(IEnumerable<T> collection) : this() { this.AddRange(collection); } #endregion Constructors #region IEnumerable<T> & IEnumerable Members IEnumerator<T> IEnumerable<T>.GetEnumerator() { if (!this.hashtableOk) { this.hashtable.Clear(); } return new UniqueLinkedListEnum(this); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return ((IEnumerable<T>)this).GetEnumerator(); } #endregion #region IDisposable Members void IDisposable.Dispose() { this.hashtable.Clear(); } #endregion #region ICollection<T> Members public bool IsEmpty { get { return (this.first == null); } } public void Add(T item) { UniqueLinkedListNode newItem = new UniqueLinkedListNode(); newItem.Next = null; newItem.Value = item; if (this.IsEmpty) { this.first = this.last = newItem; } else { UniqueLinkedListNode oldLast = this.last; oldLast.Next = newItem; newItem.Previous = oldLast; this.last = newItem; } this.hashtable.Clear(); this.containsNull = false; this.hashtableOk = false; } public void AddRange(IEnumerable<T> items) { foreach (T item in items) { this.Add(item); } } public void AddRange(UniqueLinkedList<T> list) { if (!list.IsEmpty) { if (this.IsEmpty) { this.first = list.first; this.last = list.last; } else { this.last.Next = list.first; list.first.Previous = this.last; this.last = list.last; } this.hashtableOk = false; this.containsNull = false; this.hashtable.Clear(); } } public void Clear() { this.first = null; this.last = null; this.hashtable.Clear(); this.containsNull = false; this.hashtableOk = true; } public bool Contains(T item) { this.buildDictionaryIfNeeded(); return this.hashtable.ContainsKey(item); } private void buildDictionaryIfNeeded() { if (!this.hashtableOk) { this.hashtable.Clear(); this.containsNull = false; foreach (T item in this) { } } } public T Last() { this.buildDictionaryIfNeeded(); if (this.last != null) { return this.last.Value; } else { return default(T); } } public T First() { if (this.first != null) { return this.first.Value; } else { return default(T); } } public void CopyTo(T[] array, int arrayIndex) { int i=0; foreach (T item in this) { array[arrayIndex + i] = item; i++; } } public int Count { get { this.buildDictionaryIfNeeded(); return this.hashtable.Count + (this.containsNull?1:0); } } bool ICollection<T>.IsReadOnly { get { return false; } } public bool Remove(T item) { if (this.hashtableOk) { if (item == null) { if (!this.containsNull) { return false; } } else if (!this.hashtable.ContainsKey(item)) { return false; } } return new UniqueLinkedListEnum(this).Remove(item); } #endregion #region ToString public override string ToString() { return this.displayElements(20); } public string DisplayAllElements() { return this.displayElements(int.MaxValue); } private string displayElements(int maxNumberOfElements) { StringBuilder sb = new StringBuilder(); sb.Append("["); int i = 0; foreach (T item in this) { if (i != 0) { sb.Append(", "); } if (i >= maxNumberOfElements) { sb.Append("..."); break; } sb.Append(item == null ? "<null>" : item.ToString()); i++; } sb.Append("]"); return sb.ToString(); } #endregion ToString }
[ "[", "DebuggerDisplay", "(", "\"", "this.Count = {this.Count}", "\"", ")", "]", "public", "class", "UniqueLinkedList", "<", "T", ">", ":", "ICollection", "<", "T", ">", ",", "IDisposable", "{", "region", " UniqueLinkedListNode class (linked element)", "private", "class", "UniqueLinkedListNode", "{", "public", "T", "Value", ";", "public", "UniqueLinkedListNode", "Previous", ";", "public", "UniqueLinkedListNode", "Next", ";", "}", "endregion", " UniqueLinkedListNode<T> class", "region", " UniqueLinkedListEnum class", "private", "class", "UniqueLinkedListEnum", ":", "IEnumerator", "<", "T", ">", "{", "public", "UniqueLinkedList", "<", "T", ">", "list", ";", "private", "UniqueLinkedListNode", "current", ";", "public", "UniqueLinkedListEnum", "(", "UniqueLinkedList", "<", "T", ">", "list", ")", "{", "this", ".", "current", "=", "null", ";", "this", ".", "list", "=", "list", ";", "}", "T", "IEnumerator", "<", "T", ">", ".", "Current", "{", "get", "{", "return", "this", ".", "getCurrent", "(", ")", ";", "}", "}", "object", "System", ".", "Collections", ".", "IEnumerator", ".", "Current", "{", "get", "{", "return", "this", ".", "getCurrent", "(", ")", ";", "}", "}", "private", "T", "getCurrent", "(", ")", "{", "if", "(", "this", ".", "current", "!=", "null", ")", "{", "return", "this", ".", "current", ".", "Value", ";", "}", "else", "{", "return", "default", "(", "T", ")", ";", "}", "}", "bool", "System", ".", "Collections", ".", "IEnumerator", ".", "MoveNext", "(", ")", "{", "if", "(", "this", ".", "list", ".", "reverse", ")", "{", "return", "this", ".", "getPrevious", "(", ")", ";", "}", "else", "{", "return", "this", ".", "getNext", "(", ")", ";", "}", "}", "private", "bool", "getNext", "(", ")", "{", "if", "(", "this", ".", "current", "==", "null", ")", "{", "this", ".", "current", "=", "this", ".", "list", ".", "first", ";", "}", "else", "{", "this", ".", "current", "=", "this", ".", "current", ".", "Next", ";", "}", "if", "(", "this", ".", "current", "==", "null", ")", "{", "this", ".", "list", ".", "hashtableOk", "=", "true", ";", "return", "false", ";", "}", "else", "{", "if", "(", "this", ".", "list", ".", "hashtableOk", ")", "{", "return", "true", ";", "}", "else", "{", "bool", "alreadyFound", ";", "if", "(", "this", ".", "current", ".", "Value", "==", "null", ")", "{", "alreadyFound", "=", "this", ".", "list", ".", "containsNull", ";", "}", "else", "{", "alreadyFound", "=", "this", ".", "list", ".", "hashtable", ".", "ContainsKey", "(", "this", ".", "current", ".", "Value", ")", ";", "}", "if", "(", "alreadyFound", ")", "{", "UniqueLinkedListNode", "toRemove", "=", "this", ".", "current", ";", "if", "(", "toRemove", ".", "Previous", "!=", "null", ")", "{", "toRemove", ".", "Previous", ".", "Next", "=", "toRemove", ".", "Next", ";", "}", "if", "(", "toRemove", ".", "Next", "!=", "null", ")", "{", "toRemove", ".", "Next", ".", "Previous", "=", "toRemove", ".", "Previous", ";", "}", "if", "(", "toRemove", "==", "this", ".", "list", ".", "first", ")", "{", "this", ".", "list", ".", "first", "=", "toRemove", ".", "Next", ";", "}", "if", "(", "toRemove", "==", "this", ".", "list", ".", "last", ")", "{", "this", ".", "list", ".", "last", "=", "toRemove", ".", "Previous", ";", "}", "this", ".", "current", "=", "toRemove", ".", "Previous", ";", "return", "this", ".", "getNext", "(", ")", ";", "}", "else", "{", "if", "(", "this", ".", "current", ".", "Value", "==", "null", ")", "{", "this", ".", "list", ".", "containsNull", "=", "true", ";", "}", "else", "{", "this", ".", "list", ".", "hashtable", ".", "Add", "(", "this", ".", "current", ".", "Value", ",", "null", ")", ";", "}", "return", "true", ";", "}", "}", "}", "}", "private", "bool", "getPrevious", "(", ")", "{", "if", "(", "this", ".", "current", "==", "null", ")", "{", "this", ".", "current", "=", "this", ".", "list", ".", "last", ";", "}", "else", "{", "this", ".", "current", "=", "this", ".", "current", ".", "Previous", ";", "}", "if", "(", "this", ".", "current", "==", "null", ")", "{", "this", ".", "list", ".", "hashtableOk", "=", "true", ";", "return", "false", ";", "}", "else", "{", "if", "(", "this", ".", "list", ".", "hashtableOk", ")", "{", "return", "true", ";", "}", "else", "if", "(", "this", ".", "list", ".", "hashtable", ".", "ContainsKey", "(", "this", ".", "current", ".", "Value", ")", ")", "{", "UniqueLinkedListNode", "toRemove", "=", "this", ".", "current", ";", "if", "(", "toRemove", ".", "Previous", "!=", "null", ")", "{", "toRemove", ".", "Previous", ".", "Next", "=", "toRemove", ".", "Next", ";", "}", "if", "(", "toRemove", ".", "Next", "!=", "null", ")", "{", "toRemove", ".", "Next", ".", "Previous", "=", "toRemove", ".", "Previous", ";", "}", "if", "(", "toRemove", "==", "this", ".", "list", ".", "first", ")", "{", "this", ".", "list", ".", "first", "=", "toRemove", ".", "Next", ";", "}", "if", "(", "toRemove", "==", "this", ".", "list", ".", "last", ")", "{", "this", ".", "list", ".", "last", "=", "toRemove", ".", "Previous", ";", "}", "this", ".", "current", "=", "toRemove", ".", "Next", ";", "return", "this", ".", "getPrevious", "(", ")", ";", "}", "else", "{", "this", ".", "list", ".", "hashtable", ".", "Add", "(", "this", ".", "current", ".", "Value", ",", "null", ")", ";", "return", "true", ";", "}", "}", "}", "void", "System", ".", "Collections", ".", "IEnumerator", ".", "Reset", "(", ")", "{", "this", ".", "current", "=", "null", ";", "}", "public", "bool", "Remove", "(", "T", "item", ")", "{", "this", ".", "current", "=", "null", ";", "UniqueLinkedListNode", "toRemove", "=", "null", ";", "while", "(", "this", ".", "getNext", "(", ")", ")", "{", "bool", "match", "=", "false", ";", "if", "(", "item", "==", "null", ")", "{", "match", "=", "(", "this", ".", "current", ".", "Value", "==", "null", ")", ";", "}", "else", "{", "match", "=", "this", ".", "current", ".", "Value", ".", "Equals", "(", "item", ")", ";", "}", "if", "(", "match", ")", "{", "toRemove", "=", "this", ".", "current", ";", "if", "(", "this", ".", "list", ".", "hashtableOk", ")", "{", "break", ";", "}", "}", "}", "this", ".", "current", "=", "null", ";", "if", "(", "toRemove", "==", "null", ")", "{", "return", "false", ";", "}", "else", "{", "if", "(", "toRemove", ".", "Previous", "!=", "null", ")", "{", "toRemove", ".", "Previous", ".", "Next", "=", "toRemove", ".", "Next", ";", "}", "if", "(", "toRemove", ".", "Next", "!=", "null", ")", "{", "toRemove", ".", "Next", ".", "Previous", "=", "toRemove", ".", "Previous", ";", "}", "if", "(", "toRemove", "==", "this", ".", "list", ".", "first", ")", "{", "this", ".", "list", ".", "first", "=", "toRemove", ".", "Next", ";", "}", "if", "(", "toRemove", "==", "this", ".", "list", ".", "last", ")", "{", "this", ".", "list", ".", "last", "=", "toRemove", ".", "Previous", ";", "}", "if", "(", "item", "==", "null", ")", "{", "this", ".", "list", ".", "containsNull", "=", "false", ";", "}", "else", "{", "this", ".", "list", ".", "hashtable", ".", "Remove", "(", "toRemove", ".", "Value", ")", ";", "}", "return", "true", ";", "}", "}", "public", "void", "Dispose", "(", ")", "{", "this", ".", "list", "=", "null", ";", "this", ".", "current", "=", "null", ";", "}", "}", "endregion", " UniqueLinkedListEnum class", "region", " Fields", "private", "bool", "containsNull", ";", "private", "UniqueLinkedListNode", "first", ";", "private", "UniqueLinkedListNode", "last", ";", "private", "Dictionary", "<", "T", ",", "object", ">", "hashtable", ";", "private", "bool", "hashtableOk", ";", "private", "bool", "reverse", ";", "public", "bool", "Reverse", "{", "get", "{", "return", "this", ".", "reverse", ";", "}", "set", "{", "this", ".", "reverse", "=", "value", ";", "}", "}", "endregion", " Fields", "region", " Constructors", "public", "UniqueLinkedList", "(", ")", "{", "this", ".", "first", "=", "null", ";", "this", ".", "last", "=", "null", ";", "this", ".", "hashtable", "=", "new", "Dictionary", "<", "T", ",", "object", ">", "(", ")", ";", "this", ".", "hashtableOk", "=", "true", ";", "this", ".", "reverse", "=", "false", ";", "this", ".", "containsNull", "=", "false", ";", "}", "public", "UniqueLinkedList", "(", "IEnumerable", "<", "T", ">", "collection", ")", ":", "this", "(", ")", "{", "this", ".", "AddRange", "(", "collection", ")", ";", "}", "endregion", " Constructors", "region", " IEnumerable<T> & IEnumerable Members", "IEnumerator", "<", "T", ">", "IEnumerable", "<", "T", ">", ".", "GetEnumerator", "(", ")", "{", "if", "(", "!", "this", ".", "hashtableOk", ")", "{", "this", ".", "hashtable", ".", "Clear", "(", ")", ";", "}", "return", "new", "UniqueLinkedListEnum", "(", "this", ")", ";", "}", "System", ".", "Collections", ".", "IEnumerator", "System", ".", "Collections", ".", "IEnumerable", ".", "GetEnumerator", "(", ")", "{", "return", "(", "(", "IEnumerable", "<", "T", ">", ")", "this", ")", ".", "GetEnumerator", "(", ")", ";", "}", "endregion", "region", " IDisposable Members", "void", "IDisposable", ".", "Dispose", "(", ")", "{", "this", ".", "hashtable", ".", "Clear", "(", ")", ";", "}", "endregion", "region", " ICollection<T> Members", "public", "bool", "IsEmpty", "{", "get", "{", "return", "(", "this", ".", "first", "==", "null", ")", ";", "}", "}", "public", "void", "Add", "(", "T", "item", ")", "{", "UniqueLinkedListNode", "newItem", "=", "new", "UniqueLinkedListNode", "(", ")", ";", "newItem", ".", "Next", "=", "null", ";", "newItem", ".", "Value", "=", "item", ";", "if", "(", "this", ".", "IsEmpty", ")", "{", "this", ".", "first", "=", "this", ".", "last", "=", "newItem", ";", "}", "else", "{", "UniqueLinkedListNode", "oldLast", "=", "this", ".", "last", ";", "oldLast", ".", "Next", "=", "newItem", ";", "newItem", ".", "Previous", "=", "oldLast", ";", "this", ".", "last", "=", "newItem", ";", "}", "this", ".", "hashtable", ".", "Clear", "(", ")", ";", "this", ".", "containsNull", "=", "false", ";", "this", ".", "hashtableOk", "=", "false", ";", "}", "public", "void", "AddRange", "(", "IEnumerable", "<", "T", ">", "items", ")", "{", "foreach", "(", "T", "item", "in", "items", ")", "{", "this", ".", "Add", "(", "item", ")", ";", "}", "}", "public", "void", "AddRange", "(", "UniqueLinkedList", "<", "T", ">", "list", ")", "{", "if", "(", "!", "list", ".", "IsEmpty", ")", "{", "if", "(", "this", ".", "IsEmpty", ")", "{", "this", ".", "first", "=", "list", ".", "first", ";", "this", ".", "last", "=", "list", ".", "last", ";", "}", "else", "{", "this", ".", "last", ".", "Next", "=", "list", ".", "first", ";", "list", ".", "first", ".", "Previous", "=", "this", ".", "last", ";", "this", ".", "last", "=", "list", ".", "last", ";", "}", "this", ".", "hashtableOk", "=", "false", ";", "this", ".", "containsNull", "=", "false", ";", "this", ".", "hashtable", ".", "Clear", "(", ")", ";", "}", "}", "public", "void", "Clear", "(", ")", "{", "this", ".", "first", "=", "null", ";", "this", ".", "last", "=", "null", ";", "this", ".", "hashtable", ".", "Clear", "(", ")", ";", "this", ".", "containsNull", "=", "false", ";", "this", ".", "hashtableOk", "=", "true", ";", "}", "public", "bool", "Contains", "(", "T", "item", ")", "{", "this", ".", "buildDictionaryIfNeeded", "(", ")", ";", "return", "this", ".", "hashtable", ".", "ContainsKey", "(", "item", ")", ";", "}", "private", "void", "buildDictionaryIfNeeded", "(", ")", "{", "if", "(", "!", "this", ".", "hashtableOk", ")", "{", "this", ".", "hashtable", ".", "Clear", "(", ")", ";", "this", ".", "containsNull", "=", "false", ";", "foreach", "(", "T", "item", "in", "this", ")", "{", "}", "}", "}", "public", "T", "Last", "(", ")", "{", "this", ".", "buildDictionaryIfNeeded", "(", ")", ";", "if", "(", "this", ".", "last", "!=", "null", ")", "{", "return", "this", ".", "last", ".", "Value", ";", "}", "else", "{", "return", "default", "(", "T", ")", ";", "}", "}", "public", "T", "First", "(", ")", "{", "if", "(", "this", ".", "first", "!=", "null", ")", "{", "return", "this", ".", "first", ".", "Value", ";", "}", "else", "{", "return", "default", "(", "T", ")", ";", "}", "}", "public", "void", "CopyTo", "(", "T", "[", "]", "array", ",", "int", "arrayIndex", ")", "{", "int", "i", "=", "0", ";", "foreach", "(", "T", "item", "in", "this", ")", "{", "array", "[", "arrayIndex", "+", "i", "]", "=", "item", ";", "i", "++", ";", "}", "}", "public", "int", "Count", "{", "get", "{", "this", ".", "buildDictionaryIfNeeded", "(", ")", ";", "return", "this", ".", "hashtable", ".", "Count", "+", "(", "this", ".", "containsNull", "?", "1", ":", "0", ")", ";", "}", "}", "bool", "ICollection", "<", "T", ">", ".", "IsReadOnly", "{", "get", "{", "return", "false", ";", "}", "}", "public", "bool", "Remove", "(", "T", "item", ")", "{", "if", "(", "this", ".", "hashtableOk", ")", "{", "if", "(", "item", "==", "null", ")", "{", "if", "(", "!", "this", ".", "containsNull", ")", "{", "return", "false", ";", "}", "}", "else", "if", "(", "!", "this", ".", "hashtable", ".", "ContainsKey", "(", "item", ")", ")", "{", "return", "false", ";", "}", "}", "return", "new", "UniqueLinkedListEnum", "(", "this", ")", ".", "Remove", "(", "item", ")", ";", "}", "endregion", "region", " ToString", "public", "override", "string", "ToString", "(", ")", "{", "return", "this", ".", "displayElements", "(", "20", ")", ";", "}", "public", "string", "DisplayAllElements", "(", ")", "{", "return", "this", ".", "displayElements", "(", "int", ".", "MaxValue", ")", ";", "}", "private", "string", "displayElements", "(", "int", "maxNumberOfElements", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "sb", ".", "Append", "(", "\"", "[", "\"", ")", ";", "int", "i", "=", "0", ";", "foreach", "(", "T", "item", "in", "this", ")", "{", "if", "(", "i", "!=", "0", ")", "{", "sb", ".", "Append", "(", "\"", ", ", "\"", ")", ";", "}", "if", "(", "i", ">=", "maxNumberOfElements", ")", "{", "sb", ".", "Append", "(", "\"", "...", "\"", ")", ";", "break", ";", "}", "sb", ".", "Append", "(", "item", "==", "null", "?", "\"", "<null>", "\"", ":", "item", ".", "ToString", "(", ")", ")", ";", "i", "++", ";", "}", "sb", ".", "Append", "(", "\"", "]", "\"", ")", ";", "return", "sb", ".", "ToString", "(", ")", ";", "}", "endregion", " ToString", "}" ]
The unique liked list is implemented with a linked list, thus providing very good performances with Add/AddRange.
[ "The", "unique", "liked", "list", "is", "implemented", "with", "a", "linked", "list", "thus", "providing", "very", "good", "performances", "with", "Add", "/", "AddRange", "." ]
[ "/// list end", "/// list already unique and hashtable built", "/// remove element already found", "/// and getNext from old current", "/// list begin", "/// list already unique and hashtable built", "/// remove element already found", "/// and getNext from old current", "/// this is the only occurence", "/// Here hashtable is now ok, keep it ok by removing element in it", "/// <summary>", "/// Used in foreach, perform a reverse order if set to true", "/// </summary>", "/// the hashtable may have been partialy built.", "/// in this case, just rebuild it entirely.", "/// do nothing, just iterate to build dictionary", "///OdR: Do not use '{' to have nice format in expression debug display", "///Perf" ]
[ { "param": "IDisposable", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "IDisposable", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [ { "identifier": "remarks", "docstring": "foreach(Node n in xxx)\n{\nif(!uniqueLinkedList.Contains(n))\n{\nuniqueLinkedList.Add(n);\n}\n}\nBecause it destroy and reconstructs all the hastable at each iteration.", "docstring_tokens": [ "foreach", "(", "Node", "n", "in", "xxx", ")", "{", "if", "(", "!uniqueLinkedList", ".", "Contains", "(", "n", "))", "{", "uniqueLinkedList", ".", "Add", "(", "n", ")", ";", "}", "}", "Because", "it", "destroy", "and", "reconstructs", "all", "the", "hastable", "at", "each", "iteration", "." ] } ] }
false
21
2,389
171
9ec8e3650a1647750c1ecd5c1315105136dc49d1
Sajaki/intellij-community
platform/util/src/com/intellij/openapi/util/io/PathUtil.java
[ "Apache-2.0" ]
Java
PathUtil
/** * <p>Utility methods for operations with file path strings. Unlike {@link java.io IO}, {@link java.nio.file NIO2} and {@link FileUtil}, * these methods are platform-agnostic - i.e. able to work with Windows paths on Unix systems and vice versa. * Both forward- and backward-slashes are legal separators.</p> * * <p><strong>Warning:</strong> the methods are by definition less strict and in some cases could produce incorrect results. * Unless you're certain you need the relaxed handling, prefer {@link java.nio.file NIO2} instead.</p> */
Utility methods for operations with file path strings. Warning: the methods are by definition less strict and in some cases could produce incorrect results. Unless you're certain you need the relaxed handling, prefer java.nio.file NIO2 instead.
[ "Utility", "methods", "for", "operations", "with", "file", "path", "strings", ".", "Warning", ":", "the", "methods", "are", "by", "definition", "less", "strict", "and", "in", "some", "cases", "could", "produce", "incorrect", "results", ".", "Unless", "you", "'", "re", "certain", "you", "need", "the", "relaxed", "handling", "prefer", "java", ".", "nio", ".", "file", "NIO2", "instead", "." ]
public class PathUtil { private PathUtil() { } /** * Returns {@code true} absolute UNC (even incomplete), DOS and Unix paths; {@code false} otherwise. * * @see PathUtil applicability warning */ public static boolean isAbsolute(@NotNull String path) { return path.length() > 2 && path.charAt(1) == ':' && isSlash(path.charAt(2)) && isDriveLetter(path.charAt(0)) || path.length() > 1 && isSlash(path.charAt(0)) && path.charAt(1) == path.charAt(0) || path.startsWith("/"); } /** * <p>Returns a parent path according to the rules applicable to the given path, * or {@code null} when the path is a file system root or unrecognized.</p> * <p>A path should not contain duplicated separators (except at the beginning of a UNC path), otherwise the result could be incorrect.</p> * <p>Directory traversals are not processed ({@code getParent("/a/b/..")} returns {@code "/a/b"} instead of {@code "/a"}, etc).</p> * * @see PathUtil applicability warning */ public static @Nullable String getParent(@NotNull String path) { int length = path.length(); int lastSeparator = lastSeparatorIndex(path, length); if (lastSeparator < 0) return null; if (lastSeparator == length - 1) lastSeparator = lastSeparatorIndex(path, length - 2); if (lastSeparator < 0) return null; if (length > 1 && isSlash(path.charAt(0)) && path.charAt(1) == path.charAt(0)) { // a UNC path if (lastSeparator > 1) { int prevSeparator = lastSeparatorIndex(path, lastSeparator - 1); if (prevSeparator > 1) { return path.substring(0, lastSeparator); } } return null; } if (lastSeparator == 2 && path.charAt(1) == ':' && isDriveLetter(path.charAt(0))) { // a DOS path return path.substring(0, 3); } return path.substring(0, lastSeparator == 0 ? 1 : lastSeparator); } private static boolean isSlash(char c) { return c == '/' || c == '\\'; } public static boolean isDriveLetter(char c) { return 'A' <= c && c <= 'Z' || 'a' <= c && c <= 'z'; } private static int lastSeparatorIndex(String s, int from) { return Math.max(s.lastIndexOf('/', from), s.lastIndexOf('\\', from)); } }
[ "public", "class", "PathUtil", "{", "private", "PathUtil", "(", ")", "{", "}", "/**\n * Returns {@code true} absolute UNC (even incomplete), DOS and Unix paths; {@code false} otherwise.\n *\n * @see PathUtil applicability warning\n */", "public", "static", "boolean", "isAbsolute", "(", "@", "NotNull", "String", "path", ")", "{", "return", "path", ".", "length", "(", ")", ">", "2", "&&", "path", ".", "charAt", "(", "1", ")", "==", "':'", "&&", "isSlash", "(", "path", ".", "charAt", "(", "2", ")", ")", "&&", "isDriveLetter", "(", "path", ".", "charAt", "(", "0", ")", ")", "||", "path", ".", "length", "(", ")", ">", "1", "&&", "isSlash", "(", "path", ".", "charAt", "(", "0", ")", ")", "&&", "path", ".", "charAt", "(", "1", ")", "==", "path", ".", "charAt", "(", "0", ")", "||", "path", ".", "startsWith", "(", "\"", "/", "\"", ")", ";", "}", "/**\n * <p>Returns a parent path according to the rules applicable to the given path,\n * or {@code null} when the path is a file system root or unrecognized.</p>\n * <p>A path should not contain duplicated separators (except at the beginning of a UNC path), otherwise the result could be incorrect.</p>\n * <p>Directory traversals are not processed ({@code getParent(\"/a/b/..\")} returns {@code \"/a/b\"} instead of {@code \"/a\"}, etc).</p>\n *\n * @see PathUtil applicability warning\n */", "public", "static", "@", "Nullable", "String", "getParent", "(", "@", "NotNull", "String", "path", ")", "{", "int", "length", "=", "path", ".", "length", "(", ")", ";", "int", "lastSeparator", "=", "lastSeparatorIndex", "(", "path", ",", "length", ")", ";", "if", "(", "lastSeparator", "<", "0", ")", "return", "null", ";", "if", "(", "lastSeparator", "==", "length", "-", "1", ")", "lastSeparator", "=", "lastSeparatorIndex", "(", "path", ",", "length", "-", "2", ")", ";", "if", "(", "lastSeparator", "<", "0", ")", "return", "null", ";", "if", "(", "length", ">", "1", "&&", "isSlash", "(", "path", ".", "charAt", "(", "0", ")", ")", "&&", "path", ".", "charAt", "(", "1", ")", "==", "path", ".", "charAt", "(", "0", ")", ")", "{", "if", "(", "lastSeparator", ">", "1", ")", "{", "int", "prevSeparator", "=", "lastSeparatorIndex", "(", "path", ",", "lastSeparator", "-", "1", ")", ";", "if", "(", "prevSeparator", ">", "1", ")", "{", "return", "path", ".", "substring", "(", "0", ",", "lastSeparator", ")", ";", "}", "}", "return", "null", ";", "}", "if", "(", "lastSeparator", "==", "2", "&&", "path", ".", "charAt", "(", "1", ")", "==", "':'", "&&", "isDriveLetter", "(", "path", ".", "charAt", "(", "0", ")", ")", ")", "{", "return", "path", ".", "substring", "(", "0", ",", "3", ")", ";", "}", "return", "path", ".", "substring", "(", "0", ",", "lastSeparator", "==", "0", "?", "1", ":", "lastSeparator", ")", ";", "}", "private", "static", "boolean", "isSlash", "(", "char", "c", ")", "{", "return", "c", "==", "'/'", "||", "c", "==", "'\\\\'", ";", "}", "public", "static", "boolean", "isDriveLetter", "(", "char", "c", ")", "{", "return", "'A'", "<=", "c", "&&", "c", "<=", "'Z'", "||", "'a'", "<=", "c", "&&", "c", "<=", "'z'", ";", "}", "private", "static", "int", "lastSeparatorIndex", "(", "String", "s", ",", "int", "from", ")", "{", "return", "Math", ".", "max", "(", "s", ".", "lastIndexOf", "(", "'/'", ",", "from", ")", ",", "s", ".", "lastIndexOf", "(", "'\\\\'", ",", "from", ")", ")", ";", "}", "}" ]
<p>Utility methods for operations with file path strings.
[ "<p", ">", "Utility", "methods", "for", "operations", "with", "file", "path", "strings", "." ]
[ "// a UNC path", "// a DOS path" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
14
582
127
3871d79d677ae977a3689a86cabb52bc4f660d09
JoeArrowood-E99965/Terminals
Source/Terminals.Plugins.Rdp/Properties/Resources.Designer.cs
[ "RSA-MD" ]
C#
Resources
/// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project.
A strongly-typed resource class, for looking up localized strings, etc.
[ "A", "strongly", "-", "typed", "resource", "class", "for", "looking", "up", "localized", "strings", "etc", "." ]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Terminals.Plugins.Rdp.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } internal static string Areyousureyouwanttologthissessionoff { get { return ResourceManager.GetString("Areyousureyouwanttologthissessionoff", resourceCulture); } } internal static string Areyousureyouwanttorebootthismachine { get { return ResourceManager.GetString("Areyousureyouwanttorebootthismachine", resourceCulture); } } internal static string Areyousureyouwanttoshutthismachineoff { get { return ResourceManager.GetString("Areyousureyouwanttoshutthismachineoff", resourceCulture); } } internal static string Confirmation { get { return ResourceManager.GetString("Confirmation", resourceCulture); } } internal static System.Drawing.Bitmap folder { get { object obj = ResourceManager.GetObject("folder", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } internal static string Logoff { get { return ResourceManager.GetString("Logoff", resourceCulture); } } internal static System.Drawing.Bitmap Progress { get { object obj = ResourceManager.GetObject("Progress", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } internal static string Reboot { get { return ResourceManager.GetString("Reboot", resourceCulture); } } internal static string SendMessage { get { return ResourceManager.GetString("SendMessage", resourceCulture); } } internal static string Server { get { return ResourceManager.GetString("Server", resourceCulture); } } internal static System.Drawing.Bitmap server_network { get { object obj = ResourceManager.GetObject("server_network", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } internal static string Sessions { get { return ResourceManager.GetString("Sessions", resourceCulture); } } internal static string Shutdown { get { return ResourceManager.GetString("Shutdown", resourceCulture); } } internal static System.Drawing.Bitmap treeIcon_rdp { get { object obj = ResourceManager.GetObject("treeIcon_rdp", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } }
[ "[", "global", "::", "System", ".", "CodeDom", ".", "Compiler", ".", "GeneratedCodeAttribute", "(", "\"", "System.Resources.Tools.StronglyTypedResourceBuilder", "\"", ",", "\"", "17.0.0.0", "\"", ")", "]", "[", "global", "::", "System", ".", "Diagnostics", ".", "DebuggerNonUserCodeAttribute", "(", ")", "]", "[", "global", "::", "System", ".", "Runtime", ".", "CompilerServices", ".", "CompilerGeneratedAttribute", "(", ")", "]", "internal", "class", "Resources", "{", "private", "static", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "resourceMan", ";", "private", "static", "global", "::", "System", ".", "Globalization", ".", "CultureInfo", "resourceCulture", ";", "[", "global", "::", "System", ".", "Diagnostics", ".", "CodeAnalysis", ".", "SuppressMessageAttribute", "(", "\"", "Microsoft.Performance", "\"", ",", "\"", "CA1811:AvoidUncalledPrivateCode", "\"", ")", "]", "internal", "Resources", "(", ")", "{", "}", "[", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableAttribute", "(", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableState", ".", "Advanced", ")", "]", "internal", "static", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "ResourceManager", "{", "get", "{", "if", "(", "object", ".", "ReferenceEquals", "(", "resourceMan", ",", "null", ")", ")", "{", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "temp", "=", "new", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "(", "\"", "Terminals.Plugins.Rdp.Properties.Resources", "\"", ",", "typeof", "(", "Resources", ")", ".", "Assembly", ")", ";", "resourceMan", "=", "temp", ";", "}", "return", "resourceMan", ";", "}", "}", "[", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableAttribute", "(", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableState", ".", "Advanced", ")", "]", "internal", "static", "global", "::", "System", ".", "Globalization", ".", "CultureInfo", "Culture", "{", "get", "{", "return", "resourceCulture", ";", "}", "set", "{", "resourceCulture", "=", "value", ";", "}", "}", "internal", "static", "string", "Areyousureyouwanttologthissessionoff", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Areyousureyouwanttologthissessionoff", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "Areyousureyouwanttorebootthismachine", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Areyousureyouwanttorebootthismachine", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "Areyousureyouwanttoshutthismachineoff", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Areyousureyouwanttoshutthismachineoff", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "Confirmation", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Confirmation", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "System", ".", "Drawing", ".", "Bitmap", "folder", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "folder", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "System", ".", "Drawing", ".", "Bitmap", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "string", "Logoff", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Logoff", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "System", ".", "Drawing", ".", "Bitmap", "Progress", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "Progress", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "System", ".", "Drawing", ".", "Bitmap", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "string", "Reboot", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Reboot", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "SendMessage", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "SendMessage", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "Server", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Server", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "System", ".", "Drawing", ".", "Bitmap", "server_network", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "server_network", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "System", ".", "Drawing", ".", "Bitmap", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "string", "Sessions", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Sessions", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "Shutdown", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Shutdown", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "System", ".", "Drawing", ".", "Bitmap", "treeIcon_rdp", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "treeIcon_rdp", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "System", ".", "Drawing", ".", "Bitmap", ")", "(", "obj", ")", ")", ";", "}", "}", "}" ]
A strongly-typed resource class, for looking up localized strings, etc.
[ "A", "strongly", "-", "typed", "resource", "class", "for", "looking", "up", "localized", "strings", "etc", "." ]
[ "/// <summary>", "/// Returns the cached ResourceManager instance used by this class.", "/// </summary>", "/// <summary>", "/// Overrides the current thread's CurrentUICulture property for all", "/// resource lookups using this strongly typed resource class.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Are you sure you want to log this session off?.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Are you sure you want to reboot this machine?.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Are you sure you want to shut this machine off?.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Confirmation.", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Drawing.Bitmap.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Logoff.", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Drawing.Bitmap.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Reboot.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Send Message.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Server.", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Drawing.Bitmap.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Sessions.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Shutdown.", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Drawing.Bitmap.", "/// </summary>" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
17
713
84
d6b4412507f0353f3d9a84d7e562f886012a01b3
SearchSpring/aws_security
libraries/ec2.rb
[ "Apache-2.0" ]
Ruby
Aws
# # Author:: Greg Hellings (<[email protected]>) # # # Copyright 2014, B7 Interactive, LLC # # 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.
: Greg Hellings () Copyright 2014, B7 Interactive, LLC 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 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.
[ ":", "Greg", "Hellings", "()", "Copyright", "2014", "B7", "Interactive", "LLC", "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", "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", "." ]
module Aws module Ec2 def ec2 # rubocop: disable Style/ClassVars @@ec2 ||= create_aws_interface end def create_aws_interface begin require 'fog/aws' rescue LoadError chef_gem 'fog-aws' do compile_time true if Chef::Resource::ChefGem.method_defined?(:compile_time) action :install end require 'fog/aws' end options = { provider: 'AWS', region: @current_resource.region } if @current_resource.aws_access_key_id # Only pass credentials if we have them. This allows Fog to fall back # to IAM roles. options[:aws_access_key_id] = @current_resource.aws_access_key_id options[:aws_secret_access_key] = @current_resource.aws_secret_access_key end if @current_resource.mocking options[:host] = 'localhost' options[:port] = 5000 options[:scheme] = 'http' end Fog::Compute.new(options) end end end
[ "module", "Aws", "module", "Ec2", "def", "ec2", "@@ec2", "||=", "create_aws_interface", "end", "def", "create_aws_interface", "begin", "require", "'fog/aws'", "rescue", "LoadError", "chef_gem", "'fog-aws'", "do", "compile_time", "true", "if", "Chef", "::", "Resource", "::", "ChefGem", ".", "method_defined?", "(", ":compile_time", ")", "action", ":install", "end", "require", "'fog/aws'", "end", "options", "=", "{", "provider", ":", "'AWS'", ",", "region", ":", "@current_resource", ".", "region", "}", "if", "@current_resource", ".", "aws_access_key_id", "options", "[", ":aws_access_key_id", "]", "=", "@current_resource", ".", "aws_access_key_id", "options", "[", ":aws_secret_access_key", "]", "=", "@current_resource", ".", "aws_secret_access_key", "end", "if", "@current_resource", ".", "mocking", "options", "[", ":host", "]", "=", "'localhost'", "options", "[", ":port", "]", "=", "5000", "options", "[", ":scheme", "]", "=", "'http'", "end", "Fog", "::", "Compute", ".", "new", "(", "options", ")", "end", "end", "end" ]
Author:: Greg Hellings (<[email protected]>) Copyright 2014, B7 Interactive, LLC
[ "Author", "::", "Greg", "Hellings", "(", "<greg@thesub", ".", "net", ">", ")", "Copyright", "2014", "B7", "Interactive", "LLC" ]
[ "# rubocop: disable Style/ClassVars", "# Only pass credentials if we have them. This allows Fog to fall back", "# to IAM roles." ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
17
249
150
4ffbc32143ad8c98c7e25876b4ae943d8167888a
seandilda/dnsruby
lib/dnsruby/config.rb
[ "Apache-2.0" ]
Ruby
Config
# == Description # The Config class determines the system configuration for DNS. # In particular, it determines the nameserver to target queries to. # # # It also specifies whether and how the search list and default # domain should be applied to queries, according to the following # algorithm : # # * If the name is absolute, then it is used as is. # # * If the name is not absolute, then : # # If apply_domain is true, and ndots is greater than the number # of labels in the name, then the default domain is added to the name. # # If apply_search_list is true, then each member of the search list # is appended to the name. # # The Config class has now been modified for lazy loading. Previously, the config # was loaded when a Resolver was instantiated. Now, the config is only loaded if # a query is performed (or a config parameter requested on) a Resolver which has # not yet been configured.
Description The Config class determines the system configuration for DNS. In particular, it determines the nameserver to target queries to. It also specifies whether and how the search list and default domain should be applied to queries, according to the following algorithm . If the name is absolute, then it is used as is. If the name is not absolute, then . If apply_domain is true, and ndots is greater than the number of labels in the name, then the default domain is added to the name. If apply_search_list is true, then each member of the search list is appended to the name. The Config class has now been modified for lazy loading. Previously, the config was loaded when a Resolver was instantiated. Now, the config is only loaded if a query is performed (or a config parameter requested on) a Resolver which has not yet been configured.
[ "Description", "The", "Config", "class", "determines", "the", "system", "configuration", "for", "DNS", ".", "In", "particular", "it", "determines", "the", "nameserver", "to", "target", "queries", "to", ".", "It", "also", "specifies", "whether", "and", "how", "the", "search", "list", "and", "default", "domain", "should", "be", "applied", "to", "queries", "according", "to", "the", "following", "algorithm", ".", "If", "the", "name", "is", "absolute", "then", "it", "is", "used", "as", "is", ".", "If", "the", "name", "is", "not", "absolute", "then", ".", "If", "apply_domain", "is", "true", "and", "ndots", "is", "greater", "than", "the", "number", "of", "labels", "in", "the", "name", "then", "the", "default", "domain", "is", "added", "to", "the", "name", ".", "If", "apply_search_list", "is", "true", "then", "each", "member", "of", "the", "search", "list", "is", "appended", "to", "the", "name", ".", "The", "Config", "class", "has", "now", "been", "modified", "for", "lazy", "loading", ".", "Previously", "the", "config", "was", "loaded", "when", "a", "Resolver", "was", "instantiated", ".", "Now", "the", "config", "is", "only", "loaded", "if", "a", "query", "is", "performed", "(", "or", "a", "config", "parameter", "requested", "on", ")", "a", "Resolver", "which", "has", "not", "yet", "been", "configured", "." ]
class Config # -- # @TODO@ Switches for : # # -- single socket for all packets # -- single new socket for individual client queries (including retries and multiple nameservers) # ++ # The list of nameservers to query def nameserver if (!@configured) parse_config end return @nameserver end # Should the search list be applied? attr_accessor :apply_search_list # Should the default domain be applied? attr_accessor :apply_domain # The minimum number of labels in the query name (if it is not absolute) before it is considered complete def ndots if (!@configured) parse_config end return @ndots end # Set the config. Parameter can be : # # * A String containing the name of the config file to load # e.g. /etc/resolv.conf # # * A hash with the following elements : # nameserver (String) # domain (String) # search (String) # ndots (Fixnum) # # This method should not normally be called by client code. def set_config_info(config_info) parse_config(config_info) end # Create a new Config with system default values def initialize() @mutex = Mutex.new @configured = false # parse_config end # Reset the config to default values def Config.reset c = Config.new @configured = false # c.parse_config end def parse_config(config_info=nil) #:nodoc: all @mutex.synchronize { ns = [] @nameserver = [] @domain, s, @search = nil dom="" nd = 1 @ndots = 1 @apply_search_list = true @apply_domain = true config_hash = Config.default_config_hash case config_info when nil when String config_hash.merge!(Config.parse_resolv_conf(config_info)) when Hash config_hash.merge!(config_info.dup) if String === config_hash[:nameserver] config_hash[:nameserver] = [config_hash[:nameserver]] end if String === config_hash[:search] config_hash[:search] = [config_hash[:search]] end else raise ArgumentError.new("invalid resolv configuration: #{@config_info.inspect}") end ns = config_hash[:nameserver] if config_hash.include? :nameserver s = config_hash[:search] if config_hash.include? :search nd = config_hash[:ndots] if config_hash.include? :ndots @apply_search_list = config_hash[:apply_search_list] if config_hash.include? :apply_search_list @apply_domain= config_hash[:apply_domain] if config_hash.include? :apply_domain dom = config_hash[:domain] if config_hash.include? :domain if (!@configured) send("nameserver=",ns) end @configured = true send("search=",s) send("ndots=",nd) send("domain=",dom) } Dnsruby.log.info{to_s} end # Set the default domain def domain=(dom) # @configured = true if (dom) if !dom.kind_of?(String) raise ArgumentError.new("invalid domain config: #{@domain.inspect}") end @domain = Name::split(dom) else @domain=nil end end # Set ndots def ndots=(nd) @configured = true @ndots=nd if [email protected]_of?(Integer) raise ArgumentError.new("invalid ndots config: #{@ndots.inspect}") end end # Set the default search path def search=(s) @configured = true @search=s if @search if @search.class == Array @search = @search.map {|arg| Name::split(arg) } else raise ArgumentError.new("invalid search config: search must be an array!") end else hostname = Socket.gethostname if /\./ =~ hostname @search = [Name.split($')] else @search = [[]] end end if [email protected]_of?(Array) || # [email protected]? {|ls| ls.all? {|l| Label::Str === l } } [email protected]? {|ls| ls.all? {|l| Name::Label === l } } raise ArgumentError.new("invalid search config: #{@search.inspect}") end end def check_ns(ns) #:nodoc: all if !ns.kind_of?(Array) || !ns.all? {|n| (Name === n || String === n || IPv4 === n || IPv6 === n)} raise ArgumentError.new("invalid nameserver config: #{ns.inspect}") end ns.each {|n| if (String ===n) # Make sure we can make a Name or an address from it begin a = IPv4.create(n) rescue ArgumentError begin a = IPv6.create(n) rescue ArgumentError begin a = Name.create(n) rescue ArgumentError raise ArgumentError.new("Can't interpret #{n} as IPv4, IPv6 or Name") end end end end } end # Add a nameserver to the list of nameservers. # # Can take either a single String or an array of Strings. # The new nameservers are added at a higher priority. def add_nameserver(ns) @configured = true if (ns.kind_of?String) ns=[ns] end check_ns(ns) ns.reverse_each do |n| if ([email protected]?(n)) self.nameserver=[n]+@nameserver end end end # Set the config to point to a single nameserver def nameserver=(ns) @configured = true check_ns(ns) # @nameserver = ['0.0.0.0'] if (@nameserver.class != Array || @nameserver.empty?) # Now go through and ensure that all ns point to IP addresses, not domain names @nameserver=ns Dnsruby.log.debug{"Nameservers = #{@nameserver.join(", ")}"} end def Config.resolve_server(ns) #:nodoc: all # Sanity check server # If it's an IP address, then use that for server # If it's a name, then we'll need to resolve it first server=ns if (Name === ns) ns = ns.to_s end begin addr = IPv4.create(ns) server = ns rescue Exception begin addr=IPv6.create(ns) server = ns rescue Exception begin # try to resolve server to address if ns == "localhost" server = "127.0.0.1" else # Use Dnsruby to resolve the servers # First, try the default resolvers resolver = Resolver.new found = false begin ret = resolver.query(ns) ret.answer.each {|rr| if ([Types::A, Types::AAAA].include?rr.type) addr = rr.address.to_s server = addr found = true end } rescue Exception end if (!found) # That didn't work - try recursing from the root recursor = Recursor.new ret = recursor.query(ns) ret.answer.each {|rr| if ([Types::A, Types::AAAA].include?rr.type) addr = rr.address.to_s server = addr end } if (!found) raise ArgumentError.new("Recursor can't locate #{server}") end end end rescue Exception => e Dnsruby.log.error{"Can't make sense of nameserver : #{server}, exception : #{e}"} raise ArgumentError.new("Can't make sense of nameserver : #{server}, exception : #{e}") return nil end end end return server end def Config.parse_resolv_conf(filename) #:nodoc: all nameserver = [] search = nil domain = nil ndots = 1 open(filename) {|f| f.each {|line| line.sub!(/[#;].*/, '') keyword, *args = line.split(/\s+/) args.each { |arg| arg.untaint } next unless keyword case keyword when 'nameserver' nameserver += args when 'domain' next if args.empty? domain = args[0] # if search == nil # search = [] # end # search.push(args[0]) when 'search' next if args.empty? if search == nil search = [] end args.each {|a| search.push(a)} when 'options' args.each {|arg| case arg when /\Andots:(\d+)\z/ ndots = $1.to_i end } end } } return { :nameserver => nameserver, :domain => domain, :search => search, :ndots => ndots } end def inspect #:nodoc: all to_s end def to_s if (!@configured) parse_config end ret = "Config - nameservers : " @nameserver.each {|n| ret += n.to_s + ", "} domain_string="empty" if (@domain!=nil) [email protected]_s end ret += " domain : #{domain_string}, search : " search.each {|s| ret += s + ", " } ret += " ndots : #{@ndots}" return ret end def Config.default_config_hash(filename="/etc/resolv.conf") #:nodoc: all config_hash={} if File.exist? filename config_hash = Config.parse_resolv_conf(filename) else if (/java/ =~ RUBY_PLATFORM && !(filename=~/:/)) # Problem with paths and Windows on JRuby - see if we can munge the drive... wd = Dir.getwd drive = wd.split(':')[0] if (drive.length==1) file = drive << ":" << filename if File.exist? file config_hash = Config.parse_resolv_conf(file) end end elsif /mswin32|cygwin|mingw|bccwin/ =~ RUBY_PLATFORM # @TODO@ Need to get windows domain sorted search, nameserver = Win32::Resolv.get_resolv_info # config_hash[:domain] = domain if domain config_hash[:nameserver] = nameserver if nameserver config_hash[:search] = [search].flatten if search end end config_hash end # Return the search path def search if (!@configured) parse_config end search = [] @search.each do |s| search.push(Name.new(s).to_s) end return search end # Return the default domain def domain if (!@configured) parse_config end if (@domain==nil) return nil end return Name.create(@domain).to_s end def single? #:nodoc: all if @nameserver.length == 1 return @nameserver[0] else return nil end end def get_ready if (!@configured) parse_config end end def generate_candidates(name) #:nodoc: all if !@configured parse_config end candidates = [] name = Name.create(name) if name.absolute? candidates = [name] else if (@apply_domain) if @ndots > name.length - 1 candidates.push(Name.create(name.to_a+@domain)) end end if (!@apply_search_list) candidates.push(Name.create(name.to_a)) else if @ndots <= name.length - 1 candidates.push(Name.create(name.to_a)) end candidates.concat(@search.map {|domain| Name.create(name.to_a + domain)}) if (name.length == 1) candidates.concat([Name.create(name.to_a)]) end end end return candidates end end
[ "class", "Config", "def", "nameserver", "if", "(", "!", "@configured", ")", "parse_config", "end", "return", "@nameserver", "end", "attr_accessor", ":apply_search_list", "attr_accessor", ":apply_domain", "def", "ndots", "if", "(", "!", "@configured", ")", "parse_config", "end", "return", "@ndots", "end", "def", "set_config_info", "(", "config_info", ")", "parse_config", "(", "config_info", ")", "end", "def", "initialize", "(", ")", "@mutex", "=", "Mutex", ".", "new", "@configured", "=", "false", "end", "def", "Config", ".", "reset", "c", "=", "Config", ".", "new", "@configured", "=", "false", "end", "def", "parse_config", "(", "config_info", "=", "nil", ")", "@mutex", ".", "synchronize", "{", "ns", "=", "[", "]", "@nameserver", "=", "[", "]", "@domain", ",", "s", ",", "@search", "=", "nil", "dom", "=", "\"\"", "nd", "=", "1", "@ndots", "=", "1", "@apply_search_list", "=", "true", "@apply_domain", "=", "true", "config_hash", "=", "Config", ".", "default_config_hash", "case", "config_info", "when", "nil", "when", "String", "config_hash", ".", "merge!", "(", "Config", ".", "parse_resolv_conf", "(", "config_info", ")", ")", "when", "Hash", "config_hash", ".", "merge!", "(", "config_info", ".", "dup", ")", "if", "String", "===", "config_hash", "[", ":nameserver", "]", "config_hash", "[", ":nameserver", "]", "=", "[", "config_hash", "[", ":nameserver", "]", "]", "end", "if", "String", "===", "config_hash", "[", ":search", "]", "config_hash", "[", ":search", "]", "=", "[", "config_hash", "[", ":search", "]", "]", "end", "else", "raise", "ArgumentError", ".", "new", "(", "\"invalid resolv configuration: #{@config_info.inspect}\"", ")", "end", "ns", "=", "config_hash", "[", ":nameserver", "]", "if", "config_hash", ".", "include?", ":nameserver", "s", "=", "config_hash", "[", ":search", "]", "if", "config_hash", ".", "include?", ":search", "nd", "=", "config_hash", "[", ":ndots", "]", "if", "config_hash", ".", "include?", ":ndots", "@apply_search_list", "=", "config_hash", "[", ":apply_search_list", "]", "if", "config_hash", ".", "include?", ":apply_search_list", "@apply_domain", "=", "config_hash", "[", ":apply_domain", "]", "if", "config_hash", ".", "include?", ":apply_domain", "dom", "=", "config_hash", "[", ":domain", "]", "if", "config_hash", ".", "include?", ":domain", "if", "(", "!", "@configured", ")", "send", "(", "\"nameserver=\"", ",", "ns", ")", "end", "@configured", "=", "true", "send", "(", "\"search=\"", ",", "s", ")", "send", "(", "\"ndots=\"", ",", "nd", ")", "send", "(", "\"domain=\"", ",", "dom", ")", "}", "Dnsruby", ".", "log", ".", "info", "{", "to_s", "}", "end", "def", "domain", "=", "(", "dom", ")", "if", "(", "dom", ")", "if", "!", "dom", ".", "kind_of?", "(", "String", ")", "raise", "ArgumentError", ".", "new", "(", "\"invalid domain config: #{@domain.inspect}\"", ")", "end", "@domain", "=", "Name", "::", "split", "(", "dom", ")", "else", "@domain", "=", "nil", "end", "end", "def", "ndots", "=", "(", "nd", ")", "@configured", "=", "true", "@ndots", "=", "nd", "if", "!", "@ndots", ".", "kind_of?", "(", "Integer", ")", "raise", "ArgumentError", ".", "new", "(", "\"invalid ndots config: #{@ndots.inspect}\"", ")", "end", "end", "def", "search", "=", "(", "s", ")", "@configured", "=", "true", "@search", "=", "s", "if", "@search", "if", "@search", ".", "class", "==", "Array", "@search", "=", "@search", ".", "map", "{", "|", "arg", "|", "Name", "::", "split", "(", "arg", ")", "}", "else", "raise", "ArgumentError", ".", "new", "(", "\"invalid search config: search must be an array!\"", ")", "end", "else", "hostname", "=", "Socket", ".", "gethostname", "if", "/", "\\.", "/", "=~", "hostname", "@search", "=", "[", "Name", ".", "split", "(", "$'", ")", "]", "else", "@search", "=", "[", "[", "]", "]", "end", "end", "if", "!", "@search", ".", "kind_of?", "(", "Array", ")", "||", "!", "@search", ".", "all?", "{", "|", "ls", "|", "ls", ".", "all?", "{", "|", "l", "|", "Name", "::", "Label", "===", "l", "}", "}", "raise", "ArgumentError", ".", "new", "(", "\"invalid search config: #{@search.inspect}\"", ")", "end", "end", "def", "check_ns", "(", "ns", ")", "if", "!", "ns", ".", "kind_of?", "(", "Array", ")", "||", "!", "ns", ".", "all?", "{", "|", "n", "|", "(", "Name", "===", "n", "||", "String", "===", "n", "||", "IPv4", "===", "n", "||", "IPv6", "===", "n", ")", "}", "raise", "ArgumentError", ".", "new", "(", "\"invalid nameserver config: #{ns.inspect}\"", ")", "end", "ns", ".", "each", "{", "|", "n", "|", "if", "(", "String", "===", "n", ")", "begin", "a", "=", "IPv4", ".", "create", "(", "n", ")", "rescue", "ArgumentError", "begin", "a", "=", "IPv6", ".", "create", "(", "n", ")", "rescue", "ArgumentError", "begin", "a", "=", "Name", ".", "create", "(", "n", ")", "rescue", "ArgumentError", "raise", "ArgumentError", ".", "new", "(", "\"Can't interpret #{n} as IPv4, IPv6 or Name\"", ")", "end", "end", "end", "end", "}", "end", "def", "add_nameserver", "(", "ns", ")", "@configured", "=", "true", "if", "(", "ns", ".", "kind_of?", "String", ")", "ns", "=", "[", "ns", "]", "end", "check_ns", "(", "ns", ")", "ns", ".", "reverse_each", "do", "|", "n", "|", "if", "(", "!", "@nameserver", ".", "include?", "(", "n", ")", ")", "self", ".", "nameserver", "=", "[", "n", "]", "+", "@nameserver", "end", "end", "end", "def", "nameserver", "=", "(", "ns", ")", "@configured", "=", "true", "check_ns", "(", "ns", ")", "@nameserver", "=", "ns", "Dnsruby", ".", "log", ".", "debug", "{", "\"Nameservers = #{@nameserver.join(\", \")}\"", "}", "end", "def", "Config", ".", "resolve_server", "(", "ns", ")", "server", "=", "ns", "if", "(", "Name", "===", "ns", ")", "ns", "=", "ns", ".", "to_s", "end", "begin", "addr", "=", "IPv4", ".", "create", "(", "ns", ")", "server", "=", "ns", "rescue", "Exception", "begin", "addr", "=", "IPv6", ".", "create", "(", "ns", ")", "server", "=", "ns", "rescue", "Exception", "begin", "if", "ns", "==", "\"localhost\"", "server", "=", "\"127.0.0.1\"", "else", "resolver", "=", "Resolver", ".", "new", "found", "=", "false", "begin", "ret", "=", "resolver", ".", "query", "(", "ns", ")", "ret", ".", "answer", ".", "each", "{", "|", "rr", "|", "if", "(", "[", "Types", "::", "A", ",", "Types", "::", "AAAA", "]", ".", "include?", "rr", ".", "type", ")", "addr", "=", "rr", ".", "address", ".", "to_s", "server", "=", "addr", "found", "=", "true", "end", "}", "rescue", "Exception", "end", "if", "(", "!", "found", ")", "recursor", "=", "Recursor", ".", "new", "ret", "=", "recursor", ".", "query", "(", "ns", ")", "ret", ".", "answer", ".", "each", "{", "|", "rr", "|", "if", "(", "[", "Types", "::", "A", ",", "Types", "::", "AAAA", "]", ".", "include?", "rr", ".", "type", ")", "addr", "=", "rr", ".", "address", ".", "to_s", "server", "=", "addr", "end", "}", "if", "(", "!", "found", ")", "raise", "ArgumentError", ".", "new", "(", "\"Recursor can't locate #{server}\"", ")", "end", "end", "end", "rescue", "Exception", "=>", "e", "Dnsruby", ".", "log", ".", "error", "{", "\"Can't make sense of nameserver : #{server}, exception : #{e}\"", "}", "raise", "ArgumentError", ".", "new", "(", "\"Can't make sense of nameserver : #{server}, exception : #{e}\"", ")", "return", "nil", "end", "end", "end", "return", "server", "end", "def", "Config", ".", "parse_resolv_conf", "(", "filename", ")", "nameserver", "=", "[", "]", "search", "=", "nil", "domain", "=", "nil", "ndots", "=", "1", "open", "(", "filename", ")", "{", "|", "f", "|", "f", ".", "each", "{", "|", "line", "|", "line", ".", "sub!", "(", "/", "[#;].*", "/", ",", "''", ")", "keyword", ",", "*", "args", "=", "line", ".", "split", "(", "/", "\\s", "+", "/", ")", "args", ".", "each", "{", "|", "arg", "|", "arg", ".", "untaint", "}", "next", "unless", "keyword", "case", "keyword", "when", "'nameserver'", "nameserver", "+=", "args", "when", "'domain'", "next", "if", "args", ".", "empty?", "domain", "=", "args", "[", "0", "]", "when", "'search'", "next", "if", "args", ".", "empty?", "if", "search", "==", "nil", "search", "=", "[", "]", "end", "args", ".", "each", "{", "|", "a", "|", "search", ".", "push", "(", "a", ")", "}", "when", "'options'", "args", ".", "each", "{", "|", "arg", "|", "case", "arg", "when", "/", "\\A", "ndots:(", "\\d", "+)", "\\z", "/", "ndots", "=", "$1", ".", "to_i", "end", "}", "end", "}", "}", "return", "{", ":nameserver", "=>", "nameserver", ",", ":domain", "=>", "domain", ",", ":search", "=>", "search", ",", ":ndots", "=>", "ndots", "}", "end", "def", "inspect", "to_s", "end", "def", "to_s", "if", "(", "!", "@configured", ")", "parse_config", "end", "ret", "=", "\"Config - nameservers : \"", "@nameserver", ".", "each", "{", "|", "n", "|", "ret", "+=", "n", ".", "to_s", "+", "\", \"", "}", "domain_string", "=", "\"empty\"", "if", "(", "@domain", "!=", "nil", ")", "domain_string", "=", "@domain", ".", "to_s", "end", "ret", "+=", "\" domain : #{domain_string}, search : \"", "search", ".", "each", "{", "|", "s", "|", "ret", "+=", "s", "+", "\", \"", "}", "ret", "+=", "\" ndots : #{@ndots}\"", "return", "ret", "end", "def", "Config", ".", "default_config_hash", "(", "filename", "=", "\"/etc/resolv.conf\"", ")", "config_hash", "=", "{", "}", "if", "File", ".", "exist?", "filename", "config_hash", "=", "Config", ".", "parse_resolv_conf", "(", "filename", ")", "else", "if", "(", "/", "java", "/", "=~", "RUBY_PLATFORM", "&&", "!", "(", "filename", "=~", "/", ":", "/", ")", ")", "wd", "=", "Dir", ".", "getwd", "drive", "=", "wd", ".", "split", "(", "':'", ")", "[", "0", "]", "if", "(", "drive", ".", "length", "==", "1", ")", "file", "=", "drive", "<<", "\":\"", "<<", "filename", "if", "File", ".", "exist?", "file", "config_hash", "=", "Config", ".", "parse_resolv_conf", "(", "file", ")", "end", "end", "elsif", "/", "mswin32|cygwin|mingw|bccwin", "/", "=~", "RUBY_PLATFORM", "search", ",", "nameserver", "=", "Win32", "::", "Resolv", ".", "get_resolv_info", "config_hash", "[", ":nameserver", "]", "=", "nameserver", "if", "nameserver", "config_hash", "[", ":search", "]", "=", "[", "search", "]", ".", "flatten", "if", "search", "end", "end", "config_hash", "end", "def", "search", "if", "(", "!", "@configured", ")", "parse_config", "end", "search", "=", "[", "]", "@search", ".", "each", "do", "|", "s", "|", "search", ".", "push", "(", "Name", ".", "new", "(", "s", ")", ".", "to_s", ")", "end", "return", "search", "end", "def", "domain", "if", "(", "!", "@configured", ")", "parse_config", "end", "if", "(", "@domain", "==", "nil", ")", "return", "nil", "end", "return", "Name", ".", "create", "(", "@domain", ")", ".", "to_s", "end", "def", "single?", "if", "@nameserver", ".", "length", "==", "1", "return", "@nameserver", "[", "0", "]", "else", "return", "nil", "end", "end", "def", "get_ready", "if", "(", "!", "@configured", ")", "parse_config", "end", "end", "def", "generate_candidates", "(", "name", ")", "if", "!", "@configured", "parse_config", "end", "candidates", "=", "[", "]", "name", "=", "Name", ".", "create", "(", "name", ")", "if", "name", ".", "absolute?", "candidates", "=", "[", "name", "]", "else", "if", "(", "@apply_domain", ")", "if", "@ndots", ">", "name", ".", "length", "-", "1", "candidates", ".", "push", "(", "Name", ".", "create", "(", "name", ".", "to_a", "+", "@domain", ")", ")", "end", "end", "if", "(", "!", "@apply_search_list", ")", "candidates", ".", "push", "(", "Name", ".", "create", "(", "name", ".", "to_a", ")", ")", "else", "if", "@ndots", "<=", "name", ".", "length", "-", "1", "candidates", ".", "push", "(", "Name", ".", "create", "(", "name", ".", "to_a", ")", ")", "end", "candidates", ".", "concat", "(", "@search", ".", "map", "{", "|", "domain", "|", "Name", ".", "create", "(", "name", ".", "to_a", "+", "domain", ")", "}", ")", "if", "(", "name", ".", "length", "==", "1", ")", "candidates", ".", "concat", "(", "[", "Name", ".", "create", "(", "name", ".", "to_a", ")", "]", ")", "end", "end", "end", "return", "candidates", "end", "end" ]
Description The Config class determines the system configuration for DNS.
[ "Description", "The", "Config", "class", "determines", "the", "system", "configuration", "for", "DNS", "." ]
[ "# --", "# @TODO@ Switches for :", "# ", "# -- single socket for all packets", "# -- single new socket for individual client queries (including retries and multiple nameservers)", "# ++", "# The list of nameservers to query", "# Should the search list be applied?", "# Should the default domain be applied?", "# The minimum number of labels in the query name (if it is not absolute) before it is considered complete", "# Set the config. Parameter can be :", "# ", "# * A String containing the name of the config file to load", "# e.g. /etc/resolv.conf", "# ", "# * A hash with the following elements :", "# nameserver (String)", "# domain (String)", "# search (String)", "# ndots (Fixnum)", "# ", "# This method should not normally be called by client code.", "# Create a new Config with system default values", "# parse_config", "# Reset the config to default values", "# c.parse_config", "#:nodoc: all", "# Set the default domain", "# @configured = true", "# Set ndots", "# Set the default search path", "# [email protected]? {|ls| ls.all? {|l| Label::Str === l } }", "#:nodoc: all", "# Make sure we can make a Name or an address from it", "# Add a nameserver to the list of nameservers.", "# ", "# Can take either a single String or an array of Strings.", "# The new nameservers are added at a higher priority.", "# Set the config to point to a single nameserver", "# @nameserver = ['0.0.0.0'] if (@nameserver.class != Array || @nameserver.empty?)", "# Now go through and ensure that all ns point to IP addresses, not domain names", "#:nodoc: all", "# Sanity check server", "# If it's an IP address, then use that for server", "# If it's a name, then we'll need to resolve it first", "# try to resolve server to address", "# Use Dnsruby to resolve the servers", "# First, try the default resolvers", "# That didn't work - try recursing from the root", "#:nodoc: all", "# if search == nil", "# search = []", "# end", "# search.push(args[0])", "#:nodoc: all", "#:nodoc: all", "# Problem with paths and Windows on JRuby - see if we can munge the drive...", "# @TODO@ Need to get windows domain sorted", "# config_hash[:domain] = domain if domain", "# Return the search path", "# Return the default domain", "#:nodoc: all", "#:nodoc: all" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
25
2,878
228
1cf325b41489ceb875cb5293af9eb695d0db728e
mrabusalah/domino-ui
domino-ui/src/main/java/org/dominokit/domino/ui/popover/Tooltip.java
[ "ECL-2.0", "Apache-2.0" ]
Java
Tooltip
/** * A component for showing a content when hovering over a target element * * <p>Customize the component can be done by overwriting classes provided by {@link TooltipStyles} * * <p>For example: * * <pre> * Tooltip.create(element, "Tooltip on top").position(PopupPosition.TOP); * </pre> * * @see BaseDominoElement */
A component for showing a content when hovering over a target element Customize the component can be done by overwriting classes provided by TooltipStyles For example.
[ "A", "component", "for", "showing", "a", "content", "when", "hovering", "over", "a", "target", "element", "Customize", "the", "component", "can", "be", "done", "by", "overwriting", "classes", "provided", "by", "TooltipStyles", "For", "example", "." ]
public class Tooltip extends BaseDominoElement<HTMLDivElement, Tooltip> { private final DominoElement<HTMLDivElement> element = DominoElement.of(div().css(TOOLTIP).attr("role", "tooltip")); private final DominoElement<HTMLDivElement> arrowElement = DominoElement.of(div().css(TOOLTIP_ARROW)); private final DominoElement<HTMLDivElement> innerElement = DominoElement.of(div().css(TOOLTIP_INNER)); private PopupPosition popupPosition = TOP; private final EventListener showToolTipListener; private final Consumer<Tooltip> removeHandler; private final EventListener removeToolTipListener; private Optional<ElementObserver> elementObserver = Optional.empty(); public Tooltip(HTMLElement targetElement, String text) { this(targetElement, DomGlobal.document.createTextNode(text)); } public Tooltip(HTMLElement targetElement, Node content) { element.appendChild(arrowElement); element.appendChild(innerElement); innerElement.appendChild(content); element.addCss(popupPosition.getDirectionClass()); showToolTipListener = evt -> { evt.stopPropagation(); document.body.appendChild(element.element()); element.removeCss("fade", "in"); element.addCss("fade", "in"); popupPosition.position(element.element(), targetElement); position(popupPosition); elementObserver.ifPresent(ElementObserver::remove); elementObserver = ElementUtil.onDetach(targetElement, mutationRecord -> remove()); }; removeToolTipListener = evt -> element.remove(); targetElement.addEventListener(EventType.mouseenter.getName(), showToolTipListener); targetElement.addEventListener(EventType.mouseleave.getName(), removeToolTipListener); init(this); removeHandler = tooltip -> { targetElement.removeEventListener(EventType.mouseenter.getName(), showToolTipListener); targetElement.removeEventListener(EventType.mouseleave.getName(), removeToolTipListener); elementObserver.ifPresent(ElementObserver::remove); }; } /** {@inheritDoc} */ @Override public Tooltip hide() { element.remove(); return this; } /** Removes the tooltip */ public void detach() { removeHandler.accept(this); remove(); } /** * Creates new instance with text content * * @param target the target element * @param text the text content * @return new instance */ public static Tooltip create(HTMLElement target, String text) { return new Tooltip(target, text); } /** * Creates new instance with element content * * @param target the target element * @param content the {@link Node} content * @return new instance */ public static Tooltip create(HTMLElement target, Node content) { return new Tooltip(target, content); } /** * Creates new instance with text content * * @param element the target element * @param text the text content * @return new instance */ public static Tooltip create(IsElement<?> element, String text) { return new Tooltip(element.element(), text); } /** * Creates new instance with element content * * @param element the target element * @param content the {@link Node} content * @return new instance */ public static Tooltip create(IsElement<?> element, Node content) { return new Tooltip(element.element(), content); } /** * Positions the tooltip in a new position * * @param position the {@link PopupPosition} * @return same instance */ public Tooltip position(PopupPosition position) { this.element.removeCss(popupPosition.getDirectionClass()); this.popupPosition = position; this.element.addCss(popupPosition.getDirectionClass()); return this; } /** {@inheritDoc} */ @Override public HTMLDivElement element() { return element.element(); } /** @return the arrow element */ public DominoElement<HTMLDivElement> getArrowElement() { return arrowElement; } /** @return the inner container element */ public DominoElement<HTMLDivElement> getInnerElement() { return innerElement; } /** @return the current {@link PopupPosition} */ public PopupPosition getPopupPosition() { return popupPosition; } /** {@inheritDoc} */ @Override public Tooltip setContent(Node content) { innerElement.clearElement(); innerElement.appendChild(content); return this; } }
[ "public", "class", "Tooltip", "extends", "BaseDominoElement", "<", "HTMLDivElement", ",", "Tooltip", ">", "{", "private", "final", "DominoElement", "<", "HTMLDivElement", ">", "element", "=", "DominoElement", ".", "of", "(", "div", "(", ")", ".", "css", "(", "TOOLTIP", ")", ".", "attr", "(", "\"", "role", "\"", ",", "\"", "tooltip", "\"", ")", ")", ";", "private", "final", "DominoElement", "<", "HTMLDivElement", ">", "arrowElement", "=", "DominoElement", ".", "of", "(", "div", "(", ")", ".", "css", "(", "TOOLTIP_ARROW", ")", ")", ";", "private", "final", "DominoElement", "<", "HTMLDivElement", ">", "innerElement", "=", "DominoElement", ".", "of", "(", "div", "(", ")", ".", "css", "(", "TOOLTIP_INNER", ")", ")", ";", "private", "PopupPosition", "popupPosition", "=", "TOP", ";", "private", "final", "EventListener", "showToolTipListener", ";", "private", "final", "Consumer", "<", "Tooltip", ">", "removeHandler", ";", "private", "final", "EventListener", "removeToolTipListener", ";", "private", "Optional", "<", "ElementObserver", ">", "elementObserver", "=", "Optional", ".", "empty", "(", ")", ";", "public", "Tooltip", "(", "HTMLElement", "targetElement", ",", "String", "text", ")", "{", "this", "(", "targetElement", ",", "DomGlobal", ".", "document", ".", "createTextNode", "(", "text", ")", ")", ";", "}", "public", "Tooltip", "(", "HTMLElement", "targetElement", ",", "Node", "content", ")", "{", "element", ".", "appendChild", "(", "arrowElement", ")", ";", "element", ".", "appendChild", "(", "innerElement", ")", ";", "innerElement", ".", "appendChild", "(", "content", ")", ";", "element", ".", "addCss", "(", "popupPosition", ".", "getDirectionClass", "(", ")", ")", ";", "showToolTipListener", "=", "evt", "->", "{", "evt", ".", "stopPropagation", "(", ")", ";", "document", ".", "body", ".", "appendChild", "(", "element", ".", "element", "(", ")", ")", ";", "element", ".", "removeCss", "(", "\"", "fade", "\"", ",", "\"", "in", "\"", ")", ";", "element", ".", "addCss", "(", "\"", "fade", "\"", ",", "\"", "in", "\"", ")", ";", "popupPosition", ".", "position", "(", "element", ".", "element", "(", ")", ",", "targetElement", ")", ";", "position", "(", "popupPosition", ")", ";", "elementObserver", ".", "ifPresent", "(", "ElementObserver", "::", "remove", ")", ";", "elementObserver", "=", "ElementUtil", ".", "onDetach", "(", "targetElement", ",", "mutationRecord", "->", "remove", "(", ")", ")", ";", "}", ";", "removeToolTipListener", "=", "evt", "->", "element", ".", "remove", "(", ")", ";", "targetElement", ".", "addEventListener", "(", "EventType", ".", "mouseenter", ".", "getName", "(", ")", ",", "showToolTipListener", ")", ";", "targetElement", ".", "addEventListener", "(", "EventType", ".", "mouseleave", ".", "getName", "(", ")", ",", "removeToolTipListener", ")", ";", "init", "(", "this", ")", ";", "removeHandler", "=", "tooltip", "->", "{", "targetElement", ".", "removeEventListener", "(", "EventType", ".", "mouseenter", ".", "getName", "(", ")", ",", "showToolTipListener", ")", ";", "targetElement", ".", "removeEventListener", "(", "EventType", ".", "mouseleave", ".", "getName", "(", ")", ",", "removeToolTipListener", ")", ";", "elementObserver", ".", "ifPresent", "(", "ElementObserver", "::", "remove", ")", ";", "}", ";", "}", "/** {@inheritDoc} */", "@", "Override", "public", "Tooltip", "hide", "(", ")", "{", "element", ".", "remove", "(", ")", ";", "return", "this", ";", "}", "/** Removes the tooltip */", "public", "void", "detach", "(", ")", "{", "removeHandler", ".", "accept", "(", "this", ")", ";", "remove", "(", ")", ";", "}", "/**\n * Creates new instance with text content\n *\n * @param target the target element\n * @param text the text content\n * @return new instance\n */", "public", "static", "Tooltip", "create", "(", "HTMLElement", "target", ",", "String", "text", ")", "{", "return", "new", "Tooltip", "(", "target", ",", "text", ")", ";", "}", "/**\n * Creates new instance with element content\n *\n * @param target the target element\n * @param content the {@link Node} content\n * @return new instance\n */", "public", "static", "Tooltip", "create", "(", "HTMLElement", "target", ",", "Node", "content", ")", "{", "return", "new", "Tooltip", "(", "target", ",", "content", ")", ";", "}", "/**\n * Creates new instance with text content\n *\n * @param element the target element\n * @param text the text content\n * @return new instance\n */", "public", "static", "Tooltip", "create", "(", "IsElement", "<", "?", ">", "element", ",", "String", "text", ")", "{", "return", "new", "Tooltip", "(", "element", ".", "element", "(", ")", ",", "text", ")", ";", "}", "/**\n * Creates new instance with element content\n *\n * @param element the target element\n * @param content the {@link Node} content\n * @return new instance\n */", "public", "static", "Tooltip", "create", "(", "IsElement", "<", "?", ">", "element", ",", "Node", "content", ")", "{", "return", "new", "Tooltip", "(", "element", ".", "element", "(", ")", ",", "content", ")", ";", "}", "/**\n * Positions the tooltip in a new position\n *\n * @param position the {@link PopupPosition}\n * @return same instance\n */", "public", "Tooltip", "position", "(", "PopupPosition", "position", ")", "{", "this", ".", "element", ".", "removeCss", "(", "popupPosition", ".", "getDirectionClass", "(", ")", ")", ";", "this", ".", "popupPosition", "=", "position", ";", "this", ".", "element", ".", "addCss", "(", "popupPosition", ".", "getDirectionClass", "(", ")", ")", ";", "return", "this", ";", "}", "/** {@inheritDoc} */", "@", "Override", "public", "HTMLDivElement", "element", "(", ")", "{", "return", "element", ".", "element", "(", ")", ";", "}", "/** @return the arrow element */", "public", "DominoElement", "<", "HTMLDivElement", ">", "getArrowElement", "(", ")", "{", "return", "arrowElement", ";", "}", "/** @return the inner container element */", "public", "DominoElement", "<", "HTMLDivElement", ">", "getInnerElement", "(", ")", "{", "return", "innerElement", ";", "}", "/** @return the current {@link PopupPosition} */", "public", "PopupPosition", "getPopupPosition", "(", ")", "{", "return", "popupPosition", ";", "}", "/** {@inheritDoc} */", "@", "Override", "public", "Tooltip", "setContent", "(", "Node", "content", ")", "{", "innerElement", ".", "clearElement", "(", ")", ";", "innerElement", ".", "appendChild", "(", "content", ")", ";", "return", "this", ";", "}", "}" ]
A component for showing a content when hovering over a target element <p>Customize the component can be done by overwriting classes provided by {@link TooltipStyles}
[ "A", "component", "for", "showing", "a", "content", "when", "hovering", "over", "a", "target", "element", "<p", ">", "Customize", "the", "component", "can", "be", "done", "by", "overwriting", "classes", "provided", "by", "{", "@link", "TooltipStyles", "}" ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
16
917
82
a768d5d369b2f34673ec02278d805e87f2f7c150
Gamieon/Cycles3D
Assets/Standard Assets/Collada/XmlCollada.cs
[ "MIT" ]
C#
Material
/// <summary> /// A material instantiates an effect, fills its parameters with values, and selects a technique. It describes the /// appearance of a geometric object or may perform screen-space processing to create camera-lens-like /// effects such as blurs, blooms, or color filters. /// In computer graphics, geometric objects can have many parameters that describe their material properties. /// These material properties are the parameters for the rendering computations that produce the visual /// appearance of the object in the final output. Likewise, screen-space processing and compositing may also /// require many parameters for performing computation. /// The specific set of material parameters depend upon the graphics rendering system employed. Fixed /// function, graphics pipelines require parameters to solve a predefined illumination model, such as Phong /// illumination. These parameters include terms for ambient, diffuse and specular reflectance, for example. /// In programmable graphics pipelines, the programmer defines the set of material parameters. These /// parameters satisfy the rendering algorithm defined in the vertex and pixel programs. /// </summary>
A material instantiates an effect, fills its parameters with values, and selects a technique. It describes the appearance of a geometric object or may perform screen-space processing to create camera-lens-like effects such as blurs, blooms, or color filters. In computer graphics, geometric objects can have many parameters that describe their material properties. These material properties are the parameters for the rendering computations that produce the visual appearance of the object in the final output. Likewise, screen-space processing and compositing may also require many parameters for performing computation. The specific set of material parameters depend upon the graphics rendering system employed. Fixed function, graphics pipelines require parameters to solve a predefined illumination model, such as Phong illumination. These parameters include terms for ambient, diffuse and specular reflectance, for example. In programmable graphics pipelines, the programmer defines the set of material parameters. These parameters satisfy the rendering algorithm defined in the vertex and pixel programs.
[ "A", "material", "instantiates", "an", "effect", "fills", "its", "parameters", "with", "values", "and", "selects", "a", "technique", ".", "It", "describes", "the", "appearance", "of", "a", "geometric", "object", "or", "may", "perform", "screen", "-", "space", "processing", "to", "create", "camera", "-", "lens", "-", "like", "effects", "such", "as", "blurs", "blooms", "or", "color", "filters", ".", "In", "computer", "graphics", "geometric", "objects", "can", "have", "many", "parameters", "that", "describe", "their", "material", "properties", ".", "These", "material", "properties", "are", "the", "parameters", "for", "the", "rendering", "computations", "that", "produce", "the", "visual", "appearance", "of", "the", "object", "in", "the", "final", "output", ".", "Likewise", "screen", "-", "space", "processing", "and", "compositing", "may", "also", "require", "many", "parameters", "for", "performing", "computation", ".", "The", "specific", "set", "of", "material", "parameters", "depend", "upon", "the", "graphics", "rendering", "system", "employed", ".", "Fixed", "function", "graphics", "pipelines", "require", "parameters", "to", "solve", "a", "predefined", "illumination", "model", "such", "as", "Phong", "illumination", ".", "These", "parameters", "include", "terms", "for", "ambient", "diffuse", "and", "specular", "reflectance", "for", "example", ".", "In", "programmable", "graphics", "pipelines", "the", "programmer", "defines", "the", "set", "of", "material", "parameters", ".", "These", "parameters", "satisfy", "the", "rendering", "algorithm", "defined", "in", "the", "vertex", "and", "pixel", "programs", "." ]
public class Material { public const string root = "material"; public const string id = "id"; public const string name = "name"; string _id; public string ID { get { return _id; } } string _name; public string Name { get { return _name; } } public Instance_Effect _instanceEffect; public Material(string id, string name, Instance_Effect instanceEffect) { _id = id; _name = name; _instanceEffect = instanceEffect; } public Material(XPathNodeIterator iterator, string uri) { XPathNodeIterator attributeIterator; attributeIterator = iterator.Current.Select("@" + XmlCollada.Material.id); if (attributeIterator.Count > 0) { attributeIterator.MoveNext(); _id = attributeIterator.Current.Value; } attributeIterator = iterator.Current.Select("@" + XmlCollada.Material.name); if (attributeIterator.Count > 0) { attributeIterator.MoveNext(); _name = attributeIterator.Current.Value; } XPathNodeIterator instanceEffectNodesIterator = iterator.Current.SelectChildren(XmlCollada.Instance_Effect.root, uri); if (instanceEffectNodesIterator.Count > 0) { instanceEffectNodesIterator.MoveNext(); _instanceEffect = new Instance_Effect(instanceEffectNodesIterator, uri); } } public void Save(XmlTextWriter writer) { writer.WriteStartElement(root); if (_id != null) { writer.WriteAttributeString(id, _id); } if (_name != null) { writer.WriteAttributeString(name, _name); } if (null != _instanceEffect) { _instanceEffect.Save(writer); } writer.WriteEndElement(); } }
[ "public", "class", "Material", "{", "public", "const", "string", "root", "=", "\"", "material", "\"", ";", "public", "const", "string", "id", "=", "\"", "id", "\"", ";", "public", "const", "string", "name", "=", "\"", "name", "\"", ";", "string", "_id", ";", "public", "string", "ID", "{", "get", "{", "return", "_id", ";", "}", "}", "string", "_name", ";", "public", "string", "Name", "{", "get", "{", "return", "_name", ";", "}", "}", "public", "Instance_Effect", "_instanceEffect", ";", "public", "Material", "(", "string", "id", ",", "string", "name", ",", "Instance_Effect", "instanceEffect", ")", "{", "_id", "=", "id", ";", "_name", "=", "name", ";", "_instanceEffect", "=", "instanceEffect", ";", "}", "public", "Material", "(", "XPathNodeIterator", "iterator", ",", "string", "uri", ")", "{", "XPathNodeIterator", "attributeIterator", ";", "attributeIterator", "=", "iterator", ".", "Current", ".", "Select", "(", "\"", "@", "\"", "+", "XmlCollada", ".", "Material", ".", "id", ")", ";", "if", "(", "attributeIterator", ".", "Count", ">", "0", ")", "{", "attributeIterator", ".", "MoveNext", "(", ")", ";", "_id", "=", "attributeIterator", ".", "Current", ".", "Value", ";", "}", "attributeIterator", "=", "iterator", ".", "Current", ".", "Select", "(", "\"", "@", "\"", "+", "XmlCollada", ".", "Material", ".", "name", ")", ";", "if", "(", "attributeIterator", ".", "Count", ">", "0", ")", "{", "attributeIterator", ".", "MoveNext", "(", ")", ";", "_name", "=", "attributeIterator", ".", "Current", ".", "Value", ";", "}", "XPathNodeIterator", "instanceEffectNodesIterator", "=", "iterator", ".", "Current", ".", "SelectChildren", "(", "XmlCollada", ".", "Instance_Effect", ".", "root", ",", "uri", ")", ";", "if", "(", "instanceEffectNodesIterator", ".", "Count", ">", "0", ")", "{", "instanceEffectNodesIterator", ".", "MoveNext", "(", ")", ";", "_instanceEffect", "=", "new", "Instance_Effect", "(", "instanceEffectNodesIterator", ",", "uri", ")", ";", "}", "}", "public", "void", "Save", "(", "XmlTextWriter", "writer", ")", "{", "writer", ".", "WriteStartElement", "(", "root", ")", ";", "if", "(", "_id", "!=", "null", ")", "{", "writer", ".", "WriteAttributeString", "(", "id", ",", "_id", ")", ";", "}", "if", "(", "_name", "!=", "null", ")", "{", "writer", ".", "WriteAttributeString", "(", "name", ",", "_name", ")", ";", "}", "if", "(", "null", "!=", "_instanceEffect", ")", "{", "_instanceEffect", ".", "Save", "(", "writer", ")", ";", "}", "writer", ".", "WriteEndElement", "(", ")", ";", "}", "}" ]
A material instantiates an effect, fills its parameters with values, and selects a technique.
[ "A", "material", "instantiates", "an", "effect", "fills", "its", "parameters", "with", "values", "and", "selects", "a", "technique", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
13
371
213
846372b0584363e1a68ba7f507db48ad3d8c1357
sfdc-acs/xacml-3.0
xacml-pdp/src/main/java/com/att/research/xacmlatt/pdp/std/functions/FunctionDefinitionRFC822NameMatch.java
[ "MIT" ]
Java
FunctionDefinitionRFC822NameMatch
/** * FunctionDefinitionRFC822NameMatch extends {@link com.att.research.xacmlatt.pdp.std.functions.FunctionDefinitionHomogeneousSimple} to * implement the XACML RFC822Name match predicate as functions taking one <code>String</code> and one <code>RFC822Name</code> arguments * and returning a single <code>Boolean</code> value. * * In the first implementation of XACML we had separate files for each XACML Function. * This release combines multiple Functions in fewer files to minimize code duplication. * This file supports the following XACML codes: * rfc822Name-match * * @author glenngriffin * @version $Revision: 1.1 $ * */
FunctionDefinitionRFC822NameMatch extends com.att.research.xacmlatt.pdp.std.functions.FunctionDefinitionHomogeneousSimple to implement the XACML RFC822Name match predicate as functions taking one String and one RFC822Name arguments and returning a single Boolean value. In the first implementation of XACML we had separate files for each XACML Function. This release combines multiple Functions in fewer files to minimize code duplication. This file supports the following XACML codes: rfc822Name-match @author glenngriffin @version $Revision: 1.1 $
[ "FunctionDefinitionRFC822NameMatch", "extends", "com", ".", "att", ".", "research", ".", "xacmlatt", ".", "pdp", ".", "std", ".", "functions", ".", "FunctionDefinitionHomogeneousSimple", "to", "implement", "the", "XACML", "RFC822Name", "match", "predicate", "as", "functions", "taking", "one", "String", "and", "one", "RFC822Name", "arguments", "and", "returning", "a", "single", "Boolean", "value", ".", "In", "the", "first", "implementation", "of", "XACML", "we", "had", "separate", "files", "for", "each", "XACML", "Function", ".", "This", "release", "combines", "multiple", "Functions", "in", "fewer", "files", "to", "minimize", "code", "duplication", ".", "This", "file", "supports", "the", "following", "XACML", "codes", ":", "rfc822Name", "-", "match", "@author", "glenngriffin", "@version", "$Revision", ":", "1", ".", "1", "$" ]
public class FunctionDefinitionRFC822NameMatch extends FunctionDefinitionBase<Boolean, RFC822Name> { /** * Constructor * * @param idIn Identifier */ public FunctionDefinitionRFC822NameMatch(Identifier idIn) { super(idIn, DataTypes.DT_BOOLEAN, DataTypes.DT_RFC822NAME, false); } @Override public ExpressionResult evaluate(EvaluationContext evaluationContext, List<FunctionArgument> arguments) { if (arguments == null || arguments.size() != 2) { return ExpressionResult.newError(new StdStatus(StdStatusCode.STATUS_CODE_PROCESSING_ERROR, getShortFunctionId() + " Expected 2 arguments, got " + ((arguments == null) ? "null" : arguments.size()) )); } // get the string to search for ConvertedArgument<String> stringArgument = new ConvertedArgument<>(arguments.get(0), DataTypes.DT_STRING, false); if ( ! stringArgument.isOk()) { Status decoratedStatus = new StdStatus(stringArgument.getStatus().getStatusCode(), stringArgument.getStatus().getStatusMessage() + " at arg index 0" ); return ExpressionResult.newError(getFunctionStatus(decoratedStatus)); } String searchTermString = stringArgument.getValue(); // get the RFC822Name to match with ConvertedArgument<RFC822Name> rfc822Argument = new ConvertedArgument<>(arguments.get(1), DataTypes.DT_RFC822NAME, false); if ( ! rfc822Argument.isOk()) { Status decoratedStatus = new StdStatus(rfc822Argument.getStatus().getStatusCode(), rfc822Argument.getStatus().getStatusMessage() + " at arg index 1" ); return ExpressionResult.newError(getFunctionStatus(decoratedStatus)); } RFC822Name rfc822Name = rfc822Argument.getValue(); /* * Now perform the match. */ /* * According to the spec the string must be one of the following 3 things: * - a name with an '@' in it = a full name that must exactly match the whole RFC name (domain part is ignore case) * - a domain name (without an '@' and not starting with a '.') = must match whole RFC domain name (ignore case) * - a partial domain name (without an '@') starting with a '.' = the last part of the RFC domain name (ignore case) */ String[] searchTerms = searchTermString.split("@"); if (searchTerms.length > 2) { return ExpressionResult.newError(new StdStatus(StdStatusCode.STATUS_CODE_PROCESSING_ERROR, getShortFunctionId() + " String contained more than 1 '@' in '" + searchTermString + "'" )); } if (searchTerms.length == 2 || searchTermString.endsWith("@")) { // this is an exact match if (searchTerms[0] == null || searchTerms[0].length() == 0) { return ExpressionResult.newError(new StdStatus(StdStatusCode.STATUS_CODE_PROCESSING_ERROR, getShortFunctionId() + " String missing local part in '" + searchTermString + "'" )); } if (searchTerms.length < 2 || searchTerms[1] == null || searchTerms[1].length() == 0) { return ExpressionResult.newError(new StdStatus(StdStatusCode.STATUS_CODE_PROCESSING_ERROR, getShortFunctionId() + " String missing domain part in '" + searchTermString + "'" )); } // args are ok, so check both against RFC name if (searchTerms[0].equals(rfc822Name.getLocalName()) && searchTerms[1].equalsIgnoreCase(rfc822Name.getCanonicalDomainName())) { return ER_TRUE; } else { return ER_FALSE; } } // we have only a domain name, which may be whole or partial // make it match the canonical version searchTerms[0] = searchTerms[0].toLowerCase(); if (searchTerms[0].charAt(0) == '.') { // name is partial - must match the end if (rfc822Name.getCanonicalDomainName().endsWith(searchTerms[0])) { return ER_TRUE; } else { return ER_FALSE; } } else { // name is whole domain - must match exactly if (rfc822Name.getCanonicalDomainName().equals(searchTerms[0])) { return ER_TRUE; } else { return ER_FALSE; } } } }
[ "public", "class", "FunctionDefinitionRFC822NameMatch", "extends", "FunctionDefinitionBase", "<", "Boolean", ",", "RFC822Name", ">", "{", "/**\r\n\t * Constructor\r\n\t * \r\n\t * @param idIn Identifier\r\n\t */", "public", "FunctionDefinitionRFC822NameMatch", "(", "Identifier", "idIn", ")", "{", "super", "(", "idIn", ",", "DataTypes", ".", "DT_BOOLEAN", ",", "DataTypes", ".", "DT_RFC822NAME", ",", "false", ")", ";", "}", "@", "Override", "public", "ExpressionResult", "evaluate", "(", "EvaluationContext", "evaluationContext", ",", "List", "<", "FunctionArgument", ">", "arguments", ")", "{", "if", "(", "arguments", "==", "null", "||", "arguments", ".", "size", "(", ")", "!=", "2", ")", "{", "return", "ExpressionResult", ".", "newError", "(", "new", "StdStatus", "(", "StdStatusCode", ".", "STATUS_CODE_PROCESSING_ERROR", ",", "getShortFunctionId", "(", ")", "+", "\"", " Expected 2 arguments, got ", "\"", "+", "(", "(", "arguments", "==", "null", ")", "?", "\"", "null", "\"", ":", "arguments", ".", "size", "(", ")", ")", ")", ")", ";", "}", "ConvertedArgument", "<", "String", ">", "stringArgument", "=", "new", "ConvertedArgument", "<", ">", "(", "arguments", ".", "get", "(", "0", ")", ",", "DataTypes", ".", "DT_STRING", ",", "false", ")", ";", "if", "(", "!", "stringArgument", ".", "isOk", "(", ")", ")", "{", "Status", "decoratedStatus", "=", "new", "StdStatus", "(", "stringArgument", ".", "getStatus", "(", ")", ".", "getStatusCode", "(", ")", ",", "stringArgument", ".", "getStatus", "(", ")", ".", "getStatusMessage", "(", ")", "+", "\"", " at arg index 0", "\"", ")", ";", "return", "ExpressionResult", ".", "newError", "(", "getFunctionStatus", "(", "decoratedStatus", ")", ")", ";", "}", "String", "searchTermString", "=", "stringArgument", ".", "getValue", "(", ")", ";", "ConvertedArgument", "<", "RFC822Name", ">", "rfc822Argument", "=", "new", "ConvertedArgument", "<", ">", "(", "arguments", ".", "get", "(", "1", ")", ",", "DataTypes", ".", "DT_RFC822NAME", ",", "false", ")", ";", "if", "(", "!", "rfc822Argument", ".", "isOk", "(", ")", ")", "{", "Status", "decoratedStatus", "=", "new", "StdStatus", "(", "rfc822Argument", ".", "getStatus", "(", ")", ".", "getStatusCode", "(", ")", ",", "rfc822Argument", ".", "getStatus", "(", ")", ".", "getStatusMessage", "(", ")", "+", "\"", " at arg index 1", "\"", ")", ";", "return", "ExpressionResult", ".", "newError", "(", "getFunctionStatus", "(", "decoratedStatus", ")", ")", ";", "}", "RFC822Name", "rfc822Name", "=", "rfc822Argument", ".", "getValue", "(", ")", ";", "/*\r\n\t\t * Now perform the match.\r\n\t\t */", "/*\r\n\t\t * According to the spec the string must be one of the following 3 things:\r\n\t\t * \t- a name with an '@' in it = a full name that must exactly match the whole RFC name (domain part is ignore case)\r\n\t\t * \t- a domain name (without an '@' and not starting with a '.') = must match whole RFC domain name (ignore case)\r\n\t\t * \t- a partial domain name (without an '@') starting with a '.' = the last part of the RFC domain name (ignore case)\r\n\t\t */", "String", "[", "]", "searchTerms", "=", "searchTermString", ".", "split", "(", "\"", "@", "\"", ")", ";", "if", "(", "searchTerms", ".", "length", ">", "2", ")", "{", "return", "ExpressionResult", ".", "newError", "(", "new", "StdStatus", "(", "StdStatusCode", ".", "STATUS_CODE_PROCESSING_ERROR", ",", "getShortFunctionId", "(", ")", "+", "\"", " String contained more than 1 '@' in '", "\"", "+", "searchTermString", "+", "\"", "'", "\"", ")", ")", ";", "}", "if", "(", "searchTerms", ".", "length", "==", "2", "||", "searchTermString", ".", "endsWith", "(", "\"", "@", "\"", ")", ")", "{", "if", "(", "searchTerms", "[", "0", "]", "==", "null", "||", "searchTerms", "[", "0", "]", ".", "length", "(", ")", "==", "0", ")", "{", "return", "ExpressionResult", ".", "newError", "(", "new", "StdStatus", "(", "StdStatusCode", ".", "STATUS_CODE_PROCESSING_ERROR", ",", "getShortFunctionId", "(", ")", "+", "\"", " String missing local part in '", "\"", "+", "searchTermString", "+", "\"", "'", "\"", ")", ")", ";", "}", "if", "(", "searchTerms", ".", "length", "<", "2", "||", "searchTerms", "[", "1", "]", "==", "null", "||", "searchTerms", "[", "1", "]", ".", "length", "(", ")", "==", "0", ")", "{", "return", "ExpressionResult", ".", "newError", "(", "new", "StdStatus", "(", "StdStatusCode", ".", "STATUS_CODE_PROCESSING_ERROR", ",", "getShortFunctionId", "(", ")", "+", "\"", " String missing domain part in '", "\"", "+", "searchTermString", "+", "\"", "'", "\"", ")", ")", ";", "}", "if", "(", "searchTerms", "[", "0", "]", ".", "equals", "(", "rfc822Name", ".", "getLocalName", "(", ")", ")", "&&", "searchTerms", "[", "1", "]", ".", "equalsIgnoreCase", "(", "rfc822Name", ".", "getCanonicalDomainName", "(", ")", ")", ")", "{", "return", "ER_TRUE", ";", "}", "else", "{", "return", "ER_FALSE", ";", "}", "}", "searchTerms", "[", "0", "]", "=", "searchTerms", "[", "0", "]", ".", "toLowerCase", "(", ")", ";", "if", "(", "searchTerms", "[", "0", "]", ".", "charAt", "(", "0", ")", "==", "'.'", ")", "{", "if", "(", "rfc822Name", ".", "getCanonicalDomainName", "(", ")", ".", "endsWith", "(", "searchTerms", "[", "0", "]", ")", ")", "{", "return", "ER_TRUE", ";", "}", "else", "{", "return", "ER_FALSE", ";", "}", "}", "else", "{", "if", "(", "rfc822Name", ".", "getCanonicalDomainName", "(", ")", ".", "equals", "(", "searchTerms", "[", "0", "]", ")", ")", "{", "return", "ER_TRUE", ";", "}", "else", "{", "return", "ER_FALSE", ";", "}", "}", "}", "}" ]
FunctionDefinitionRFC822NameMatch extends {@link com.att.research.xacmlatt.pdp.std.functions.FunctionDefinitionHomogeneousSimple} to implement the XACML RFC822Name match predicate as functions taking one <code>String</code> and one <code>RFC822Name</code> arguments and returning a single <code>Boolean</code> value.
[ "FunctionDefinitionRFC822NameMatch", "extends", "{", "@link", "com", ".", "att", ".", "research", ".", "xacmlatt", ".", "pdp", ".", "std", ".", "functions", ".", "FunctionDefinitionHomogeneousSimple", "}", "to", "implement", "the", "XACML", "RFC822Name", "match", "predicate", "as", "functions", "taking", "one", "<code", ">", "String<", "/", "code", ">", "and", "one", "<code", ">", "RFC822Name<", "/", "code", ">", "arguments", "and", "returning", "a", "single", "<code", ">", "Boolean<", "/", "code", ">", "value", "." ]
[ "// get the string to search for\r", "// get the RFC822Name to match with\r", "// this is an exact match\r", "// args are ok, so check both against RFC name\r", "// we have only a domain name, which may be whole or partial\r", "// make it match the canonical version\r", "// name is partial - must match the end\r", "// name is whole domain - must match exactly\r" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
19
1,032
167