repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
josdem/client
client-view/src/main/java/com/all/client/view/dnd/ModelTreeTransferHandler.java
13535
/** * Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2011 Eric Haddad Koenig 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. */ package com.all.client.view.dnd; import java.awt.datatransfer.Transferable; import java.util.ArrayList; import javax.swing.JComponent; import javax.swing.JTree; import javax.swing.TransferHandler; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.TreePath; import com.all.appControl.control.ViewEngine; import com.all.client.model.ModelTransfereable; import com.all.core.model.Model; import com.all.shared.model.ModelCollection; import com.all.shared.model.ModelSource; public class ModelTreeTransferHandler extends TransferHandler { private static final long serialVersionUID = 1L; private final JTree tree; private final boolean remoteSource; private final ViewEngine viewEngine; public ModelTreeTransferHandler(JTree tree, boolean remoteSource, ViewEngine viewEngine) { this.tree = tree; this.remoteSource = remoteSource; this.viewEngine = viewEngine; } @Override public Transferable createTransferable(JComponent c) { java.util.List<Object> selection = new ArrayList<Object>(); for (TreePath path : tree.getSelectionPaths()) { Object model = ((DefaultMutableTreeNode) path.getLastPathComponent()).getUserObject(); selection.add(model); } ModelCollection modelCollection = new ModelCollection(selection); modelCollection.cleanUp(); if (remoteSource) { modelCollection.setRemote(true); } if (modelCollection.isEmpty()) { return null; } else { return new ModelTransfereable(remoteSource ? ModelSource.remote() : ModelSource.local(), modelCollection, viewEngine.get(Model.TRACK_REPOSITORY)); } } @Override public boolean canImport(TransferSupport support) { return false; } @Override public void exportDone(JComponent source, Transferable data, int action) { } @Override public boolean importData(TransferSupport support) { return true; } public int getSourceActions(JComponent c) { return COPY; } }
apache-2.0
twcook/siscolo
src/generator/ccd_19e452e8_8e2d_46ba_a88c_2afd34ca8d71.py
41849
# -*- coding: UTF-8 -*- import datetime import shortuuid from randomstuff import upper_bool, lower_bool def ccd_19e452e8_8e2d_46ba_a88c_2afd34ca8d71(recno,dobstr,agestr,examdate): examdatestr = str(examdate.strftime('%Y-%m-%d')) fname = 'data/'+recno+'/'+shortuuid.uuid()+'.xml' f = open(fname,'w') fstr=("""<?xml version="1.0" encoding="UTF-8"?> <mlhim243:ccd-19e452e8-8e2d-46ba-a88c-2afd34ca8d71 xmlns:mlhim243="http://www.mlhim.org/xmlns/mlhim2/2_4_3" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:owl="http://www.w3.org/2002/07/owl#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:sawsdl="http://www.w3.org/ns/sawsdl" xmlns:sawsdlrdf="http://www.w3.org/ns/sawsdl#" xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.mlhim.org/xmlns/mlhim2/2_4_3 ccd-19e452e8-8e2d-46ba-a88c-2afd34ca8d71.xsd"> <mlhim243:el-9de3b321-08e0-447f-abae-49b64c9e3583> <mlhim243:entry-links> <mlhim243:data-name>AghDym9CP4KeH8_HU</mlhim243:data-name> <mlhim243:valid-time-begin>2014-09-13T21:23:43</mlhim243:valid-time-begin> <mlhim243:valid-time-end>2015-05-10T21:23:43Z</mlhim243:valid-time-end> <mlhim243:DvURI-dv>http://qBSFLtEJ/</mlhim243:DvURI-dv> <mlhim243:relation>hyDpYK.5qw</mlhim243:relation> </mlhim243:entry-links> <mlhim243:entry-audit> <mlhim243:originating-system-audit> <mlhim243:system-id> <mlhim243:data-name>SaOs</mlhim243:data-name> <mlhim243:valid-time-begin>2014-09-07T21:23:43</mlhim243:valid-time-begin> <mlhim243:valid-time-end>2015-08-31T21:23:43Z</mlhim243:valid-time-end> <mlhim243:DvString-dv>r-7DKrPHwUzU</mlhim243:DvString-dv> <mlhim243:language>de-DE</mlhim243:language> <mlhim243:id-name>AL_5neTl9y</mlhim243:id-name> <mlhim243:issuer>Fw</mlhim243:issuer> <mlhim243:assignor>ChIwNTropwjXxNVZj-</mlhim243:assignor> </mlhim243:system-id> <mlhim243:provider> <mlhim243:party-name>mMW1</mlhim243:party-name> <mlhim243:external-ref> <mlhim243:data-name>kzbG_WxyQI</mlhim243:data-name> <mlhim243:DvURI-dv>http://aVcSDRsk/</mlhim243:DvURI-dv> <mlhim243:relation>d4C4f-zC</mlhim243:relation> </mlhim243:external-ref> <mlhim243:el-c4665b57-b737-4eef-b1a4-46ecd2298121> <mlhim243:cluster-subject>PartyIdentified Details (BR)</mlhim243:cluster-subject> <mlhim243:el-7117e7ac-d879-4f8b-8719-2892050409e3> <mlhim243:el-cc5c08c4-4426-4a68-a59a-b7bef285624d> <mlhim243:data-name>Bairro</mlhim243:data-name> <mlhim243:DvString-dv>ueO</mlhim243:DvString-dv> </mlhim243:el-cc5c08c4-4426-4a68-a59a-b7bef285624d> </mlhim243:el-7117e7ac-d879-4f8b-8719-2892050409e3> <mlhim243:el-96017054-3fdb-4819-af9b-892d386c132c> <mlhim243:el-f487863a-773e-4f5a-9cc8-a66802d0589f> <mlhim243:data-name>Código Postal (Brazil)</mlhim243:data-name> <mlhim243:DvString-dv>21050-060</mlhim243:DvString-dv> </mlhim243:el-f487863a-773e-4f5a-9cc8-a66802d0589f> </mlhim243:el-96017054-3fdb-4819-af9b-892d386c132c> <mlhim243:el-43850c7b-d3bf-4888-957b-d00cc97674ab> <mlhim243:el-9cc073cf-1640-45cb-a595-4ac1992e6727> <mlhim243:data-name>Endereço da Rua</mlhim243:data-name> <mlhim243:DvString-dv>g6eS7</mlhim243:DvString-dv> </mlhim243:el-9cc073cf-1640-45cb-a595-4ac1992e6727> </mlhim243:el-43850c7b-d3bf-4888-957b-d00cc97674ab> <mlhim243:el-8cc87b41-f721-4792-879b-fb07dd9f918c> <mlhim243:el-5dd3d0ce-b97f-48ee-925b-05f4cf0a2cb2> <mlhim243:data-name>Estados Brasileiros (UF) e o distrito Federal</mlhim243:data-name> <mlhim243:DvString-dv>RN</mlhim243:DvString-dv> </mlhim243:el-5dd3d0ce-b97f-48ee-925b-05f4cf0a2cb2> </mlhim243:el-8cc87b41-f721-4792-879b-fb07dd9f918c> <mlhim243:el-e5afc39d-57ba-47eb-ad1d-4d5751d4de3d> <mlhim243:el-28b5de47-4bc5-4f80-9eba-240608986e95> <mlhim243:data-name>Município</mlhim243:data-name> <mlhim243:DvString-dv>IsHDhLAs9jlMYz2IDUN2K1WpFQ</mlhim243:DvString-dv> </mlhim243:el-28b5de47-4bc5-4f80-9eba-240608986e95> </mlhim243:el-e5afc39d-57ba-47eb-ad1d-4d5751d4de3d> <mlhim243:el-31ce977b-35d0-40a7-977a-2015460a627c> <mlhim243:el-6843bb68-d5e3-4eca-96c2-ffedb5f7f936> <mlhim243:data-name>Nome</mlhim243:data-name> <mlhim243:DvString-dv>x4K5fFvbnLJvhSpSFd2JJxZbi6DY</mlhim243:DvString-dv> </mlhim243:el-6843bb68-d5e3-4eca-96c2-ffedb5f7f936> </mlhim243:el-31ce977b-35d0-40a7-977a-2015460a627c> <mlhim243:el-7d2791b9-bfb4-404f-8dc9-34f3f5a59be2> <mlhim243:el-24264eba-781a-4ab7-b08b-d1f227b9c1a5> <mlhim243:data-name>Telefone (BR)</mlhim243:data-name> <mlhim243:DvString-dv>9988-0066</mlhim243:DvString-dv> </mlhim243:el-24264eba-781a-4ab7-b08b-d1f227b9c1a5> </mlhim243:el-7d2791b9-bfb4-404f-8dc9-34f3f5a59be2> </mlhim243:el-c4665b57-b737-4eef-b1a4-46ecd2298121> </mlhim243:provider> <mlhim243:location xsi:type="mlhim243:ct-bb5cb04c-c94d-4b2b-b6fe-c883763d8993"> <mlhim243:el-a81b03aa-4a99-40aa-abaf-d917e9e95d2f> <mlhim243:data-name>UF</mlhim243:data-name> <mlhim243:DvString-dv>SC</mlhim243:DvString-dv> </mlhim243:el-a81b03aa-4a99-40aa-abaf-d917e9e95d2f> </mlhim243:location> <mlhim243:timestamp>2015-07-20T21:23:43Z</mlhim243:timestamp> <mlhim243:subject xsi:type="mlhim243:PartySelfType"> <mlhim243:party-name>Self</mlhim243:party-name> </mlhim243:subject> <mlhim243:version-id>e6</mlhim243:version-id> </mlhim243:originating-system-audit> <mlhim243:originating-system-ids> <mlhim243:data-name>aym9sYahcin9hM2CP</mlhim243:data-name> <mlhim243:valid-time-begin>2014-01-31T21:23:43</mlhim243:valid-time-begin> <mlhim243:valid-time-end>2014-11-29T21:23:43</mlhim243:valid-time-end> <mlhim243:DvString-dv>SB</mlhim243:DvString-dv> <mlhim243:language>nl-NL</mlhim243:language> <mlhim243:id-name>PWIf__I</mlhim243:id-name> <mlhim243:issuer>ubZK0LxedfajWOyz3TI</mlhim243:issuer> <mlhim243:assignor>CWRuXebnAX2UTet_u0oojtWEnTsHY</mlhim243:assignor> </mlhim243:originating-system-ids> <mlhim243:originating-system-ids> <mlhim243:data-name>RKZqyYXT</mlhim243:data-name> <mlhim243:valid-time-begin>2015-08-15T21:23:43</mlhim243:valid-time-begin> <mlhim243:valid-time-end>2014-12-10T21:23:43</mlhim243:valid-time-end> <mlhim243:DvString-dv>WRH8</mlhim243:DvString-dv> <mlhim243:language>da-DK</mlhim243:language> <mlhim243:id-name>oRhE9FsS</mlhim243:id-name> <mlhim243:issuer>cC9</mlhim243:issuer> <mlhim243:assignor>Ay8TTJIsiP2P69.dd</mlhim243:assignor> </mlhim243:originating-system-ids> <mlhim243:feeder-system-audit> <mlhim243:system-id> <mlhim243:data-name>VRaeObCrwifCweQtAYlCMkh1FIw2</mlhim243:data-name> <mlhim243:valid-time-begin>2015-04-28T21:23:43Z</mlhim243:valid-time-begin> <mlhim243:valid-time-end>2015-08-16T21:23:43</mlhim243:valid-time-end> <mlhim243:DvString-dv>uWMV</mlhim243:DvString-dv> <mlhim243:language>ar-EG</mlhim243:language> <mlhim243:id-name>gTS</mlhim243:id-name> <mlhim243:issuer>McSSKa5DaAeWfVCT</mlhim243:issuer> <mlhim243:assignor>n7mv72Wc</mlhim243:assignor> </mlhim243:system-id> <mlhim243:provider> <mlhim243:party-name>W</mlhim243:party-name> <mlhim243:external-ref> <mlhim243:data-name>SyCVBUnw2egfCyibGGi</mlhim243:data-name> <mlhim243:DvURI-dv>http://pFRLJLzI/</mlhim243:DvURI-dv> <mlhim243:relation>BF2QJ</mlhim243:relation> </mlhim243:external-ref> <mlhim243:el-c4665b57-b737-4eef-b1a4-46ecd2298121> <mlhim243:cluster-subject>PartyIdentified Details (BR)</mlhim243:cluster-subject> <mlhim243:el-7117e7ac-d879-4f8b-8719-2892050409e3> <mlhim243:el-cc5c08c4-4426-4a68-a59a-b7bef285624d> <mlhim243:data-name>Bairro</mlhim243:data-name> <mlhim243:DvString-dv>BySigProy9ITatCA_VmH8Q3_km8MXw</mlhim243:DvString-dv> </mlhim243:el-cc5c08c4-4426-4a68-a59a-b7bef285624d> </mlhim243:el-7117e7ac-d879-4f8b-8719-2892050409e3> <mlhim243:el-96017054-3fdb-4819-af9b-892d386c132c> <mlhim243:el-f487863a-773e-4f5a-9cc8-a66802d0589f> <mlhim243:data-name>Código Postal (Brazil)</mlhim243:data-name> <mlhim243:DvString-dv>21050-060</mlhim243:DvString-dv> </mlhim243:el-f487863a-773e-4f5a-9cc8-a66802d0589f> </mlhim243:el-96017054-3fdb-4819-af9b-892d386c132c> <mlhim243:el-43850c7b-d3bf-4888-957b-d00cc97674ab> <mlhim243:el-9cc073cf-1640-45cb-a595-4ac1992e6727> <mlhim243:data-name>Endereço da Rua</mlhim243:data-name> <mlhim243:DvString-dv>VmOjkcQHNDeiYX6</mlhim243:DvString-dv> </mlhim243:el-9cc073cf-1640-45cb-a595-4ac1992e6727> </mlhim243:el-43850c7b-d3bf-4888-957b-d00cc97674ab> <mlhim243:el-8cc87b41-f721-4792-879b-fb07dd9f918c> <mlhim243:el-5dd3d0ce-b97f-48ee-925b-05f4cf0a2cb2> <mlhim243:data-name>Estados Brasileiros (UF) e o distrito Federal</mlhim243:data-name> <mlhim243:DvString-dv>TO</mlhim243:DvString-dv> </mlhim243:el-5dd3d0ce-b97f-48ee-925b-05f4cf0a2cb2> </mlhim243:el-8cc87b41-f721-4792-879b-fb07dd9f918c> <mlhim243:el-e5afc39d-57ba-47eb-ad1d-4d5751d4de3d> <mlhim243:el-28b5de47-4bc5-4f80-9eba-240608986e95> <mlhim243:data-name>Município</mlhim243:data-name> <mlhim243:DvString-dv>MskgRB3xG</mlhim243:DvString-dv> </mlhim243:el-28b5de47-4bc5-4f80-9eba-240608986e95> </mlhim243:el-e5afc39d-57ba-47eb-ad1d-4d5751d4de3d> <mlhim243:el-31ce977b-35d0-40a7-977a-2015460a627c> <mlhim243:el-6843bb68-d5e3-4eca-96c2-ffedb5f7f936> <mlhim243:data-name>Nome</mlhim243:data-name> <mlhim243:DvString-dv>SL.PHOmmYi2TdV1H86I</mlhim243:DvString-dv> </mlhim243:el-6843bb68-d5e3-4eca-96c2-ffedb5f7f936> </mlhim243:el-31ce977b-35d0-40a7-977a-2015460a627c> <mlhim243:el-7d2791b9-bfb4-404f-8dc9-34f3f5a59be2> <mlhim243:el-24264eba-781a-4ab7-b08b-d1f227b9c1a5> <mlhim243:data-name>Telefone (BR)</mlhim243:data-name> <mlhim243:DvString-dv>9988-0066</mlhim243:DvString-dv> </mlhim243:el-24264eba-781a-4ab7-b08b-d1f227b9c1a5> </mlhim243:el-7d2791b9-bfb4-404f-8dc9-34f3f5a59be2> </mlhim243:el-c4665b57-b737-4eef-b1a4-46ecd2298121> </mlhim243:provider> <mlhim243:location xsi:type="mlhim243:ct-d78c40bb-1b31-4713-9ed7-d9ea1906e8ac"> <mlhim243:el-83ac12f7-1aab-42f7-a1ed-96459631bcbc> <mlhim243:data-name>CNES</mlhim243:data-name> <mlhim243:DvString-dv>J64fKC3Q</mlhim243:DvString-dv> </mlhim243:el-83ac12f7-1aab-42f7-a1ed-96459631bcbc> </mlhim243:location> <mlhim243:timestamp>2014-09-11T21:23:43Z</mlhim243:timestamp> <mlhim243:subject xsi:type="mlhim243:ct-83fc62c8-8df8-472a-b590-d8ecea82d695"> <mlhim243:party-name>LL78vE0yAJDjEo2Mp</mlhim243:party-name> <mlhim243:el-4c8a56b0-c452-4b78-a861-1f2a47163693> <mlhim243:data-name>External Reference for PartyIdentified</mlhim243:data-name> <mlhim243:DvURI-dv>http://cSZHWqay/</mlhim243:DvURI-dv> <mlhim243:relation>Party Associated with the record</mlhim243:relation> </mlhim243:el-4c8a56b0-c452-4b78-a861-1f2a47163693> <mlhim243:el-c4665b57-b737-4eef-b1a4-46ecd2298121> <mlhim243:cluster-subject>PartyIdentified Details (BR)</mlhim243:cluster-subject> <mlhim243:el-7117e7ac-d879-4f8b-8719-2892050409e3> <mlhim243:el-cc5c08c4-4426-4a68-a59a-b7bef285624d> <mlhim243:data-name>Bairro</mlhim243:data-name> <mlhim243:DvString-dv>Uj7Xb3q</mlhim243:DvString-dv> </mlhim243:el-cc5c08c4-4426-4a68-a59a-b7bef285624d> </mlhim243:el-7117e7ac-d879-4f8b-8719-2892050409e3> <mlhim243:el-96017054-3fdb-4819-af9b-892d386c132c> <mlhim243:el-f487863a-773e-4f5a-9cc8-a66802d0589f> <mlhim243:data-name>Código Postal (Brazil)</mlhim243:data-name> <mlhim243:DvString-dv>21050-060</mlhim243:DvString-dv> </mlhim243:el-f487863a-773e-4f5a-9cc8-a66802d0589f> </mlhim243:el-96017054-3fdb-4819-af9b-892d386c132c> <mlhim243:el-43850c7b-d3bf-4888-957b-d00cc97674ab> <mlhim243:el-9cc073cf-1640-45cb-a595-4ac1992e6727> <mlhim243:data-name>Endereço da Rua</mlhim243:data-name> <mlhim243:DvString-dv>xRSNUqN-BRLwX_ZmThKzd7D</mlhim243:DvString-dv> </mlhim243:el-9cc073cf-1640-45cb-a595-4ac1992e6727> </mlhim243:el-43850c7b-d3bf-4888-957b-d00cc97674ab> <mlhim243:el-8cc87b41-f721-4792-879b-fb07dd9f918c> <mlhim243:el-5dd3d0ce-b97f-48ee-925b-05f4cf0a2cb2> <mlhim243:data-name>Estados Brasileiros (UF) e o distrito Federal</mlhim243:data-name> <mlhim243:DvString-dv>TO</mlhim243:DvString-dv> </mlhim243:el-5dd3d0ce-b97f-48ee-925b-05f4cf0a2cb2> </mlhim243:el-8cc87b41-f721-4792-879b-fb07dd9f918c> <mlhim243:el-e5afc39d-57ba-47eb-ad1d-4d5751d4de3d> <mlhim243:el-28b5de47-4bc5-4f80-9eba-240608986e95> <mlhim243:data-name>Município</mlhim243:data-name> <mlhim243:DvString-dv>yie4c</mlhim243:DvString-dv> </mlhim243:el-28b5de47-4bc5-4f80-9eba-240608986e95> </mlhim243:el-e5afc39d-57ba-47eb-ad1d-4d5751d4de3d> <mlhim243:el-31ce977b-35d0-40a7-977a-2015460a627c> <mlhim243:el-6843bb68-d5e3-4eca-96c2-ffedb5f7f936> <mlhim243:data-name>Nome</mlhim243:data-name> <mlhim243:DvString-dv>gKTz51</mlhim243:DvString-dv> </mlhim243:el-6843bb68-d5e3-4eca-96c2-ffedb5f7f936> </mlhim243:el-31ce977b-35d0-40a7-977a-2015460a627c> <mlhim243:el-7d2791b9-bfb4-404f-8dc9-34f3f5a59be2> <mlhim243:el-24264eba-781a-4ab7-b08b-d1f227b9c1a5> <mlhim243:data-name>Telefone (BR)</mlhim243:data-name> <mlhim243:DvString-dv>9988-0066</mlhim243:DvString-dv> </mlhim243:el-24264eba-781a-4ab7-b08b-d1f227b9c1a5> </mlhim243:el-7d2791b9-bfb4-404f-8dc9-34f3f5a59be2> </mlhim243:el-c4665b57-b737-4eef-b1a4-46ecd2298121> </mlhim243:subject> <mlhim243:version-id>SPaBqJoUVCLdVw1_zvhx</mlhim243:version-id> </mlhim243:feeder-system-audit> <mlhim243:feeder-system-ids> <mlhim243:data-name>KK</mlhim243:data-name> <mlhim243:valid-time-begin>2014-12-27T21:23:43</mlhim243:valid-time-begin> <mlhim243:valid-time-end>2015-02-11T21:23:43</mlhim243:valid-time-end> <mlhim243:DvString-dv>KbqsvvMBHej_J</mlhim243:DvString-dv> <mlhim243:language>sv-SE</mlhim243:language> <mlhim243:id-name>p1ighuWnIazfpY_oJTAuhTCppIr1</mlhim243:id-name> <mlhim243:issuer>CXzh0f4</mlhim243:issuer> <mlhim243:assignor>odL</mlhim243:assignor> </mlhim243:feeder-system-ids> <mlhim243:feeder-system-ids> <mlhim243:data-name>mGQDovW.e.JswrExdyy05FD0mh</mlhim243:data-name> <mlhim243:valid-time-begin>2014-12-11T21:23:43</mlhim243:valid-time-begin> <mlhim243:valid-time-end>2014-11-15T21:23:43</mlhim243:valid-time-end> <mlhim243:DvString-dv>J_-8h-qVHpc6NVu3T9uey09ZfFL</mlhim243:DvString-dv> <mlhim243:language>nl-NL</mlhim243:language> <mlhim243:id-name>Zb25c.ZsCAmEj2TjyKNN</mlhim243:id-name> <mlhim243:issuer>_3Fu4NypDPvJ1B8b2r-JOngKzDH</mlhim243:issuer> <mlhim243:assignor>j</mlhim243:assignor> </mlhim243:feeder-system-ids> <mlhim243:original-content> <mlhim243:data-name>AzfDC6DhZM9gYT4gsnCbCsIp2J_l</mlhim243:data-name> <mlhim243:valid-time-begin>2015-01-29T21:23:43Z</mlhim243:valid-time-begin> <mlhim243:valid-time-end>2014-01-11T21:23:43</mlhim243:valid-time-end> <mlhim243:DvURI-dv>http://PwmYwjSb/</mlhim243:DvURI-dv> <mlhim243:relation>QRbdE5.ZTu4dd8iMsN2eS</mlhim243:relation> </mlhim243:original-content> </mlhim243:entry-audit> <mlhim243:language>pt-BR</mlhim243:language> <mlhim243:encoding>utf-8</mlhim243:encoding> <mlhim243:el-83fc62c8-8df8-472a-b590-d8ecea82d695> <mlhim243:party-name>NHFQTwz3</mlhim243:party-name> <mlhim243:el-4c8a56b0-c452-4b78-a861-1f2a47163693> <mlhim243:data-name>External Reference for PartyIdentified</mlhim243:data-name> <mlhim243:valid-time-begin>2014-02-05T21:23:43</mlhim243:valid-time-begin> <mlhim243:valid-time-end>2015-10-29T21:23:43Z</mlhim243:valid-time-end> <mlhim243:DvURI-dv>http://eNtNhUwK/</mlhim243:DvURI-dv> <mlhim243:relation>Party Associated with the record</mlhim243:relation> </mlhim243:el-4c8a56b0-c452-4b78-a861-1f2a47163693> <mlhim243:el-c4665b57-b737-4eef-b1a4-46ecd2298121> <mlhim243:cluster-subject>PartyIdentified Details (BR)</mlhim243:cluster-subject> <mlhim243:el-7117e7ac-d879-4f8b-8719-2892050409e3> <mlhim243:el-cc5c08c4-4426-4a68-a59a-b7bef285624d> <mlhim243:data-name>Bairro</mlhim243:data-name> <mlhim243:DvString-dv>_ju66a62VQj6x9s3b2</mlhim243:DvString-dv> </mlhim243:el-cc5c08c4-4426-4a68-a59a-b7bef285624d> </mlhim243:el-7117e7ac-d879-4f8b-8719-2892050409e3> <mlhim243:el-96017054-3fdb-4819-af9b-892d386c132c> <mlhim243:el-f487863a-773e-4f5a-9cc8-a66802d0589f> <mlhim243:data-name>Código Postal (Brazil)</mlhim243:data-name> <mlhim243:DvString-dv>21050-060</mlhim243:DvString-dv> </mlhim243:el-f487863a-773e-4f5a-9cc8-a66802d0589f> </mlhim243:el-96017054-3fdb-4819-af9b-892d386c132c> <mlhim243:el-43850c7b-d3bf-4888-957b-d00cc97674ab> <mlhim243:el-9cc073cf-1640-45cb-a595-4ac1992e6727> <mlhim243:data-name>Endereço da Rua</mlhim243:data-name> <mlhim243:DvString-dv>VBE9rHw7HJ_fIypDc</mlhim243:DvString-dv> </mlhim243:el-9cc073cf-1640-45cb-a595-4ac1992e6727> </mlhim243:el-43850c7b-d3bf-4888-957b-d00cc97674ab> <mlhim243:el-8cc87b41-f721-4792-879b-fb07dd9f918c> <mlhim243:el-5dd3d0ce-b97f-48ee-925b-05f4cf0a2cb2> <mlhim243:data-name>Estados Brasileiros (UF) e o distrito Federal</mlhim243:data-name> <mlhim243:DvString-dv>AM</mlhim243:DvString-dv> </mlhim243:el-5dd3d0ce-b97f-48ee-925b-05f4cf0a2cb2> </mlhim243:el-8cc87b41-f721-4792-879b-fb07dd9f918c> <mlhim243:el-e5afc39d-57ba-47eb-ad1d-4d5751d4de3d> <mlhim243:el-28b5de47-4bc5-4f80-9eba-240608986e95> <mlhim243:data-name>Município</mlhim243:data-name> <mlhim243:DvString-dv>Qk8P</mlhim243:DvString-dv> </mlhim243:el-28b5de47-4bc5-4f80-9eba-240608986e95> </mlhim243:el-e5afc39d-57ba-47eb-ad1d-4d5751d4de3d> <mlhim243:el-31ce977b-35d0-40a7-977a-2015460a627c> <mlhim243:el-6843bb68-d5e3-4eca-96c2-ffedb5f7f936> <mlhim243:data-name>Nome</mlhim243:data-name> <mlhim243:DvString-dv>FU</mlhim243:DvString-dv> </mlhim243:el-6843bb68-d5e3-4eca-96c2-ffedb5f7f936> </mlhim243:el-31ce977b-35d0-40a7-977a-2015460a627c> <mlhim243:el-7d2791b9-bfb4-404f-8dc9-34f3f5a59be2> <mlhim243:el-24264eba-781a-4ab7-b08b-d1f227b9c1a5> <mlhim243:data-name>Telefone (BR)</mlhim243:data-name> <mlhim243:DvString-dv>9988-0066</mlhim243:DvString-dv> </mlhim243:el-24264eba-781a-4ab7-b08b-d1f227b9c1a5> </mlhim243:el-7d2791b9-bfb4-404f-8dc9-34f3f5a59be2> </mlhim243:el-c4665b57-b737-4eef-b1a4-46ecd2298121> </mlhim243:el-83fc62c8-8df8-472a-b590-d8ecea82d695> <mlhim243:el-83fc62c8-8df8-472a-b590-d8ecea82d695> <mlhim243:party-name>x-MwNQZBe2DIT</mlhim243:party-name> <mlhim243:el-4c8a56b0-c452-4b78-a861-1f2a47163693> <mlhim243:data-name>External Reference for PartyIdentified</mlhim243:data-name> <mlhim243:valid-time-begin>2014-04-25T21:23:43</mlhim243:valid-time-begin> <mlhim243:valid-time-end>2015-06-02T21:23:43Z</mlhim243:valid-time-end> <mlhim243:DvURI-dv>http://YYDrTWMJ/</mlhim243:DvURI-dv> <mlhim243:relation>Party Associated with the record</mlhim243:relation> </mlhim243:el-4c8a56b0-c452-4b78-a861-1f2a47163693> <mlhim243:el-c4665b57-b737-4eef-b1a4-46ecd2298121> <mlhim243:cluster-subject>PartyIdentified Details (BR)</mlhim243:cluster-subject> <mlhim243:el-7117e7ac-d879-4f8b-8719-2892050409e3> <mlhim243:el-cc5c08c4-4426-4a68-a59a-b7bef285624d> <mlhim243:data-name>Bairro</mlhim243:data-name> <mlhim243:DvString-dv>H3hfAYcVF59I5BG</mlhim243:DvString-dv> </mlhim243:el-cc5c08c4-4426-4a68-a59a-b7bef285624d> </mlhim243:el-7117e7ac-d879-4f8b-8719-2892050409e3> <mlhim243:el-96017054-3fdb-4819-af9b-892d386c132c> <mlhim243:el-f487863a-773e-4f5a-9cc8-a66802d0589f> <mlhim243:data-name>Código Postal (Brazil)</mlhim243:data-name> <mlhim243:DvString-dv>21050-060</mlhim243:DvString-dv> </mlhim243:el-f487863a-773e-4f5a-9cc8-a66802d0589f> </mlhim243:el-96017054-3fdb-4819-af9b-892d386c132c> <mlhim243:el-43850c7b-d3bf-4888-957b-d00cc97674ab> <mlhim243:el-9cc073cf-1640-45cb-a595-4ac1992e6727> <mlhim243:data-name>Endereço da Rua</mlhim243:data-name> <mlhim243:DvString-dv>S6UaGbtaM.tZ6fIYg1e0s</mlhim243:DvString-dv> </mlhim243:el-9cc073cf-1640-45cb-a595-4ac1992e6727> </mlhim243:el-43850c7b-d3bf-4888-957b-d00cc97674ab> <mlhim243:el-8cc87b41-f721-4792-879b-fb07dd9f918c> <mlhim243:el-5dd3d0ce-b97f-48ee-925b-05f4cf0a2cb2> <mlhim243:data-name>Estados Brasileiros (UF) e o distrito Federal</mlhim243:data-name> <mlhim243:DvString-dv>AP</mlhim243:DvString-dv> </mlhim243:el-5dd3d0ce-b97f-48ee-925b-05f4cf0a2cb2> </mlhim243:el-8cc87b41-f721-4792-879b-fb07dd9f918c> <mlhim243:el-e5afc39d-57ba-47eb-ad1d-4d5751d4de3d> <mlhim243:el-28b5de47-4bc5-4f80-9eba-240608986e95> <mlhim243:data-name>Município</mlhim243:data-name> <mlhim243:DvString-dv>LsCgGyIT.FdfE6eUhAkZH</mlhim243:DvString-dv> </mlhim243:el-28b5de47-4bc5-4f80-9eba-240608986e95> </mlhim243:el-e5afc39d-57ba-47eb-ad1d-4d5751d4de3d> <mlhim243:el-31ce977b-35d0-40a7-977a-2015460a627c> <mlhim243:el-6843bb68-d5e3-4eca-96c2-ffedb5f7f936> <mlhim243:data-name>Nome</mlhim243:data-name> <mlhim243:DvString-dv>LRLVDWGz9Jce07LVVYIqBNT.sb1Ip6</mlhim243:DvString-dv> </mlhim243:el-6843bb68-d5e3-4eca-96c2-ffedb5f7f936> </mlhim243:el-31ce977b-35d0-40a7-977a-2015460a627c> <mlhim243:el-7d2791b9-bfb4-404f-8dc9-34f3f5a59be2> <mlhim243:el-24264eba-781a-4ab7-b08b-d1f227b9c1a5> <mlhim243:data-name>Telefone (BR)</mlhim243:data-name> <mlhim243:DvString-dv>9988-0066</mlhim243:DvString-dv> </mlhim243:el-24264eba-781a-4ab7-b08b-d1f227b9c1a5> </mlhim243:el-7d2791b9-bfb4-404f-8dc9-34f3f5a59be2> </mlhim243:el-c4665b57-b737-4eef-b1a4-46ecd2298121> </mlhim243:el-83fc62c8-8df8-472a-b590-d8ecea82d695> <mlhim243:other-participations> <mlhim243:performer xsi:type="mlhim243:PartySelfType"> <mlhim243:party-name>Self</mlhim243:party-name> </mlhim243:performer> <mlhim243:function> <mlhim243:data-name>Kjfb</mlhim243:data-name> <mlhim243:valid-time-begin>2014-03-07T21:23:43</mlhim243:valid-time-begin> <mlhim243:valid-time-end>2015-02-17T21:23:43</mlhim243:valid-time-end> <mlhim243:DvString-dv>mqheNtVr</mlhim243:DvString-dv> <mlhim243:language>el-GR</mlhim243:language> </mlhim243:function> <mlhim243:mode> <mlhim243:data-name>_nVmFU</mlhim243:data-name> <mlhim243:valid-time-begin>2014-05-13T21:23:43Z</mlhim243:valid-time-begin> <mlhim243:valid-time-end>2015-11-01T21:23:43</mlhim243:valid-time-end> <mlhim243:DvString-dv>THBrZJsJKUk</mlhim243:DvString-dv> <mlhim243:language>ar-EG</mlhim243:language> </mlhim243:mode> <mlhim243:start-time>2015-10-19T21:23:43Z</mlhim243:start-time> <mlhim243:end-time>2014-10-06T21:23:43Z</mlhim243:end-time> </mlhim243:other-participations> <mlhim243:protocol-id> <mlhim243:data-name>kT3_Z0VmPHXX-dOcMAETde</mlhim243:data-name> <mlhim243:valid-time-begin>2014-07-30T21:23:43Z</mlhim243:valid-time-begin> <mlhim243:valid-time-end>2015-06-12T21:23:43</mlhim243:valid-time-end> <mlhim243:DvString-dv>IDH2CwrOV6QME.57QFk_sdVfWumZbA</mlhim243:DvString-dv> <mlhim243:language>zh-CHT</mlhim243:language> <mlhim243:id-name>Pltz-Cs</mlhim243:id-name> <mlhim243:issuer>VjPYJkpMQkw4s-4P</mlhim243:issuer> <mlhim243:assignor>R8gOu5A</mlhim243:assignor> </mlhim243:protocol-id> <mlhim243:current-state/> <mlhim243:workflow-id> <mlhim243:data-name>qwj94ZDv-Vl.JEih4</mlhim243:data-name> <mlhim243:valid-time-begin>2014-03-07T21:23:43</mlhim243:valid-time-begin> <mlhim243:valid-time-end>2015-08-22T21:23:43Z</mlhim243:valid-time-end> <mlhim243:DvURI-dv>http://sOoraFZE/</mlhim243:DvURI-dv> <mlhim243:relation>hp0tKuPj5wBBlDz5mMp2</mlhim243:relation> </mlhim243:workflow-id> <mlhim243:attestation> <mlhim243:attested-view> <mlhim243:data-name>nSMy.ObVx</mlhim243:data-name> <mlhim243:valid-time-begin>2013-12-16T21:23:43Z</mlhim243:valid-time-begin> <mlhim243:valid-time-end>2014-07-24T21:23:43Z</mlhim243:valid-time-end> <mlhim243:size>-104627251</mlhim243:size> <mlhim243:encoding>tw5vID.GFjny4SCRLBbD7ZZTySQ_</mlhim243:encoding> <mlhim243:language>fr-FR</mlhim243:language> <mlhim243:mime-type>YkjlVO_9rLLDY9Gms.G0haMdQ299r</mlhim243:mime-type> <mlhim243:compression-type>W1ttoRY5TvsuXS13Da</mlhim243:compression-type> <mlhim243:hash-result>TFB</mlhim243:hash-result> <mlhim243:hash-function>cHT.29Rd-92hkIjMpBdSAPj6hRe</mlhim243:hash-function> <mlhim243:alt-txt>A6c181zfZLSsDPpxBZTI</mlhim243:alt-txt> <mlhim243:uri>http://NZPHWksI/</mlhim243:uri> <mlhim243:media-content>70697087</mlhim243:media-content> </mlhim243:attested-view> <mlhim243:proof> <mlhim243:data-name>gAoEpfYJ</mlhim243:data-name> <mlhim243:valid-time-begin>2015-01-09T21:23:43</mlhim243:valid-time-begin> <mlhim243:valid-time-end>2014-10-12T21:23:43Z</mlhim243:valid-time-end> <mlhim243:size>-1714095171</mlhim243:size> <mlhim243:encoding>CNt6V7BKQ5eRtCpdm.u</mlhim243:encoding> <mlhim243:language>he-IL</mlhim243:language> <mlhim243:DvParsable-dv>xmNk7N4O9bS4dfZRepYc5pPTcG</mlhim243:DvParsable-dv> <mlhim243:formalism>G6At1Yq</mlhim243:formalism> </mlhim243:proof> <mlhim243:reason> <mlhim243:data-name>Rw_XbhIN2cfqIB90SQ.j5K.Sn7DL</mlhim243:data-name> <mlhim243:valid-time-begin>2014-03-01T21:23:43Z</mlhim243:valid-time-begin> <mlhim243:valid-time-end>2015-07-02T21:23:43Z</mlhim243:valid-time-end> <mlhim243:DvString-dv>rM1704G7rYew51g0a7g</mlhim243:DvString-dv> <mlhim243:language>da-DK</mlhim243:language> </mlhim243:reason> <mlhim243:committer xsi:type="mlhim243:ct-83fc62c8-8df8-472a-b590-d8ecea82d695"> <mlhim243:party-name>rNaSvKhECpX</mlhim243:party-name> <mlhim243:el-4c8a56b0-c452-4b78-a861-1f2a47163693> <mlhim243:data-name>External Reference for PartyIdentified</mlhim243:data-name> <mlhim243:valid-time-begin>2015-11-04T21:23:43</mlhim243:valid-time-begin> <mlhim243:valid-time-end>2013-12-19T21:23:43Z</mlhim243:valid-time-end> <mlhim243:DvURI-dv>http://rzEouTbv/</mlhim243:DvURI-dv> <mlhim243:relation>Party Associated with the record</mlhim243:relation> </mlhim243:el-4c8a56b0-c452-4b78-a861-1f2a47163693> <mlhim243:el-c4665b57-b737-4eef-b1a4-46ecd2298121> <mlhim243:cluster-subject>PartyIdentified Details (BR)</mlhim243:cluster-subject> <mlhim243:el-7117e7ac-d879-4f8b-8719-2892050409e3> <mlhim243:el-cc5c08c4-4426-4a68-a59a-b7bef285624d> <mlhim243:data-name>Bairro</mlhim243:data-name> <mlhim243:DvString-dv>H</mlhim243:DvString-dv> </mlhim243:el-cc5c08c4-4426-4a68-a59a-b7bef285624d> </mlhim243:el-7117e7ac-d879-4f8b-8719-2892050409e3> <mlhim243:el-96017054-3fdb-4819-af9b-892d386c132c> <mlhim243:el-f487863a-773e-4f5a-9cc8-a66802d0589f> <mlhim243:data-name>Código Postal (Brazil)</mlhim243:data-name> <mlhim243:DvString-dv>21050-060</mlhim243:DvString-dv> </mlhim243:el-f487863a-773e-4f5a-9cc8-a66802d0589f> </mlhim243:el-96017054-3fdb-4819-af9b-892d386c132c> <mlhim243:el-43850c7b-d3bf-4888-957b-d00cc97674ab> <mlhim243:el-9cc073cf-1640-45cb-a595-4ac1992e6727> <mlhim243:data-name>Endereço da Rua</mlhim243:data-name> <mlhim243:DvString-dv>lbc812UxZuIHMR0DRri4yh</mlhim243:DvString-dv> </mlhim243:el-9cc073cf-1640-45cb-a595-4ac1992e6727> </mlhim243:el-43850c7b-d3bf-4888-957b-d00cc97674ab> <mlhim243:el-8cc87b41-f721-4792-879b-fb07dd9f918c> <mlhim243:el-5dd3d0ce-b97f-48ee-925b-05f4cf0a2cb2> <mlhim243:data-name>Estados Brasileiros (UF) e o distrito Federal</mlhim243:data-name> <mlhim243:DvString-dv>MS</mlhim243:DvString-dv> </mlhim243:el-5dd3d0ce-b97f-48ee-925b-05f4cf0a2cb2> </mlhim243:el-8cc87b41-f721-4792-879b-fb07dd9f918c> <mlhim243:el-e5afc39d-57ba-47eb-ad1d-4d5751d4de3d> <mlhim243:el-28b5de47-4bc5-4f80-9eba-240608986e95> <mlhim243:data-name>Município</mlhim243:data-name> <mlhim243:DvString-dv>Yd5Df9u</mlhim243:DvString-dv> </mlhim243:el-28b5de47-4bc5-4f80-9eba-240608986e95> </mlhim243:el-e5afc39d-57ba-47eb-ad1d-4d5751d4de3d> <mlhim243:el-31ce977b-35d0-40a7-977a-2015460a627c> <mlhim243:el-6843bb68-d5e3-4eca-96c2-ffedb5f7f936> <mlhim243:data-name>Nome</mlhim243:data-name> <mlhim243:DvString-dv>nb03</mlhim243:DvString-dv> </mlhim243:el-6843bb68-d5e3-4eca-96c2-ffedb5f7f936> </mlhim243:el-31ce977b-35d0-40a7-977a-2015460a627c> <mlhim243:el-7d2791b9-bfb4-404f-8dc9-34f3f5a59be2> <mlhim243:el-24264eba-781a-4ab7-b08b-d1f227b9c1a5> <mlhim243:data-name>Telefone (BR)</mlhim243:data-name> <mlhim243:DvString-dv>9988-0066</mlhim243:DvString-dv> </mlhim243:el-24264eba-781a-4ab7-b08b-d1f227b9c1a5> </mlhim243:el-7d2791b9-bfb4-404f-8dc9-34f3f5a59be2> </mlhim243:el-c4665b57-b737-4eef-b1a4-46ecd2298121> </mlhim243:committer> <mlhim243:time-committed>2014-09-28T21:23:43Z</mlhim243:time-committed> <mlhim243:is-pending>true</mlhim243:is-pending> </mlhim243:attestation> <mlhim243:el-2a94c03c-1c28-4870-a15e-56c31d97146b> <mlhim243:cluster-subject>Requisição</mlhim243:cluster-subject> <mlhim243:el-ea406263-1d2b-42ed-83ad-4d69fa8faa71> <mlhim243:cluster-subject>Dados Residencias</mlhim243:cluster-subject> <mlhim243:el-16b5f3ee-3bd4-4696-9493-e1202038c7ca> <mlhim243:el-4ac686a8-5ed1-42b0-a88a-bbc28e558e31> <mlhim243:data-name>Número</mlhim243:data-name> <mlhim243:DvString-dv>H3RdB4epiXAuDRC</mlhim243:DvString-dv> </mlhim243:el-4ac686a8-5ed1-42b0-a88a-bbc28e558e31> </mlhim243:el-16b5f3ee-3bd4-4696-9493-e1202038c7ca> </mlhim243:el-ea406263-1d2b-42ed-83ad-4d69fa8faa71> <mlhim243:el-ecd9dcd7-beb8-4cc0-8bba-67b21791c33d> <mlhim243:cluster-subject>Identificação do laboratório</mlhim243:cluster-subject> <mlhim243:el-6b3e45bb-5f07-40b6-b8dd-326a50c907f6> <mlhim243:el-a970586b-13eb-4faa-8384-f0cd5cc8d364> <mlhim243:data-name>CNPJ do laboratório</mlhim243:data-name> <mlhim243:DvString-dv>kEcMTKLIi806QIQ.sbaHmoue-uwP4P</mlhim243:DvString-dv> </mlhim243:el-a970586b-13eb-4faa-8384-f0cd5cc8d364> </mlhim243:el-6b3e45bb-5f07-40b6-b8dd-326a50c907f6> <mlhim243:el-01672468-82a2-48a3-8faf-0de7b38f4307> <mlhim243:el-aab44c67-a125-4586-84d3-9ec328fbb1ff> <mlhim243:data-name>Nome do Laboratório</mlhim243:data-name> <mlhim243:DvString-dv>z4ryq-</mlhim243:DvString-dv> </mlhim243:el-aab44c67-a125-4586-84d3-9ec328fbb1ff> </mlhim243:el-01672468-82a2-48a3-8faf-0de7b38f4307> <mlhim243:el-0f6ad0f3-88f5-4262-802a-a4db63f7cbc0> <mlhim243:el-d4edbcd4-e4ca-49a8-b731-d384f370e496> <mlhim243:data-name>Número do exame</mlhim243:data-name> <mlhim243:DvString-dv>EiOg2n5nFEeunKqOg1LE4</mlhim243:DvString-dv> </mlhim243:el-d4edbcd4-e4ca-49a8-b731-d384f370e496> </mlhim243:el-0f6ad0f3-88f5-4262-802a-a4db63f7cbc0> <mlhim243:el-b70a45e4-5544-46cd-a602-5305cb7dfebe> <mlhim243:el-a7e29790-1d9c-4eca-bc5b-34025eac069b> <mlhim243:data-name>Recebido em:</mlhim243:data-name> <mlhim243:dvtemporal-date>"""+examdatestr+"""</mlhim243:dvtemporal-date> </mlhim243:el-a7e29790-1d9c-4eca-bc5b-34025eac069b> </mlhim243:el-b70a45e4-5544-46cd-a602-5305cb7dfebe> </mlhim243:el-ecd9dcd7-beb8-4cc0-8bba-67b21791c33d> <mlhim243:el-3d6e9221-efe2-46db-adab-75c3d3b7f9de> <mlhim243:cluster-subject>Informações pessoais</mlhim243:cluster-subject> <mlhim243:el-d829499f-6dc0-41db-b19c-99b13f850060> <mlhim243:el-5e4467ff-9743-42ea-ba2b-a82b0b1a8ef2> <mlhim243:data-name>Apelido da Mulher</mlhim243:data-name> <mlhim243:DvString-dv>sOyXY</mlhim243:DvString-dv> </mlhim243:el-5e4467ff-9743-42ea-ba2b-a82b0b1a8ef2> </mlhim243:el-d829499f-6dc0-41db-b19c-99b13f850060> <mlhim243:el-3cf1d747-741a-47a1-a127-0730b5a8a6ae> <mlhim243:el-03fbd757-7915-4bfb-988b-f86817ff6d64> <mlhim243:data-name>Cartão SUS</mlhim243:data-name> <mlhim243:DvString-dv>hIOIQlEJcnbUlzziI40HK9spR</mlhim243:DvString-dv> </mlhim243:el-03fbd757-7915-4bfb-988b-f86817ff6d64> </mlhim243:el-3cf1d747-741a-47a1-a127-0730b5a8a6ae> <mlhim243:el-983484a7-727f-409b-8f97-1d441ef81a56> <mlhim243:el-6c96618b-27e5-4812-b9c7-bd54fa87d887> <mlhim243:data-name>CPF</mlhim243:data-name> <mlhim243:DvString-dv>bXiWe</mlhim243:DvString-dv> </mlhim243:el-6c96618b-27e5-4812-b9c7-bd54fa87d887> </mlhim243:el-983484a7-727f-409b-8f97-1d441ef81a56> <mlhim243:el-74d24949-11b3-4e94-a0d0-7ce1ac4b6b9e> <mlhim243:el-f54b7d0c-911b-442e-8556-b35d9f2a3627> <mlhim243:data-name>Escolaridade</mlhim243:data-name> <mlhim243:DvString-dv>1º Incompleto</mlhim243:DvString-dv> </mlhim243:el-f54b7d0c-911b-442e-8556-b35d9f2a3627> </mlhim243:el-74d24949-11b3-4e94-a0d0-7ce1ac4b6b9e> <mlhim243:el-53fe102a-918a-4722-854e-8086c38ddf11> <mlhim243:el-edcfd756-c559-4218-bda5-98d8006db225> <mlhim243:data-name>Identidade</mlhim243:data-name> <mlhim243:DvString-dv>x9YZEv</mlhim243:DvString-dv> </mlhim243:el-edcfd756-c559-4218-bda5-98d8006db225> </mlhim243:el-53fe102a-918a-4722-854e-8086c38ddf11> <mlhim243:el-7a5f8c49-bcf3-4fb1-9780-552aaf13d222> <mlhim243:el-e2006666-4af2-424c-8246-05efd9e72c11> <mlhim243:data-name>Mãe</mlhim243:data-name> <mlhim243:DvString-dv>onsNt8N0zmUizH2n.3FZXY9grcK</mlhim243:DvString-dv> </mlhim243:el-e2006666-4af2-424c-8246-05efd9e72c11> </mlhim243:el-7a5f8c49-bcf3-4fb1-9780-552aaf13d222> <mlhim243:el-a56cb826-ac49-4bad-be49-4acb67441f85> <mlhim243:el-4abcc0c8-f677-4723-9be2-9e380af44ea7> <mlhim243:data-name>Nome</mlhim243:data-name> <mlhim243:DvString-dv>qPaorHcpeBayYEQDk8LusmudzwA</mlhim243:DvString-dv> </mlhim243:el-4abcc0c8-f677-4723-9be2-9e380af44ea7> </mlhim243:el-a56cb826-ac49-4bad-be49-4acb67441f85> <mlhim243:el-b826bda8-d16f-4ded-b94f-0ca1c6752d17> <mlhim243:el-ca3341b5-4de3-47b7-a4e3-65e099b5dbd8> <mlhim243:data-name>Órgão Emissor</mlhim243:data-name> <mlhim243:DvString-dv>h02kCV</mlhim243:DvString-dv> </mlhim243:el-ca3341b5-4de3-47b7-a4e3-65e099b5dbd8> </mlhim243:el-b826bda8-d16f-4ded-b94f-0ca1c6752d17> <mlhim243:el-bb5cb04c-c94d-4b2b-b6fe-c883763d8993> <mlhim243:el-a81b03aa-4a99-40aa-abaf-d917e9e95d2f> <mlhim243:data-name>UF</mlhim243:data-name> <mlhim243:DvString-dv>PB</mlhim243:DvString-dv> </mlhim243:el-a81b03aa-4a99-40aa-abaf-d917e9e95d2f> </mlhim243:el-bb5cb04c-c94d-4b2b-b6fe-c883763d8993> <mlhim243:el-928c3d32-95a9-4749-9ccc-f9735451bd8f> <mlhim243:el-4dfcfac4-87c6-4d43-8644-208068ff406b> <mlhim243:data-name>Idade</mlhim243:data-name> <mlhim243:magnitude>"""+agestr+"""</mlhim243:magnitude> <mlhim243:error>0</mlhim243:error> <mlhim243:accuracy>0</mlhim243:accuracy> <mlhim243:el-b7b01351-c5b3-461d-9748-43ac5e2a90b6> <mlhim243:data-name>Anos</mlhim243:data-name> <mlhim243:DvString-dv>Years</mlhim243:DvString-dv> </mlhim243:el-b7b01351-c5b3-461d-9748-43ac5e2a90b6> </mlhim243:el-4dfcfac4-87c6-4d43-8644-208068ff406b> </mlhim243:el-928c3d32-95a9-4749-9ccc-f9735451bd8f> <mlhim243:el-cfa47018-22a7-4d8b-b643-76507411a549> <mlhim243:el-05006946-bc7a-4c34-8c58-d1e7618afa40> <mlhim243:data-name>Data de Nascimento</mlhim243:data-name> <mlhim243:dvtemporal-date>"""+dobstr+"""</mlhim243:dvtemporal-date> </mlhim243:el-05006946-bc7a-4c34-8c58-d1e7618afa40> </mlhim243:el-cfa47018-22a7-4d8b-b643-76507411a549> </mlhim243:el-3d6e9221-efe2-46db-adab-75c3d3b7f9de> <mlhim243:el-ee8c3378-1684-4077-802e-ee8cdcb8e80c> <mlhim243:cluster-subject>Requisição de exame</mlhim243:cluster-subject> <mlhim243:el-d78c40bb-1b31-4713-9ed7-d9ea1906e8ac> <mlhim243:el-83ac12f7-1aab-42f7-a1ed-96459631bcbc> <mlhim243:data-name>CNES</mlhim243:data-name> <mlhim243:DvString-dv>RgXLLvluqD3O7B7ABBIXXSE.MW</mlhim243:DvString-dv> </mlhim243:el-83ac12f7-1aab-42f7-a1ed-96459631bcbc> </mlhim243:el-d78c40bb-1b31-4713-9ed7-d9ea1906e8ac> <mlhim243:el-3239fd57-5765-42b8-bb85-af1c0338193c> <mlhim243:el-cafff88f-b4a7-420a-8894-b6229fda1a97> <mlhim243:data-name>Município</mlhim243:data-name> <mlhim243:DvString-dv>WKjTUqFFKMKy1zPrlpvhqzpewFkFt</mlhim243:DvString-dv> </mlhim243:el-cafff88f-b4a7-420a-8894-b6229fda1a97> </mlhim243:el-3239fd57-5765-42b8-bb85-af1c0338193c> <mlhim243:el-541ae033-caf0-4ca2-837c-0839de6fd217> <mlhim243:el-3281ea23-5529-47f2-8631-f2dfa34733c5> <mlhim243:data-name>Prontuário</mlhim243:data-name> <mlhim243:DvString-dv>kny8qhUN9QbiR</mlhim243:DvString-dv> </mlhim243:el-3281ea23-5529-47f2-8631-f2dfa34733c5> </mlhim243:el-541ae033-caf0-4ca2-837c-0839de6fd217> <mlhim243:el-bb5cb04c-c94d-4b2b-b6fe-c883763d8993> <mlhim243:el-a81b03aa-4a99-40aa-abaf-d917e9e95d2f> <mlhim243:data-name>UF</mlhim243:data-name> <mlhim243:DvString-dv>MG</mlhim243:DvString-dv> </mlhim243:el-a81b03aa-4a99-40aa-abaf-d917e9e95d2f> </mlhim243:el-bb5cb04c-c94d-4b2b-b6fe-c883763d8993> <mlhim243:el-74173550-fbf7-47be-bd95-650c03b98822> <mlhim243:el-e8326326-7ff7-4f48-90f1-021f6be65319> <mlhim243:data-name>Unidade de saúde</mlhim243:data-name> <mlhim243:DvString-dv>na1_BEmawnd0m5u</mlhim243:DvString-dv> </mlhim243:el-e8326326-7ff7-4f48-90f1-021f6be65319> </mlhim243:el-74173550-fbf7-47be-bd95-650c03b98822> </mlhim243:el-ee8c3378-1684-4077-802e-ee8cdcb8e80c> </mlhim243:el-2a94c03c-1c28-4870-a15e-56c31d97146b> </mlhim243:el-9de3b321-08e0-447f-abae-49b64c9e3583> </mlhim243:ccd-19e452e8-8e2d-46ba-a88c-2afd34ca8d71> """) f.write(fstr) f.close() return
apache-2.0
bambooforest/segments
setup.py
1528
from setuptools import setup, find_packages setup( name='segments', version="2.1.4.dev0", description='', long_description=open("README.md").read(), long_description_content_type="text/markdown", author='Steven Moran and Robert Forkel', author_email='steven.moran@uzh.ch', url='https://github.com/cldf/segments', install_requires=[ 'regex', 'csvw>=1.5.6', 'clldutils>=1.7.3', ], extras_require={ 'dev': ['flake8', 'wheel', 'twine'], 'test': [ 'pytest>=3.6', 'pytest-mock', 'mock', 'pytest-cov', ], }, license='Apache 2.0', zip_safe=False, keywords='tokenizer', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Natural Language :: English', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy' ], packages=find_packages(where="src"), package_dir={"": "src"}, include_package_data=True, entry_points={ 'console_scripts': [ "segments = segments.__main__:main", ] }, )
apache-2.0
echohn/send_email
test/test_email.rb
369
#!/usr/bin/env ruby # encoding: utf-8 require 'send_email' SendEmail.smtp = '192.168.12.1' mail = SendEmail::Mail.new( :from => 'from@testmail.com' , :to => 'to@testmail.com' , :cc => 'cc@testmail.com', :subject => 'Test Mail Subject', :msg => "<h1>Hellow world!</h1>", :attachement => ARGV, :format => 'HTML') mail.send
apache-2.0
karussell/fastutil
src/it/unimi/dsi/fastutil/doubles/Double2ObjectLinkedOpenHashMap.java
47126
/* Generic definitions */ /* Assertions (useful to generate conditional code) */ /* Current type and class (and size, if applicable) */ /* Value methods */ /* Interfaces (keys) */ /* Interfaces (values) */ /* Abstract implementations (keys) */ /* Abstract implementations (values) */ /* Static containers (keys) */ /* Static containers (values) */ /* Implementations */ /* Synchronized wrappers */ /* Unmodifiable wrappers */ /* Other wrappers */ /* Methods (keys) */ /* Methods (values) */ /* Methods (keys/values) */ /* Methods that have special names depending on keys (but the special names depend on values) */ /* Equality */ /* Object/Reference-only definitions (keys) */ /* Primitive-type-only definitions (keys) */ /* Object/Reference-only definitions (values) */ /* * Copyright (C) 2002-2013 Sebastiano Vigna * * 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. */ package it.unimi.dsi.fastutil.doubles; import it.unimi.dsi.fastutil.Hash; import it.unimi.dsi.fastutil.HashCommon; import it.unimi.dsi.fastutil.booleans.BooleanArrays; import static it.unimi.dsi.fastutil.HashCommon.arraySize; import static it.unimi.dsi.fastutil.HashCommon.maxFill; import java.util.Map; import java.util.NoSuchElementException; import it.unimi.dsi.fastutil.objects.ObjectCollection; import it.unimi.dsi.fastutil.objects.AbstractObjectCollection; import it.unimi.dsi.fastutil.objects.ObjectIterator; import it.unimi.dsi.fastutil.objects.ObjectArrays; import java.util.Comparator; import it.unimi.dsi.fastutil.objects.AbstractObjectSortedSet; import it.unimi.dsi.fastutil.objects.ObjectListIterator; import it.unimi.dsi.fastutil.objects.ObjectBidirectionalIterator; import it.unimi.dsi.fastutil.objects.ObjectSortedSet; /** A type-specific linked hash map with with a fast, small-footprint implementation. * * <P>Instances of this class use a hash table to represent a map. The table is * enlarged as needed by doubling its size when new entries are created, but it is <em>never</em> made * smaller (even on a {@link #clear()}). A family of {@linkplain #trim() trimming * methods} lets you control the size of the table; this is particularly useful * if you reuse instances of this class. * * <P>Iterators generated by this map will enumerate pairs in the same order in which they * have been added to the map (addition of pairs whose key is already present * in the set does not change the iteration order). Note that this order has nothing in common with the natural * order of the keys. The order is kept by means of a doubly linked list, represented * <i>via</i> an array of longs parallel to the table. * * <P>This class implements the interface of a sorted map, so to allow easy * access of the iteration order: for instance, you can get the first key * in iteration order with {@link #firstKey()} without having to create an * iterator; however, this class partially violates the {@link java.util.SortedMap} * contract because all submap methods throw an exception and {@link * #comparator()} returns always <code>null</code>. * * <p>Additional methods, such as <code>getAndMoveToFirst()</code>, make it easy * to use instances of this class as a cache (e.g., with LRU policy). * * <P>The iterators provided by the views of this class using are type-specific * {@linkplain java.util.ListIterator list iterators}, and can be started at any * element <em>which is a key of the map</em>, or * a {@link NoSuchElementException} exception will be thrown. * If, however, the provided element is not the first or last key in the * set, the first access to the list index will require linear time, as in the worst case * the entire key set must be scanned in iteration order to retrieve the positional * index of the starting key. If you use just the methods of a type-specific {@link it.unimi.dsi.fastutil.BidirectionalIterator}, * however, all operations will be performed in constant time. * * @see Hash * @see HashCommon */ public class Double2ObjectLinkedOpenHashMap <V> extends AbstractDouble2ObjectSortedMap <V> implements java.io.Serializable, Cloneable, Hash { private static final long serialVersionUID = 0L; private static final boolean ASSERTS = false; /** The array of keys. */ protected transient double key[]; /** The array of values. */ protected transient V value[]; /** The array telling whether a position is used. */ protected transient boolean used[]; /** The acceptable load factor. */ protected final float f; /** The current table size. */ protected transient int n; /** Threshold after which we rehash. It must be the table size times {@link #f}. */ protected transient int maxFill; /** The mask for wrapping a position counter. */ protected transient int mask; /** Number of entries in the set. */ protected int size; /** Cached set of entries. */ protected transient volatile FastSortedEntrySet <V> entries; /** Cached set of keys. */ protected transient volatile DoubleSortedSet keys; /** Cached collection of values. */ protected transient volatile ObjectCollection <V> values; /** The index of the first entry in iteration order. It is valid iff {@link #size} is nonzero; otherwise, it contains -1. */ protected transient int first = -1; /** The index of the last entry in iteration order. It is valid iff {@link #size} is nonzero; otherwise, it contains -1. */ protected transient int last = -1; /** For each entry, the next and the previous entry in iteration order, * stored as <code>((prev & 0xFFFFFFFFL) << 32) | (next & 0xFFFFFFFFL)</code>. * The first entry contains predecessor -1, and the last entry * contains successor -1. */ protected transient long link[]; /* Macros for transforming the bi-directional long link. Return values are 32-bit int indexes. * SET_UPPER and SET_LOWER do a masked assignment as described at * http://www-graphics.stanford.edu/~seander/bithacks.html#MaskedMerge */ /** Creates a new hash map. * * <p>The actual table size will be the least power of two greater than <code>expected</code>/<code>f</code>. * * @param expected the expected number of elements in the hash set. * @param f the load factor. */ @SuppressWarnings("unchecked") public Double2ObjectLinkedOpenHashMap( final int expected, final float f ) { if ( f <= 0 || f > 1 ) throw new IllegalArgumentException( "Load factor must be greater than 0 and smaller than or equal to 1" ); if ( expected < 0 ) throw new IllegalArgumentException( "The expected number of elements must be nonnegative" ); this.f = f; n = arraySize( expected, f ); mask = n - 1; maxFill = maxFill( n, f ); key = new double[ n ]; value = (V[]) new Object[ n ]; used = new boolean[ n ]; link = new long[ n ]; } /** Creates a new hash map with {@link Hash#DEFAULT_LOAD_FACTOR} as load factor. * * @param expected the expected number of elements in the hash map. */ public Double2ObjectLinkedOpenHashMap( final int expected ) { this( expected, DEFAULT_LOAD_FACTOR ); } /** Creates a new hash map with initial expected {@link Hash#DEFAULT_INITIAL_SIZE} entries * and {@link Hash#DEFAULT_LOAD_FACTOR} as load factor. */ public Double2ObjectLinkedOpenHashMap() { this( DEFAULT_INITIAL_SIZE, DEFAULT_LOAD_FACTOR ); } /** Creates a new hash map copying a given one. * * @param m a {@link Map} to be copied into the new hash map. * @param f the load factor. */ public Double2ObjectLinkedOpenHashMap( final Map<? extends Double, ? extends V> m, final float f ) { this( m.size(), f ); putAll( m ); } /** Creates a new hash map with {@link Hash#DEFAULT_LOAD_FACTOR} as load factor copying a given one. * * @param m a {@link Map} to be copied into the new hash map. */ public Double2ObjectLinkedOpenHashMap( final Map<? extends Double, ? extends V> m ) { this( m, DEFAULT_LOAD_FACTOR ); } /** Creates a new hash map copying a given type-specific one. * * @param m a type-specific map to be copied into the new hash map. * @param f the load factor. */ public Double2ObjectLinkedOpenHashMap( final Double2ObjectMap <V> m, final float f ) { this( m.size(), f ); putAll( m ); } /** Creates a new hash map with {@link Hash#DEFAULT_LOAD_FACTOR} as load factor copying a given type-specific one. * * @param m a type-specific map to be copied into the new hash map. */ public Double2ObjectLinkedOpenHashMap( final Double2ObjectMap <V> m ) { this( m, DEFAULT_LOAD_FACTOR ); } /** Creates a new hash map using the elements of two parallel arrays. * * @param k the array of keys of the new hash map. * @param v the array of corresponding values in the new hash map. * @param f the load factor. * @throws IllegalArgumentException if <code>k</code> and <code>v</code> have different lengths. */ public Double2ObjectLinkedOpenHashMap( final double[] k, final V v[], final float f ) { this( k.length, f ); if ( k.length != v.length ) throw new IllegalArgumentException( "The key array and the value array have different lengths (" + k.length + " and " + v.length + ")" ); for( int i = 0; i < k.length; i++ ) this.put( k[ i ], v[ i ] ); } /** Creates a new hash map with {@link Hash#DEFAULT_LOAD_FACTOR} as load factor using the elements of two parallel arrays. * * @param k the array of keys of the new hash map. * @param v the array of corresponding values in the new hash map. * @throws IllegalArgumentException if <code>k</code> and <code>v</code> have different lengths. */ public Double2ObjectLinkedOpenHashMap( final double[] k, final V v[] ) { this( k, v, DEFAULT_LOAD_FACTOR ); } /* * The following methods implements some basic building blocks used by * all accessors. They are (and should be maintained) identical to those used in OpenHashSet.drv. */ public V put(final double k, final V v) { // The starting point. int pos = (int)it.unimi.dsi.fastutil.HashCommon.murmurHash3(Double.doubleToRawLongBits(k)) & mask; // There's always an unused entry. while( used[ pos ] ) { if ( ( (key[ pos ]) == (k) ) ) { final V oldValue = value[ pos ]; value[ pos ] = v; return oldValue; } pos = ( pos + 1 ) & mask; } used[ pos ] = true; key[ pos ] = k; value[ pos ] = v; if ( size == 0 ) { first = last = pos; // Special case of SET_UPPER_LOWER( link[ pos ], -1, -1 ); link[ pos ] = -1L; } else { link[ last ] ^= ( ( link[ last ] ^ ( pos & 0xFFFFFFFFL ) ) & 0xFFFFFFFFL ); link[ pos ] = ( ( last & 0xFFFFFFFFL ) << 32 ) | ( -1 & 0xFFFFFFFFL ); last = pos; } if ( ++size >= maxFill ) rehash( arraySize( size + 1, f ) ); if ( ASSERTS ) checkTable(); return defRetValue; } public V put( final Double ok, final V ov ) { final V v = (ov); final double k = ((ok).doubleValue()); // The starting point. int pos = (int)it.unimi.dsi.fastutil.HashCommon.murmurHash3(Double.doubleToRawLongBits(k)) & mask; // There's always an unused entry. while( used[ pos ] ) { if ( ( (key[ pos ]) == (k) ) ) { final V oldValue = (value[ pos ]); value[ pos ] = v; return oldValue; } pos = ( pos + 1 ) & mask; } used[ pos ] = true; key[ pos ] = k; value[ pos ] = v; if ( size == 0 ) { first = last = pos; // Special case of SET_UPPER_LOWER( link[ pos ], -1, -1 ); link[ pos ] = -1L; } else { link[ last ] ^= ( ( link[ last ] ^ ( pos & 0xFFFFFFFFL ) ) & 0xFFFFFFFFL ); link[ pos ] = ( ( last & 0xFFFFFFFFL ) << 32 ) | ( -1 & 0xFFFFFFFFL ); last = pos; } if ( ++size >= maxFill ) rehash( arraySize( size + 1, f ) ); if ( ASSERTS ) checkTable(); return (this.defRetValue); } /** Shifts left entries with the specified hash code, starting at the specified position, * and empties the resulting free entry. * * @param pos a starting position. * @return the position cleared by the shifting process. */ protected final int shiftKeys( int pos ) { // Shift entries with the same hash. int last, slot; for(;;) { pos = ( ( last = pos ) + 1 ) & mask; while( used[ pos ] ) { slot = (int)it.unimi.dsi.fastutil.HashCommon.murmurHash3(Double.doubleToRawLongBits(key[ pos ])) & mask; if ( last <= pos ? last >= slot || slot > pos : last >= slot && slot > pos ) break; pos = ( pos + 1 ) & mask; } if ( ! used[ pos ] ) break; key[ last ] = key[ pos ]; value[ last ] = value[ pos ]; fixPointers( pos, last ); } used[ last ] = false; value[ last ] = null; return last; } @SuppressWarnings("unchecked") public V remove( final double k ) { // The starting point. int pos = (int)it.unimi.dsi.fastutil.HashCommon.murmurHash3(Double.doubleToRawLongBits(k)) & mask; // There's always an unused entry. while( used[ pos ] ) { if ( ( (key[ pos ]) == (k) ) ) { size--; fixPointers( pos ); final V v = value[ pos ]; shiftKeys( pos ); return v; } pos = ( pos + 1 ) & mask; } return defRetValue; } @SuppressWarnings("unchecked") public V remove( final Object ok ) { final double k = ((((Double)(ok)).doubleValue())); // The starting point. int pos = (int)it.unimi.dsi.fastutil.HashCommon.murmurHash3(Double.doubleToRawLongBits(k)) & mask; // There's always an unused entry. while( used[ pos ] ) { if ( ( (key[ pos ]) == (k) ) ) { size--; fixPointers( pos ); final V v = value[ pos ]; shiftKeys( pos ); return (v); } pos = ( pos + 1 ) & mask; } return (this.defRetValue); } /** Removes the mapping associated with the first key in iteration order. * @return the value previously associated with the first key in iteration order. * @throws NoSuchElementException is this map is empty. */ public V removeFirst() { if ( size == 0 ) throw new NoSuchElementException(); --size; final int pos = first; // Abbreviated version of fixPointers(pos) first = (int) link[ pos ]; if ( 0 <= first ) { // Special case of SET_PREV( link[ first ], -1 ) link[ first ] |= (-1 & 0xFFFFFFFFL) << 32; } final V v = value[ pos ]; shiftKeys( pos ); return v; } /** Removes the mapping associated with the last key in iteration order. * @return the value previously associated with the last key in iteration order. * @throws NoSuchElementException is this map is empty. */ public V removeLast() { if ( size == 0 ) throw new NoSuchElementException(); --size; final int pos = last; // Abbreviated version of fixPointers(pos) last = (int) ( link[ pos ] >>> 32 ); if ( 0 <= last ) { // Special case of SET_NEXT( link[ last ], -1 ) link[ last ] |= -1 & 0xFFFFFFFFL; } final V v = value[ pos ]; shiftKeys( pos ); return v; } private void moveIndexToFirst( final int i ) { if ( size == 1 || first == i ) return; if ( last == i ) { last = (int) ( link[ i ] >>> 32 ); // Special case of SET_NEXT( link[ last ], -1 ); link[ last ] |= -1 & 0xFFFFFFFFL; } else { final long linki = link[ i ]; final int prev = (int) ( linki >>> 32 ); final int next = (int) linki; link[ prev ] ^= ( ( link[ prev ] ^ ( linki & 0xFFFFFFFFL ) ) & 0xFFFFFFFFL ); link[ next ] ^= ( ( link[ next ] ^ ( linki & 0xFFFFFFFF00000000L ) ) & 0xFFFFFFFF00000000L ); } link[ first ] ^= ( ( link[ first ] ^ ( ( i & 0xFFFFFFFFL ) << 32 ) ) & 0xFFFFFFFF00000000L ); link[ i ] = ( ( -1 & 0xFFFFFFFFL ) << 32 ) | ( first & 0xFFFFFFFFL ); first = i; } private void moveIndexToLast( final int i ) { if ( size == 1 || last == i ) return; if ( first == i ) { first = (int) link[ i ]; // Special case of SET_PREV( link[ first ], -1 ); link[ first ] |= (-1 & 0xFFFFFFFFL) << 32; } else { final long linki = link[ i ]; final int prev = (int) ( linki >>> 32 ); final int next = (int) linki; link[ prev ] ^= ( ( link[ prev ] ^ ( linki & 0xFFFFFFFFL ) ) & 0xFFFFFFFFL ); link[ next ] ^= ( ( link[ next ] ^ ( linki & 0xFFFFFFFF00000000L ) ) & 0xFFFFFFFF00000000L ); } link[ last ] ^= ( ( link[ last ] ^ ( i & 0xFFFFFFFFL ) ) & 0xFFFFFFFFL ); link[ i ] = ( ( last & 0xFFFFFFFFL ) << 32 ) | ( -1 & 0xFFFFFFFFL ); last = i; } /** Returns the value to which the given key is mapped; if the key is present, it is moved to the first position of the iteration order. * * @param k the key. * @return the corresponding value, or the {@linkplain #defaultReturnValue() default return value} if no value was present for the given key. */ public V getAndMoveToFirst( final double k ) { final double key[] = this.key; final boolean used[] = this.used; final int mask = this.mask; // The starting point. int pos = (int)it.unimi.dsi.fastutil.HashCommon.murmurHash3(Double.doubleToRawLongBits(k)) & mask; // There's always an unused entry. while( used[ pos ] ) { if( ( (k) == (key[ pos ]) ) ) { moveIndexToFirst( pos ); return value[ pos ]; } pos = ( pos + 1 ) & mask; } return defRetValue; } /** Returns the value to which the given key is mapped; if the key is present, it is moved to the last position of the iteration order. * * @param k the key. * @return the corresponding value, or the {@linkplain #defaultReturnValue() default return value} if no value was present for the given key. */ public V getAndMoveToLast( final double k ) { final double key[] = this.key; final boolean used[] = this.used; final int mask = this.mask; // The starting point. int pos = (int)it.unimi.dsi.fastutil.HashCommon.murmurHash3(Double.doubleToRawLongBits(k)) & mask; // There's always an unused entry. while( used[ pos ] ) { if( ( (k) == (key[ pos ]) ) ) { moveIndexToLast( pos ); return value[ pos ]; } pos = ( pos + 1 ) & mask; } return defRetValue; } /** Adds a pair to the map; if the key is already present, it is moved to the first position of the iteration order. * * @param k the key. * @param v the value. * @return the old value, or the {@linkplain #defaultReturnValue() default return value} if no value was present for the given key. */ public V putAndMoveToFirst( final double k, final V v ) { final double key[] = this.key; final boolean used[] = this.used; final int mask = this.mask; // The starting point. int pos = (int)it.unimi.dsi.fastutil.HashCommon.murmurHash3(Double.doubleToRawLongBits(k)) & mask; // There's always an unused entry. while( used[ pos ] ) { if ( ( (k) == (key[ pos ]) ) ) { final V oldValue = value[ pos ]; value[ pos ] = v; moveIndexToFirst( pos ); return oldValue; } pos = ( pos + 1 ) & mask; } used[ pos ] = true; key[ pos ] = k; value[ pos ] = v; if ( size == 0 ) { first = last = pos; // Special case of SET_UPPER_LOWER( link[ pos ], -1, -1 ); link[ pos ] = -1L; } else { link[ first ] ^= ( ( link[ first ] ^ ( ( pos & 0xFFFFFFFFL ) << 32 ) ) & 0xFFFFFFFF00000000L ); link[ pos ] = ( ( -1 & 0xFFFFFFFFL ) << 32 ) | ( first & 0xFFFFFFFFL ); first = pos; } if ( ++size >= maxFill ) rehash( arraySize( size, f ) ); if ( ASSERTS ) checkTable(); return defRetValue; } /** Adds a pair to the map; if the key is already present, it is moved to the last position of the iteration order. * * @param k the key. * @param v the value. * @return the old value, or the {@linkplain #defaultReturnValue() default return value} if no value was present for the given key. */ public V putAndMoveToLast( final double k, final V v ) { final double key[] = this.key; final boolean used[] = this.used; final int mask = this.mask; // The starting point. int pos = (int)it.unimi.dsi.fastutil.HashCommon.murmurHash3(Double.doubleToRawLongBits(k)) & mask; // There's always an unused entry. while( used[ pos ] ) { if ( ( (k) == (key[ pos ]) ) ) { final V oldValue = value[ pos ]; value[ pos ] = v; moveIndexToLast( pos ); return oldValue; } pos = ( pos + 1 ) & mask; } used[ pos ] = true; key[ pos ] = k; value[ pos ] = v; if ( size == 0 ) { first = last = pos; // Special case of SET_UPPER_LOWER( link[ pos ], -1, -1 ); link[ pos ] = -1L; } else { link[ last ] ^= ( ( link[ last ] ^ ( pos & 0xFFFFFFFFL ) ) & 0xFFFFFFFFL ); link[ pos ] = ( ( last & 0xFFFFFFFFL ) << 32 ) | ( -1 & 0xFFFFFFFFL ); last = pos; } if ( ++size >= maxFill ) rehash( arraySize( size, f ) ); if ( ASSERTS ) checkTable(); return defRetValue; } public V get( final Double ok ) { final double k = ((ok).doubleValue()); // The starting point. int pos = (int)it.unimi.dsi.fastutil.HashCommon.murmurHash3(Double.doubleToRawLongBits( k)) & mask; // There's always an unused entry. while( used[ pos ] ) { if ( ( (key[ pos ]) == ( k) ) ) return (value[ pos ]); pos = ( pos + 1 ) & mask; } return (this.defRetValue); } @SuppressWarnings("unchecked") public V get( final double k ) { // The starting point. int pos = (int)it.unimi.dsi.fastutil.HashCommon.murmurHash3(Double.doubleToRawLongBits(k)) & mask; // There's always an unused entry. while( used[ pos ] ) { if ( ( (key[ pos ]) == (k) ) ) return value[ pos ]; pos = ( pos + 1 ) & mask; } return defRetValue; } @SuppressWarnings("unchecked") public boolean containsKey( final double k ) { // The starting point. int pos = (int)it.unimi.dsi.fastutil.HashCommon.murmurHash3(Double.doubleToRawLongBits(k)) & mask; // There's always an unused entry. while( used[ pos ] ) { if ( ( (key[ pos ]) == (k) ) ) return true; pos = ( pos + 1 ) & mask; } return false; } public boolean containsValue( final Object v ) { final V value[] = this.value; final boolean used[] = this.used; for( int i = n; i-- != 0; ) if ( used[ i ] && ( (value[ i ]) == null ? (v) == null : (value[ i ]).equals(v) ) ) return true; return false; } /* Removes all elements from this map. * * <P>To increase object reuse, this method does not change the table size. * If you want to reduce the table size, you must use {@link #trim()}. * */ public void clear() { if ( size == 0 ) return; size = 0; BooleanArrays.fill( used, false ); // We null all object entries so that the garbage collector can do its work. ObjectArrays.fill( value, null ); first = last = -1; } public int size() { return size; } public boolean isEmpty() { return size == 0; } /** A no-op for backward compatibility. * * @param growthFactor unused. * @deprecated Since <code>fastutil</code> 6.1.0, hash tables are doubled when they are too full. */ @Deprecated public void growthFactor( int growthFactor ) {} /** Gets the growth factor (2). * * @return the growth factor of this set, which is fixed (2). * @see #growthFactor(int) * @deprecated Since <code>fastutil</code> 6.1.0, hash tables are doubled when they are too full. */ @Deprecated public int growthFactor() { return 16; } /** The entry class for a hash map does not record key and value, but * rather the position in the hash table of the corresponding entry. This * is necessary so that calls to {@link java.util.Map.Entry#setValue(Object)} are reflected in * the map */ private final class MapEntry implements Double2ObjectMap.Entry <V>, Map.Entry<Double, V> { // The table index this entry refers to, or -1 if this entry has been deleted. private int index; MapEntry( final int index ) { this.index = index; } public Double getKey() { return (Double.valueOf(key[ index ])); } public double getDoubleKey() { return key[ index ]; } public V getValue() { return (value[ index ]); } public V setValue( final V v ) { final V oldValue = value[ index ]; value[ index ] = v; return oldValue; } @SuppressWarnings("unchecked") public boolean equals( final Object o ) { if (!(o instanceof Map.Entry)) return false; Map.Entry<Double, V> e = (Map.Entry<Double, V>)o; return ( (key[ index ]) == (((e.getKey()).doubleValue())) ) && ( (value[ index ]) == null ? ((e.getValue())) == null : (value[ index ]).equals((e.getValue())) ); } public int hashCode() { return it.unimi.dsi.fastutil.HashCommon.double2int(key[ index ]) ^ ( (value[ index ]) == null ? 0 : (value[ index ]).hashCode() ); } public String toString() { return key[ index ] + "=>" + value[ index ]; } } /** Modifies the {@link #link} vector so that the given entry is removed. * * <P>If the given entry is the first or the last one, this method will complete * in constant time; otherwise, it will have to search for the given entry. * * @param i the index of an entry. */ protected void fixPointers( final int i ) { if ( size == 0 ) { first = last = -1; return; } if ( first == i ) { first = (int) link[ i ]; if (0 <= first) { // Special case of SET_PREV( link[ first ], -1 ) link[ first ] |= (-1 & 0xFFFFFFFFL) << 32; } return; } if ( last == i ) { last = (int) ( link[ i ] >>> 32 ); if (0 <= last) { // Special case of SET_NEXT( link[ last ], -1 ) link[ last ] |= -1 & 0xFFFFFFFFL; } return; } final long linki = link[ i ]; final int prev = (int) ( linki >>> 32 ); final int next = (int) linki; link[ prev ] ^= ( ( link[ prev ] ^ ( linki & 0xFFFFFFFFL ) ) & 0xFFFFFFFFL ); link[ next ] ^= ( ( link[ next ] ^ ( linki & 0xFFFFFFFF00000000L ) ) & 0xFFFFFFFF00000000L ); } /** Modifies the {@link #link} vector for a shift from s to d. * * <P>If the given entry is the first or the last one, this method will complete * in constant time; otherwise, it will have to search for the given entry. * * @param s the source position. * @param d the destination position. */ protected void fixPointers( int s, int d ) { if ( size == 1 ) { first = last = d; // Special case of SET_UPPER_LOWER( link[ d ], -1, -1 ) link[ d ] = -1L; return; } if ( first == s ) { first = d; link[ (int) link[ s ] ] ^= ( ( link[ (int) link[ s ] ] ^ ( ( d & 0xFFFFFFFFL ) << 32 ) ) & 0xFFFFFFFF00000000L ); link[ d ] = link[ s ]; return; } if ( last == s ) { last = d; link[ (int) ( link[ s ] >>> 32 )] ^= ( ( link[ (int) ( link[ s ] >>> 32 )] ^ ( d & 0xFFFFFFFFL ) ) & 0xFFFFFFFFL ); link[ d ] = link[ s ]; return; } final long links = link[ s ]; final int prev = (int) ( links >>> 32 ); final int next = (int) links; link[ prev ] ^= ( ( link[ prev ] ^ ( d & 0xFFFFFFFFL ) ) & 0xFFFFFFFFL ); link[ next ] ^= ( ( link[ next ] ^ ( ( d & 0xFFFFFFFFL ) << 32 ) ) & 0xFFFFFFFF00000000L ); link[ d ] = links; } /** Returns the first key of this map in iteration order. * * @return the first key in iteration order. */ public double firstDoubleKey() { if ( size == 0 ) throw new NoSuchElementException(); return key[ first ]; } /** Returns the last key of this map in iteration order. * * @return the last key in iteration order. */ public double lastDoubleKey() { if ( size == 0 ) throw new NoSuchElementException(); return key[ last ]; } public DoubleComparator comparator() { return null; } public Double2ObjectSortedMap <V> tailMap( double from ) { throw new UnsupportedOperationException(); } public Double2ObjectSortedMap <V> headMap( double to ) { throw new UnsupportedOperationException(); } public Double2ObjectSortedMap <V> subMap( double from, double to ) { throw new UnsupportedOperationException(); } /** A list iterator over a linked map. * * <P>This class provides a list iterator over a linked hash map. The empty constructor runs in * constant time. The one-argument constructor needs to search for the given key, but it is * optimized for the case of {@link java.util.SortedMap#lastKey()}, in which case runs in constant time, too. */ private class MapIterator { /** The entry that will be returned by the next call to {@link java.util.ListIterator#previous()} (or <code>null</code> if no previous entry exists). */ int prev = -1; /** The entry that will be returned by the next call to {@link java.util.ListIterator#next()} (or <code>null</code> if no next entry exists). */ int next = -1; /** The last entry that was returned (or -1 if we did not iterate or used {@link java.util.Iterator#remove()}). */ int curr = -1; /** The current index (in the sense of a {@link java.util.ListIterator}). Note that this value is not meaningful when this iterator has been created using the nonempty constructor.*/ int index = -1; private MapIterator() { next = first; index = 0; } private MapIterator( final double from ) { if ( ( (key[ last ]) == (from) ) ) { prev = last; index = size; } else { // The starting point. int pos = (int)it.unimi.dsi.fastutil.HashCommon.murmurHash3(Double.doubleToRawLongBits(from)) & mask; // There's always an unused entry. while( used[ pos ] ) { if ( ( (key[ pos ]) == (from) ) ) { // Note: no valid index known. next = (int) link[ pos ]; prev = pos; return; } pos = ( pos + 1 ) & mask; } throw new NoSuchElementException( "The key " + from + " does not belong to this map." ); } } public boolean hasNext() { return next != -1; } public boolean hasPrevious() { return prev != -1; } private final void ensureIndexKnown() { if ( index >= 0 ) return; if ( prev == -1 ) { index = 0; return; } if ( next == -1 ) { index = size; return; } int pos = first; index = 1; while( pos != prev ) { pos = (int) link[ pos ]; index++; } } public int nextIndex() { ensureIndexKnown(); return index; } public int previousIndex() { ensureIndexKnown(); return index - 1; } public int nextEntry() { if ( ! hasNext() ) return size(); curr = next; next = (int) link[ curr ]; prev = curr; if ( index >= 0 ) index++; return curr; } public int previousEntry() { if ( ! hasPrevious() ) return -1; curr = prev; prev = (int) ( link[ curr ] >>> 32 ); next = curr; if ( index >= 0 ) index--; return curr; } @SuppressWarnings("unchecked") public void remove() { ensureIndexKnown(); if ( curr == -1 ) throw new IllegalStateException(); if ( curr == prev ) { /* If the last operation was a next(), we are removing an entry that preceeds the current index, and thus we must decrement it. */ index--; prev = (int) ( link[ curr ] >>> 32 ); } else next = (int) link[ curr ]; size--; /* Now we manually fix the pointers. Because of our knowledge of next and prev, this is going to be faster than calling fixPointers(). */ if ( prev == -1 ) first = next; else link[ prev ] ^= ( ( link[ prev ] ^ ( next & 0xFFFFFFFFL ) ) & 0xFFFFFFFFL ); if ( next == -1 ) last = prev; else link[ next ] ^= ( ( link[ next ] ^ ( ( prev & 0xFFFFFFFFL ) << 32 ) ) & 0xFFFFFFFF00000000L ); int last, slot, pos = curr; // We have to horribly duplicate the shiftKeys() code because we need to update next/prev. for(;;) { pos = ( ( last = pos ) + 1 ) & mask; while( used[ pos ] ) { slot = (int)it.unimi.dsi.fastutil.HashCommon.murmurHash3(Double.doubleToRawLongBits(key[ pos ])) & mask; if ( last <= pos ? last >= slot || slot > pos : last >= slot && slot > pos ) break; pos = ( pos + 1 ) & mask; } if ( ! used[ pos ] ) break; key[ last ] = key[ pos ]; value[ last ] = value[ pos ]; if ( next == pos ) next = last; if ( prev == pos ) prev = last; fixPointers( pos, last ); } used[ last ] = false; value[ last ] = null; curr = -1; } public int skip( final int n ) { int i = n; while( i-- != 0 && hasNext() ) nextEntry(); return n - i - 1; } public int back( final int n ) { int i = n; while( i-- != 0 && hasPrevious() ) previousEntry(); return n - i - 1; } } private class EntryIterator extends MapIterator implements ObjectListIterator<Double2ObjectMap.Entry <V> > { private MapEntry entry; public EntryIterator() {} public EntryIterator( double from ) { super( from ); } public MapEntry next() { return entry = new MapEntry( nextEntry() ); } public MapEntry previous() { return entry = new MapEntry( previousEntry() ); } @Override public void remove() { super.remove(); entry.index = -1; // You cannot use a deleted entry. } public void set( Double2ObjectMap.Entry <V> ok ) { throw new UnsupportedOperationException(); } public void add( Double2ObjectMap.Entry <V> ok ) { throw new UnsupportedOperationException(); } } private class FastEntryIterator extends MapIterator implements ObjectListIterator<Double2ObjectMap.Entry <V> > { final BasicEntry <V> entry = new BasicEntry <V> ( ((double)0), (null) ); public FastEntryIterator() {} public FastEntryIterator( double from ) { super( from ); } public BasicEntry <V> next() { final int e = nextEntry(); entry.key = key[ e ]; entry.value = value[ e ]; return entry; } public BasicEntry <V> previous() { final int e = previousEntry(); entry.key = key[ e ]; entry.value = value[ e ]; return entry; } public void set( Double2ObjectMap.Entry <V> ok ) { throw new UnsupportedOperationException(); } public void add( Double2ObjectMap.Entry <V> ok ) { throw new UnsupportedOperationException(); } } private final class MapEntrySet extends AbstractObjectSortedSet<Double2ObjectMap.Entry <V> > implements FastSortedEntrySet <V> { public ObjectBidirectionalIterator<Double2ObjectMap.Entry <V> > iterator() { return new EntryIterator(); } public Comparator<? super Double2ObjectMap.Entry <V> > comparator() { return null; } public ObjectSortedSet<Double2ObjectMap.Entry <V> > subSet( Double2ObjectMap.Entry <V> fromElement, Double2ObjectMap.Entry <V> toElement) { throw new UnsupportedOperationException(); } public ObjectSortedSet<Double2ObjectMap.Entry <V> > headSet( Double2ObjectMap.Entry <V> toElement ) { throw new UnsupportedOperationException(); } public ObjectSortedSet<Double2ObjectMap.Entry <V> > tailSet( Double2ObjectMap.Entry <V> fromElement ) { throw new UnsupportedOperationException(); } public Double2ObjectMap.Entry <V> first() { if ( size == 0 ) throw new NoSuchElementException(); return new MapEntry( Double2ObjectLinkedOpenHashMap.this.first ); } public Double2ObjectMap.Entry <V> last() { if ( size == 0 ) throw new NoSuchElementException(); return new MapEntry( Double2ObjectLinkedOpenHashMap.this.last ); } @SuppressWarnings("unchecked") public boolean contains( final Object o ) { if ( !( o instanceof Map.Entry ) ) return false; final Map.Entry<Double, V> e = (Map.Entry<Double, V>)o; final double k = ((e.getKey()).doubleValue()); // The starting point. int pos = (int)it.unimi.dsi.fastutil.HashCommon.murmurHash3(Double.doubleToRawLongBits(k)) & mask; // There's always an unused entry. while( used[ pos ] ) { if ( ( (key[ pos ]) == (k) ) ) return ( (value[ pos ]) == null ? ((e.getValue())) == null : (value[ pos ]).equals((e.getValue())) ); pos = ( pos + 1 ) & mask; } return false; } @SuppressWarnings("unchecked") public boolean remove( final Object o ) { if ( !( o instanceof Map.Entry ) ) return false; final Map.Entry<Double, V> e = (Map.Entry<Double, V>)o; final double k = ((e.getKey()).doubleValue()); // The starting point. int pos = (int)it.unimi.dsi.fastutil.HashCommon.murmurHash3(Double.doubleToRawLongBits(k)) & mask; // There's always an unused entry. while( used[ pos ] ) { if ( ( (key[ pos ]) == (k) ) ) { Double2ObjectLinkedOpenHashMap.this.remove( e.getKey() ); return true; } pos = ( pos + 1 ) & mask; } return false; } public int size() { return size; } public void clear() { Double2ObjectLinkedOpenHashMap.this.clear(); } public ObjectBidirectionalIterator<Double2ObjectMap.Entry <V> > iterator( final Double2ObjectMap.Entry <V> from ) { return new EntryIterator( ((from.getKey()).doubleValue()) ); } public ObjectBidirectionalIterator<Double2ObjectMap.Entry <V> > fastIterator() { return new FastEntryIterator(); } public ObjectBidirectionalIterator<Double2ObjectMap.Entry <V> > fastIterator( final Double2ObjectMap.Entry <V> from ) { return new FastEntryIterator( ((from.getKey()).doubleValue()) ); } } public FastSortedEntrySet <V> double2ObjectEntrySet() { if ( entries == null ) entries = new MapEntrySet(); return entries; } /** An iterator on keys. * * <P>We simply override the {@link java.util.ListIterator#next()}/{@link java.util.ListIterator#previous()} methods * (and possibly their type-specific counterparts) so that they return keys * instead of entries. */ private final class KeyIterator extends MapIterator implements DoubleListIterator { public KeyIterator( final double k ) { super( k ); } public double previousDouble() { return key[ previousEntry() ]; } public void set( double k ) { throw new UnsupportedOperationException(); } public void add( double k ) { throw new UnsupportedOperationException(); } public Double previous() { return (Double.valueOf(key[ previousEntry() ])); } public void set( Double ok ) { throw new UnsupportedOperationException(); } public void add( Double ok ) { throw new UnsupportedOperationException(); } public KeyIterator() { super(); } public double nextDouble() { return key[ nextEntry() ]; } public Double next() { return (Double.valueOf(key[ nextEntry() ])); } } private final class KeySet extends AbstractDoubleSortedSet { public DoubleListIterator iterator( final double from ) { return new KeyIterator( from ); } public DoubleListIterator iterator() { return new KeyIterator(); } public int size() { return size; } public boolean contains( double k ) { return containsKey( k ); } public boolean remove( double k ) { final int oldSize = size; Double2ObjectLinkedOpenHashMap.this.remove( k ); return size != oldSize; } public void clear() { Double2ObjectLinkedOpenHashMap.this.clear(); } public double firstDouble() { if ( size == 0 ) throw new NoSuchElementException(); return key[ first ]; } public double lastDouble() { if ( size == 0 ) throw new NoSuchElementException(); return key[ last ]; } public DoubleComparator comparator() { return null; } final public DoubleSortedSet tailSet( double from ) { throw new UnsupportedOperationException(); } final public DoubleSortedSet headSet( double to ) { throw new UnsupportedOperationException(); } final public DoubleSortedSet subSet( double from, double to ) { throw new UnsupportedOperationException(); } } public DoubleSortedSet keySet() { if ( keys == null ) keys = new KeySet(); return keys; } /** An iterator on values. * * <P>We simply override the {@link java.util.ListIterator#next()}/{@link java.util.ListIterator#previous()} methods * (and possibly their type-specific counterparts) so that they return values * instead of entries. */ private final class ValueIterator extends MapIterator implements ObjectListIterator <V> { public V previous() { return value[ previousEntry() ]; } public void set( V v ) { throw new UnsupportedOperationException(); } public void add( V v ) { throw new UnsupportedOperationException(); } public ValueIterator() { super(); } public V next() { return value[ nextEntry() ]; } } public ObjectCollection <V> values() { if ( values == null ) values = new AbstractObjectCollection <V>() { public ObjectIterator <V> iterator() { return new ValueIterator(); } public int size() { return size; } public boolean contains( Object v ) { return containsValue( v ); } public void clear() { Double2ObjectLinkedOpenHashMap.this.clear(); } }; return values; } /** A no-op for backward compatibility. The kind of tables implemented by * this class never need rehashing. * * <P>If you need to reduce the table size to fit exactly * this set, use {@link #trim()}. * * @return true. * @see #trim() * @deprecated A no-op. */ @Deprecated public boolean rehash() { return true; } /** Rehashes the map, making the table as small as possible. * * <P>This method rehashes the table to the smallest size satisfying the * load factor. It can be used when the set will not be changed anymore, so * to optimize access speed and size. * * <P>If the table size is already the minimum possible, this method * does nothing. * * @return true if there was enough memory to trim the map. * @see #trim(int) */ public boolean trim() { final int l = arraySize( size, f ); if ( l >= n ) return true; try { rehash( l ); } catch(OutOfMemoryError cantDoIt) { return false; } return true; } /** Rehashes this map if the table is too large. * * <P>Let <var>N</var> be the smallest table size that can hold * <code>max(n,{@link #size()})</code> entries, still satisfying the load factor. If the current * table size is smaller than or equal to <var>N</var>, this method does * nothing. Otherwise, it rehashes this map in a table of size * <var>N</var>. * * <P>This method is useful when reusing maps. {@linkplain #clear() Clearing a * map} leaves the table size untouched. If you are reusing a map * many times, you can call this method with a typical * size to avoid keeping around a very large table just * because of a few large transient maps. * * @param n the threshold for the trimming. * @return true if there was enough memory to trim the map. * @see #trim() */ public boolean trim( final int n ) { final int l = HashCommon.nextPowerOfTwo( (int)Math.ceil( n / f ) ); if ( this.n <= l ) return true; try { rehash( l ); } catch( OutOfMemoryError cantDoIt ) { return false; } return true; } /** Resizes the map. * * <P>This method implements the basic rehashing strategy, and may be * overriden by subclasses implementing different rehashing strategies (e.g., * disk-based rehashing). However, you should not override this method * unless you understand the internal workings of this class. * * @param newN the new size */ @SuppressWarnings("unchecked") protected void rehash( final int newN ) { int i = first, prev = -1, newPrev = -1, t, pos; double k; final double key[] = this.key; final V value[] = this.value; final int newMask = newN - 1; final double newKey[] = new double[ newN ]; final V newValue[] = (V[]) new Object[newN]; final boolean newUsed[] = new boolean[ newN ]; final long link[] = this.link; final long newLink[] = new long[ newN ]; first = -1; for( int j = size; j-- != 0; ) { k = key[ i ]; pos = (int)it.unimi.dsi.fastutil.HashCommon.murmurHash3(Double.doubleToRawLongBits(k)) & newMask; while ( newUsed[ pos ] ) pos = ( pos + 1 ) & newMask; newUsed[ pos ] = true; newKey[ pos ] = k; newValue[ pos ] = value[ i ]; if ( prev != -1 ) { newLink[ newPrev ] ^= ( ( newLink[ newPrev ] ^ ( pos & 0xFFFFFFFFL ) ) & 0xFFFFFFFFL ); newLink[ pos ] ^= ( ( newLink[ pos ] ^ ( ( newPrev & 0xFFFFFFFFL ) << 32 ) ) & 0xFFFFFFFF00000000L ); newPrev = pos; } else { newPrev = first = pos; // Special case of SET(newLink[ pos ], -1, -1); newLink[ pos ] = -1L; } t = i; i = (int) link[ i ]; prev = t; } n = newN; mask = newMask; maxFill = maxFill( n, f ); this.key = newKey; this.value = newValue; this.used = newUsed; this.link = newLink; this.last = newPrev; if ( newPrev != -1 ) // Special case of SET_NEXT( newLink[ newPrev ], -1 ); newLink[ newPrev ] |= -1 & 0xFFFFFFFFL; } /** Returns a deep copy of this map. * * <P>This method performs a deep copy of this hash map; the data stored in the * map, however, is not cloned. Note that this makes a difference only for object keys. * * @return a deep copy of this map. */ @SuppressWarnings("unchecked") public Double2ObjectLinkedOpenHashMap <V> clone() { Double2ObjectLinkedOpenHashMap <V> c; try { c = (Double2ObjectLinkedOpenHashMap <V>)super.clone(); } catch(CloneNotSupportedException cantHappen) { throw new InternalError(); } c.keys = null; c.values = null; c.entries = null; c.key = key.clone(); c.value = value.clone(); c.used = used.clone(); c.link = link.clone(); return c; } /** Returns a hash code for this map. * * This method overrides the generic method provided by the superclass. * Since <code>equals()</code> is not overriden, it is important * that the value returned by this method is the same value as * the one returned by the overriden method. * * @return a hash code for this map. */ public int hashCode() { int h = 0; for( int j = size, i = 0, t = 0; j-- != 0; ) { while( ! used[ i ] ) i++; t = it.unimi.dsi.fastutil.HashCommon.double2int(key[ i ]); if ( this != value[ i ] ) t ^= ( (value[ i ]) == null ? 0 : (value[ i ]).hashCode() ); h += t; i++; } return h; } private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException { final double key[] = this.key; final V value[] = this.value; final MapIterator i = new MapIterator(); s.defaultWriteObject(); for( int j = size, e; j-- != 0; ) { e = i.nextEntry(); s.writeDouble( key[ e ] ); s.writeObject( value[ e ] ); } } @SuppressWarnings("unchecked") private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException { s.defaultReadObject(); n = arraySize( size, f ); maxFill = maxFill( n, f ); mask = n - 1; final double key[] = this.key = new double[ n ]; final V value[] = this.value = (V[]) new Object[ n ]; final boolean used[] = this.used = new boolean[ n ]; final long link[] = this.link = new long[ n ]; int prev = -1; first = last = -1; double k; V v; for( int i = size, pos = 0; i-- != 0; ) { k = s.readDouble(); v = (V) s.readObject(); pos = (int)it.unimi.dsi.fastutil.HashCommon.murmurHash3(Double.doubleToRawLongBits(k)) & mask; while ( used[ pos ] ) pos = ( pos + 1 ) & mask; used[ pos ] = true; key[ pos ] = k; value[ pos ] = v; if ( first != -1 ) { link[ prev ] ^= ( ( link[ prev ] ^ ( pos & 0xFFFFFFFFL ) ) & 0xFFFFFFFFL ); link[ pos ] ^= ( ( link[ pos ] ^ ( ( prev & 0xFFFFFFFFL ) << 32 ) ) & 0xFFFFFFFF00000000L ); prev = pos; } else { prev = first = pos; // Special case of SET_PREV( newLink[ pos ], -1 ); link[ pos ] |= (-1L & 0xFFFFFFFFL) << 32; } } last = prev; if ( prev != -1 ) // Special case of SET_NEXT( link[ prev ], -1 ); link[ prev ] |= -1 & 0xFFFFFFFFL; if ( ASSERTS ) checkTable(); } private void checkTable() {} }
apache-2.0
liangdas/mqantserver
bin/chat/js/client.js
7274
var mqant=window.mqant var username; var users; var roomName; var base = 1000; var increase = 25; var reg = /^[a-zA-Z0-9_\u4e00-\u9fa5]+$/; var LOGIN_ERROR = "There is no server to log in, please wait."; var LENGTH_ERROR = "Name/Channel is too long or too short. 20 character max."; var NAME_ERROR = "Bad character in Name/Channel. Can only have letters, numbers, Chinese characters, and '_'"; var DUPLICATE_ERROR = "Please change your name to login."; util = { urlRE: /https?:\/\/([-\w\.]+)+(:\d+)?(\/([^\s]*(\?\S+)?)?)?/g, // html sanitizer toStaticHTML: function(inputHtml) { inputHtml = inputHtml.toString(); return inputHtml.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;"); }, //pads n with zeros on the left, //digits is minimum length of output //zeroPad(3, 5); returns "005" //zeroPad(2, 500); returns "500" zeroPad: function(digits, n) { n = n.toString(); while(n.length < digits) n = '0' + n; return n; }, //it is almost 8 o'clock PM here //timeString(new Date); returns "19:49" timeString: function(date) { var minutes = date.getMinutes().toString(); var hours = date.getHours().toString(); return this.zeroPad(2, hours) + ":" + this.zeroPad(2, minutes); }, //does the argument only contain whitespace? isBlank: function(text) { var blank = /^\s*$/; return(text.match(blank) !== null); } }; //always view the most recent message when it is added function scrollDown(base) { window.scrollTo(0, base); $("#entry").focus(); }; // add message on board function addMessage(from, target, text, time) { var name = (target == '*' ? 'all' : target); if(text === null) return; if(time == null) { // if the time is null or undefined, use the current time. time = new Date(); } else if((time instanceof Date) === false) { // if it's a timestamp, interpret it time = new Date(time); } //every message you see is actually a table with 3 cols: // the time, // the person who caused the event, // and the content var messageElement = $(document.createElement("table")); messageElement.addClass("message"); // sanitize text = util.toStaticHTML(text); var content = '<tr>' + ' <td class="date">' + util.timeString(time) + '</td>' + ' <td class="nick">【' + util.toStaticHTML(from) + '】 --》 【' + name + '】: ' + '</td>' + ' <td class="msg-text">' + text + '</td>' + '</tr>'; messageElement.html(content); //the log is the stream that we view $("#chatHistory").append(messageElement); base += increase; scrollDown(base); }; // show tip function tip(type, name) { var tip,title; switch(type){ case 'online': tip = name + ' is online now.'; title = 'Online Notify'; break; case 'offline': tip = name + ' is offline now.'; title = 'Offline Notify'; break; case 'message': tip = name + ' is saying now.' title = 'Message Notify'; break; } var pop=new Pop(title, tip); }; // init user list function initUserList(data) { users = data.users; for(var i = 0; i < users.length; i++) { var slElement = $(document.createElement("option")); slElement.attr("value", users[i]); slElement.text(users[i]); $("#usersList").append(slElement); } }; // add user in user list function addUser(user) { var slElement = $(document.createElement("option")); slElement.attr("value", user); slElement.text(user); $("#usersList").append(slElement); }; // remove user from user list function removeUser(user) { $("#usersList option").each( function() { if($(this).val() === user) $(this).remove(); }); }; // set your name function setName() { $("#name").text(username); }; // set your room function setRoom() { $("#room").text(roomName); }; // show error function showError(content) { $("#loginError").text(content); $("#loginError").show(); }; // show login panel function showLogin() { $("#loginView").show(); $("#chatHistory").hide(); $("#toolbar").hide(); $("#loginError").hide(); $("#loginUser").focus(); }; // show chat panel function showChat() { $("#loginView").hide(); $("#loginError").hide(); $("#toolbar").show(); $("entry").focus(); scrollDown(base); }; $(document).ready(function() { //when first time into chat room. showLogin(); //wait message from the server. mqant.on('Chat/OnChat', function(data) { var message=JSON.parse(data.payloadString) addMessage(message.from, message.target, message.msg); $("#chatHistory").show(); if(message.from !== username) tip('message', message.from); }); //update user list mqant.on('Chat/OnJoin', function(data) { var message=JSON.parse(data.payloadString) var user = message.user; tip('online', user); addUser(user); }); //update user list mqant.on('Chat/OnLeave', function(data) { var message=JSON.parse(data.payloadString) var user = message.user; tip('offline', user); removeUser(user); }); //handle disconect message, occours when the client is disconnect with servers //deal with login button click. $("#login").click(function() { username = $("#loginUser").attr("value"); roomName = $('#channelList').val(); if(username.length > 20 || username.length == 0 || roomName.length > 20 || roomName.length == 0) { showError(LENGTH_ERROR); return false; } if(!reg.test(username) || !reg.test(roomName)) { showError(NAME_ERROR); return false; } var useSSL = 'https:' == document.location.protocol ? true :false ; mqant.init({ host: window.location.hostname, port: 3653, client_id: "111", useSSL:useSSL, onSuccess:function() { console.log("onConnected"); var topic = "Login/HD_Login"; mqant.request(topic, { "userName": username, "passWord": "Hello,anyone!" }, function(data) { var message=JSON.parse(data.payloadString) if(message.Error!="") { showError(message.Error); return; } mqant.request("Chat/HD_JoinChat",{ "roomName": roomName }, function(data) { var message=JSON.parse(data.payloadString) if(message.Error!="") { showError(message.Error); return; } setName(); setRoom(); showChat(); initUserList(message.Result); }); }); }, onConnectionLost:function(reason) { showLogin(); } }); }); //deal with chat mode. $("#entry").keypress(function(e) { var topic = "Chat/HD_Say"; var target = $("#usersList").val(); if(e.keyCode != 13 /* Return */ ) return; var msg = $("#entry").attr("value").replace("\n", ""); if(!util.isBlank(msg)) { mqant.request(topic, { roomName: roomName, content: msg, from: username, target: target }, function(data) { var message=JSON.parse(data.payloadString) $("#entry").attr("value", ""); // clear the entry field. if(target != '*' && target != username) { if(message.Error!="") { addMessage(username, target,msg +" error ("+message.Error+")"); }else{ addMessage(username, target, msg); } $("#chatHistory").show(); } }); } }); });
apache-2.0
zibhub/GNDMS
neomodel/src/de/zib/gndms/neomodel/common/Session.java
6259
package de.zib.gndms.neomodel.common; /* * Copyright 2008-2010 Zuse Institute Berlin (ZIB) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import de.zib.gndms.model.gorfx.types.TaskState; import de.zib.gndms.neomodel.gorfx.Task; import de.zib.gndms.neomodel.gorfx.TaskFlowType; import org.apache.lucene.search.NumericRangeQuery; import org.jetbrains.annotations.NotNull; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.PropertyContainer; import org.neo4j.graphdb.Transaction; import org.neo4j.graphdb.index.Index; import org.neo4j.graphdb.index.IndexHits; import java.util.Calendar; import java.util.LinkedList; import java.util.List; /** * Session * * @author try ste fan pla nti kow zib * @version $Id$ * * User: stepn Date: 05.09.2008 Time: 14:48:36 */ public class Session { private static final String OFFER_TYPE_T = classNickName(TaskFlowType.class); private static final String TASK_T = classNickName(Task.class); private final @NotNull GraphDatabaseService gdb; private final @NotNull Transaction tx; private final @NotNull String gridName; private final @NotNull ReprSession reprSession; private ClassLoader classLoader; public Session(@NotNull Dao dao, @NotNull String gridName, @NotNull GraphDatabaseService gdb) { this.gdb = gdb; this.tx = gdb.beginTx(); this.gridName = gridName; this.reprSession = new ReprSession(dao, this); } public TaskFlowType createTaskFlowType() { final Node node = gdb.createNode(); final TaskFlowType offerType = new TaskFlowType(reprSession, OFFER_TYPE_T, node); offerType.onCreate(reprSession); return offerType; } public TaskFlowType findTaskFlowType( @NotNull String offerTypeId ) { final Node node = getTypeIndex(OFFER_TYPE_T).get(gridName, offerTypeId).getSingle(); if( node != null ) return new TaskFlowType(reprSession, OFFER_TYPE_T, node ); else return null; } public Task createTask() { final Node node = gdb.createNode(); final Task task = taskFromNode( node ); task.onCreate(reprSession); return task; } public Task findTask(@NotNull String taskId) { return taskFromNode( getTypeIndex(TASK_T).get(gridName, taskId).getSingle() ); } private Task taskFromNode( Node node ) { if( node != null ) return createTask( node, TASK_T ); else return null; } protected Task createTask( final Node node, final String type ) { final Task task = new Task( reprSession, type, node ); task.setClassLoader( classLoader ); return task; } public Task findTaskForResource ( @NotNull String resourceId ) { Index<Node> idx = getTypeIndex( typeIndexNickName( TASK_T, Task.RESOURCE_ID_IDX ) ); return taskFromNode( idx.get( gridName, resourceId ).getSingle() ); } public Iterable<Task> listTasksByState(@NotNull TaskState state) { final Index<Node> index = gdb.index().forNodes(typeIndexNickName(TASK_T, Task.TASK_STATE_IDX)); final IndexHits<Node> query = index.get(getGridName(), state.name()); final List<Task> list = new LinkedList<Task>(); for (Node node: query) list.add( createTask( node, getGridName() ) ); return list; } public Iterable<Task> listTasks() { final Index<Node> index = gdb.index().forNodes(ModelNode.TYPE_INDEX_IDX); final IndexHits<Node> query = index.get(getGridName(), classNickName(Task.class)); final List<Task> list = new LinkedList<Task>(); for (Node node: query) list.add( createTask( node, getGridName() ) ); return list; } @SuppressWarnings({"UnnecessaryLocalVariable"}) public Iterable<Task> listTasksDeadBeforeTimeout(@NotNull Calendar timeout) { final Index<Node> index = gdb.index().forNodes(typeIndexNickName(TASK_T, Task.TERMINATION_TIME_IDX)); final IndexHits<Node> query = index.query(NumericRangeQuery.newLongRange(getGridName(), 0L, timeout.getTimeInMillis(), true, false)); final List<Task> list = new LinkedList<Task>(); for (Node node: query) list.add( createTask( node, getGridName() ) ); return list; } protected Index<Node> getTypeIndex(@NotNull String indexName) { return gdb.index().forNodes(indexName); } @NotNull public String getGridName() { return gridName; } public void failure() { tx.failure(); } public void success() { tx.success(); } public void finish() { tx.finish(); } @NotNull protected static String classNickName(Class c) { return c.getSimpleName(); } @NotNull protected static String typeIndexNickName(String typeNick, String... names) { return ModelElement.getTypeNickIndexName(typeNick, names); } public <U extends PropertyContainer> void setSingleIndex(@NotNull Index<U> index, @NotNull U repr, String key, String oldVal, String newVal) { if (oldVal != null) index.remove(repr, key, oldVal); if (index.get(key, newVal).size() > 0) { this.failure(); throw new IllegalArgumentException("Graph element already exists"); } index.add(repr, key, newVal); } public void setClassLoader( final ClassLoader classLoader ) { this.classLoader = classLoader; } public ClassLoader getClassLoader() { return classLoader; } }
apache-2.0
caseykramer/libphonenumber-csharp
csharp/PhoneNumbers/Properties/AssemblyInfo.cs
590
// <auto-generated/> using System.Reflection; [assembly: AssemblyTitleAttribute("PhoneNumbers")] [assembly: AssemblyDescriptionAttribute("Google's libphonenumber")] [assembly: AssemblyProductAttribute("PhoneNumbers")] [assembly: AssemblyCopyrightAttribute("Copyright © 2015-2016 Google")] [assembly: AssemblyVersionAttribute("7.6.2.0")] [assembly: AssemblyFileVersionAttribute("7.6.2.0")] [assembly: AssemblyKeyFileAttribute("key.snk")] namespace System { internal static class AssemblyVersionInformation { internal const string Version = "7.6.2.0"; } }
apache-2.0
korfuri/goref
testprograms/interfaces/lib/lib.go
965
// Package lib contains interfaces and types that implement them. It // is very similar to package main, whose interfaces its types also // implements. package lib // IfaceLibA is a simple test interface. type IfaceLibA interface { A() } // IfaceLibB is a simple test interface. type IfaceLibB interface { B() } // IfaceLibAB is a simple test interface that extends IfaceLibA and // IfaceLibB. type IfaceLibAB interface { A() B() } // LibA implements IfaceLibA type LibA int // libB implements IfaceLibB, and is unexported type libB int // LibC doesn't implement anything from this package but implements // the unexported main.ifaceC. type LibC int // LibAB implements IfaceLibAB type LibAB int // A implements IfaceLibA func (a LibA) A() {} // B implements IfaceLibB func (b libB) B() {} // C is just a member functions of LibC func (c LibC) C() {} // A implements IfaceLibA func (ab LibAB) A() {} // B implements IfaceLibB func (ab LibAB) B() {}
apache-2.0
reportportal/service-api
src/main/java/com/epam/ta/reportportal/core/analyzer/auto/client/model/cluster/ClusterData.java
1313
/* * Copyright 2021 EPAM Systems * * 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. */ package com.epam.ta.reportportal.core.analyzer.auto.client.model.cluster; import java.util.List; /** * @author <a href="mailto:ivan_budayeu@epam.com">Ivan Budayeu</a> */ public class ClusterData { private Long project; private Long launchId; private List<ClusterInfoRs> clusters; public ClusterData() { } public Long getProject() { return project; } public void setProject(Long project) { this.project = project; } public Long getLaunchId() { return launchId; } public void setLaunchId(Long launchId) { this.launchId = launchId; } public List<ClusterInfoRs> getClusters() { return clusters; } public void setClusters(List<ClusterInfoRs> clusters) { this.clusters = clusters; } }
apache-2.0
ewill15/usfx
vista/login/nuevo_usuario_admin.html.php
7313
<div style="width: 40%; margin: 4% 0px 0px 33%;"> <h2 class="title">Registrar nuevo usuario</h2> </div> <div class="post"> <div class="entry"> <form id="registrar" class="nuevo" action="control/index.php" method="post"> <div> <label class="required" style="width: 25%">Nombre </label> <input id="nombre" name="nombre" type="text"/> <span class="required" style="left:7.5em;position:absolute;">&nbsp;&nbsp;</span> </div> <div> <label style="width: 25%">Apellido</label> <input id="apellido" name="apellido" type="text"/> <span class="required"style="left:7.5em;position:absolute;">&nbsp;&nbsp;</span> </div> <div> <label style="width: 25%">Area </label> <select id="area" name="area" class="required"> <option value="">[ Seleccione area ]</option> <option value="10">Administraci&oacute;n</option> <option value="1">Certificaci&oacute;n</option> <option value="2">Fiscalizaci&oacute;n</option> <option value="3">Laboratorio</option> </select> <span class="required"style="left:7.5em;position:absolute;">&nbsp;&nbsp;</span> </div> <div> <label style="width: 25%">Usuario </label> <input id="login" name="login" type="text"/> <span class="required" style="left:7.5em;position:absolute;">&nbsp;&nbsp;</span> <span class="checked"></span> </div> <div> <label style="width: 25%">Generar contrase&ntilde;a</label> <input id="generar" class="genpass input-not-edit" name="generar" type="text" readonly="true"/> <!--<input type="button" name="submit" value="Generar" class="button-generar ui-state-default ui-corner-all" id="generarbutton" style="position: absolute; left: 50%; top: 45.7%;">--> <button id="generar-pass" class="btn btn-success"> <span class="glyphicon glyphicon-cog"></span> Generar </button> </div> <div> <label style="width: 25%">Contrase&ntilde;a </label> <input type="password" name="pass" id="pass" style="height: 45%;"> <span class="required" style="left:7.5em;position:absolute;">&nbsp;&nbsp;</span> </div> <div style="margin-top: 2em"> <label style="width: 25%">Repita Contrase&ntilde;a</label> <input id="pass2" name="pass2" type="password"/> </div> <input type="hidden" id="usuario" name="usuario" value="<?php echo $_SESSION['usr_nivel']?>"/> <div style="margin-left: 65%"> <button id="enviar-usuario" class="btn btn-success"> <span class="glyphicon glyphicon-user"></span> Registrar </button> </div> <div style="float: left; width: 60%;"> <span class="required">&nbsp;&nbsp;</span>Los campos son obligatorios </div> <div>&nbsp;</div> </form> <?php include '../vista/error/errores.php'; include '../vista/confirmacion/confirmar.html'; ?> </div> </div> <script type="text/javascript"> $(document).ready(function() { $("#area").selectmenu(); $("#errores").css({ "padding" : "0 .7em", "width" : "35em" }); $('<span></span>').insertBefore('.mensaje').css({ 'float' : 'left', 'margin-right' : '.3em', 'margin-top' : '0.5em' }).addClass("ui-icon ui-icon-alert"); $("#generar-pass").on("click",function(event){ event.preventDefault(); $.funciones.generarPass('generar'); $() }); $("#registrar").validar(); $("#registrar").registrar(); }) </script> <!-- Validacion y envio de datos--> <script type="text/javascript"> $(document).ready(function() { $(".password").after("<div><span class='avisoA' >(Debe ser m&iacute;nimo 6 caracteres)</span></div>"); // verificar disponibilidad del nombre de usuario $("#login").blur(function() { $.funciones.verificarDisponibilidad('login'); }); $("input[name=submit1]").click(function() { $("#registrar").submit(); }); $("#registrar").ajaxForm({ url : 'control/index.php?mdl=usuario&pag=registrar', type : 'post', resetForm : true, beforeSubmit : showRequest, success : showResponse }); function showRequest(formData, jqForm, options) { var mensaje = ''; var form = jqForm[0]; if (!form.nombre.value || form.nombre.length < 3) { mensaje += '<div>- Nombre inv&aacute;lido</div>'; $("#nombre").css({ backgroundColor : "#f5c9c9" }); } else { $("#nombre").css({ backgroundColor : "" }); } if (!form.apellido.value || form.apellido.length < 3) { mensaje += '<div>- Apellido inv&aacute;lido</div>'; $("#apellido").css({ backgroundColor : "#f5c9c9" }); } else { $("#apellido").css({ backgroundColor : "" }); } if (!form.area.value) { mensaje += '<div>- Area inv&aacute;lido</div>'; $("#area").css({ backgroundColor : "#f5c9c9" }); } else { $("#area").css({ backgroundColor : "" }); } if (!form.login.value || form.login.length < 5) { mensaje += '<div>- Nombre de usuario inv&aacute;lido </div>'; $("#login").css({ backgroundColor : "#f5c9c9" }); } else { $("#login").css({ backgroundColor : "" }); } if (!form.pass.value || form.pass.length <= 6) { mensaje += '<div >- Contrase&ntilde;a inv&aacute;lida(Debe tener por lo menos 6 caracteres)</div>'; $("#pass").css({ backgroundColor : "#f5c9c9" }); } else { $("#pass").css({ backgroundColor : "" }); } if (!form.pass2.value || form.pass2.length <= 6) { mensaje += '<div>- La contrase&ntilde;a es invalida</div>'; $("#pass2").css({ backgroundColor : "#f5c9c9" }); } else { $("#pass2").css({ backgroundColor : "" }); } if (form.pass.value != form.pass2.value) { mensaje += '<div>- Las contrase&ntilde;as son diferentes</div>'; $("#pass2").css({ backgroundColor : "#f5c9c9" }); } else { $("#pass2").css({ backgroundColor : "" }); } if (mensaje != '') { $("#errores div p .mensaje").empty().append('Se han detectado los siguientes errores: <br>' + mensaje); $("#errores").css('margin-top', '4em').fadeIn('slow'); return false; } else { $("#errores").fadeOut('slow'); return true; } } function showResponse(responseText, statusText, xhr, $form) { switch (responseText) { case 'error','': $(".checked").empty(); $("#dialog:ui-dialog").dialog("destroy"); $(".ui-icon").addClass(" ui-icon-alert").after(statusText); $("#dialog-message").attr('title', 'Informacion').fadeIn(); $("#dialog-message").dialog({ dialogClass: "no-close", modal : true, resizable : false, buttons : { Ok : function() { $(this).dialog("close"); } } }); break; case 'OK': $(".checked").empty(); $("#dialog:ui-dialog").dialog("destroy"); $("#ui-icon").addClass("ui-icon-info").empty().after("Registro exitoso!!!"); $("#dialog-message").attr('title', 'Informacion'); $("#dialog-message").dialog({ dialogClass: "no-close", modal : true, resizable : false, buttons : { Ok : function() { $(this).dialog("close"); } } }); setTimeout($.funciones.recargarVerDatosAdmin('login', 'listar'), 10000); break; } } }); </script>
apache-2.0
badlogicmanpreet/aura
aura-integration-test/src/test/java/org/auraframework/integration/test/security/CSRFTokenValidationHttpTest.java
6517
/* * Copyright (C) 2013 salesforce.com, inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.auraframework.integration.test.security; import java.util.HashMap; import java.util.Map; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.methods.HttpPost; import org.apache.http.util.EntityUtils; import org.auraframework.Aura; import org.auraframework.http.AuraBaseServlet; import org.auraframework.test.util.AuraHttpTestCase; import org.auraframework.util.json.JsFunction; import org.auraframework.util.json.Json; import org.auraframework.util.json.JsonEncoder; import org.auraframework.util.json.JsonReader; import org.auraframework.util.test.annotation.AuraTestLabels; /** * This test verifies that the aura servlet checks for CSRF token before * servicing any requests. All requests to aura are posted to /aura and handled * by the AuraServlet. A CSRF token is generated with the very first request and * sent back to the Client. Every subsequent request from the client has the * CSRF token embedded as a request parameter. * * @hierarchy Aura.Security * @priority high * @userStory a07B0000000DV9S */ public class CSRFTokenValidationHttpTest extends AuraHttpTestCase { public CSRFTokenValidationHttpTest(String name) { super(name); } private Map<String, String> makeBasePostParams() { Map<String, Object> message = new HashMap<>(); Map<String, Object> actionInstance = new HashMap<>(); actionInstance.put("descriptor", "java://org.auraframework.components.test.java.controller.JavaTestController/ACTION$getString"); Map<String, Object> actionParams = new HashMap<>(); actionParams.put("param", "some string"); actionInstance.put("params", actionParams); Map<?, ?>[] actions = { actionInstance }; message.put("actions", actions); String jsonMessage = JsonEncoder.serialize(message); Map<String, String> params = new HashMap<>(); params.put("message", jsonMessage); return params; } /** * Test to post a request to aura servlet without a CSRF token. This test * tries to request a action defined on a controller. But the request does * not have a valid CSRF token, hence the request should fail to fetch the * def. */ @SuppressWarnings("unchecked") @AuraTestLabels("auraSanity") public void testVerifyPostWithoutToken() throws Exception { Map<String, String> params = makeBasePostParams(); params.put("aura.context", String.format("{\"mode\":\"FTEST\",\"fwuid\":\"%s\"}", Aura.getConfigAdapter().getAuraFrameworkNonce())); HttpPost post = obtainPostMethod("/aura", params); HttpResponse httpResponse = perform(post); int statusCode = getStatusCode(httpResponse); String response = getResponseBody(httpResponse); post.releaseConnection(); assertNotNull(response); if (statusCode != HttpStatus.SC_OK || !response.endsWith("/*ERROR*/")) { fail("Should not be able to post to aura servlet without a valid CSRF token"); } if (response.startsWith(AuraBaseServlet.CSRF_PROTECT)) { response = "/*" + response; } Map<String, Object> json = (Map<String, Object>) new JsonReader().read(response); assertEquals(true, json.get("exceptionEvent")); Map<String, Object> event = (Map<String, Object>) json.get("event"); assertEquals("Expected to see a aura:systemError event", "markup://aura:systemError", event.get("descriptor")); assertEquals("Missing parameter value for aura.token", ((Map<String, Object>) ((Map<String, Object>) ((Map<String, Object>) (event.get("attributes"))) .get(Json.ApplicationKey.VALUE.toString())).get("values")).get("message")); Object f = json.get("defaultHandler"); assertEquals(JsFunction.class, f.getClass()); assertEquals("throw new $A.auraError('unknown error');", ((JsFunction) f).getBody()); } /** * Test to post a request to aura servlet with an invalid CSRF token. This * test tries to request a action defined on a controller. But the request * does not have a valid CSRF token, hence the request should fail to fetch * the def. */ // W-1064983 - NO CSRF validation currently public void _testVerifyPostWithInvalidToken() throws Exception { Map<String, String> params = makeBasePostParams(); // Invalid token params.put("aura.token", "invalid"); params.put("aura.context", "{\"mode\":\"FTEST\"}"); HttpPost post = obtainPostMethod("/aura", params); HttpResponse httpResponse = perform(post); int statusCode = getStatusCode(httpResponse); EntityUtils.consume(httpResponse.getEntity()); post.releaseConnection(); if (statusCode != HttpStatus.SC_NOT_FOUND) { fail("Should not be able to post to aura servlet with an invalid CSRF token"); } } /** * Test to post a request to aura servlet with a valid CSRF token. This test * tries to request an action defined on a controller. */ @AuraTestLabels("auraSanity") public void testVerifyPostWithValidToken() throws Exception { Map<String, String> params = makeBasePostParams(); // Valid token params.put("aura.token", getCsrfToken()); params.put("aura.context", String.format("{\"mode\":\"FTEST\",\"fwuid\":\"%s\"}", Aura.getConfigAdapter().getAuraFrameworkNonce())); HttpPost post = obtainPostMethod("/aura", params); HttpResponse httpResponse = perform(post); int statusCode = getStatusCode(httpResponse); EntityUtils.consume(httpResponse.getEntity()); post.releaseConnection(); assertEquals("Failed to post to aura servlet", HttpStatus.SC_OK, statusCode); } }
apache-2.0
DeeJaVu/tvstreamscript
includes/show.class.php
86683
<?php class Show{ public $episode_schema = array("show_id","season","episode","title","description","date_added","thumbnail","views","checked"); public $embed_schema = array("episode_id","embed","link","lang","weight"); public $show_schema = array("title","description","thumbnail","permalink","sidereel_url","imdb_id","type","featured","imdb_rating","meta"); public function __construct(){ } public function getList($page = null, $start=null, $limit=null, $sortby="id", $sortdir="DESC", $search_term = null){ if (!$limit){ $limit = 50; } $sortby = mysql_real_escape_string($sortby); $sortdir = mysql_real_escape_string($sortdir); $limit = mysql_real_escape_string($limit); if ($page){ $page = mysql_real_escape_string($page); $start = ($page-1)*$limit; $limit = "LIMIT $start,$limit"; } elseif ($start) { $start = mysql_real_escape_string($start); $limit = "LIMIT $start,$limit"; } else { $limit = "LIMIT $limit"; } if ($search_term){ $search_term = " WHERE title LIKE '%".mysql_real_escape_string($search_term)."%'"; } else { $search_term = ""; } $e = mysql_query("SELECT * FROM shows $search_term ORDER BY $sortby $sortdir $limit") or die(mysql_error()); $shows = array(); $ids = array(); if (mysql_num_rows($e)){ while($s = mysql_fetch_assoc($e)){ extract($s); $shows[$id]=$s; $shows[$id]['title'] = json_decode($shows[$id]['title'],true); $shows[$id]['description'] = json_decode($shows[$id]['description'],true); $shows[$id]['episode_count'] = 0; $ids[] = $id; } $e = mysql_query("SELECT count(*) as episode_count, show_id FROM episodes WHERE show_id IN (".implode(",",$ids).") GROUP BY show_id") or die(mysql_error()); if (mysql_num_rows($e)){ while($s = mysql_fetch_assoc($e)){ $shows[$s['show_id']]['episode_count'] = $s['episode_count']; } } } return $shows; } /* Returns all the possible embed languages from the database */ public function getEmbedLanguages(){ if (isset($_SESSION['embed_languages'])){ return $_SESSION['embed_languages']; } else { $res = array(); $e = mysql_query("SELECT DISTINCT lang FROM embeds") or die(mysql_error()); if (mysql_num_rows($e)){ while($s = mysql_fetch_assoc($e)){ $res[] = $s['lang']; } } $_SESSION['embed_languages'] = $res; return $res; } } /* Gets $limit similar show to $show_id */ public function getSimilar($show_id, $limit, $lang=false){ $show_id = mysql_real_escape_string($show_id); $res = array(); $query = "SELECT shows.* FROM shows, similar_shows WHERE similar_shows.show1 = '$show_id' AND similar_shows.show2 = shows.id ORDER BY score DESC LIMIT $limit"; $e = mysql_query($query) or die(mysql_error()); if (mysql_num_rows($e)){ while($s = mysql_fetch_assoc($e)){ $res[$s['id']] = $this->formatShowData($s, false, $lang); } } return $res; } /* Returns the newest episodes, don't care about if it has embed or not */ public function getNewestEpisodes($date_from,$limit=20){ $date_from = date("Y-m-d",strtotime($date_from)); $res = array(); $e = mysql_query("SELECT episodes.id, episodes.season, episodes.episode, episodes.thumbnail, shows.title, shows.permalink FROM episodes,shows WHERE shows.id = episodes.show_id AND episodes.date_added>='$date_from' ORDER BY id DESC LIMIT $limit") or die(mysql_error()); if (mysql_num_rows($e)){ while($s = mysql_fetch_assoc($e)){ $res[$s['id']] = $s; } } return $res; } /* Method to add an embed code to an episode, doesn't add it if it's already there */ public function addEmbed($episode_id, $embed, $lang='ENG', $link='', $weight=0){ $episode_id = mysql_real_escape_string($episode_id); $embed = mysql_real_escape_string(stripslashes(stripslashes(urldecode($embed)))); $link = mysql_real_escape_string($link); $weight = mysql_real_escape_string($weight); $check = mysql_query("SELECT * FROM embeds WHERE embed='$embed' AND episode_id='$episode_id'") or die(mysql_error()); if (mysql_num_rows($check)==0){ $insert = mysql_query("INSERT INTO embeds(episode_id,embed,link,lang,weight) VALUES('$episode_id','$embed','$link','$lang','$weight')") or die(mysql_error()); return mysql_insert_id(); } else { return false; } } /* Removes all embeds of an episode */ public function deleteAllEmbeds($episode_id){ $episode_id = mysql_real_escape_string($episode_id); $del = mysql_query("DELETE FROM embeds WHERE episode_id='$episode_id'") or die(mysql_error()); } /* Removes an embed from an episode */ public function deleteEmbed($episode_id, $embed_id){ $embed_id = mysql_real_escape_string($embed_id); $episode_id = mysql_real_escape_string($episode_id); $e = mysql_query("DELETE FROM embeds WHERE episode_id='$episode_id' AND id='$embed_id'") or die(mysql_error()); } /* Updates the thumbnail for the episode */ public function updateEpisodeThumbnail($episode_id,$thumb_file){ $episode_id = mysql_real_escape_string($episode_id); $thumb_file = mysql_real_escape_string($thumb_file); $up = mysql_query("UPDATE episodes SET thumbnail='$thumb_file' WHERE id='$episode_id'") or die(mysql_error()); } /* Updates the show and the episode date */ public function setEpisodeDate($episode_id,$show_id){ $episode_id = (int) $episode_id; $show_id = (int) $show_id; $up = mysql_query("UPDATE episodes SET date_added=NOW() WHERE id='$episode_id'"); $up = mysql_query("UPDATE shows SET last_episode=NOW() WHERE id='$show_id'"); } /* List shows based on views */ public function getPopularShows($lang=false, $limit = 20){ $limit = (int) $limit; $e = mysql_query("SELECT shows.title AS showtitle, show_id AS showid, shows.thumbnail, SUM( `views` ) AS views FROM episodes, shows WHERE shows.id = episodes.show_id GROUP BY `show_id` ORDER BY SUM(`views`) desc LIMIT $limit") or die(mysql_error()); $topshows = array(); if (mysql_num_rows($e)){ while($s = mysql_fetch_array($e)){ extract($s); $topshows[$showid] = array(); $topshows[$showid]['views'] = $views; $topshows[$showid]['thumbnail'] = $thumbnail; if (!$lang){ $topshows[$showid]['showtitle'] = json_decode($showtitle,true); } else { $topshows[$showid]['showtitle'] = json_decode($showtitle,true); $topshows[$showid]['showtitle'] = $topshows[$showid]['showtitle'][$lang]; } } } return $topshows; } /* Updates an embed code */ public function updateEmbedCode($episode_id, $embed_id, $embed_code){ $embed_id = mysql_real_escape_string($embed_id); $episode_id = mysql_real_escape_string($episode_id); $embed_code = mysql_real_escape_string(stripslashes(stripslashes(urldecode($embed_code)))); $e = mysql_query("UPDATE embeds SET embed='$embed_code' WHERE episode_id='$episode_id' AND id='$embed_id'") or die(mysql_error()); } /* Returns a string representation of the embed's provider */ public function getEmbedType($embed, $link = false){ global $basepath; include($basepath."/includes/filehost.list.php"); $embed = strtolower(stripslashes(stripslashes(urldecode($embed)))); foreach($filehosts as $match => $filehost_name){ if (substr_count($embed,$match)){ return $filehost_name; } } if ($link){ $url_parts = parse_url($link); if (isset($url_parts['host']) && $url_parts['host']){ if (strpos($url_parts['host'],"www.") === 0){ $url_parts['host'] = substr($url_parts['host'],4); } return $url_parts['host']; } else { return ""; } } else { return ""; } } /* Returns all the embeds for the given episode id */ public function getEpisodeEmbeds($epid){ $embeds = array(); $counter = 0; $e = mysql_query("SELECT * FROM embeds WHERE episode_id=$epid ORDER BY weight DESC") or die(mysql_error()); if (mysql_num_rows($e)){ while($s = mysql_fetch_array($e)){ extract($s); if ($embed){ $embeds[$counter]['type'] = $this->getEmbedType($embed, $link); $embeds[$counter]['embed']=stripslashes(stripslashes(urldecode($embed))); $embeds[$counter]['link'] = $link; $embeds[$counter]['id']=$id; $embeds[$counter]['lang'] = $lang; $embeds[$counter]['weight'] = $weight; $counter++; } } } return $embeds; } /* Returnss the list of episodes which hasn't been submitted to a given submit target */ public function getUnsubmitted($type){ $e = mysql_query("SELECT episode_id FROM tv_submits WHERE `type`=$type") or die(mysql_error()); if (mysql_num_rows($e)){ $tmp = array(); while($s = mysql_fetch_array($e)){ extract($s); $tmp[]=$episode_id; } $add = " AND episodes.id NOT IN (".implode(",",$tmp).")"; } else { $add = ""; } $e = mysql_query("SELECT episodes.id,episodes.season,episodes.episode,episodes.title,episodes.description,shows.title as showtitle,shows.permalink,shows.sidereel_url FROM episodes,shows WHERE shows.id=episodes.show_id $add") or die(mysql_error()); $episodes = array(); if (mysql_num_rows($e)){ while($s = mysql_fetch_assoc($e)){ extract($s); $episodes[$id]=$s; } } return $episodes; } /* Get 3 dimensional array of the existing episodes from the database */ public function getExistingEpisodes($showid){ $e = mysql_query("SELECT season,episode FROM episodes WHERE show_id=$showid") or die(mysql_error()); $eps = array(); if (mysql_num_rows($e)){ while($s = mysql_fetch_array($e)){ extract($s); if (!array_key_exists($season,$eps)) $eps[$season]=array(); $eps[$season][]=$episode; } } return $eps; } /* Returns a list of shows organized by ABC */ public function getAlphabet($lang=false){ $e = mysql_query("SELECT SUBSTRING(LOWER(`shows`.`title`),1,1) as `letter` FROM shows,episodes WHERE `shows`.`id`=`episodes`.`show_id` AND `shows`.`type`=1 GROUP BY `letter` ORDER BY letter"); $alphabet = array(); if (mysql_num_rows($e)>0){ while($s=mysql_fetch_array($e)){ extract($s); $alphabet[$letter]=array(); $shows = mysql_query("SELECT id,permalink,thumbnail,title,description FROM shows WHERE type=1 AND LOWER(`title`) LIKE '$letter%'") or die(mysql_error()); if (mysql_num_rows($shows)){ while($sh=mysql_fetch_array($shows)){ extract($sh); $alphabet[$letter][$id]=array(); $alphabet[$letter][$id]['perma'] = $permalink; $alphabet[$letter][$id]['thumbnail'] = $thumbnail; if ($lang){ $alphabet[$letter][$id]['title'] = json_decode($title, true); $alphabet[$letter][$id]['title'] = $alphabet[$letter][$id]['title'][$lang]; $alphabet[$letter][$id]['description'] = json_decode($description, true); $alphabet[$letter][$id]['description'] = $alphabet[$letter][$id]['description'][$lang]; } else { $alphabet[$letter][$id]['title'] = json_decode($title, true); $alphabet[$letter][$id]['description'] = json_decode($description, true); } } } } } return $alphabet; } /* Returns the domain from an URL */ private function getDomain($url){ $url = strtolower($url); $url = str_replace("https://","",$url); $url = str_replace("http://","",$url); $url = str_replace("www.","",$url); $tmp = explode("%3f",$url); $url = $tmp[0]; $tmp = explode("%2f",$url); $url = $tmp[0]; $tmp = explode("/",$url); $url = $tmp[0]; $tmp = explode("?",$url); $url = $tmp[0]; return $url; } /* Check if the given season/episode exists for the given show */ public function exists($showid,$season,$episode){ $showid = mysql_real_escape_string($showid); $season = mysql_real_escape_string($season); $episode = mysql_real_escape_string($episode); $e = mysql_query("SELECT id FROM episodes WHERE show_id='$showid' AND episode='$episode' AND season='$season'") or die(mysql_error()); if (mysql_num_rows($e)){ return true; } else { return false; } } public function getLink($link_id){ $link_id = mysql_real_escape_string($link_id); $res = mysql_query("SELECT submitted_links.*, shows.id as show_id FROM submitted_links, shows WHERE submitted_links.`type`='1' AND submitted_links.imdb_id = shows.imdb_id AND submitted_links.id='$link_id'") or die(mysql_error()); if (mysql_num_rows($res)){ return mysql_fetch_assoc($res); } else { return false; } } /* Returns a list of user submitted links for the given episode */ public function getLinks($status = null, $lang=false){ if ($status !== null){ $status_add = " AND submitted_links.status='$status'"; } else { $status_add = ""; } $links = array(); $e = mysql_query("SELECT submitted_links.*, users.username, shows.title as show_title, shows.id as show_id FROM submitted_links LEFT JOIN shows ON shows.imdb_id=submitted_links.imdb_id LEFT JOIN users ON users.id=submitted_links.user_id WHERE submitted_links.type = 1 $status_add ORDER BY submitted_links.date_submitted DESC") or die(mysql_error()); if (mysql_num_rows($e)){ while($s = mysql_fetch_assoc($e)){ $links[$s['id']] = $s; if ($s['show_title']){ $links[$s['id']]['show_title'] = json_decode($links[$s['id']]['show_title'],true); if ($lang){ $links[$s['id']]['show_title'] = $links[$s['id']]['show_title'][$lang]; } } } } return $links; } /* Removes a show */ public function deleteShow($showid){ global $basepath; $showid = mysql_real_escape_string($showid); $e = mysql_query("SELECT thumbnail FROM shows WHERE id=$showid") or die(mysql_error()); if (mysql_num_rows($e)){ extract(mysql_fetch_array($e)); if (isset($thumbnail) && $thumbnail){ if (file_exists($basepath."/thumbs/".$thumbnail)){ unlink($basepath."/thumbs/".$thumbnail); } } $e = mysql_query("DELETE FROM broken_episodes WHERE episodeid IN (SELECT id FROM episodes WHERE show_id=$showid)") or die(mysql_error()); $e = mysql_query("DELETE FROM ratings WHERE episodeid IN (SELECT id FROM episodes WHERE show_id=$showid)") or die(mysql_error()); $e = mysql_query("DELETE FROM tv_submits WHERE episode_id IN (SELECT id FROM episodes WHERE show_id=$showid)") or die(mysql_error()); $e = mysql_query("DELETE FROM embeds WHERE episode_id IN (SELECT id FROM episodes WHERE show_id='$showid')") or die(mysql_error()); $e = mysql_query("DELETE FROM episodes WHERE show_id=$showid") or die(mysql_error()); $e = mysql_query("DELETE FROM shows WHERE id=$showid") or die(mysql_error()); $e = mysql_query("DELETE FROM tv_tags_join WHERE show_id=$showid") or die(mysql_error()); } } /* Removes an episode */ public function deleteEpisode($episode_id){ global $basepath; $episode_id = mysql_real_escape_string($episode_id); $e = mysql_query("SELECT thumbnail FROM episodes WHERE id='$episode_id'") or die(mysql_error()); if (mysql_num_rows($e)){ extract(mysql_fetch_assoc($e)); if ($thumbnail && file_exists($basepath."/thumbs/".$thumbnail)){ unlink($basepath."/thumbs/".$thumbnail); } $e = mysql_query("DELETE FROM embeds WHERE episode_id='$episode_id'") or die(mysql_error()); $e = mysql_query("DELETE FROM broken_episodes WHERE episodeid='$episode_id'") or die(mysql_error()); $e = mysql_query("DELETE FROM ratings WHERE episodeid='$episode_id'") or die(mysql_error()); $e = mysql_query("DELETE FROM tv_submits WHERE episode_id='$episode_id'") or die(mysql_error()); $e = mysql_query("DELETE FROM episodes WHERE id='$episode_id'") or die(mysql_error()); } } /* Returns $limit number random shows (with episodes) */ public function getRandomShow($limit, $lang = false, $excluded_ids = array()){ $limit = (int) $limit; if (count($excluded_ids)){ foreach($excluded_ids as $key => $val){ $excluded_ids[$key] = mysql_real_escape_string($val); } $add = " AND id NOT IN (".implode(",",$excluded_ids).")"; } else { $add = ""; } $e = mysql_query("SELECT * FROM shows WHERE type=1 AND id IN (SELECT DISTINCT show_id FROM episodes) $add ORDER BY rand() LIMIT $limit") or die(mysql_error()); $shows = array(); if (mysql_num_rows($e)>0){ while($s = mysql_fetch_assoc($e)){ $shows[$s['id']] = $this->formatShowData($s, false, $lang); } } return $shows; } /* Returns a list of featured shows */ public function getFeatured($limit=10, $lang = null){ $shows = array(); $e = mysql_query("SELECT * FROM shows WHERE `type`=1 AND featured='1' ORDER BY rand() LIMIT $limit") or die(mysql_error()); if (mysql_num_rows($e)){ while($s = mysql_fetch_assoc($e)){ $shows[$s['id']] = $this->formatShowData($s, false, $lang); } } return $shows; } /* Returns all the shows which have episodes */ public function getAllShowsWithEpisodes($lang=null,$p=null,$l=null,$sortby=null){ if ($p && $l){ $start = ($p-1)*$l; $limit = " LIMIT $start,$l"; } else { $limit = ""; } if (!$sortby || $sortby == 'abc'){ $order = "ORDER BY title ASC"; } elseif ($sortby == 'date') { $order = "ORDER BY last_episode DESC"; } elseif ($sortby == 'imdb_rating'){ $order = "ORDER BY imdb_rating DESC"; } $e = mysql_query("SELECT * FROM shows WHERE type=1 AND id IN (SELECT show_id FROM episodes) $order $limit") or die(mysql_error()); $shows = array(); if (mysql_num_rows($e)>0){ while($s = mysql_fetch_array($e)){ $shows[$s['id']] = $this->formatShowData($s, false, $lang); } } return $shows; } /* Returns all the shows */ public function getAllShows($p=null, $l=null, $lang = null){ if ($p && $l){ $start = ($p-1)*$l; $limit = " LIMIT $start,$l"; } else { $limit = ""; } $e = mysql_query("SELECT * FROM shows WHERE type=1 ORDER BY title ASC $limit") or die(mysql_error()); $shows = array(); if (mysql_num_rows($e)>0){ while($s = mysql_fetch_array($e)){ $shows[$s['id']] = $this->formatShowData($s, false, $lang); } } return $shows; } /* Returns the list of seasons for a given show */ public function getSeasons($show_id){ $show_id = mysql_real_escape_string($show_id); $seasons = array(); $e = mysql_query("SELECT season FROM episodes WHERE show_id='$show_id' GROUP BY season ORDER BY season ASC"); if (mysql_num_rows($e)){ while($s = mysql_fetch_array($e)){ extract($s); $seasons[]=$season; } } return $seasons; } /* Returns a show matching title in given language */ public function getShowByTitle($title, $lang = "en"){ $title = mysql_real_escape_string($title); $title = preg_replace("/[^a-zA-Z0-9 ]+/i","%",$title); $lang = mysql_real_escape_string($lang); $query = "SELECT * FROM shows WHERE type=1 AND title LIKE '%\"$lang\":\"$title\"%' LIMIT 1"; $e = mysql_query($query) or die(mysql_error()); if (mysql_num_rows($e)){ return $this->formatShowData(mysql_fetch_assoc($e), false, $lang); } else { return array(); } } public function getShowByImdb($imdb_id, $lang = "en"){ $imdb_id = mysql_real_escape_string($imdb_id); $query = "SELECT * FROM shows WHERE type=1 AND imdb_id='$imdb_id' LIMIT 1"; $e = mysql_query($query) or die(mysql_error()); if (mysql_num_rows($e)){ return $this->formatShowData(mysql_fetch_assoc($e), false, $lang); } else { return array(); } } public function formatShowData($data, $nested = true, $lang = false){ if ($nested){ $data['meta'] = json_decode($data['meta'], true); $shows[$data['id']]=$data; if (!$lang){ $shows[$data['id']]['title'] = json_decode($shows[$data['id']]['title'],true); $shows[$data['id']]['description'] = json_decode($shows[$data['id']]['description'],true); } else { $shows[$data['id']]['title'] = json_decode($shows[$data['id']]['title'],true); $shows[$data['id']]['title'] = $shows[$data['id']]['title'][$lang]; $shows[$data['id']]['description'] = json_decode($shows[$data['id']]['description'],true); $shows[$data['id']]['description'] = $shows[$data['id']]['description'][$lang]; } return $shows; } else { $data['meta'] = json_decode($data['meta'], true); if (!$lang){ $data['title'] = json_decode($data['title'],true); $data['description'] = json_decode($data['description'],true); } else { $data['title'] = json_decode($data['title'],true); $data['title'] = $data['title'][$lang]; $data['description'] = json_decode($data['description'],true); $data['description'] = $data['description'][$lang]; } return $data; } } /* Returns show details matching permalink */ public function getShowByPerma($perma, $lang=null){ $perma = mysql_real_escape_string($perma); $e = mysql_query("SELECT * FROM shows WHERE type=1 AND permalink='$perma'") or die(mysql_error()); if (mysql_num_rows($e)>0){ return $this->formatShowData(mysql_fetch_assoc($e), true, $lang); } return array(); } /* Validate a show */ public function validate($params,$update=0){ $errors = array(); if (!isset($_SESSION['global_languages'])){ return array("99" => "Session expired"); } else { foreach($_SESSION['global_languages'] as $lang_code => $lang_name){ if (!isset($params['title'][$lang_code]) || !$params['title'][$lang_code]){ $errors[1][$lang_code] = "Please enter the $lang_name title for this show"; } if (!isset($params['description'][$lang_code]) || !$params['description'][$lang_code]){ $errors[3][$lang_code] = "Please enter the $lang_name description for this show"; } } if (!isset($params['thumbnail']) || !$params['thumbnail']){ $errors[2]='Please upload a default image'; } if (isset($params['sidereel_url']) && $params['sidereel_url'] && !substr_count($params['sidereel_url'],"http://www.sidereel.com/")){ $errors[4] = "Invalid Sidereel url. URL format must be http://www.sidereel.com/[SHOWNAME]"; } if (isset($params['imdb_rating']) && $params['imdb_rating'] && !is_numeric($params['imdb_rating'])){ $errors[7] = "IMDB rating must be numeric"; } if (isset($params['year_started']) && $params['year_started'] && !is_numeric($params['year_started'])){ $errors[8] = "Year must be numeric"; } if (!isset($params['imdb_id']) || substr_count($params['imdb_id'],"tt")==0){ $errors[6] = "Invalid IMDB id. It should be in format: tt12345"; } else { $imdb = mysql_real_escape_string($params['imdb_id']); if (!$update){ $check = mysql_query("SELECT * FROM shows WHERE imdb_id='$imdb'") or die(mysql_error()); } else { $update = mysql_real_escape_string($update); $check = mysql_query("SELECT * FROM shows WHERE imdb_id='$imdb' AND id!='$update'") or die(mysql_error()); } if (mysql_num_rows($check)){ $errors[6] = "This IMDB id is already in use"; } } return $errors; } } /* Method to validate a multi language tag */ public function validateCategory($category){ $errors = array(); if (!isset($_SESSION['global_languages'])){ return array("99" => "Session expired"); } foreach($_SESSION['global_languages'] as $lang_code => $lang_name){ if (!isset($category[$lang_code]) || !$category[$lang_code]){ $errors[$lang_code] = "Please enter a $lang_name category title"; } } return $errors; } /* Method to add a multi-language tag */ public function addCategory($category){ $perma = $this->makePerma($category['en']); $category = mysql_real_escape_string(json_encode($category)); $e = mysql_query("SELECT * FROM tv_tags WHERE tag='$category' OR perma='$perma'") or die(mysql_error()); if (mysql_num_rows($e)==0){ $e = mysql_query("INSERT INTO tv_tags(tag,perma) VALUES('$category','$perma')") or die(mysql_error()); return 1; } else { return 0; } } /* Add / update show categories */ public function saveCategories($showid,$categories){ $showid = mysql_real_escape_string($showid); $e = mysql_query("DELETE FROM tv_tags_join WHERE show_id='$showid'") or die(mysql_error()); foreach($categories as $key => $category_id){ $val = mysql_real_escape_string($category_id); $e = mysql_query("INSERT INTO tv_tags_join(show_id,tag_id) VALUES('$showid','$category_id')") or die(mysql_error()); } } /* Remove a tag and all of it's members */ public function deleteTag($tagid){ $tagid = mysql_real_escape_string($tagid); $e = mysql_query("DELETE FROM tv_tags_join WHERE tag_id='$tagid'") or die(mysql_error()); $e = mysql_query("DELETE FROM tv_tags WHERE id='$tagid'") or die(mysql_error()); } public function getShowCountByCategory($tag_id){ $tag_id = mysql_real_escape_string($tag_id); $e = mysql_query("SELECT count(*) as show_count FROM shows WHERE id IN (SELECT show_id FROM tv_tags_join WHERE tag_id='$tag_id')") or die(mysql_error()); if (mysql_num_rows($e)){ extract(mysql_fetch_assoc($e)); return $show_count; } else { return 0; } } /* Returns all the shows matching a tag */ public function getShowsByCategory($tag_id, $lang = null, $page = 1, $limit = 40, $sortby = "date"){ $tag_id = mysql_real_escape_string($tag_id); $page = (int) $page; $limit = (int) $limit; if (!$page) $page = 1; if (!$limit) $limit = 1; $start = ($page-1) * $limit; $limit = " LIMIT $start, $limit"; if (!$sortby || $sortby == 'abc'){ $order = "ORDER BY title ASC"; } elseif ($sortby == 'date') { $order = "ORDER BY last_episode DESC"; } elseif ($sortby == 'imdb_rating'){ $order = "ORDER BY imdb_rating DESC"; } $e = mysql_query("SELECT * FROM shows WHERE id IN (SELECT show_id FROM tv_tags_join WHERE tag_id='$tag_id') $order $limit") or die(mysql_error()); $shows = array(); if (mysql_num_rows($e)){ while($s = mysql_fetch_assoc($e)){ $shows[$s['id']] = $this->formatShowData($s, false, $lang); } } return $shows; } /* Returns a category matching a permalink */ public function getCategoryByPerma($perma, $lang = null){ $perma = mysql_real_escape_string($perma); $e = mysql_query("SELECT id,tag FROM tv_tags WHERE perma='$perma'") or die(mysql_error()); if (mysql_num_rows($e)){ extract(mysql_fetch_array($e)); $tag = json_decode($tag,true); if ($lang){ $tag = $tag[$lang]; } return array("id" => $id, "tag" => $tag); } else { return ''; } } /* Method to retrieve all the tags for a given show */ public function getShowCategories($show_id, $get_info = false, $lang = false){ $show_id = mysql_real_escape_string($show_id); $tags = array(); if (!$get_info){ $e = mysql_query("SELECT tag_id FROM tv_tags_join WHERE show_id='$show_id'") or die(mysql_error()); if (mysql_num_rows($e)){ while($s = mysql_fetch_array($e)){ extract($s); $tags[]=$tag_id; } } } else { $e = mysql_query("SELECT * FROM tv_tags, tv_tags_join WHERE tv_tags_join.show_id='$show_id' AND tv_tags_join.tag_id=tv_tags.id") or die(mysql_error()); if (mysql_num_rows($e)){ while($s = mysql_fetch_assoc($e)){ $tags[$s['id']] = $s; $tags[$s['id']]['tag'] = json_decode($tags[$s['id']]['tag'], true); if ($lang){ if (isset($tags[$s['id']]['tag'][$lang])){ $tags[$s['id']]['tag'] = $tags[$s['id']]['tag'][$lang]; } elseif (isset($tags[$s['id']]['tag']['en'])) { $tags[$s['id']]['tag'] = $tags[$s['id']]['tag']['en']; } } } } } return $tags; } /* Lists all the categories */ public function getCategories($lang=null, $limit=0, $order="tag ASC"){ $categories = array(); if ($limit){ $add = "LIMIT $limit"; } else { $add = ''; } $e = mysql_query("SELECT * FROM tv_tags ORDER BY $order") or die(mysql_error()); if (mysql_num_rows($e)){ while($s = mysql_fetch_array($e)){ extract($s); $tag = json_decode($tag,true); if ($lang){ $tag = $tag[$lang]; } $categories[$id]['name']=$tag; $categories[$id]['perma']=$perma; } } return $categories; } /* Returns $limit latest episodes */ public function getLatestEpisodes($limit){ $maxepisodes = mysql_query("SELECT MAX(`id`) as maxid FROM episodes GROUP BY show_id") or die(mysql_error()); $episodes = array(); if (mysql_num_rows($maxepisodes)){ $maxids = array(); while($s = mysql_fetch_array($maxepisodes)){ $maxids[]=$s['maxid']; } $query = "SELECT shows.id as showid,shows.permalink,episodes.thumbnail,shows.thumbnail as category_thumbnail,shows.title as showtitle,episodes.episode, episodes.season, episodes.description, episodes.title as episodetitle FROM episodes, shows WHERE episodes.show_id=shows.id AND episodes.id IN (".implode(",",$maxids).") GROUP by shows.id,episodes.season ORDER BY episodes.id DESC LIMIT $limit"; $e = mysql_query($query) or die(mysql_error()); if (mysql_num_rows($e)){ while($s=mysql_fetch_array($e)){ extract($s); $episodes[$showid]=array(); $episodes[$showid]['showtitle']=$showtitle; $episodes[$showid]['showid']=$showid; if ($thumbnail){ $episodes[$showid]['thumbnail']=$thumbnail; } else { $episodes[$showid]['thumbnail']=$category_thumbnail; } $episodes[$showid]['episode']=$episode; $episodes[$showid]['season']=$season; $episodes[$showid]['description']=$description; $episodes[$showid]['permalink']=$permalink; $episodes[$showid]['episodetitle']=$episodetitle; if (!$episodes[$showid]['episodetitle']){ $episodes[$showid]['episodetitle'] = "Season $season, Episode $episode"; } } } } return $episodes; } /* Get all the language flags for a given list of episode ids */ public function getEpisodeFlags($ids){ $flags = array(); // getting embed languages if (count($ids)){ $e = mysql_query("SELECT episode_id,lang FROM embeds WHERE episode_id IN (".implode(",",$ids).")") or die(mysql_error()); if (mysql_num_rows($e)){ while($s = mysql_fetch_assoc($e)){ if (!array_key_exists($s['episode_id'],$flags)){ $flags[$s['episode_id']] = array(); } if (!in_array($s['lang'],$flags[$s['episode_id']])){ $flags[$s['episode_id']][] = $s['lang']; } } } } return $flags; } /* Method to return episodes where we have embed codes */ public function getRealLatestEpisodes($limit,$lang = null){ $episodes = array(); $query = "SELECT episodes.date_added, shows.id as showid,shows.permalink,episodes.thumbnail,shows.thumbnail as category_thumbnail,shows.title as showtitle,episodes.episode, episodes.season, episodes.description, episodes.title as episodetitle, episodes.id as epid FROM episodes, shows WHERE episodes.show_id=shows.id ORDER BY episodes.date_added DESC LIMIT $limit"; $e = mysql_query($query) or die(mysql_error()); $counter = 0; if (mysql_num_rows($e)){ $ids = array(); while($s=mysql_fetch_array($e)){ extract($s); $episodes[$counter]=array(); if (!$lang){ $episodes[$counter]['showtitle'] = json_decode($showtitle,true); } else { $showtitle = json_decode($showtitle,true); $episodes[$counter]['showtitle'] = $showtitle[$lang]; } $episodes[$counter]['showid']=$showid; $episodes[$counter]['epid']=$epid; if ($thumbnail){ $episodes[$counter]['thumbnail']=$thumbnail; } else { $episodes[$counter]['thumbnail']=$category_thumbnail; } $episodes[$counter]['episode']=$episode; $episodes[$counter]['season']=$season; $episodes[$counter]['description']=$description; $episodes[$counter]['permalink']=$permalink; $episodes[$counter]['episodetitle']=$episodetitle; $episodes[$counter]['date_added']=$date_added; if (!$episodes[$counter]['episodetitle']){ $episodes[$counter]['episodetitle'] = "Season $season, Episode $episode"; } $counter++; $ids[] = $epid; } // getting embed languages $flags = $this->getEpisodeFlags($ids); foreach($episodes as $key => $val){ if (array_key_exists($val['epid'],$flags)){ $episodes[$key]['languages'] = $flags[$val['epid']]; } else { $episodes[$key]['languages'] = array(); } } } return $episodes; } /* Global validate function for a new episode */ public function validateEpisode($params, $no_embeds = false){ $errors = array(); if (!isset($params['show_id']) || !$params['show_id'] || !is_numeric($params['show_id'])){ $errors[1] = "Please select a TV show"; } if (!isset($params['season']) || !$params['season'] || !is_numeric($params['season'])){ $errors[2] = "Please enter the season number"; } if (!isset($params['episode']) || !$params['episode'] || !is_numeric($params['episode'])){ $errors[3] = "Please enter the episode number"; } // checking for real embeds if (!$no_embeds){ if (isset($params['from']) && $params['from']=="admin"){ if (!isset($params['embed_enabled']) || !is_array($params['embed_enabled']) || !count($params['embed_enabled'])){ $errors[4] = "Please add at least one embed"; } else { $found = false; foreach($params['embed_enabled'] as $embed_id => $val){ if (isset($params['embeds'][$embed_id]) && $params['embeds'][$embed_id]){ $found = true; break; } } if (!$found){ $errors[4] = "Please add at least one embed"; } } } elseif (!isset($params['embeds']) || !is_array($params['embeds']) || !count($params['embeds'])){ $errors[4] = "Please add at least one embed"; } } return $errors; } /* Function to update episode data */ public function updateEpisode($episode_id,$params){ $episode_id = mysql_real_escape_string($episode_id); $updates = array(); foreach($params as $key => $val){ $updates[] = "`".mysql_real_escape_string($key)."`='".mysql_real_escape_string($val)."'"; } $up = mysql_query("UPDATE episodes SET ".implode(",",$updates)." WHERE id='$episode_id'") or die(mysql_error()); } /* Function to add a new episode with embed codes */ public function saveEpisode($params){ $fields = array(); $values = array(); if (!isset($params['title']) || !$params['title']){ $params['title'] = "Season ".$params['season']." Episode ".$params['episode']; } foreach($params as $key => $val){ if (!is_array($val) && in_array($key,$this->episode_schema)){ $fields[] = "`".mysql_real_escape_string($key)."`"; $values[] = "'".mysql_real_escape_string($val)."'"; } } $episode_id = $this->getEpisode($params['show_id'],$params['season'],$params['episode']); if (!$episode_id){ $fields[] = "`date_added`"; $values[] = "'".date("Y-m-d H:i:s")."'"; $ins = mysql_query("INSERT INTO episodes(".implode(",",$fields).") VALUES(".implode(",",$values).")") or die(mysql_error()); $episode_id = mysql_insert_id(); } if (isset($params['embeds']) && is_array($params['embeds']) && count($params['embeds'])){ foreach($params['embeds'] as $key => $val){ $embed = mysql_real_escape_string(urldecode($val)); if (isset($params['embed_langs'][$key])){ $language = mysql_real_escape_string($params['embed_langs'][$key]); } else { $language = "ENG"; } $this->addEmbed($episode_id,$embed,$language); } } $this->setEpisodeDate($episode_id,$params['show_id']); return $episode_id; } /* Makes a clean, url friendly representation of a string */ public function makePerma($str, $replace=array(), $delimiter='-') { if( !empty($replace) ) { $str = str_replace((array)$replace, ' ', $str); } $clean = iconv('UTF-8', 'ASCII//TRANSLIT', $str); $clean = preg_replace("/[^a-zA-Z0-9\/_|+ -]/", '', $clean); $clean = strtolower(trim($clean, '-')); $clean = preg_replace("/[\/_|+ -]+/", $delimiter, $clean); return $clean; } /* Saves a new show */ public function save($params){ $permalink = $this->makePerma($params['title']['en']); $title = mysql_real_escape_string(json_encode($params['title'])); $description = mysql_real_escape_string(json_encode($params['description'])); $thumbnail = mysql_real_escape_string($params['thumbnail']); if (isset($params['sidereel_url'])){ $sidereel_url = mysql_real_escape_string($params['sidereel_url']); } else { $sidereel_url = ''; } if (isset($params['featured']) && $params['featured']){ $featured = 1; } else { $featured = 0; } if (isset($params['imdb_id'])){ $imdb_id = mysql_real_escape_string($params['imdb_id']); } else { $imdb_id = "-1"; } if (isset($params['imdb_rating']) && $params['imdb_rating']){ $imdb_rating = mysql_real_escape_string($params['imdb_rating']); } else { $imdb_rating = 0; } $meta = array(); if (isset($params['year_started']) && $params['year_started']){ $meta['year_started'] = (int) $params['year_started']; } if (isset($params['stars']) && $params['stars'] && is_array($params['stars']) && count($params['stars'])){ $stars = array(); foreach($params['stars'] as $key => $star){ if (trim($star)){ $stars[] = $star; } } if (count($stars)){ $meta['stars'] = $stars; } } if (isset($params['creators']) && $params['creators'] && is_array($params['creators']) && count($params['creators'])){ $creators = array(); foreach($params['creators'] as $key => $creator){ if (trim($creator)){ $creators[] = $creator; } } if (count($creators)){ $meta['creators'] = $creators; } } if (count($meta)){ $meta = mysql_real_escape_string(json_encode($meta)); } else { $meta = ''; } $e = mysql_query("INSERT INTO shows (title, imdb_id, description, thumbnail, permalink, type, sidereel_url, featured, imdb_rating, meta) VALUES ('$title','$imdb_id','$description','$thumbnail','$permalink',1,'$sidereel_url','$featured','$imdb_rating','$meta')") or die(mysql_error()); return mysql_insert_id(); } /* Updates show_id with given parameters */ public function update($params,$show_id){ global $basepath; $show_id = mysql_real_escape_string($show_id); $check = mysql_query("SELECT thumbnail as thumbnail_to_delete FROM shows WHERE id='$show_id'") or die(mysql_error()); if(mysql_num_rows($check)){ extract(mysql_fetch_assoc($check)); $title = mysql_real_escape_string(json_encode($params['title'])); $description = mysql_real_escape_string(json_encode($params['description'])); $thumbnail = mysql_real_escape_string($params['thumbnail']); if (isset($params['sidereel_url'])){ $sidereel_url = mysql_real_escape_string($params['sidereel_url']); } else { $sidereel_url = ''; } $imdb_id = mysql_real_escape_string($params['imdb_id']); if (isset($params['featured']) && $params['featured']){ $featured = 1; } else { $featured = 0; } if (isset($params['imdb_rating']) && $params['imdb_rating']){ $imdb_rating = mysql_real_escape_string($params['imdb_rating']); } else { $imdb_rating = 0; } $meta = array(); if (isset($params['year_started']) && $params['year_started']){ $meta['year_started'] = (int) $params['year_started']; } if (isset($params['stars']) && $params['stars'] && is_array($params['stars']) && count($params['stars'])){ $stars = array(); foreach($params['stars'] as $key => $star){ if (trim($star)){ $stars[] = $star; } } if (count($stars)){ $meta['stars'] = $stars; } } if (isset($params['creators']) && $params['creators'] && is_array($params['creators']) && count($params['creators'])){ $creators = array(); foreach($params['creators'] as $key => $creator){ if (trim($creator)){ $creators[] = $creator; } } if (count($creators)){ $meta['creators'] = $creators; } } if (count($meta)){ $meta = mysql_real_escape_string(json_encode($meta)); } else { $meta = ''; } $e = mysql_query("UPDATE shows SET title='$title',description='$description',thumbnail='$thumbnail',sidereel_url='$sidereel_url', imdb_id='$imdb_id', featured='$featured', imdb_rating='$imdb_rating', meta='$meta' WHERE id=$show_id") or die(mysql_error()); if ($thumbnail_to_delete!=$thumbnail && file_exists($basepath."/thumbs/".$thumbnail_to_delete)){ unlink($basepath."/thumbs/".$thumbnail_to_delete); } return true; } else { return false; } } /* Returns a show based on id */ public function getShow($id, $nested=1, $lang=false){ $id = mysql_real_escape_string($id); $e = mysql_query("SELECT * FROM shows WHERE id='$id'") or die(mysql_error()); if (mysql_num_rows($e)){ return $this->formatShowData(mysql_fetch_assoc($e), $nested, $lang); } else { return array(); } } /* Returns all the shows having at least one episode */ public function getShows($getcounts=null, $lang = false){ $shows = array(); if ($getcounts){ $e = mysql_query("SELECT shows.*,count(*) as `cnt`,episodes.title as episodetitle FROM shows LEFT JOIN episodes ON shows.id=episodes.show_id WHERE shows.type=1 GROUP BY shows.id ORDER BY shows.title ASC") or die(mysql_error()); } else { $e = mysql_query("SELECT * FROM shows WHERE type=1 ORDER BY title ASC") or die(mysql_error()); } if (mysql_num_rows($e)){ while($s = mysql_fetch_assoc($e)){ extract($s); $shows[$s['id']]=$s; if (!$lang){ $shows[$s['id']]['title'] = json_decode($shows[$s['id']]['title'],true); $shows[$s['id']]['description'] = json_decode($shows[$s['id']]['description'],true); } else { $shows[$s['id']]['title'] = json_decode($shows[$s['id']]['title'],true); $shows[$s['id']]['title'] = $shows[$s['id']]['title'][$lang]; $shows[$s['id']]['description'] = json_decode($shows[$s['id']]['description'],true); $shows[$s['id']]['description'] = $shows[$s['id']]['description'][$lang]; } if ($getcounts){ if ((!$episodetitle) && ($cnt==1)){ $getcount = mysql_query("SELECT count(*) as cnt FROM episodes WHERE show_id=$id") or die(mysql_error()); extract(mysql_fetch_array($getcount)); } $shows[$id]['episodecount']=$cnt; } } } return $shows; } /* Lists episodes belonging to a show / season */ public function getEpisodes($showid, $season=null, $lang = false, $embed_lang = array()){ $episodes = array(); if ($season){ $season = mysql_real_escape_string($season); $add = "AND season=$season"; } else { $add = ''; } if (count($embed_lang)){ foreach($embed_lang as $key => $val){ $embed_lang[$key] = "'".$val."'"; } $lang_add = " AND episodes.id IN (SELECT episode_id FROM embeds WHERE lang IN (".implode(",",$embed_lang)."))"; } else { $lang_add = ""; } $e = mysql_query("SELECT shows.id as showid,episodes.embed,episodes.title as episodetitle,shows.permalink,shows.thumbnail as category_thumbnail,episodes.thumbnail,shows.title as showtitle,episodes.id as epid,episodes.episode,episodes.description,episodes.season,episodes.title as episodetitle FROM episodes, shows WHERE episodes.show_id=shows.id AND episodes.show_id=$showid $add $lang_add ORDER BY episodes.season DESC,episodes.episode DESC") or die(mysql_error()); if (mysql_num_rows($e)){ $ids = array(); while($s=mysql_fetch_array($e)){ extract($s); $episodes[$epid]=array(); $episodes[$epid]['episodetitle']=$episodetitle; if (!$lang){ $episodes[$epid]['title'] = json_decode($showtitle,true); } else { $episodes[$epid]['title'] = json_decode($showtitle,true); if (isset($episodes[$epid]['title'][$lang])){ $episodes[$epid]['title'] = $episodes[$epid]['title'][$lang]; } else { $episodes[$epid]['title'] = $episodes[$epid]['title']['en']; } } if ($thumbnail){ $episodes[$epid]['thumbnail'] = $thumbnail; } else { $episodes[$epid]['thumbnail'] = $category_thumbnail; } if (!$episodes[$epid]['episodetitle']){ $episodes[$epid]['episodetitle'] = "Season $season, Episode $episode"; } $episodes[$epid]['description']=$description; $episodes[$epid]['season']=$season; $episodes[$epid]['episode']=$episode; $episodes[$epid]['embed']=$embed; $ids[] = $epid; } // getting embed languages if (count($ids)){ $flags = $this->getEpisodeFlags($ids); $flags = $this->getEpisodeFlags($ids); foreach($episodes as $episode_id => $val){ if (array_key_exists($episode_id,$flags)){ $episodes[$episode_id]['languages'] = $flags[$episode_id]; } else { $episodes[$episode_id]['languages'] = array(); } } } } return $episodes; } /* Returns all episodes from the database */ public function getAllEpisodes(){ $episodes = array(); $e = mysql_query("SELECT shows.id as showid,episodes.embed,episodes.title as episodetitle,shows.permalink,shows.thumbnail as category_thumbnail,episodes.thumbnail,shows.title as showtitle,episodes.id as epid,episodes.episode,episodes.description,episodes.season,episodes.title as episodetitle FROM episodes, shows WHERE episodes.show_id=shows.id ORDER BY episodes.season DESC,episodes.episode DESC") or die(mysql_error()); if (mysql_num_rows($e)){ while($s=mysql_fetch_array($e)){ extract($s); $episodes[$epid]=array(); $episodes[$epid]['title']=$showtitle; $episodes[$epid]['description']=$description; if ($thumbnail){ $episodes[$epid]['thumbnail']=$thumbnail; } else { $episodes[$epid]['thumbnail']=$category_thumbnail; } $episodes[$epid]['season']=$season; $episodes[$epid]['episode']=$episode; $episodes[$epid]['episodetitle']=$episodetitle; if (!$episodes[$epid]['episodetitle']){ $episodes[$epid]['episodetitle'] = "Season $season, Episode $episode"; } $episodes[$epid]['embed']=$embed; } } return $episodes; } /* Search by metadata */ public function searchByMeta($params, $lang = null){ if (isset($params['creator'])){ $params['creator'] = preg_replace("/[^a-zA-Z0-9 ]/i","%",$params['creator']); $query = "meta LIKE '%\"creators\":[%\"".mysql_real_escape_string($params['creator'])."\"%]%'"; } elseif (isset($params['star'])){ $params['star'] = preg_replace("/[^a-zA-Z0-9 ]/i","%",$params['star']); $query = "meta LIKE '%\"stars\":[%\"".mysql_real_escape_string($params['star'])."\"%]%'"; } elseif (isset($params['year_started'])){ $params['year_started'] = (int) $params['year_started']; $query = "meta LIKE '%\"year_started\":\"".mysql_real_escape_string($params['year_started'])."\"%' OR meta LIKE '%\"year_started\":".mysql_real_escape_string($params['year_started'])."%'"; } $shows = array(); $query = "SELECT * FROM shows WHERE $query ORDER BY last_episode DESC"; $res = mysql_query($query) or die(mysql_error()); if (mysql_num_rows($res)){ while($s = mysql_fetch_assoc($res)){ $shows[$s['id']] = $this->formatShowData($s, false, $lang); } } return $shows; } /* Search function */ public function search($q, $lang=null){ $episodes = array(); $q = mysql_real_escape_string($q); $q = preg_replace("/[^a-zA-Z0-9 ]/i","%",$q); $query = "SELECT shows.id as show_id,episodes.embed,episodes.title as episodetitle,shows.permalink,shows.thumbnail as category_thumbnail,episodes.thumbnail,shows.title as showtitle,episodes.id as epid,episodes.episode,episodes.description,episodes.season,episodes.title as episodetitle FROM episodes, shows WHERE episodes.show_id=shows.id AND (episodes.title LIKE '%$q%' OR episodes.description LIKE '%$q%' OR shows.description LIKE '%$q%' OR shows.title LIKE '%$q%') ORDER BY episodes.season DESC,episodes.episode DESC"; $e = mysql_query($query) or die(mysql_error()); if (mysql_num_rows($e)){ $ids = array(); while($s=mysql_fetch_assoc($e)){ extract($s); $episodes[$epid]=array(); if (!$lang){ $episodes[$epid]['title'] = json_decode($showtitle,true); } else { $showtitle = json_decode($showtitle,true); $episodes[$epid]['title'] = $showtitle[$lang]; } $episodes[$epid]['title'] = stripslashes($episodes[$epid]['title']); $episodes[$epid]['description'] = nl2br(stripslashes($description)); if ($thumbnail){ $episodes[$epid]['thumbnail'] = $thumbnail; } else { $episodes[$epid]['thumbnail'] = $category_thumbnail; } $episodes[$epid]['show_id']=$show_id; $episodes[$epid]['season']=$season; $episodes[$epid]['episode']=$episode; $episodes[$epid]['permalink']=$permalink; $episodes[$epid]['episodetitle']=$episodetitle; if (!$episodes[$epid]['episodetitle']){ $episodes[$epid]['episodetitle'] = "Season $season, Episode $episode"; } $episodes[$epid]['embed']=$embed; $ids[] = $epid; } if (count($ids)){ $flags = $this->getEpisodeFlags($ids); foreach($episodes as $episode_id => $val){ if (array_key_exists($episode_id,$flags)){ $episodes[$episode_id]['languages'] = $flags[$episode_id]; } else { $episodes[$episode_id]['languages'] = array(); } } } } return $episodes; } /* Returns the first day of the given month */ public function firstOfMonth($date) { return date("Y-m-d", strtotime(date('m',strtotime($date)).'/01/'.date('Y',strtotime($date)).' 00:00:00')); } /* Returns the last day of the given month */ public function lastOfMonth($date) { return date("Y-m-d", strtotime('-1 second',strtotime('+1 month',strtotime(date('m',strtotime($date)).'/01/'.date('Y',strtotime($date)).' 00:00:00')))); } /* Returns a from-to value for a period id */ public function getPeriod($period){ if ($period==1){ $from = date("Y-m-d"); $to = date("Y-m-d"); } // today if ($period==2){ $from = date("Y-m-d",strtotime("yesterday")); $to = date("Y-m-d",strtotime("yesterday")); } // yesterday if ($period==3){ $from = date("Y-m-d",strtotime("7 days ago")); $to = date("Y-m-d"); } // this week if ($period==4){ $from = date("Y-m")."-01"; $to = date("Y-m-d"); } // this month if ($period==5){ $from = "0000-00-00"; $to = date("Y-m-d"); } // all time if ($period==6){ $from = $this->firstOfMonth(date("Y-m-d",strtotime("1 month ago"))); $to = $this->lastOfMonth(date("Y-m-d",strtotime("1 month ago"))); } // last month if ($period==7){ $from = $this->firstOfMonth(date("Y-m-d",strtotime("2 month ago"))); $to = $this->lastOfMonth(date("Y-m-d",strtotime("2 month ago"))); } // two months ago return array("from" => $from, "to" => $to); } /* Returns all the episodes added in the given period */ public function getByPeriod($period,$lang=false,$embed_lang=array()){ $period = $this->getPeriod($period); extract($period); $from .= " 00:00:00"; $to .= " 23:59:59"; if (count($embed_lang)){ foreach($embed_lang as $key => $val){ $embed_lang[$key] = "'".$val."'"; } $lang_add = " AND episodes.id IN (SELECT episode_id FROM embeds WHERE lang IN (".implode(",",$embed_lang)."))"; } else { $lang_add = ""; } $e = mysql_query("SELECT shows.id as showid,episodes.embed,episodes.title as episodetitle,shows.permalink,shows.thumbnail,shows.title as showtitle,episodes.id as epid,episodes.episode,episodes.description,episodes.season,episodes.title as episodetitle FROM episodes, shows WHERE episodes.show_id=shows.id AND episodes.date_added>='$from' AND episodes.date_added<='$to' $lang_add ORDER BY episodes.id ASC") or die(mysql_error()); $episodes = array(); if (mysql_num_rows($e)){ while($s=mysql_fetch_array($e)){ extract($s); $episodes[$epid]=array(); if (!$lang){ $episodes[$epid]['title'] = json_decode($showtitle,true); $episodes[$epid]['description'] = json_decode($description,true); } else { $episodes[$epid]['title'] = json_decode($showtitle,true); if (isset($episodes[$epid]['title'][$lang])){ $episodes[$epid]['title'] = $episodes[$epid]['title'][$lang]; } else { $episodes[$epid]['title'] = $episodes[$epid]['title']['en']; } $episodes[$epid]['description'] = json_decode($description,true); if (isset($episodes[$epid]['description'][$lang])){ $episodes[$epid]['description'] = $episodes[$epid]['description'][$lang]; } else { $episodes[$epid]['description'] = $episodes[$epid]['description']['en']; } } $episodes[$epid]['thumbnail']=$thumbnail; $episodes[$epid]['season']=$season; $episodes[$epid]['episode']=$episode; $episodes[$epid]['episodetitle']=$episodetitle; if (!$episodes[$epid]['episodetitle']){ $episodes[$epid]['episodetitle'] = "Season $season, Episode $episode"; } $episodes[$epid]['embed']=$embed; } } return $episodes; } /* Gives a count of all the episodes in the db */ public function getEpisodeCount(){ $e = mysql_query("SELECT count(*) as total FROM episodes") or die(mysql_error()); extract(mysql_fetch_array($e)); return $total; } /* Counts all the shows with at least one episode */ public function getShowCountWithEpisodes(){ $e = mysql_query("SELECT count(*) as total FROM shows WHERE id IN (SELECT show_id FROM episodes)") or die(mysql_error()); extract(mysql_fetch_array($e)); return $total; } /* Total show count */ public function getShowCount($search_term = null){ if ($search_term){ $search_term = "WHERE title LIKE '%".mysql_real_escape_string($search_term)."%'"; } else { $search_term = ""; } $e = mysql_query("SELECT count(*) as total FROM shows $search_term") or die(mysql_error()); extract(mysql_fetch_array($e)); return $total; } /* Number of episode ratings */ public function getRatingCount(){ $e = mysql_query("SELECT count(*) as total FROM ratings") or die(mysql_error()); extract(mysql_fetch_array($e)); return $total; } /* Number of broken episode reports */ public function getBrokenCount(){ $e = mysql_query("SELECT count(*) as total FROM broken_episodes") or die(mysql_error()); extract(mysql_fetch_array($e)); return $total; } /* Increments the view counter for given episode */ public function addView($episodeid){ $episodeid = mysql_real_escape_string($episodeid); $e = mysql_query("UPDATE episodes SET views=views+1 WHERE id='$episodeid'") or die(mysql_error()); } /* Lists episodes based on views */ public function getCounts($page,$lang=false){ $start = ($page-1)*100; $e = mysql_query("SELECT episodes.title as episodetitle,shows.title as showtitle,episodes.id as epid,episodes.views,episodes.season,episodes.episode,shows.id as showid FROM episodes,shows WHERE shows.id=episodes.show_id ORDER BY views DESC limit $start,100") or die(mysql_error()); $counts = array(); if (mysql_num_rows($e)){ while($sor = mysql_fetch_array($e)){ extract($sor); $counts[$epid]=array(); $counts[$epid]['episodetitle']=$episodetitle; if (!$counts[$epid]['episodetitle']){ $counts[$epid]['episodetitle'] = "Season $season, Episode $episode"; } if (!$lang){ $counts[$epid]['showtitle'] = json_decode($showtitle,true); } else { $counts[$epid]['showtitle'] = json_decode($showtitle,true); $counts[$epid]['showtitle'] = $counts[$epid]['showtitle'][$lang]; } $counts[$epid]['views']=$views; $counts[$epid]['showid']=$showid; $counts[$epid]['episode']=$episode; $counts[$epid]['season']=$season; } } return $counts; } /* Returns a list of broken episode reports */ public function getBroken($page,$lang=false){ $start = ($page-1)*5; $e = mysql_query("SELECT broken_episodes.user_id,broken_episodes.user_agent,broken_episodes.id as brokenid,broken_episodes.problem,shows.permalink,shows.id as showid,episodes.title as episodetitle,shows.title as showtitle,episodes.id as epid,episodes.views,episodes.season,episodes.episode,broken_episodes.reportdate,broken_episodes.ip FROM episodes,shows,broken_episodes WHERE broken_episodes.episodeid=episodes.id AND shows.id=episodes.show_id ORDER BY broken_episodes.id DESC limit $start,50") or die(mysql_error()); $broken = array(); if (mysql_num_rows($e)){ $user_ids = array(); $user_map = array(); while($sor = mysql_fetch_array($e)){ extract($sor); $broken[$brokenid]=array(); $broken[$brokenid]['episodetitle']=$episodetitle; if (!$broken[$brokenid]['episodetitle']){ $broken[$brokenid]['episodetitle'] = "Season $season, Episode $episode"; } if (!$lang){ $broken[$brokenid]['showtitle'] = json_decode($showtitle,true); } else { $broken[$brokenid]['showtitle'] = json_decode($showtitle,true); $broken[$brokenid]['showtitle'] = $broken[$brokenid]['showtitle'][$lang]; } $broken[$brokenid]['views']=$views; $broken[$brokenid]['episode']=$episode; $broken[$brokenid]['date']=$reportdate; $broken[$brokenid]['ip']=$ip; $broken[$brokenid]['season']=$season; $broken[$brokenid]['problem']=$problem; $broken[$brokenid]['episodeid']=$epid; $broken[$brokenid]['showid']=$showid; $broken[$brokenid]['user_agent']=$user_agent; $broken[$brokenid]['url']='/'.$permalink.'/season/'.$season.'/episode/'.$episode; $broken[$brokenid]['user'] = array(); if ($user_id && !in_array($user_id,$user_ids)){ $user_ids[] = $user_id; } if ($user_id){ if (!array_key_exists($user_id,$user_map)){ $user_map[$user_id] = array(); } $user_map[$user_id][] = $brokenid; } } if (count($user_ids)){ $e = mysql_query("SELECT id as user_id,username,email FROM users WHERE id IN (".implode(",",$user_ids).")") or die(mysql_error()); if (mysql_num_rows($e)){ while($s = mysql_fetch_assoc($e)){ foreach($user_map[$s['user_id']] as $key => $val){ $broken[$val]['user'] = $s; } } } } } return $broken; } /* Removes a broken episode report */ public function deleteBroken($id){ $id = mysql_real_escape_string($id); $e = mysql_query("DELETE FROM broken_episodes WHERE id=$id") or die(mysql_error()); } /* Removes an episode rating */ public function deleteRating($id){ $id = mysql_real_escape_string($id); $e = mysql_query("DELETE FROM ratings WHERE id=$id") or die(mysql_error()); } /* Lists episode ratings */ public function getRatings($page,$lang=false){ $start = ($page-1)*100; $e = mysql_query("SELECT ratings.id as ratingid,episodes.title as episodetitle,episodes.season,episodes.episode,shows.title as showtitle,episodes.id as epid,ratings.rating,ratings.ip,ratings.ratingdate FROM ratings,episodes,shows WHERE ratings.episodeid=episodes.id AND episodes.show_id=shows.id ORDER BY ratingdate DESC LIMIT $start,100") or die(mysql_error()); $ratings = array(); if (mysql_num_rows($e)){ while($sor = mysql_fetch_array($e)){ extract($sor); $ratings[$ratingid]=array(); $ratings[$ratingid]['episodetitle']=$episodetitle; if (!$ratings[$ratingid]['episodetitle']){ $ratings[$ratingid]['episodetitle'] = "Season $season, Episode $episode"; } if (!$lang){ $ratings[$ratingid]['showtitle'] = json_decode($showtitle,true); } else { $ratings[$ratingid]['showtitle'] = json_decode($showtitle,true); $ratings[$ratingid]['showtitle'] = $ratings[$ratingid]['showtitle'][$lang]; } $ratings[$ratingid]['rating']=$rating; $ratings[$ratingid]['date']=$ratingdate; $ratings[$ratingid]['ip']=$ip; $ratings[$ratingid]['episodeid']=$epid; } } return $ratings; } /* Marks an episode to be submitted to a given submit target */ public function addSubmit($epid,$type,$link){ $link = mysql_real_escape_string($link); $e = mysql_query("SELECT id FROM tv_submits WHERE episode_id=$epid AND type=$type") or die(mysql_error()); if (mysql_num_rows($e)==0){ $today = date("Y-m-d H:i:s"); $e = mysql_query("INSERT INTO tv_submits(episode_id,type,link,timestamp) VALUES($epid,$type,'$link','$today')") or die(mysql_error()); } } /* Returns a list of all the submitted episodes to the given submit target */ public function getAllSubmits($type){ $submits = array(); $e = mysql_query("SELECT * FROM tv_submits WHERE type=$type") or die(mysql_error()); if (mysql_num_rows($e)){ while($s = mysql_fetch_array($e)){ extract($s); $submits[$episode_id]=array(); $submits[$episode_id]['link']=$link; $submits[$episode_id]['timestamp']=$timestamp; } } return $submits; } /* Adds a broken episode report */ public function reportEpisode($episode,$problem,$ip,$user_agent=''){ $episode = mysql_real_escape_string($episode); $problem = mysql_real_escape_string($problem); $user_agent = mysql_real_escape_string($user_agent); $e = mysql_query("SELECT id FROM broken_episodes WHERE ip='$ip' AND episodeid='$episode'") or die(mysql_error()); if (isset($_SESSION['loggeduser_id']) && $_SESSION['loggeduser_id']){ $user_id = $_SESSION['loggeduser_id']; } else { $user_id = 0; } if (mysql_num_rows($e)==0){ $today = date("Y-m-d H:i:s"); $e = mysql_query("INSERT INTO broken_episodes(episodeid,reportdate,problem,ip,user_id,user_agent) VALUES('$episode','$today','$problem','$ip','$user_id','$user_agent')") or die(mysql_error()); } } /* Returns the average rating for the episode */ public function getRating($episodeid){ $episodeid = mysql_real_escape_string($episodeid); $average = 0; $e = mysql_query("SELECT AVG(`rating`) as average FROM ratings WHERE episodeid='$episodeid'") or die(mysql_error()); if (mysql_num_rows($e)>0){ extract(mysql_fetch_array($e)); } return $average; } /* Adds an episode rating */ public function addRating($episodeid,$rating,$ip){ $episodeid = mysql_real_escape_string($episodeid); $rating = mysql_real_escape_string($rating); $e = mysql_query("SELECT id FROM ratings WHERE episodeid='$episodeid' AND ip='$ip'") or die(mysql_error()); $today = date("Y-m-d H:i:s"); if (mysql_num_rows($e)>0){ extract(mysql_fetch_array($e)); $e = mysql_query("UPDATE ratings SET rating=$rating,ratingdate='$today' WHERE ip='$ip' AND episodeid='$episodeid'") or die(mysql_error()); } else { $e = mysql_query("INSERT INTO ratings(episodeid,rating,ip,ratingdate) VALUES('$episodeid','$rating','$ip','$today')") or die(mysql_error()); } return 1; } /* Returns episode details */ public function getEpisodeById($id,$lang=false){ $e = mysql_query("SELECT shows.id as showid,shows.sidereel_url,episodes.embed,episodes.title as episodetitle,shows.permalink,shows.thumbnail,shows.title as showtitle,episodes.thumbnail as episode_thumbnail, episodes.id as epid,episodes.episode,episodes.description,episodes.season,episodes.title as episodetitle FROM episodes, shows WHERE episodes.show_id=shows.id AND episodes.id=$id") or die(mysql_error()); $ep = array(); if (mysql_num_rows($e)){ extract(mysql_fetch_array($e)); $ep['title']=$episodetitle; $ep['description']=$description; if ($episode_thumbnail){ $ep['thumbnail']=$episode_thumbnail; } else { $ep['thumbnail']=$thumbnail; } $ep['season']=$season; $ep['episode']=$episode; if (!$episodetitle) $episodetitle = "Season $season, Episode $episode"; $ep['episodetitle']=$episodetitle; $ep['embed'] = $embed; if (!$lang){ $ep['showtitle'] = json_decode($showtitle,true); } else { $ep['showtitle'] = json_decode($showtitle,true); $ep['showtitle'] = $ep['showtitle'][$lang]; } $ep['show_sidereel']=$sidereel_url; $ep['showid']=$showid; $ep['show_perma']=$permalink; $ep['url']="/".$permalink."/season/".$season."/episode/".$episode; } return $ep; } /* Returns episode data based on show_id episode and season number */ public function getEpisode($showid,$season,$episode){ $season = mysql_real_escape_string($season); $episode = mysql_real_escape_string($episode); $showid = mysql_real_escape_string($showid); $e = mysql_query("SELECT * FROM episodes WHERE season=$season AND episode=$episode AND show_id=$showid") or die(mysql_error()); if (mysql_num_rows($e)){ extract(mysql_fetch_assoc($e)); $ret = array(); $ret['id'] = $id; $ret['title'] = $title; if (!$ret['title']){ $ret['title']="Season $season, Episode $episode"; } $ret['description'] = $description; $ret['episodeid'] = $id; $ret['thumbnail'] = $thumbnail; return $ret; } else { return 0; } } /* gets the season / episode number for the latest episode of the specified show */ public function getLatestEpisodeDetails($showid){ $e = mysql_query("SELECT season,episode FROM episodes WHERE show_id=$showid ORDER BY season DESC,episode DESC LIMIT 1") or die(mysql_error()); if (mysql_num_rows($e)){ extract(mysql_fetch_array($e)); return array("season" => $season,"episode" => $episode); } else { return array("season" => 0,"episode" => 0); } } /* Get the latest episode for a given show */ public function getLatestEpisode($showid=null){ if (@$showid){ $add=" AND shows.id=$showid"; } else { $add=""; } $query = "SELECT episodes.show_id as `catid`,episodes.thumbnail,shows.thumbnail as category_thumbnail,shows.title,episodes.season,MAX(`episodes`.`season`) as `maxseason`,MAX(`episodes`.`episode`) as maxepisode FROM episodes,shows WHERE episodes.show_id=shows.id $add GROUP BY episodes.show_id,episodes.season"; $e = mysql_query($query) or die(mysql_error()); $ret = array(); if (mysql_num_rows($e)){ while($s=mysql_fetch_array($e)){ extract($s); if ($maxseason==$season){ $ret[$catid]=array(); $ret[$catid]['season']=$maxseason; $ret[$catid]['episode']=$maxepisode; $ret[$catid]['title']=$title; if (!$ret[$catid]['title']){ $ret[$catid]['title'] = "Season $maxseason, Episode $maxepisode"; } if ($thumbnail){ $ret[$catid]['thumbnail']=$thumbnail; } else { $ret[$catid]['thumbnail']=$category_thumbnail; } } } } return $ret; } /* Gets the next episode from given position */ public function getNextEpisode($show_id,$season,$episode){ $show_id = mysql_real_escape_string($show_id); $season = mysql_real_escape_string($season); $episode = mysql_real_escape_string($episode); $e = mysql_query("SELECT season,episode FROM episodes WHERE ((season='$season' AND episode>'$episode') OR (season>$season AND episode<$episode)) AND show_id='$show_id' ORDER BY season ASC, episode ASC LIMIT 1") or die(mysql_error()); $res = array(); if (mysql_num_rows($e)){ extract(mysql_fetch_assoc($e)); $res['season'] = $season; $res['episode'] = $episode; } return $res; } /* Gets the previous episode from given position */ public function getPrevEpisode($show_id,$season,$episode){ $show_id = mysql_real_escape_string($show_id); $season = mysql_real_escape_string($season); $episode = mysql_real_escape_string($episode); $e = mysql_query("SELECT season,episode FROM episodes WHERE ((season='$season' AND episode<'$episode') OR (season<$season AND episode>$episode)) AND show_id='$show_id' ORDER BY season DESC, episode DESC LIMIT 1") or die(mysql_error()); $res = array(); if (mysql_num_rows($e)){ extract(mysql_fetch_assoc($e)); $res['season'] = $season; $res['episode'] = $episode; } return $res; } /* Returns the newest episodes */ public function getLastAdditions($limit=20,$perma=null){ $ret = array(); if ($perma){ $permaadd = " AND shows.permalink='".mysql_real_escape_string($perma)."' "; } else { $permaadd = ''; } $query = "SELECT episodes.*,episodes.thumbnail,shows.title as showtitle,shows.id as showid,shows.permalink,shows.thumbnail as show_thumbnail FROM shows,episodes WHERE shows.id=episodes.show_id $permaadd ORDER BY episodes.id DESC LIMIT $limit"; $e = mysql_query($query) or die(mysql_error()); if (mysql_num_rows($e)){ while($s = mysql_fetch_array($e)){ extract($s); $ret[$id]=array(); $ret[$id]['showtitle']=$showtitle; $ret[$id]['title']=$title; if (!$ret[$id]['title']){ $ret[$id]['title'] = "Season $season, Episode $episode"; } $ret[$id]['showid']=$showid; $ret[$id]['season']=$season; $ret[$id]['episode']=$episode; $ret[$id]['description']=$description; $ret[$id]['embed']=$embed; $ret[$id]['thumbnail']=$thumbnail; $ret[$id]['show_thumbnail']=$show_thumbnail; $ret[$id]['thumbnail']=$thumbnail; $ret[$id]['perma']=$permalink; $ret[$id]['date_added']=$date_added; } } return $ret; } /* Returns similar shows to the given ids */ public function getSimilarShows($ids,$limit=20,$lang=false){ $e = mysql_query("SELECT * FROM similar_shows WHERE show1 IN (".implode(",",$ids).") AND show2 IN (SELECT DISTINCT show_id FROM episodes)") or die(mysql_error()); $shows = array(); if (mysql_num_rows($e)){ $similar = array(); while($s = mysql_fetch_assoc($e)){ if (!in_array($s['show2'],$ids)){ @$similar[$s['show2']]+=$s['score']; } } arsort($similar); $similar_ids = array(); foreach($similar as $key => $val){ $similar_ids[] = $key; if (count($similar_ids)>=$limit){ break; } } $e = mysql_query("SELECT * FROM shows WHERE id IN (".implode(",",$similar_ids).")") or die(mysql_error()); if (mysql_num_rows($e)){ while($s = mysql_fetch_assoc($e)){ $shows[$s['id']] = $this->formatShowData($s, false, $lang); } } } return $shows; } }?>
apache-2.0
centreon/centreon-broker
bam/src/bool_xor.cc
1134
/* ** Copyright 2014 Centreon ** ** 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. ** ** For more information : contact@centreon.com */ #include "com/centreon/broker/bam/bool_xor.hh" using namespace com::centreon::broker::bam; /** * Get the hard value. * * @return Evaluation of the expression with hard values. */ double bool_xor::value_hard() { return (!_left_hard && _right_hard) || (_left_hard && !_right_hard); } /** * Get the soft value. * * @return Evaluation of the expression with soft values. */ double bool_xor::value_soft() { return (!_left_soft && _right_soft) || (_left_soft && !_right_soft); }
apache-2.0
DaniPix/Countries
app/src/main/java/com/readr/ro/countries/service/DownloadManagerListener.java
266
package com.readr.ro.countries.service; /** * Created by Domnica on 12/9/2016. */ public interface DownloadManagerListener { enum CompletionStatus { SUCCESS, FAILED, CANCELED } void onMediaComplete(Object mid, CompletionStatus status); }
apache-2.0
jmullercuber/siemens2014
siemens2014/src/driver.js
4165
#!/usr/bin/env rhino print("Hello, World!"); //importClass(Packages.org.model.Board); // driver shouldn't interact with Boards importClass(Packages.org.samjoey.parse.Parser); importClass(Packages.org.samjoey.model.Game); importPackage(Packages.org.samjoey.calculator); importClass(Packages.org.samjoey.pattern.PatternFinder); importClass(Packages.org.samjoey.graphing.GraphUtility); load("org/samjoey/gameLooper/GameLooper.js"); // import straight js load("org/samjoey/calculator/calcDefs.js"); // in JS, use arguments vs args var CLIArgs = { 'fileLoc': "", 'verbose': false, 'graphs': true }; for (var i in arguments) { var arg = arguments[i]; switch (true) { // Verbose case (arg.indexOf('-v')==0 || arg.indexOf('--verbose')==0 || arg.indexOf('/v')==0): if(arg.indexOf(':')>1) { // param, like this "$ ./driver.js -v:false" CLIArgs['verbose'] = (arg.substring(arg.indexOf(':')+1)).toLowerCase() === 'true'; // cast parameter to boolean, false is default } else { // no param, like this "$ ./driver.js -v" CLIArgs['verbose'] = true; } break; // Graphs case (arg.indexOf('-g')==0 || arg.indexOf('--graphs')==0 || arg.indexOf('/g')==0): if(arg.indexOf(':')>1) { // param, like this "$ ./driver.js -g:false" CLIArgs['graphs'] = (arg.substring(arg.indexOf(':')+1)).toLowerCase() === 'true'; // cast parameter to boolean, false is default } else { // no param, like this "$ ./driver.js -g" CLIArgs['graphs'] = true; } break; default: if (i == arguments.length-1) { // if last argument file = new java.io.File(arg); if (file.exists()) { // allows for argument to be non-absolute CLIArgs['fileLoc'] += file.getCanonicalPath(); break; } else { throw new Error("Not a valid file"); } } throw new Error("Unknown argument -->" + arg + "<--"); } } // Retrieve an ArrayList of Games to analyze var gameList = Parser.parseGames(CLIArgs['fileLoc']); // Get access to a GameLooper var gameLooper = new GameLooper(); gameLooper.addCalculator(TotalisticUnweightedCenter('x')); gameLooper.addCalculator(TotalisticWeightedCenter('x')); //gameLooper.addCalculator(PieceCountVars(white_or_black_or_all, weighted_or_unweighted)); var calcType = { 'Players': ["White", "Black", "Total"], 'Weights': ["Weighted", "Unweighted"] }; for (i in calcType['Players']) { gameLooper.addCalculator(AveragePieceValue(calcType['Players'][i])); for (j in calcType['Weights']) { gameLooper.addCalculator(PieceCountVars(calcType['Players'][i], calcType['Weights'][j])); } } gameLooper.addCalculator(new JCalculatorChecks("Black")); gameLooper.addCalculator(new JCalculatorChecks("White")); gameLooper.addCalculator(new JCalculatorMoveTime("")); gameLooper.addCalculator(new JCalculatorMoveTime("White")); gameLooper.addCalculator(new JCalculatorMoveTime("Black")); gameLooper.addCalculator(new JCalculatorPawnMovement()); //gameLooper.addCalculator(new JCalculatorMoveDistance("")); //gameLooper.addCalculator(new JCalculatorMoveDistance("Black")); //gameLooper.addCalculator(new JCalculatorMoveDistance("White")); gameLooper.addCalculator(new JCalculatorMoveDistance()); gameLooper.addCalculator(new JCalculatorWhiteMoveDistance()); gameLooper.addCalculator(new JCalculatorBlackMoveDistance()); gameLooper.addCalculator(Symmetry("reflect")); gameLooper.addCalculator(Symmetry("rotate")); // gameLooper.addCalculator(<calcNameHere>); // For every game... for (var i=0; i<gameList.size(); i++) { // save to a variable var currentGame = gameList.get(i); // pass to the correct gameLooper // may have different gls finding different stuff gameLooper.open(currentGame); // do your magic! gameLooper.calculate(); // show the results if (CLIArgs['verbose']) { print("-----------------------------------"); gameLooper.read(); } // prepare to move on to the next gameLooper.close(); } // Do the graphical stuff in a new thread if (CLIArgs['graphs']) { (new java.lang.Thread( function() { // For notation check Rhino documentation. JavaScript Functions as Java Interfaces GraphUtility.createGraphs(gameList); } )).start(); } print('Done');
apache-2.0
opetrovski/development
oscm-portal/javasrc/org/oscm/ui/converter/PaymentTypeConverter.java
1670
/******************************************************************************* * Copyright FUJITSU LIMITED 2017 *******************************************************************************/ package org.oscm.ui.converter; import org.oscm.internal.intf.AccountService; import org.oscm.internal.vo.VOPaymentInfo; import javax.ejb.EJB; import javax.enterprise.context.RequestScoped; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.convert.Converter; import javax.inject.Named; @Named @RequestScoped public class PaymentTypeConverter implements Converter { private AccountService accountingService; @Override public Object getAsObject(FacesContext context, UIComponent component, String value) { VOPaymentInfo retVal = null; for (VOPaymentInfo vopsp : accountingService.getPaymentInfos()) { if ((Long.valueOf(vopsp.getKey()).toString().equals(value))) { retVal = vopsp; } } return retVal; } @Override public String getAsString(FacesContext context, UIComponent component, Object object) { String retVal; if (!(object instanceof VOPaymentInfo)) { retVal = ""; } else { retVal = String.valueOf(((VOPaymentInfo) object).getKey()); } return retVal; } public AccountService getAccountingService() { return accountingService; } @EJB public void setAccountingService(AccountService accountingService) { this.accountingService = accountingService; } }
apache-2.0
prometheus/node_exporter
collector/fibrechannel_linux.go
6534
// Copyright 2021 The Prometheus Authors // 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. //go:build linux && !nofibrechannel // +build linux,!nofibrechannel package collector import ( "fmt" "os" "github.com/go-kit/log" "github.com/go-kit/log/level" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/procfs/sysfs" ) const maxUint64 = ^uint64(0) type fibrechannelCollector struct { fs sysfs.FS metricDescs map[string]*prometheus.Desc logger log.Logger subsystem string } func init() { registerCollector("fibrechannel", defaultEnabled, NewFibreChannelCollector) } // NewFibreChannelCollector returns a new Collector exposing FibreChannel stats. func NewFibreChannelCollector(logger log.Logger) (Collector, error) { var i fibrechannelCollector var err error i.fs, err = sysfs.NewFS(*sysPath) if err != nil { return nil, fmt.Errorf("failed to open sysfs: %w", err) } i.logger = logger // Detailed description for all metrics. descriptions := map[string]string{ "dumped_frames_total": "Number of dumped frames", "loss_of_signal_total": "Number of times signal has been lost", "loss_of_sync_total": "Number of failures on either bit or transmission word boundaries", "rx_frames_total": "Number of frames received", "error_frames_total": "Number of errors in frames", "invalid_tx_words_total": "Number of invalid words transmitted by host port", "seconds_since_last_reset_total": "Number of seconds since last host port reset", "tx_words_total": "Number of words transmitted by host port", "invalid_crc_total": "Invalid Cyclic Redundancy Check count", "nos_total": "Number Not_Operational Primitive Sequence received by host port", "fcp_packet_aborts_total": "Number of aborted packets", "rx_words_total": "Number of words received by host port", "tx_frames_total": "Number of frames transmitted by host port", "link_failure_total": "Number of times the host port link has failed", "name": "Name of Fibre Channel HBA", "speed": "Current operating speed", "port_state": "Current port state", "port_type": "Port type, what the port is connected to", "symbolic_name": "Symoblic Name", "node_name": "Node Name as hexadecimal string", "port_id": "Port ID as string", "port_name": "Port Name as hexadecimal string", "fabric_name": "Fabric Name; 0 if PTP", "dev_loss_tmo": "Device Loss Timeout in seconds", "supported_classes": "The FC classes supported", "supported_speeds": "The FC speeds supported", } i.metricDescs = make(map[string]*prometheus.Desc) i.subsystem = "fibrechannel" for metricName, description := range descriptions { i.metricDescs[metricName] = prometheus.NewDesc( prometheus.BuildFQName(namespace, i.subsystem, metricName), description, []string{"fc_host"}, nil, ) } return &i, nil } func (c *fibrechannelCollector) pushMetric(ch chan<- prometheus.Metric, name string, value uint64, host string, valueType prometheus.ValueType) { ch <- prometheus.MustNewConstMetric(c.metricDescs[name], valueType, float64(value), host) } func (c *fibrechannelCollector) pushCounter(ch chan<- prometheus.Metric, name string, value uint64, host string) { // Don't push counters that aren't implemented (a counter equal to maxUint64 is unimplemented by the HBA firmware) if value != maxUint64 { c.pushMetric(ch, name, value, host, prometheus.CounterValue) } } func (c *fibrechannelCollector) Update(ch chan<- prometheus.Metric) error { hosts, err := c.fs.FibreChannelClass() if err != nil { if os.IsNotExist(err) { level.Debug(c.logger).Log("msg", "fibrechannel statistics not found, skipping") return ErrNoData } return fmt.Errorf("error obtaining FibreChannel class info: %s", err) } for _, host := range hosts { infoDesc := prometheus.NewDesc( prometheus.BuildFQName(namespace, c.subsystem, "info"), "Non-numeric data from /sys/class/fc_host/<host>, value is always 1.", []string{"fc_host", "speed", "port_state", "port_type", "port_id", "port_name", "fabric_name", "symbolic_name", "supported_classes", "supported_speeds", "dev_loss_tmo"}, nil, ) infoValue := 1.0 // First push the Host values ch <- prometheus.MustNewConstMetric(infoDesc, prometheus.GaugeValue, infoValue, host.Name, host.Speed, host.PortState, host.PortType, host.PortID, host.PortName, host.FabricName, host.SymbolicName, host.SupportedClasses, host.SupportedSpeeds, host.DevLossTMO) // Then the counters c.pushCounter(ch, "dumped_frames_total", host.Counters.DumpedFrames, host.Name) c.pushCounter(ch, "error_frames_total", host.Counters.ErrorFrames, host.Name) c.pushCounter(ch, "invalid_crc_total", host.Counters.InvalidCRCCount, host.Name) c.pushCounter(ch, "rx_frames_total", host.Counters.RXFrames, host.Name) c.pushCounter(ch, "rx_words_total", host.Counters.RXWords, host.Name) c.pushCounter(ch, "tx_frames_total", host.Counters.TXFrames, host.Name) c.pushCounter(ch, "tx_words_total", host.Counters.TXWords, host.Name) c.pushCounter(ch, "seconds_since_last_reset_total", host.Counters.SecondsSinceLastReset, host.Name) c.pushCounter(ch, "invalid_tx_words_total", host.Counters.InvalidTXWordCount, host.Name) c.pushCounter(ch, "link_failure_total", host.Counters.LinkFailureCount, host.Name) c.pushCounter(ch, "loss_of_sync_total", host.Counters.LossOfSyncCount, host.Name) c.pushCounter(ch, "loss_of_signal_total", host.Counters.LossOfSignalCount, host.Name) c.pushCounter(ch, "nos_total", host.Counters.NosCount, host.Name) c.pushCounter(ch, "fcp_packet_aborts_total", host.Counters.FCPPacketAborts, host.Name) } return nil }
apache-2.0
jentfoo/aws-sdk-java
aws-java-sdk-greengrass/src/main/java/com/amazonaws/services/greengrass/AWSGreengrass.java
63087
/* * Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ package com.amazonaws.services.greengrass; import javax.annotation.Generated; import com.amazonaws.*; import com.amazonaws.regions.*; import com.amazonaws.services.greengrass.model.*; /** * Interface for accessing AWS Greengrass. * <p> * <b>Note:</b> Do not directly implement this interface, new methods are added to it regularly. Extend from * {@link com.amazonaws.services.greengrass.AbstractAWSGreengrass} instead. * </p> * <p> * AWS IoT Greengrass seamlessly extends AWS onto physical devices so they can act locally on the data they generate, * while still using the cloud for management, analytics, and durable storage. AWS IoT Greengrass ensures your devices * can respond quickly to local events and operate with intermittent connectivity. AWS IoT Greengrass minimizes the cost * of transmitting data to the cloud by allowing you to author AWS Lambda functions that execute locally. */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public interface AWSGreengrass { /** * The region metadata service name for computing region endpoints. You can use this value to retrieve metadata * (such as supported regions) of the service. * * @see RegionUtils#getRegionsForService(String) */ String ENDPOINT_PREFIX = "greengrass"; /** * Associates a role with a group. Your Greengrass core will use the role to access AWS cloud services. The role's * permissions should allow Greengrass core Lambda functions to perform actions against the cloud. * * @param associateRoleToGroupRequest * @return Result of the AssociateRoleToGroup operation returned by the service. * @throws BadRequestException * invalid request * @throws InternalServerErrorException * server error * @sample AWSGreengrass.AssociateRoleToGroup * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/AssociateRoleToGroup" * target="_top">AWS API Documentation</a> */ AssociateRoleToGroupResult associateRoleToGroup(AssociateRoleToGroupRequest associateRoleToGroupRequest); /** * Associates a role with your account. AWS IoT Greengrass will use the role to access your Lambda functions and AWS * IoT resources. This is necessary for deployments to succeed. The role must have at least minimum permissions in * the policy ''AWSGreengrassResourceAccessRolePolicy''. * * @param associateServiceRoleToAccountRequest * @return Result of the AssociateServiceRoleToAccount operation returned by the service. * @throws BadRequestException * invalid request * @throws InternalServerErrorException * server error * @sample AWSGreengrass.AssociateServiceRoleToAccount * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/AssociateServiceRoleToAccount" * target="_top">AWS API Documentation</a> */ AssociateServiceRoleToAccountResult associateServiceRoleToAccount(AssociateServiceRoleToAccountRequest associateServiceRoleToAccountRequest); /** * Creates a connector definition. You may provide the initial version of the connector definition now or use * ''CreateConnectorDefinitionVersion'' at a later time. * * @param createConnectorDefinitionRequest * @return Result of the CreateConnectorDefinition operation returned by the service. * @throws BadRequestException * invalid request * @sample AWSGreengrass.CreateConnectorDefinition * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/CreateConnectorDefinition" * target="_top">AWS API Documentation</a> */ CreateConnectorDefinitionResult createConnectorDefinition(CreateConnectorDefinitionRequest createConnectorDefinitionRequest); /** * Creates a version of a connector definition which has already been defined. * * @param createConnectorDefinitionVersionRequest * @return Result of the CreateConnectorDefinitionVersion operation returned by the service. * @throws BadRequestException * invalid request * @sample AWSGreengrass.CreateConnectorDefinitionVersion * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/CreateConnectorDefinitionVersion" * target="_top">AWS API Documentation</a> */ CreateConnectorDefinitionVersionResult createConnectorDefinitionVersion(CreateConnectorDefinitionVersionRequest createConnectorDefinitionVersionRequest); /** * Creates a core definition. You may provide the initial version of the core definition now or use * ''CreateCoreDefinitionVersion'' at a later time. Greengrass groups must each contain exactly one Greengrass core. * * @param createCoreDefinitionRequest * Information needed to create a core definition. * @return Result of the CreateCoreDefinition operation returned by the service. * @throws BadRequestException * invalid request * @sample AWSGreengrass.CreateCoreDefinition * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/CreateCoreDefinition" * target="_top">AWS API Documentation</a> */ CreateCoreDefinitionResult createCoreDefinition(CreateCoreDefinitionRequest createCoreDefinitionRequest); /** * Creates a version of a core definition that has already been defined. Greengrass groups must each contain exactly * one Greengrass core. * * @param createCoreDefinitionVersionRequest * @return Result of the CreateCoreDefinitionVersion operation returned by the service. * @throws BadRequestException * invalid request * @sample AWSGreengrass.CreateCoreDefinitionVersion * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/CreateCoreDefinitionVersion" * target="_top">AWS API Documentation</a> */ CreateCoreDefinitionVersionResult createCoreDefinitionVersion(CreateCoreDefinitionVersionRequest createCoreDefinitionVersionRequest); /** * Creates a deployment. ''CreateDeployment'' requests are idempotent with respect to the ''X-Amzn-Client-Token'' * token and the request parameters. * * @param createDeploymentRequest * @return Result of the CreateDeployment operation returned by the service. * @throws BadRequestException * invalid request * @sample AWSGreengrass.CreateDeployment * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/CreateDeployment" target="_top">AWS * API Documentation</a> */ CreateDeploymentResult createDeployment(CreateDeploymentRequest createDeploymentRequest); /** * Creates a device definition. You may provide the initial version of the device definition now or use * ''CreateDeviceDefinitionVersion'' at a later time. * * @param createDeviceDefinitionRequest * @return Result of the CreateDeviceDefinition operation returned by the service. * @throws BadRequestException * invalid request * @sample AWSGreengrass.CreateDeviceDefinition * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/CreateDeviceDefinition" * target="_top">AWS API Documentation</a> */ CreateDeviceDefinitionResult createDeviceDefinition(CreateDeviceDefinitionRequest createDeviceDefinitionRequest); /** * Creates a version of a device definition that has already been defined. * * @param createDeviceDefinitionVersionRequest * @return Result of the CreateDeviceDefinitionVersion operation returned by the service. * @throws BadRequestException * invalid request * @sample AWSGreengrass.CreateDeviceDefinitionVersion * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/CreateDeviceDefinitionVersion" * target="_top">AWS API Documentation</a> */ CreateDeviceDefinitionVersionResult createDeviceDefinitionVersion(CreateDeviceDefinitionVersionRequest createDeviceDefinitionVersionRequest); /** * Creates a Lambda function definition which contains a list of Lambda functions and their configurations to be * used in a group. You can create an initial version of the definition by providing a list of Lambda functions and * their configurations now, or use ''CreateFunctionDefinitionVersion'' later. * * @param createFunctionDefinitionRequest * @return Result of the CreateFunctionDefinition operation returned by the service. * @throws BadRequestException * invalid request * @sample AWSGreengrass.CreateFunctionDefinition * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/CreateFunctionDefinition" * target="_top">AWS API Documentation</a> */ CreateFunctionDefinitionResult createFunctionDefinition(CreateFunctionDefinitionRequest createFunctionDefinitionRequest); /** * Creates a version of a Lambda function definition that has already been defined. * * @param createFunctionDefinitionVersionRequest * Information needed to create a function definition version. * @return Result of the CreateFunctionDefinitionVersion operation returned by the service. * @throws BadRequestException * invalid request * @sample AWSGreengrass.CreateFunctionDefinitionVersion * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/CreateFunctionDefinitionVersion" * target="_top">AWS API Documentation</a> */ CreateFunctionDefinitionVersionResult createFunctionDefinitionVersion(CreateFunctionDefinitionVersionRequest createFunctionDefinitionVersionRequest); /** * Creates a group. You may provide the initial version of the group or use ''CreateGroupVersion'' at a later time. * Tip: You can use the ''gg_group_setup'' package (https://github.com/awslabs/aws-greengrass-group-setup) as a * library or command-line application to create and deploy Greengrass groups. * * @param createGroupRequest * @return Result of the CreateGroup operation returned by the service. * @throws BadRequestException * invalid request * @sample AWSGreengrass.CreateGroup * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/CreateGroup" target="_top">AWS API * Documentation</a> */ CreateGroupResult createGroup(CreateGroupRequest createGroupRequest); /** * Creates a CA for the group. If a CA already exists, it will rotate the existing CA. * * @param createGroupCertificateAuthorityRequest * @return Result of the CreateGroupCertificateAuthority operation returned by the service. * @throws BadRequestException * invalid request * @throws InternalServerErrorException * server error * @sample AWSGreengrass.CreateGroupCertificateAuthority * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/CreateGroupCertificateAuthority" * target="_top">AWS API Documentation</a> */ CreateGroupCertificateAuthorityResult createGroupCertificateAuthority(CreateGroupCertificateAuthorityRequest createGroupCertificateAuthorityRequest); /** * Creates a version of a group which has already been defined. * * @param createGroupVersionRequest * @return Result of the CreateGroupVersion operation returned by the service. * @throws BadRequestException * invalid request * @sample AWSGreengrass.CreateGroupVersion * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/CreateGroupVersion" target="_top">AWS * API Documentation</a> */ CreateGroupVersionResult createGroupVersion(CreateGroupVersionRequest createGroupVersionRequest); /** * Creates a logger definition. You may provide the initial version of the logger definition now or use * ''CreateLoggerDefinitionVersion'' at a later time. * * @param createLoggerDefinitionRequest * @return Result of the CreateLoggerDefinition operation returned by the service. * @throws BadRequestException * invalid request * @sample AWSGreengrass.CreateLoggerDefinition * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/CreateLoggerDefinition" * target="_top">AWS API Documentation</a> */ CreateLoggerDefinitionResult createLoggerDefinition(CreateLoggerDefinitionRequest createLoggerDefinitionRequest); /** * Creates a version of a logger definition that has already been defined. * * @param createLoggerDefinitionVersionRequest * @return Result of the CreateLoggerDefinitionVersion operation returned by the service. * @throws BadRequestException * invalid request * @sample AWSGreengrass.CreateLoggerDefinitionVersion * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/CreateLoggerDefinitionVersion" * target="_top">AWS API Documentation</a> */ CreateLoggerDefinitionVersionResult createLoggerDefinitionVersion(CreateLoggerDefinitionVersionRequest createLoggerDefinitionVersionRequest); /** * Creates a resource definition which contains a list of resources to be used in a group. You can create an initial * version of the definition by providing a list of resources now, or use ''CreateResourceDefinitionVersion'' later. * * @param createResourceDefinitionRequest * @return Result of the CreateResourceDefinition operation returned by the service. * @throws BadRequestException * invalid request * @sample AWSGreengrass.CreateResourceDefinition * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/CreateResourceDefinition" * target="_top">AWS API Documentation</a> */ CreateResourceDefinitionResult createResourceDefinition(CreateResourceDefinitionRequest createResourceDefinitionRequest); /** * Creates a version of a resource definition that has already been defined. * * @param createResourceDefinitionVersionRequest * @return Result of the CreateResourceDefinitionVersion operation returned by the service. * @throws BadRequestException * invalid request * @sample AWSGreengrass.CreateResourceDefinitionVersion * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/CreateResourceDefinitionVersion" * target="_top">AWS API Documentation</a> */ CreateResourceDefinitionVersionResult createResourceDefinitionVersion(CreateResourceDefinitionVersionRequest createResourceDefinitionVersionRequest); /** * Creates a software update for a core or group of cores (specified as an IoT thing group.) Use this to update the * OTA Agent as well as the Greengrass core software. It makes use of the IoT Jobs feature which provides additional * commands to manage a Greengrass core software update job. * * @param createSoftwareUpdateJobRequest * @return Result of the CreateSoftwareUpdateJob operation returned by the service. * @throws BadRequestException * invalid request * @throws InternalServerErrorException * server error * @sample AWSGreengrass.CreateSoftwareUpdateJob * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/CreateSoftwareUpdateJob" * target="_top">AWS API Documentation</a> */ CreateSoftwareUpdateJobResult createSoftwareUpdateJob(CreateSoftwareUpdateJobRequest createSoftwareUpdateJobRequest); /** * Creates a subscription definition. You may provide the initial version of the subscription definition now or use * ''CreateSubscriptionDefinitionVersion'' at a later time. * * @param createSubscriptionDefinitionRequest * @return Result of the CreateSubscriptionDefinition operation returned by the service. * @throws BadRequestException * invalid request * @sample AWSGreengrass.CreateSubscriptionDefinition * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/CreateSubscriptionDefinition" * target="_top">AWS API Documentation</a> */ CreateSubscriptionDefinitionResult createSubscriptionDefinition(CreateSubscriptionDefinitionRequest createSubscriptionDefinitionRequest); /** * Creates a version of a subscription definition which has already been defined. * * @param createSubscriptionDefinitionVersionRequest * @return Result of the CreateSubscriptionDefinitionVersion operation returned by the service. * @throws BadRequestException * invalid request * @sample AWSGreengrass.CreateSubscriptionDefinitionVersion * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/CreateSubscriptionDefinitionVersion" * target="_top">AWS API Documentation</a> */ CreateSubscriptionDefinitionVersionResult createSubscriptionDefinitionVersion( CreateSubscriptionDefinitionVersionRequest createSubscriptionDefinitionVersionRequest); /** * Deletes a connector definition. * * @param deleteConnectorDefinitionRequest * @return Result of the DeleteConnectorDefinition operation returned by the service. * @throws BadRequestException * invalid request * @sample AWSGreengrass.DeleteConnectorDefinition * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/DeleteConnectorDefinition" * target="_top">AWS API Documentation</a> */ DeleteConnectorDefinitionResult deleteConnectorDefinition(DeleteConnectorDefinitionRequest deleteConnectorDefinitionRequest); /** * Deletes a core definition. * * @param deleteCoreDefinitionRequest * @return Result of the DeleteCoreDefinition operation returned by the service. * @throws BadRequestException * invalid request * @sample AWSGreengrass.DeleteCoreDefinition * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/DeleteCoreDefinition" * target="_top">AWS API Documentation</a> */ DeleteCoreDefinitionResult deleteCoreDefinition(DeleteCoreDefinitionRequest deleteCoreDefinitionRequest); /** * Deletes a device definition. * * @param deleteDeviceDefinitionRequest * @return Result of the DeleteDeviceDefinition operation returned by the service. * @throws BadRequestException * invalid request * @sample AWSGreengrass.DeleteDeviceDefinition * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/DeleteDeviceDefinition" * target="_top">AWS API Documentation</a> */ DeleteDeviceDefinitionResult deleteDeviceDefinition(DeleteDeviceDefinitionRequest deleteDeviceDefinitionRequest); /** * Deletes a Lambda function definition. * * @param deleteFunctionDefinitionRequest * @return Result of the DeleteFunctionDefinition operation returned by the service. * @throws BadRequestException * invalid request * @sample AWSGreengrass.DeleteFunctionDefinition * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/DeleteFunctionDefinition" * target="_top">AWS API Documentation</a> */ DeleteFunctionDefinitionResult deleteFunctionDefinition(DeleteFunctionDefinitionRequest deleteFunctionDefinitionRequest); /** * Deletes a group. * * @param deleteGroupRequest * @return Result of the DeleteGroup operation returned by the service. * @throws BadRequestException * invalid request * @sample AWSGreengrass.DeleteGroup * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/DeleteGroup" target="_top">AWS API * Documentation</a> */ DeleteGroupResult deleteGroup(DeleteGroupRequest deleteGroupRequest); /** * Deletes a logger definition. * * @param deleteLoggerDefinitionRequest * @return Result of the DeleteLoggerDefinition operation returned by the service. * @throws BadRequestException * invalid request * @sample AWSGreengrass.DeleteLoggerDefinition * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/DeleteLoggerDefinition" * target="_top">AWS API Documentation</a> */ DeleteLoggerDefinitionResult deleteLoggerDefinition(DeleteLoggerDefinitionRequest deleteLoggerDefinitionRequest); /** * Deletes a resource definition. * * @param deleteResourceDefinitionRequest * @return Result of the DeleteResourceDefinition operation returned by the service. * @throws BadRequestException * invalid request * @sample AWSGreengrass.DeleteResourceDefinition * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/DeleteResourceDefinition" * target="_top">AWS API Documentation</a> */ DeleteResourceDefinitionResult deleteResourceDefinition(DeleteResourceDefinitionRequest deleteResourceDefinitionRequest); /** * Deletes a subscription definition. * * @param deleteSubscriptionDefinitionRequest * @return Result of the DeleteSubscriptionDefinition operation returned by the service. * @throws BadRequestException * invalid request * @sample AWSGreengrass.DeleteSubscriptionDefinition * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/DeleteSubscriptionDefinition" * target="_top">AWS API Documentation</a> */ DeleteSubscriptionDefinitionResult deleteSubscriptionDefinition(DeleteSubscriptionDefinitionRequest deleteSubscriptionDefinitionRequest); /** * Disassociates the role from a group. * * @param disassociateRoleFromGroupRequest * @return Result of the DisassociateRoleFromGroup operation returned by the service. * @throws BadRequestException * invalid request * @throws InternalServerErrorException * server error * @sample AWSGreengrass.DisassociateRoleFromGroup * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/DisassociateRoleFromGroup" * target="_top">AWS API Documentation</a> */ DisassociateRoleFromGroupResult disassociateRoleFromGroup(DisassociateRoleFromGroupRequest disassociateRoleFromGroupRequest); /** * Disassociates the service role from your account. Without a service role, deployments will not work. * * @param disassociateServiceRoleFromAccountRequest * @return Result of the DisassociateServiceRoleFromAccount operation returned by the service. * @throws InternalServerErrorException * server error * @sample AWSGreengrass.DisassociateServiceRoleFromAccount * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/DisassociateServiceRoleFromAccount" * target="_top">AWS API Documentation</a> */ DisassociateServiceRoleFromAccountResult disassociateServiceRoleFromAccount( DisassociateServiceRoleFromAccountRequest disassociateServiceRoleFromAccountRequest); /** * Retrieves the role associated with a particular group. * * @param getAssociatedRoleRequest * @return Result of the GetAssociatedRole operation returned by the service. * @throws BadRequestException * invalid request * @throws InternalServerErrorException * server error * @sample AWSGreengrass.GetAssociatedRole * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/GetAssociatedRole" target="_top">AWS * API Documentation</a> */ GetAssociatedRoleResult getAssociatedRole(GetAssociatedRoleRequest getAssociatedRoleRequest); /** * Returns the status of a bulk deployment. * * @param getBulkDeploymentStatusRequest * @return Result of the GetBulkDeploymentStatus operation returned by the service. * @throws BadRequestException * invalid request * @sample AWSGreengrass.GetBulkDeploymentStatus * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/GetBulkDeploymentStatus" * target="_top">AWS API Documentation</a> */ GetBulkDeploymentStatusResult getBulkDeploymentStatus(GetBulkDeploymentStatusRequest getBulkDeploymentStatusRequest); /** * Retrieves the connectivity information for a core. * * @param getConnectivityInfoRequest * @return Result of the GetConnectivityInfo operation returned by the service. * @throws BadRequestException * invalid request * @throws InternalServerErrorException * server error * @sample AWSGreengrass.GetConnectivityInfo * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/GetConnectivityInfo" target="_top">AWS * API Documentation</a> */ GetConnectivityInfoResult getConnectivityInfo(GetConnectivityInfoRequest getConnectivityInfoRequest); /** * Retrieves information about a connector definition. * * @param getConnectorDefinitionRequest * @return Result of the GetConnectorDefinition operation returned by the service. * @throws BadRequestException * invalid request * @sample AWSGreengrass.GetConnectorDefinition * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/GetConnectorDefinition" * target="_top">AWS API Documentation</a> */ GetConnectorDefinitionResult getConnectorDefinition(GetConnectorDefinitionRequest getConnectorDefinitionRequest); /** * Retrieves information about a connector definition version, including the connectors that the version contains. * Connectors are prebuilt modules that interact with local infrastructure, device protocols, AWS, and other cloud * services. * * @param getConnectorDefinitionVersionRequest * @return Result of the GetConnectorDefinitionVersion operation returned by the service. * @throws BadRequestException * invalid request * @sample AWSGreengrass.GetConnectorDefinitionVersion * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/GetConnectorDefinitionVersion" * target="_top">AWS API Documentation</a> */ GetConnectorDefinitionVersionResult getConnectorDefinitionVersion(GetConnectorDefinitionVersionRequest getConnectorDefinitionVersionRequest); /** * Retrieves information about a core definition version. * * @param getCoreDefinitionRequest * @return Result of the GetCoreDefinition operation returned by the service. * @throws BadRequestException * invalid request * @sample AWSGreengrass.GetCoreDefinition * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/GetCoreDefinition" target="_top">AWS * API Documentation</a> */ GetCoreDefinitionResult getCoreDefinition(GetCoreDefinitionRequest getCoreDefinitionRequest); /** * Retrieves information about a core definition version. * * @param getCoreDefinitionVersionRequest * @return Result of the GetCoreDefinitionVersion operation returned by the service. * @throws BadRequestException * invalid request * @sample AWSGreengrass.GetCoreDefinitionVersion * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/GetCoreDefinitionVersion" * target="_top">AWS API Documentation</a> */ GetCoreDefinitionVersionResult getCoreDefinitionVersion(GetCoreDefinitionVersionRequest getCoreDefinitionVersionRequest); /** * Returns the status of a deployment. * * @param getDeploymentStatusRequest * @return Result of the GetDeploymentStatus operation returned by the service. * @throws BadRequestException * invalid request * @sample AWSGreengrass.GetDeploymentStatus * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/GetDeploymentStatus" target="_top">AWS * API Documentation</a> */ GetDeploymentStatusResult getDeploymentStatus(GetDeploymentStatusRequest getDeploymentStatusRequest); /** * Retrieves information about a device definition. * * @param getDeviceDefinitionRequest * @return Result of the GetDeviceDefinition operation returned by the service. * @throws BadRequestException * invalid request * @sample AWSGreengrass.GetDeviceDefinition * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/GetDeviceDefinition" target="_top">AWS * API Documentation</a> */ GetDeviceDefinitionResult getDeviceDefinition(GetDeviceDefinitionRequest getDeviceDefinitionRequest); /** * Retrieves information about a device definition version. * * @param getDeviceDefinitionVersionRequest * @return Result of the GetDeviceDefinitionVersion operation returned by the service. * @throws BadRequestException * invalid request * @sample AWSGreengrass.GetDeviceDefinitionVersion * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/GetDeviceDefinitionVersion" * target="_top">AWS API Documentation</a> */ GetDeviceDefinitionVersionResult getDeviceDefinitionVersion(GetDeviceDefinitionVersionRequest getDeviceDefinitionVersionRequest); /** * Retrieves information about a Lambda function definition, including its creation time and latest version. * * @param getFunctionDefinitionRequest * @return Result of the GetFunctionDefinition operation returned by the service. * @throws BadRequestException * invalid request * @sample AWSGreengrass.GetFunctionDefinition * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/GetFunctionDefinition" * target="_top">AWS API Documentation</a> */ GetFunctionDefinitionResult getFunctionDefinition(GetFunctionDefinitionRequest getFunctionDefinitionRequest); /** * Retrieves information about a Lambda function definition version, including which Lambda functions are included * in the version and their configurations. * * @param getFunctionDefinitionVersionRequest * @return Result of the GetFunctionDefinitionVersion operation returned by the service. * @throws BadRequestException * invalid request * @sample AWSGreengrass.GetFunctionDefinitionVersion * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/GetFunctionDefinitionVersion" * target="_top">AWS API Documentation</a> */ GetFunctionDefinitionVersionResult getFunctionDefinitionVersion(GetFunctionDefinitionVersionRequest getFunctionDefinitionVersionRequest); /** * Retrieves information about a group. * * @param getGroupRequest * @return Result of the GetGroup operation returned by the service. * @throws BadRequestException * invalid request * @sample AWSGreengrass.GetGroup * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/GetGroup" target="_top">AWS API * Documentation</a> */ GetGroupResult getGroup(GetGroupRequest getGroupRequest); /** * Retreives the CA associated with a group. Returns the public key of the CA. * * @param getGroupCertificateAuthorityRequest * @return Result of the GetGroupCertificateAuthority operation returned by the service. * @throws BadRequestException * invalid request * @throws InternalServerErrorException * server error * @sample AWSGreengrass.GetGroupCertificateAuthority * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/GetGroupCertificateAuthority" * target="_top">AWS API Documentation</a> */ GetGroupCertificateAuthorityResult getGroupCertificateAuthority(GetGroupCertificateAuthorityRequest getGroupCertificateAuthorityRequest); /** * Retrieves the current configuration for the CA used by the group. * * @param getGroupCertificateConfigurationRequest * @return Result of the GetGroupCertificateConfiguration operation returned by the service. * @throws BadRequestException * invalid request * @throws InternalServerErrorException * server error * @sample AWSGreengrass.GetGroupCertificateConfiguration * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/GetGroupCertificateConfiguration" * target="_top">AWS API Documentation</a> */ GetGroupCertificateConfigurationResult getGroupCertificateConfiguration(GetGroupCertificateConfigurationRequest getGroupCertificateConfigurationRequest); /** * Retrieves information about a group version. * * @param getGroupVersionRequest * @return Result of the GetGroupVersion operation returned by the service. * @throws BadRequestException * invalid request * @sample AWSGreengrass.GetGroupVersion * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/GetGroupVersion" target="_top">AWS API * Documentation</a> */ GetGroupVersionResult getGroupVersion(GetGroupVersionRequest getGroupVersionRequest); /** * Retrieves information about a logger definition. * * @param getLoggerDefinitionRequest * @return Result of the GetLoggerDefinition operation returned by the service. * @throws BadRequestException * invalid request * @sample AWSGreengrass.GetLoggerDefinition * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/GetLoggerDefinition" target="_top">AWS * API Documentation</a> */ GetLoggerDefinitionResult getLoggerDefinition(GetLoggerDefinitionRequest getLoggerDefinitionRequest); /** * Retrieves information about a logger definition version. * * @param getLoggerDefinitionVersionRequest * @return Result of the GetLoggerDefinitionVersion operation returned by the service. * @throws BadRequestException * invalid request * @sample AWSGreengrass.GetLoggerDefinitionVersion * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/GetLoggerDefinitionVersion" * target="_top">AWS API Documentation</a> */ GetLoggerDefinitionVersionResult getLoggerDefinitionVersion(GetLoggerDefinitionVersionRequest getLoggerDefinitionVersionRequest); /** * Retrieves information about a resource definition, including its creation time and latest version. * * @param getResourceDefinitionRequest * @return Result of the GetResourceDefinition operation returned by the service. * @throws BadRequestException * invalid request * @sample AWSGreengrass.GetResourceDefinition * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/GetResourceDefinition" * target="_top">AWS API Documentation</a> */ GetResourceDefinitionResult getResourceDefinition(GetResourceDefinitionRequest getResourceDefinitionRequest); /** * Retrieves information about a resource definition version, including which resources are included in the version. * * @param getResourceDefinitionVersionRequest * @return Result of the GetResourceDefinitionVersion operation returned by the service. * @throws BadRequestException * invalid request * @sample AWSGreengrass.GetResourceDefinitionVersion * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/GetResourceDefinitionVersion" * target="_top">AWS API Documentation</a> */ GetResourceDefinitionVersionResult getResourceDefinitionVersion(GetResourceDefinitionVersionRequest getResourceDefinitionVersionRequest); /** * Retrieves the service role that is attached to your account. * * @param getServiceRoleForAccountRequest * @return Result of the GetServiceRoleForAccount operation returned by the service. * @throws InternalServerErrorException * server error * @sample AWSGreengrass.GetServiceRoleForAccount * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/GetServiceRoleForAccount" * target="_top">AWS API Documentation</a> */ GetServiceRoleForAccountResult getServiceRoleForAccount(GetServiceRoleForAccountRequest getServiceRoleForAccountRequest); /** * Retrieves information about a subscription definition. * * @param getSubscriptionDefinitionRequest * @return Result of the GetSubscriptionDefinition operation returned by the service. * @throws BadRequestException * invalid request * @sample AWSGreengrass.GetSubscriptionDefinition * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/GetSubscriptionDefinition" * target="_top">AWS API Documentation</a> */ GetSubscriptionDefinitionResult getSubscriptionDefinition(GetSubscriptionDefinitionRequest getSubscriptionDefinitionRequest); /** * Retrieves information about a subscription definition version. * * @param getSubscriptionDefinitionVersionRequest * @return Result of the GetSubscriptionDefinitionVersion operation returned by the service. * @throws BadRequestException * invalid request * @sample AWSGreengrass.GetSubscriptionDefinitionVersion * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/GetSubscriptionDefinitionVersion" * target="_top">AWS API Documentation</a> */ GetSubscriptionDefinitionVersionResult getSubscriptionDefinitionVersion(GetSubscriptionDefinitionVersionRequest getSubscriptionDefinitionVersionRequest); /** * Gets a paginated list of the deployments that have been started in a bulk deployment operation, and their current * deployment status. * * @param listBulkDeploymentDetailedReportsRequest * @return Result of the ListBulkDeploymentDetailedReports operation returned by the service. * @throws BadRequestException * invalid request * @sample AWSGreengrass.ListBulkDeploymentDetailedReports * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/ListBulkDeploymentDetailedReports" * target="_top">AWS API Documentation</a> */ ListBulkDeploymentDetailedReportsResult listBulkDeploymentDetailedReports(ListBulkDeploymentDetailedReportsRequest listBulkDeploymentDetailedReportsRequest); /** * Returns a list of bulk deployments. * * @param listBulkDeploymentsRequest * @return Result of the ListBulkDeployments operation returned by the service. * @throws BadRequestException * invalid request * @sample AWSGreengrass.ListBulkDeployments * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/ListBulkDeployments" target="_top">AWS * API Documentation</a> */ ListBulkDeploymentsResult listBulkDeployments(ListBulkDeploymentsRequest listBulkDeploymentsRequest); /** * Lists the versions of a connector definition, which are containers for connectors. Connectors run on the * Greengrass core and contain built-in integration with local infrastructure, device protocols, AWS, and other * cloud services. * * @param listConnectorDefinitionVersionsRequest * @return Result of the ListConnectorDefinitionVersions operation returned by the service. * @throws BadRequestException * invalid request * @sample AWSGreengrass.ListConnectorDefinitionVersions * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/ListConnectorDefinitionVersions" * target="_top">AWS API Documentation</a> */ ListConnectorDefinitionVersionsResult listConnectorDefinitionVersions(ListConnectorDefinitionVersionsRequest listConnectorDefinitionVersionsRequest); /** * Retrieves a list of connector definitions. * * @param listConnectorDefinitionsRequest * @return Result of the ListConnectorDefinitions operation returned by the service. * @sample AWSGreengrass.ListConnectorDefinitions * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/ListConnectorDefinitions" * target="_top">AWS API Documentation</a> */ ListConnectorDefinitionsResult listConnectorDefinitions(ListConnectorDefinitionsRequest listConnectorDefinitionsRequest); /** * Lists the versions of a core definition. * * @param listCoreDefinitionVersionsRequest * @return Result of the ListCoreDefinitionVersions operation returned by the service. * @throws BadRequestException * invalid request * @sample AWSGreengrass.ListCoreDefinitionVersions * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/ListCoreDefinitionVersions" * target="_top">AWS API Documentation</a> */ ListCoreDefinitionVersionsResult listCoreDefinitionVersions(ListCoreDefinitionVersionsRequest listCoreDefinitionVersionsRequest); /** * Retrieves a list of core definitions. * * @param listCoreDefinitionsRequest * @return Result of the ListCoreDefinitions operation returned by the service. * @sample AWSGreengrass.ListCoreDefinitions * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/ListCoreDefinitions" target="_top">AWS * API Documentation</a> */ ListCoreDefinitionsResult listCoreDefinitions(ListCoreDefinitionsRequest listCoreDefinitionsRequest); /** * Returns a history of deployments for the group. * * @param listDeploymentsRequest * @return Result of the ListDeployments operation returned by the service. * @throws BadRequestException * invalid request * @sample AWSGreengrass.ListDeployments * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/ListDeployments" target="_top">AWS API * Documentation</a> */ ListDeploymentsResult listDeployments(ListDeploymentsRequest listDeploymentsRequest); /** * Lists the versions of a device definition. * * @param listDeviceDefinitionVersionsRequest * @return Result of the ListDeviceDefinitionVersions operation returned by the service. * @throws BadRequestException * invalid request * @sample AWSGreengrass.ListDeviceDefinitionVersions * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/ListDeviceDefinitionVersions" * target="_top">AWS API Documentation</a> */ ListDeviceDefinitionVersionsResult listDeviceDefinitionVersions(ListDeviceDefinitionVersionsRequest listDeviceDefinitionVersionsRequest); /** * Retrieves a list of device definitions. * * @param listDeviceDefinitionsRequest * @return Result of the ListDeviceDefinitions operation returned by the service. * @sample AWSGreengrass.ListDeviceDefinitions * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/ListDeviceDefinitions" * target="_top">AWS API Documentation</a> */ ListDeviceDefinitionsResult listDeviceDefinitions(ListDeviceDefinitionsRequest listDeviceDefinitionsRequest); /** * Lists the versions of a Lambda function definition. * * @param listFunctionDefinitionVersionsRequest * @return Result of the ListFunctionDefinitionVersions operation returned by the service. * @throws BadRequestException * invalid request * @sample AWSGreengrass.ListFunctionDefinitionVersions * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/ListFunctionDefinitionVersions" * target="_top">AWS API Documentation</a> */ ListFunctionDefinitionVersionsResult listFunctionDefinitionVersions(ListFunctionDefinitionVersionsRequest listFunctionDefinitionVersionsRequest); /** * Retrieves a list of Lambda function definitions. * * @param listFunctionDefinitionsRequest * @return Result of the ListFunctionDefinitions operation returned by the service. * @sample AWSGreengrass.ListFunctionDefinitions * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/ListFunctionDefinitions" * target="_top">AWS API Documentation</a> */ ListFunctionDefinitionsResult listFunctionDefinitions(ListFunctionDefinitionsRequest listFunctionDefinitionsRequest); /** * Retrieves the current CAs for a group. * * @param listGroupCertificateAuthoritiesRequest * @return Result of the ListGroupCertificateAuthorities operation returned by the service. * @throws BadRequestException * invalid request * @throws InternalServerErrorException * server error * @sample AWSGreengrass.ListGroupCertificateAuthorities * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/ListGroupCertificateAuthorities" * target="_top">AWS API Documentation</a> */ ListGroupCertificateAuthoritiesResult listGroupCertificateAuthorities(ListGroupCertificateAuthoritiesRequest listGroupCertificateAuthoritiesRequest); /** * Lists the versions of a group. * * @param listGroupVersionsRequest * @return Result of the ListGroupVersions operation returned by the service. * @throws BadRequestException * invalid request * @sample AWSGreengrass.ListGroupVersions * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/ListGroupVersions" target="_top">AWS * API Documentation</a> */ ListGroupVersionsResult listGroupVersions(ListGroupVersionsRequest listGroupVersionsRequest); /** * Retrieves a list of groups. * * @param listGroupsRequest * @return Result of the ListGroups operation returned by the service. * @sample AWSGreengrass.ListGroups * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/ListGroups" target="_top">AWS API * Documentation</a> */ ListGroupsResult listGroups(ListGroupsRequest listGroupsRequest); /** * Lists the versions of a logger definition. * * @param listLoggerDefinitionVersionsRequest * @return Result of the ListLoggerDefinitionVersions operation returned by the service. * @throws BadRequestException * invalid request * @sample AWSGreengrass.ListLoggerDefinitionVersions * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/ListLoggerDefinitionVersions" * target="_top">AWS API Documentation</a> */ ListLoggerDefinitionVersionsResult listLoggerDefinitionVersions(ListLoggerDefinitionVersionsRequest listLoggerDefinitionVersionsRequest); /** * Retrieves a list of logger definitions. * * @param listLoggerDefinitionsRequest * @return Result of the ListLoggerDefinitions operation returned by the service. * @sample AWSGreengrass.ListLoggerDefinitions * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/ListLoggerDefinitions" * target="_top">AWS API Documentation</a> */ ListLoggerDefinitionsResult listLoggerDefinitions(ListLoggerDefinitionsRequest listLoggerDefinitionsRequest); /** * Lists the versions of a resource definition. * * @param listResourceDefinitionVersionsRequest * @return Result of the ListResourceDefinitionVersions operation returned by the service. * @throws BadRequestException * invalid request * @sample AWSGreengrass.ListResourceDefinitionVersions * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/ListResourceDefinitionVersions" * target="_top">AWS API Documentation</a> */ ListResourceDefinitionVersionsResult listResourceDefinitionVersions(ListResourceDefinitionVersionsRequest listResourceDefinitionVersionsRequest); /** * Retrieves a list of resource definitions. * * @param listResourceDefinitionsRequest * @return Result of the ListResourceDefinitions operation returned by the service. * @sample AWSGreengrass.ListResourceDefinitions * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/ListResourceDefinitions" * target="_top">AWS API Documentation</a> */ ListResourceDefinitionsResult listResourceDefinitions(ListResourceDefinitionsRequest listResourceDefinitionsRequest); /** * Lists the versions of a subscription definition. * * @param listSubscriptionDefinitionVersionsRequest * @return Result of the ListSubscriptionDefinitionVersions operation returned by the service. * @throws BadRequestException * invalid request * @sample AWSGreengrass.ListSubscriptionDefinitionVersions * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/ListSubscriptionDefinitionVersions" * target="_top">AWS API Documentation</a> */ ListSubscriptionDefinitionVersionsResult listSubscriptionDefinitionVersions( ListSubscriptionDefinitionVersionsRequest listSubscriptionDefinitionVersionsRequest); /** * Retrieves a list of subscription definitions. * * @param listSubscriptionDefinitionsRequest * @return Result of the ListSubscriptionDefinitions operation returned by the service. * @sample AWSGreengrass.ListSubscriptionDefinitions * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/ListSubscriptionDefinitions" * target="_top">AWS API Documentation</a> */ ListSubscriptionDefinitionsResult listSubscriptionDefinitions(ListSubscriptionDefinitionsRequest listSubscriptionDefinitionsRequest); /** * Retrieves a list of resource tags for a resource arn. * * @param listTagsForResourceRequest * @return Result of the ListTagsForResource operation returned by the service. * @throws BadRequestException * invalid request * @sample AWSGreengrass.ListTagsForResource * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/ListTagsForResource" target="_top">AWS * API Documentation</a> */ ListTagsForResourceResult listTagsForResource(ListTagsForResourceRequest listTagsForResourceRequest); /** * Resets a group's deployments. * * @param resetDeploymentsRequest * Information needed to reset deployments. * @return Result of the ResetDeployments operation returned by the service. * @throws BadRequestException * invalid request * @sample AWSGreengrass.ResetDeployments * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/ResetDeployments" target="_top">AWS * API Documentation</a> */ ResetDeploymentsResult resetDeployments(ResetDeploymentsRequest resetDeploymentsRequest); /** * Deploys multiple groups in one operation. This action starts the bulk deployment of a specified set of group * versions. Each group version deployment will be triggered with an adaptive rate that has a fixed upper limit. We * recommend that you include an ''X-Amzn-Client-Token'' token in every ''StartBulkDeployment'' request. These * requests are idempotent with respect to the token and the request parameters. * * @param startBulkDeploymentRequest * @return Result of the StartBulkDeployment operation returned by the service. * @throws BadRequestException * invalid request * @sample AWSGreengrass.StartBulkDeployment * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/StartBulkDeployment" target="_top">AWS * API Documentation</a> */ StartBulkDeploymentResult startBulkDeployment(StartBulkDeploymentRequest startBulkDeploymentRequest); /** * Stops the execution of a bulk deployment. This action returns a status of ''Stopping'' until the deployment is * stopped. You cannot start a new bulk deployment while a previous deployment is in the ''Stopping'' state. This * action doesn't rollback completed deployments or cancel pending deployments. * * @param stopBulkDeploymentRequest * @return Result of the StopBulkDeployment operation returned by the service. * @throws BadRequestException * invalid request * @sample AWSGreengrass.StopBulkDeployment * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/StopBulkDeployment" target="_top">AWS * API Documentation</a> */ StopBulkDeploymentResult stopBulkDeployment(StopBulkDeploymentRequest stopBulkDeploymentRequest); /** * Add resource tags to a Greengrass Resource. Valid resources are Group, Connector, Core, Device, Function, Logger, * Subscription, and Resource Defintions, and also BulkDeploymentIds. * * @param tagResourceRequest * A map of the key-value pairs for the resource tag. * @return Result of the TagResource operation returned by the service. * @throws BadRequestException * invalid request * @sample AWSGreengrass.TagResource * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/TagResource" target="_top">AWS API * Documentation</a> */ TagResourceResult tagResource(TagResourceRequest tagResourceRequest); /** * Remove resource tags from a Greengrass Resource. * * @param untagResourceRequest * @return Result of the UntagResource operation returned by the service. * @throws BadRequestException * invalid request * @sample AWSGreengrass.UntagResource * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/UntagResource" target="_top">AWS API * Documentation</a> */ UntagResourceResult untagResource(UntagResourceRequest untagResourceRequest); /** * Updates the connectivity information for the core. Any devices that belong to the group which has this core will * receive this information in order to find the location of the core and connect to it. * * @param updateConnectivityInfoRequest * Connectivity information. * @return Result of the UpdateConnectivityInfo operation returned by the service. * @throws BadRequestException * invalid request * @throws InternalServerErrorException * server error * @sample AWSGreengrass.UpdateConnectivityInfo * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/UpdateConnectivityInfo" * target="_top">AWS API Documentation</a> */ UpdateConnectivityInfoResult updateConnectivityInfo(UpdateConnectivityInfoRequest updateConnectivityInfoRequest); /** * Updates a connector definition. * * @param updateConnectorDefinitionRequest * @return Result of the UpdateConnectorDefinition operation returned by the service. * @throws BadRequestException * invalid request * @sample AWSGreengrass.UpdateConnectorDefinition * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/UpdateConnectorDefinition" * target="_top">AWS API Documentation</a> */ UpdateConnectorDefinitionResult updateConnectorDefinition(UpdateConnectorDefinitionRequest updateConnectorDefinitionRequest); /** * Updates a core definition. * * @param updateCoreDefinitionRequest * @return Result of the UpdateCoreDefinition operation returned by the service. * @throws BadRequestException * invalid request * @sample AWSGreengrass.UpdateCoreDefinition * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/UpdateCoreDefinition" * target="_top">AWS API Documentation</a> */ UpdateCoreDefinitionResult updateCoreDefinition(UpdateCoreDefinitionRequest updateCoreDefinitionRequest); /** * Updates a device definition. * * @param updateDeviceDefinitionRequest * @return Result of the UpdateDeviceDefinition operation returned by the service. * @throws BadRequestException * invalid request * @sample AWSGreengrass.UpdateDeviceDefinition * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/UpdateDeviceDefinition" * target="_top">AWS API Documentation</a> */ UpdateDeviceDefinitionResult updateDeviceDefinition(UpdateDeviceDefinitionRequest updateDeviceDefinitionRequest); /** * Updates a Lambda function definition. * * @param updateFunctionDefinitionRequest * @return Result of the UpdateFunctionDefinition operation returned by the service. * @throws BadRequestException * invalid request * @sample AWSGreengrass.UpdateFunctionDefinition * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/UpdateFunctionDefinition" * target="_top">AWS API Documentation</a> */ UpdateFunctionDefinitionResult updateFunctionDefinition(UpdateFunctionDefinitionRequest updateFunctionDefinitionRequest); /** * Updates a group. * * @param updateGroupRequest * @return Result of the UpdateGroup operation returned by the service. * @throws BadRequestException * invalid request * @sample AWSGreengrass.UpdateGroup * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/UpdateGroup" target="_top">AWS API * Documentation</a> */ UpdateGroupResult updateGroup(UpdateGroupRequest updateGroupRequest); /** * Updates the Certificate expiry time for a group. * * @param updateGroupCertificateConfigurationRequest * @return Result of the UpdateGroupCertificateConfiguration operation returned by the service. * @throws BadRequestException * invalid request * @throws InternalServerErrorException * server error * @sample AWSGreengrass.UpdateGroupCertificateConfiguration * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/UpdateGroupCertificateConfiguration" * target="_top">AWS API Documentation</a> */ UpdateGroupCertificateConfigurationResult updateGroupCertificateConfiguration( UpdateGroupCertificateConfigurationRequest updateGroupCertificateConfigurationRequest); /** * Updates a logger definition. * * @param updateLoggerDefinitionRequest * @return Result of the UpdateLoggerDefinition operation returned by the service. * @throws BadRequestException * invalid request * @sample AWSGreengrass.UpdateLoggerDefinition * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/UpdateLoggerDefinition" * target="_top">AWS API Documentation</a> */ UpdateLoggerDefinitionResult updateLoggerDefinition(UpdateLoggerDefinitionRequest updateLoggerDefinitionRequest); /** * Updates a resource definition. * * @param updateResourceDefinitionRequest * @return Result of the UpdateResourceDefinition operation returned by the service. * @throws BadRequestException * invalid request * @sample AWSGreengrass.UpdateResourceDefinition * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/UpdateResourceDefinition" * target="_top">AWS API Documentation</a> */ UpdateResourceDefinitionResult updateResourceDefinition(UpdateResourceDefinitionRequest updateResourceDefinitionRequest); /** * Updates a subscription definition. * * @param updateSubscriptionDefinitionRequest * @return Result of the UpdateSubscriptionDefinition operation returned by the service. * @throws BadRequestException * invalid request * @sample AWSGreengrass.UpdateSubscriptionDefinition * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/UpdateSubscriptionDefinition" * target="_top">AWS API Documentation</a> */ UpdateSubscriptionDefinitionResult updateSubscriptionDefinition(UpdateSubscriptionDefinitionRequest updateSubscriptionDefinitionRequest); /** * Shuts down this client object, releasing any resources that might be held open. This is an optional method, and * callers are not expected to call it, but can if they want to explicitly release any open resources. Once a client * has been shutdown, it should not be used to make any more requests. */ void shutdown(); /** * Returns additional metadata for a previously executed successful request, typically used for debugging issues * where a service isn't acting as expected. This data isn't considered part of the result data returned by an * operation, so it's available through this separate, diagnostic interface. * <p> * Response metadata is only cached for a limited period of time, so if you need to access this extra diagnostic * information for an executed request, you should use this method to retrieve it as soon as possible after * executing a request. * * @param request * The originally executed request. * * @return The response metadata for the specified request, or null if none is available. */ ResponseMetadata getCachedResponseMetadata(AmazonWebServiceRequest request); }
apache-2.0
CarpOrange/CarpDoctor
MPChartLib/src/com/github/mikephil/charting/renderer/PieChartRenderer.java
16318
package com.github.mikephil.charting.renderer; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Paint.Align; import android.graphics.Paint.Style; import android.graphics.PointF; import android.graphics.RectF; import android.text.Layout; import android.text.StaticLayout; import android.text.TextPaint; import com.github.mikephil.charting.animation.ChartAnimator; import com.github.mikephil.charting.charts.PieChart; import com.github.mikephil.charting.data.Entry; import com.github.mikephil.charting.data.PieData; import com.github.mikephil.charting.data.PieDataSet; import com.github.mikephil.charting.utils.Highlight; import com.github.mikephil.charting.utils.Utils; import com.github.mikephil.charting.utils.ViewPortHandler; import java.util.List; public class PieChartRenderer extends DataRenderer { protected PieChart mChart; /** * paint for the hole in the center of the pie chart and the transparent * circle */ protected Paint mHolePaint; protected Paint mTransparentCirclePaint; /** * paint object for the text that can be displayed in the center of the * chart */ private TextPaint mCenterTextPaint; private StaticLayout mCenterTextLayout; private String mCenterTextLastValue; private RectF mCenterTextLastBounds = new RectF(); private RectF[] mRectBuffer = { new RectF(), new RectF(), new RectF() }; /** Bitmap for drawing the center hole */ protected Bitmap mDrawBitmap; protected Canvas mBitmapCanvas; public PieChartRenderer(PieChart chart, ChartAnimator animator, ViewPortHandler viewPortHandler) { super(animator, viewPortHandler); mChart = chart; mHolePaint = new Paint(Paint.ANTI_ALIAS_FLAG); mHolePaint.setColor(Color.WHITE); mHolePaint.setStyle(Style.FILL); mTransparentCirclePaint = new Paint(Paint.ANTI_ALIAS_FLAG); mTransparentCirclePaint.setColor(Color.WHITE); mTransparentCirclePaint.setStyle(Style.FILL); mCenterTextPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG); mCenterTextPaint.setColor(Color.BLACK); mCenterTextPaint.setTextSize(Utils.convertDpToPixel(12f)); mCenterTextPaint.setTextAlign(Align.CENTER); mValuePaint.setTextSize(Utils.convertDpToPixel(13f)); mValuePaint.setColor(Color.WHITE); mValuePaint.setTextAlign(Align.CENTER); } public Paint getPaintHole() { return mHolePaint; } public Paint getPaintTransparentCircle() { return mTransparentCirclePaint; } public TextPaint getPaintCenterText() { return mCenterTextPaint; } @Override public void initBuffers() { // TODO Auto-generated method stub } @Override public void drawData(Canvas c) { int width = (int) mViewPortHandler.getChartWidth(); int height = (int) mViewPortHandler.getChartHeight(); if (mDrawBitmap == null || (mDrawBitmap.getWidth() != width) || (mDrawBitmap.getHeight() != height)) { if (width > 0 && height > 0) { mDrawBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_4444); mBitmapCanvas = new Canvas(mDrawBitmap); } else return; } mDrawBitmap.eraseColor(Color.TRANSPARENT); PieData pieData = mChart.getData(); for (PieDataSet set : pieData.getDataSets()) { if (set.isVisible()) drawDataSet(c, set); } } protected void drawDataSet(Canvas c, PieDataSet dataSet) { float angle = mChart.getRotationAngle(); List<Entry> entries = dataSet.getYVals(); float[] drawAngles = mChart.getDrawAngles(); for (int j = 0; j < entries.size(); j++) { float newangle = drawAngles[j]; float sliceSpace = dataSet.getSliceSpace(); Entry e = entries.get(j); // draw only if the value is greater than zero if ((Math.abs(e.getVal()) > 0.000001)) { if (!mChart.needsHighlight(e.getXIndex(), mChart.getData().getIndexOfDataSet(dataSet))) { mRenderPaint.setColor(dataSet.getColor(j)); mBitmapCanvas.drawArc(mChart.getCircleBox(), (angle + sliceSpace / 2f) * mAnimator.getPhaseY(), (newangle - sliceSpace / 2f) * mAnimator.getPhaseY(), true, mRenderPaint); } } angle += newangle * mAnimator.getPhaseX(); } } @Override public void drawValues(Canvas c) { PointF center = mChart.getCenterCircleBox(); // get whole the radius float r = mChart.getRadius(); float rotationAngle = mChart.getRotationAngle(); float[] drawAngles = mChart.getDrawAngles(); float[] absoluteAngles = mChart.getAbsoluteAngles(); float off = r / 10f * 3.6f; if (mChart.isDrawHoleEnabled()) { off = (r - (r / 100f * mChart.getHoleRadius())) / 2f; } r -= off; // offset to keep things inside the chart PieData data = mChart.getData(); List<PieDataSet> dataSets = data.getDataSets(); boolean drawXVals = mChart.isDrawSliceTextEnabled(); int cnt = 0; for (int i = 0; i < dataSets.size(); i++) { PieDataSet dataSet = dataSets.get(i); if (!dataSet.isDrawValuesEnabled() && !drawXVals) continue; // apply the text-styling defined by the DataSet applyValueTextStyle(dataSet); List<Entry> entries = dataSet.getYVals(); for (int j = 0, maxEntry = Math.min( (int) Math.ceil(entries.size() * mAnimator.getPhaseX()), entries.size()); j < maxEntry; j++) { // offset needed to center the drawn text in the slice float offset = drawAngles[cnt] / 2; // calculate the text position float x = (float) (r * Math.cos(Math.toRadians((rotationAngle + absoluteAngles[cnt] - offset) * mAnimator.getPhaseY())) + center.x); float y = (float) (r * Math.sin(Math.toRadians((rotationAngle + absoluteAngles[cnt] - offset) * mAnimator.getPhaseY())) + center.y); float value = mChart.isUsePercentValuesEnabled() ? entries.get(j).getVal() / mChart.getYValueSum() * 100f : entries.get(j).getVal(); String val = dataSet.getValueFormatter().getFormattedValue(value); float lineHeight = Utils.calcTextHeight(mValuePaint, val) + Utils.convertDpToPixel(4f); boolean drawYVals = dataSet.isDrawValuesEnabled(); // draw everything, depending on settings if (drawXVals && drawYVals) { c.drawText(val, x, y, mValuePaint); if (j < data.getXValCount()) c.drawText(data.getXVals().get(j), x, y + lineHeight, mValuePaint); } else if (drawXVals && !drawYVals) { if (j < data.getXValCount()) c.drawText(data.getXVals().get(j), x, y + lineHeight / 2f, mValuePaint); } else if (!drawXVals && drawYVals) { c.drawText(val, x, y + lineHeight / 2f, mValuePaint); } cnt++; } } } @Override public void drawExtras(Canvas c) { // drawCircles(c); drawHole(c); c.drawBitmap(mDrawBitmap, 0, 0, mRenderPaint); drawCenterText(c); } /** * draws the hole in the center of the chart and the transparent circle / * hole */ protected void drawHole(Canvas c) { if (mChart.isDrawHoleEnabled()) { float transparentCircleRadius = mChart.getTransparentCircleRadius(); float holeRadius = mChart.getHoleRadius(); float radius = mChart.getRadius(); PointF center = mChart.getCenterCircleBox(); if (transparentCircleRadius > holeRadius && mAnimator.getPhaseX() >= 1f && mAnimator.getPhaseY() >= 1f) { int color = mTransparentCirclePaint.getColor(); // make transparent mTransparentCirclePaint.setColor(color & 0x60FFFFFF); // draw the transparent-circle mBitmapCanvas.drawCircle(center.x, center.y, radius / 100 * transparentCircleRadius, mTransparentCirclePaint); mTransparentCirclePaint.setColor(color); } // draw the hole-circle mBitmapCanvas.drawCircle(center.x, center.y, radius / 100 * holeRadius, mHolePaint); } } /** * draws the description text in the center of the pie chart makes most * sense when center-hole is enabled */ protected void drawCenterText(Canvas c) { String centerText = mChart.getCenterText(); if (mChart.isDrawCenterTextEnabled() && centerText != null) { PointF center = mChart.getCenterCircleBox(); if (mChart.isCenterTextWordWrapEnabled()) { float innerRadius = mChart.isDrawHoleEnabled() && mChart.isHoleTransparent() ? mChart.getRadius() * (mChart.getHoleRadius() / 100f) : mChart.getRadius(); RectF holeRect = mRectBuffer[0]; holeRect.left = center.x - innerRadius; holeRect.top = center.y - innerRadius; holeRect.right = center.x + innerRadius; holeRect.bottom = center.y + innerRadius; RectF boundingRect = mRectBuffer[1]; boundingRect.set(holeRect); float radiusPercent = mChart.getCenterTextRadiusPercent(); if (radiusPercent > 0.0) { boundingRect.inset((boundingRect.width() - boundingRect.width() * radiusPercent) / 2.f, (boundingRect.height() - boundingRect.height() * radiusPercent) / 2.f); } if (!centerText.equals(mCenterTextLastValue) || !boundingRect.equals(mCenterTextLastBounds)) { // Next time we won't recalculate StaticLayout... mCenterTextLastBounds.set(boundingRect); mCenterTextLastValue = centerText; // If width is 0, it will crash. Always have a minimum of 1 mCenterTextLayout = new StaticLayout(centerText, 0, centerText.length(), mCenterTextPaint, (int)Math.max(Math.ceil(mCenterTextLastBounds.width()), 1.f), Layout.Alignment.ALIGN_NORMAL, 1.f, 0.f, false); } // I wish we could make an ellipse clipping path on Android to clip to the hole... // If we ever find out how, this is the place to add it, based on holeRect //float layoutWidth = Utils.getStaticLayoutMaxWidth(mCenterTextLayout); float layoutHeight = mCenterTextLayout.getHeight(); c.save(); c.translate(boundingRect.centerX(), boundingRect.top + (boundingRect.height() - layoutHeight) / 2.f); mCenterTextLayout.draw(c); c.restore(); } else { // get all lines from the text String[] lines = centerText.split("\n"); float maxlineheight = 0f; // calc the maximum line height for (String line : lines) { float curHeight = Utils.calcTextHeight(mCenterTextPaint, line); if (curHeight > maxlineheight) maxlineheight = curHeight; } float linespacing = maxlineheight * 0.25f; float totalheight = maxlineheight * lines.length - linespacing * (lines.length - 1); int cnt = lines.length; float y = center.y; for (int i = 0; i < lines.length; i++) { String line = lines[lines.length - i - 1]; c.drawText(line, center.x, y + maxlineheight * cnt - totalheight / 2f, mCenterTextPaint); cnt--; y -= linespacing; } } } } @Override public void drawHighlighted(Canvas c, Highlight[] indices) { float rotationAngle = mChart.getRotationAngle(); float angle = 0f; float[] drawAngles = mChart.getDrawAngles(); float[] absoluteAngles = mChart.getAbsoluteAngles(); for (int i = 0; i < indices.length; i++) { // get the index to highlight int xIndex = indices[i].getXIndex(); if (xIndex >= drawAngles.length) continue; if (xIndex == 0) angle = rotationAngle; else angle = rotationAngle + absoluteAngles[xIndex - 1]; angle *= mAnimator.getPhaseY(); float sliceDegrees = drawAngles[xIndex]; PieDataSet set = mChart.getData() .getDataSetByIndex(indices[i] .getDataSetIndex()); if (set == null) continue; float shift = set.getSelectionShift(); RectF circleBox = mChart.getCircleBox(); /** * Make the box containing current arc larger equally in every * dimension, to preserve shape of arc. Code provided by: * * @link https://github.com/wogg */ RectF highlighted = new RectF(circleBox.left - shift, circleBox.top - shift, circleBox.right + shift, circleBox.bottom + shift); mRenderPaint.setColor(set.getColor(xIndex)); // redefine the rect that contains the arc so that the // highlighted pie is not cut off mBitmapCanvas.drawArc(highlighted, angle + set.getSliceSpace() / 2f, sliceDegrees * mAnimator.getPhaseY() - set.getSliceSpace() / 2f, true, mRenderPaint); } } /** * This gives all pie-slices a rounded edge. * * @param c */ protected void drawRoundedSlices(Canvas c) { if (!mChart.isDrawRoundedSlicesEnabled()) return; PieDataSet dataSet = mChart.getData().getDataSet(); if (!dataSet.isVisible()) return; PointF center = mChart.getCenterCircleBox(); float r = mChart.getRadius(); // calculate the radius of the "slice-circle" float circleRadius = (r - (r * mChart.getHoleRadius() / 100f)) / 2f; List<Entry> entries = dataSet.getYVals(); float[] drawAngles = mChart.getDrawAngles(); float angle = mChart.getRotationAngle(); for (int j = 0; j < entries.size(); j++) { float newangle = drawAngles[j]; Entry e = entries.get(j); // draw only if the value is greater than zero if ((Math.abs(e.getVal()) > 0.000001)) { float x = (float) ((r - circleRadius) * Math.cos(Math.toRadians((angle + newangle) * mAnimator.getPhaseY())) + center.x); float y = (float) ((r - circleRadius) * Math.sin(Math.toRadians((angle + newangle) * mAnimator.getPhaseY())) + center.y); mRenderPaint.setColor(dataSet.getColor(j)); mBitmapCanvas.drawCircle(x, y, circleRadius, mRenderPaint); } angle += newangle * mAnimator.getPhaseX(); } } }
apache-2.0
mF2C/COMPSs
compss/runtime/adaptors/agent/CommAgent/commons/src/main/java/es/bsc/compss/agent/comm/messages/LostNodeCommand.java
1842
/* * Copyright 2002-2019 Barcelona Supercomputing Center (www.bsc.es) * * 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. * */ package es.bsc.compss.agent.comm.messages; import es.bsc.comm.Connection; import es.bsc.compss.agent.comm.CommAgent; import es.bsc.compss.nio.NIOAgent; import es.bsc.compss.nio.commands.Command; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; /** * Command to add remove all the resources associated to one node. */ public class LostNodeCommand implements Command { private static final long serialVersionUID = 1L; private String node; public LostNodeCommand() { } public LostNodeCommand(String node) { this.node = node; } @Override public void handle(NIOAgent agent, Connection cnctn) { ((CommAgent) agent).lostNode(node); cnctn.finishConnection(); } @Override public void writeExternal(ObjectOutput oo) throws IOException { oo.writeUTF(node); } @Override public void readExternal(ObjectInput oi) throws IOException, ClassNotFoundException { this.node = oi.readUTF(); } @Override public void error(NIOAgent agent, Connection c) { System.err.println("Error processing Lost node command in connection " + c.hashCode()); } }
apache-2.0
RadekKoubsky/SilverWare
cdi-microservice-provider/src/main/java/io/silverware/microservices/providers/cdi/CdiMicroserviceProvider.java
13836
/* * -----------------------------------------------------------------------\ * SilverWare *   * Copyright (C) 2010 - 2013 the original author or authors. *   * 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. * -----------------------------------------------------------------------/ */ package io.silverware.microservices.providers.cdi; import io.silverware.microservices.Context; import io.silverware.microservices.MicroserviceMetaData; import io.silverware.microservices.annotations.Microservice; import io.silverware.microservices.annotations.MicroserviceReference; import io.silverware.microservices.annotations.MicroserviceVersion; import io.silverware.microservices.providers.MicroserviceProvider; import io.silverware.microservices.providers.cdi.builtin.Configuration; import io.silverware.microservices.providers.cdi.builtin.CurrentContext; import io.silverware.microservices.providers.cdi.builtin.Storage; import io.silverware.microservices.providers.cdi.internal.MicroserviceProxyBean; import io.silverware.microservices.providers.cdi.internal.MicroservicesCDIExtension; import io.silverware.microservices.providers.cdi.internal.MicroservicesInitEvent; import io.silverware.microservices.silver.CdiSilverService; import io.silverware.microservices.util.Utils; import io.silverware.microservices.util.VersionComparator; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jboss.weld.environment.se.Weld; import org.jboss.weld.environment.se.WeldContainer; import java.lang.annotation.Annotation; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import javax.annotation.Priority; import javax.enterprise.context.Dependent; import javax.enterprise.context.spi.CreationalContext; import javax.enterprise.event.Observes; import javax.enterprise.inject.spi.Bean; import javax.enterprise.inject.spi.BeanManager; import javax.enterprise.util.AnnotationLiteral; import javax.interceptor.AroundInvoke; import javax.interceptor.Interceptor; import javax.interceptor.InvocationContext; /** * @author <a href="mailto:marvenec@gmail.com">Martin Večeřa</a> * Changes in version resolution in lookupMicroservice * @author Slavomir Krupa (slavomir.krupa@gmail.com) */ public class CdiMicroserviceProvider implements MicroserviceProvider, CdiSilverService { /** * Logger. */ private static final Logger log = LogManager.getLogger(CdiMicroserviceProvider.class); private boolean deployed = false; /** * Microservices context. */ private Context context; @Override public void initialize(final Context context) { this.context = context; } @Override public Context getContext() { return this.context; } @Override public boolean isDeployed() { return this.deployed; } @Override public void run() { try { log.info("Hello from CDI microservice provider!"); final Weld weld = new Weld(); final MicroservicesCDIExtension microservicesCDIExtension = new MicroservicesCDIExtension(this.context); System.setProperty("org.jboss.weld.se.archive.isolation", "false"); weld.addExtension(microservicesCDIExtension); final WeldContainer container = weld.initialize(); this.context.getProperties().put(BEAN_MANAGER, container.getBeanManager()); this.context.getProperties().put(CDI_CONTAINER, container); this.context.getProperties().put(Storage.STORAGE, new HashMap<String, Object>()); log.info("Discovered the following microservice implementations:"); this.context.getMicroservices().forEach(metaData -> log.info((" - " + metaData.toString()))); log.info("Total count of discovered microservice injection points: " + microservicesCDIExtension.getInjectionPointsCount()); this.deployed = true; container.event().select(MicroservicesInitEvent.class).fire(new MicroservicesInitEvent(this.context, container.getBeanManager(), container)); container.event().select(MicroservicesStartedEvent.class).fire(new MicroservicesStartedEvent(this.context, container.getBeanManager(), container)); try { while (!Thread.currentThread().isInterrupted()) { Thread.sleep(1000); } } catch (final InterruptedException ie) { Utils.shutdownLog(log, ie); } finally { this.deployed = false; try { weld.shutdown(); } catch (final IllegalStateException e) { // nothing, this is just fine, weld was already terminated } } } catch (final Exception e) { log.error("CDI microservice provider failed: ", e); } } @Override @SuppressWarnings("checkstyle:JavadocMethod") public Set<Object> lookupMicroservice(final MicroserviceMetaData microserviceMetaData) { // name can not be null - contract of MicroserviceMetaData final String name = microserviceMetaData.getName(); final Class<?> type = microserviceMetaData.getType(); final Set<Annotation> qualifiers = microserviceMetaData.getQualifiers(); final String apiVersion = microserviceMetaData.getApiVersion(); final Set<Object> matchingBeansByName = new HashSet<>(); final Set<Object> matchingBeansByType = new HashSet<>(); boolean wasAlternative = false; /* We are in search for a CDI bean that meets the provided meta-data. If there is a MicroserviceVersion annotation and it is not matching the version in metadata we skip that bean automatically. Input and corresponding output is as follows: * name specified in MicroserviceReference or derived from data type (both class or interface) * beans having the same name in Microservice annotation * beans having the same name according to CDI * the injection point is interface and name matches interface type name * beans implementing the interface and matching the qualifiers In all cases, there must be precisely one result or an error is thrown. */ final BeanManager beanManager = ((BeanManager) this.context.getProperties().get(BEAN_MANAGER)); final Set<Bean<?>> beans = beanManager.getBeans(type, qualifiers.toArray(new Annotation[qualifiers.size()])); for (final Bean<?> bean : beans) { if (bean.getBeanClass().isAnnotationPresent(Microservice.class) && !(bean instanceof MicroserviceProxyBean)) { final Bean<?> theBean = beanManager.resolve(Collections.singleton(bean)); if (theBean.getBeanClass().isAnnotationPresent(MicroserviceVersion.class)) { final MicroserviceVersion versionAnnotation = theBean.getBeanClass().getAnnotation(MicroserviceVersion.class); String implementationVersion = versionAnnotation.implementation(); if (!VersionComparator.forVersion(implementationVersion).satisfies(apiVersion)) { continue; } } final Microservice microserviceAnnotation = theBean.getBeanClass().getAnnotation(Microservice.class); if ((!microserviceAnnotation.value().isEmpty() && name.equals(microserviceAnnotation.value())) || (microserviceAnnotation.value().isEmpty() && name.equals(theBean.getName()))) { matchingBeansByName.add(beanManager.getReference(theBean, type, beanManager.createCreationalContext(theBean))); } else if (type.isAssignableFrom(theBean.getBeanClass())) { final Set<Annotation> qualifiersToCompare = new HashSet<>(theBean.getQualifiers()); qualifiers.stream().forEach(qualifiersToCompare::remove); if (qualifiersToCompare.size() == 0) { if (bean.isAlternative()) { if (!wasAlternative) { matchingBeansByType.clear(); matchingBeansByType.add(beanManager.getReference(theBean, type, beanManager.createCreationalContext(theBean))); wasAlternative = true; } else { matchingBeansByType.add(beanManager.getReference(theBean, type, beanManager.createCreationalContext(theBean))); throw new IllegalStateException(String.format("There are more than alternate beans matching the query: %s. The beans are: %s.", microserviceMetaData.toString(), matchingBeansByType.toString())); } } else { if (!wasAlternative) { matchingBeansByType.add(beanManager.getReference(theBean, type, beanManager.createCreationalContext(theBean))); } else { // ignore this bean } } } } } } if (matchingBeansByName.size() == 1) { return matchingBeansByName; } if (matchingBeansByName.size() > 1 || matchingBeansByType.size() > 1) { throw new IllegalStateException(String.format("There are more than one beans matching the query: %s. The beans are: %s.", microserviceMetaData.toString(), matchingBeansByType.toString())); } // now we know that matchingBeansByType.size() <= 1 return matchingBeansByType; } @Override public Set<Object> lookupLocalMicroservice(final MicroserviceMetaData metaData) { return lookupMicroservice(metaData); } static Object getMicroserviceProxy(final Context context, final Class clazz) { return ((WeldContainer) context.getProperties().get(CDI_CONTAINER)).instance().select(clazz).select(new MicroserviceReferenceLiteral("")).get(); } static Object getMicroserviceProxy(final Context context, final Class clazz, final String beanName) { return ((WeldContainer) context.getProperties().get(CDI_CONTAINER)).instance().select(clazz).select(new MicroserviceReferenceLiteral(beanName)).get(); } public <T> T lookupBean(final Class<T> type) { return ((WeldContainer) this.context.getProperties().get(CDI_CONTAINER)).instance().select(type).get(); } @Override public <T> T findByType(final Class<T> type) { final BeanManager beanManager = (BeanManager) this.context.getProperties().get(BEAN_MANAGER); final Set<T> beans = new HashSet<>(); final Set<Bean<?>> definitions = beanManager.getBeans(type); final Bean<?> bean = beanManager.resolve(definitions); final CreationalContext<?> creationalContext = beanManager.createCreationalContext(bean); final Object result = beanManager.getReference(bean, type, creationalContext); return result == null ? null : type.cast(result); } private static class MicroserviceReferenceLiteral extends AnnotationLiteral<MicroserviceReference> implements MicroserviceReference { private final String name; public MicroserviceReferenceLiteral(final String name) { this.name = name; } @Override public String value() { return this.name; } } @Dependent @Interceptor() @Priority(Interceptor.Priority.APPLICATION) @SuppressWarnings("checkstyle:JavadocType") public static class LoggingInterceptor { @AroundInvoke public Object log(final InvocationContext ic) throws Exception { log.info("AroundInvoke " + ic.toString()); return ic.proceed(); } } @SuppressWarnings({ "unused", "checkstyle:JavadocType" }) @Microservice public static class SilverWareConfiguration implements Configuration { private Context context; @Override public Object getProperty(final String propertyName) { return this.context.getProperties().get(propertyName); } public void eventObserver(@Observes final MicroservicesInitEvent event) { this.context = event.getContext(); } } @SuppressWarnings({ "unused", "unchecked", "checkstyle:JavadocType" }) @Microservice public static class SilverWareStorage implements Storage { private Context context; private Map<String, Object> getStorage() { return (Map<String, Object>) this.context.getProperties().get(STORAGE); } @Override public void put(final String key, final Object value) { getStorage().put(key, value); } @Override public Object get(final String key) { return getStorage().get(key); } @Override public boolean drop(final String key) { return getStorage().remove(key) != null; } public void eventObserver(@Observes final MicroservicesInitEvent event) { this.context = event.getContext(); } } @SuppressWarnings({ "unused", "checkstyle:JavadocMethod" }) @Microservice public static class SilverWareCurrentContext implements CurrentContext { private Context context; @Override public Context getContext() { return this.context; } public void eventObserver(@Observes final MicroservicesInitEvent event) { this.context = event.getContext(); } } }
apache-2.0
yzsme/Linux-KIT-3
server/bin/plugins/apache.php
144
<?php /** * Created by PhpStorm. * User: zhensheng * Date: 16-8-27 * Time: 上午11:14 */ namespace linuxkit3\plugins; class apache { }
apache-2.0
francisrod01/udacity-android-sunshine-app
app/src/main/java/com/example/android/sunshine/app/sync/SunshineSyncAdapter.java
23948
package com.example.android.sunshine.app.sync; import android.accounts.Account; import android.accounts.AccountManager; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.AbstractThreadedSyncAdapter; import android.content.ContentProviderClient; import android.content.ContentResolver; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.SyncRequest; import android.content.SyncResult; import android.database.Cursor; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.app.NotificationCompat; import android.support.v4.app.TaskStackBuilder; import android.text.format.Time; import android.util.Log; import com.example.android.sunshine.app.BuildConfig; import com.example.android.sunshine.app.MainActivity; import com.example.android.sunshine.app.R; import com.example.android.sunshine.app.Utility; import com.example.android.sunshine.app.data.WeatherContract.LocationEntry; import com.example.android.sunshine.app.data.WeatherContract.WeatherEntry; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.Vector; import java.util.concurrent.TimeUnit; /** * Created by Francis Rodrigues on 4/16/17. */ public class SunshineSyncAdapter extends AbstractThreadedSyncAdapter { public final String LOG_TAG = SunshineSyncAdapter.class.getSimpleName(); // Interval at which to sync with the weather, in seconds. // 60 seconds (1 minute) * 180 = 3 hours. public static final int SYNC_INTERVAL = 60 * 180; public static final int SYNC_FLEXTIME = SYNC_INTERVAL / 3; private static final long DAY_IN_MILLIS = TimeUnit.DAYS.toMillis(1); // 1000 * 60 * 60 * 24 private static final int WEATHER_NOTIFICATION_ID = 3004; // Notification data will be pulled from the database. Add projection. private static final String[] NOTIFY_WEATHER_PROJECTION = new String[]{ WeatherEntry.COLUMN_WEATHER_ID, WeatherEntry.COLUMN_MAX_TEMP, WeatherEntry.COLUMN_MIN_TEMP, WeatherEntry.COLUMN_SHORT_DESC }; // These indices must match the projection. private static final int INDEX_WEATHER_ID = 0; private static final int INDEX_MAX_TEMP = 1; private static final int INDEX_MIN_TEMP = 2; private static final int INDEX_SHORT_DESC = 3; /** * SunshineSyncAdapter constructor. * * @param context * @param autoInitialize */ public SunshineSyncAdapter(Context context, boolean autoInitialize) { super(context, autoInitialize); } @Override public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) { Log.d(LOG_TAG, "Starting sync..."); String locationQuery = Utility.getPreferredLocation(getContext()); // These two need to be declared outside the try/catch // so that they can be closed in the finally block. HttpURLConnection urlConnection = null; BufferedReader reader = null; // Will contain the raw JSON response as a string. String forecastJsonStr = null; String format = "json"; String units = "metric"; int numDays = 14; try { // Construct the URL for the OpenWeatherMap query. // Possible parameters are available at "OWMs'" forecast API page, at // http://openweathermap.org/API#forecast final String FORECAST_BASE_URL = "http://api.openweathermap.org/data/2.5/forecast/daily?"; final String QUERY_PARAM = "q"; final String FORMAT_PARAM = "mode"; final String UNITS_PARAM = "units"; final String DAYS_PARAM = "cnt"; final String APPID_PARAM = "APPID"; Uri buildUri = Uri.parse(FORECAST_BASE_URL).buildUpon() .appendQueryParameter(QUERY_PARAM, locationQuery) .appendQueryParameter(FORMAT_PARAM, format) .appendQueryParameter(UNITS_PARAM, units) .appendQueryParameter(DAYS_PARAM, Integer.toString(numDays)) .appendQueryParameter(APPID_PARAM, BuildConfig.OPEN_WEATHER_MAP_API_KEY) .build(); URL url = new URL(buildUri.toString()); // Create the request to OpenWeatherMap, and open the connection. urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.connect(); // Read the input stream into a String. InputStream inputStream = urlConnection.getInputStream(); StringBuffer buffer = new StringBuffer(); if (inputStream == null) { // Nothing to do here. return; } reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) { // Since it's JSON, adding a newline isn't necessary (it won't affect parsing) // But it does make debugging a *lot* easier if you print out the completed // buffer for debugging. buffer.append(line + "\n"); } if (buffer.length() == 0) { // Stream was empty. No point in parsing. return; } forecastJsonStr = buffer.toString(); getWeatherDataFromJson(forecastJsonStr, locationQuery); } catch (IOException e) { Log.e(LOG_TAG, "IOException ", e); // If the code didn't successfully get the weather data, there's no point in attempting // to parse it. e.printStackTrace(); } catch (JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); e.printStackTrace(); } finally { if (urlConnection != null) { urlConnection.disconnect(); } if (reader != null) { try { reader.close(); } catch (IOException e) { Log.e(LOG_TAG, "Error closing stream", e); e.printStackTrace(); } } } } /** * Take the String representing the complete forecast in JSON Format and * pull out the data we need to construct the Strings needed for the wireframes. * * Fortunately parsing is easy: Constructor takes the JSON string and converts it * into an Object hierarchy for us. * * @param forecastJsonStr * @param locationSetting * @throws JSONException */ private void getWeatherDataFromJson(String forecastJsonStr, String locationSetting) throws JSONException { // Now we have a String representing the complete forecast in JSON Format. // These are the names of the JSON objects that need to be extracted. // Location information. final String OWM_CITY = "city"; final String OWM_CITY_NAME = "name"; final String OWM_COORD = "coord"; // Location coordinate. final String OWM_LATITUDE = "lat"; final String OWM_LONGITUDE = "lon"; // Weather information. Each day's forecast info is an element of the "list" array. final String OWM_LIST = "list"; final String OWM_PRESSURE = "pressure"; final String OWM_HUMIDITY = "humidity"; final String OWM_WINDSPEED = "speed"; final String OWM_WIND_DIRECTION = "deg"; // All temperatures are children of the "temp" object. final String OWM_TEMPERATURE = "temp"; final String OWM_MAX = "max"; final String OWM_MIN = "min"; final String OWM_WEATHER = "weather"; final String OWM_DESCRIPTION = "main"; final String OWM_WEATHER_ID = "id"; try { JSONObject forecastJson = new JSONObject(forecastJsonStr); JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST); JSONObject cityJson = forecastJson.getJSONObject(OWM_CITY); String cityName = cityJson.getString(OWM_CITY_NAME); JSONObject cityCoord = cityJson.getJSONObject(OWM_COORD); double cityLatitude = cityCoord.getDouble(OWM_LATITUDE); double cityLongitude = cityCoord.getDouble(OWM_LONGITUDE); long locationId = addLocation(locationSetting, cityName, cityLatitude, cityLongitude); // Insert the new weather information into the database. Vector<ContentValues> cvVector = new Vector<>(weatherArray.length()); // OWM returns daily forecasts based upon the local time of the city that is being // asked for, which means that we need to know the GMT offset to translate this data // properly. // Sing this dta is also sent in-order and the first day is always the // current day, we're going to take advantage of that to get a nice // normalized UTC date for all of our weather. Time dayTime = new Time(); dayTime.setToNow(); // We start at the day returned by local time. Otherwise this is a mess. int julianStartDay = Time.getJulianDay(System.currentTimeMillis(), dayTime.gmtoff); // Now we work exclusively in UTC. dayTime = new Time(); for (int i = 0; i < weatherArray.length(); i++) { // These are the values that will be collected. long dateTime; double pressure; int humidity; double windSpeed; double windDirection; double high; double low; String description; int weatherId; // Get the JSON object representing the day. JSONObject dayForecast = weatherArray.getJSONObject(i); // Cheating to convert this to UTC time, which is what we want anyhow. dateTime = dayTime.setJulianDay(julianStartDay + i); pressure = dayForecast.getDouble(OWM_PRESSURE); humidity = dayForecast.getInt(OWM_HUMIDITY); windSpeed = dayForecast.getDouble(OWM_WINDSPEED); windDirection = dayForecast.getDouble(OWM_WIND_DIRECTION); // Description is in a child array called "weather", which is 1 element long. // That element also contains a weather code. JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0); description = weatherObject.getString(OWM_DESCRIPTION); weatherId = weatherObject.getInt(OWM_WEATHER_ID); // Temperatures are in a child object called "temp". Try not to name variables // "temp" when working with temperature. It confuses everybody. JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE); high = temperatureObject.getDouble(OWM_MAX); low = temperatureObject.getDouble(OWM_MIN); ContentValues weatherValues = new ContentValues(); weatherValues.put(WeatherEntry.COLUMN_LOC_KEY, locationId); weatherValues.put(WeatherEntry.COLUMN_DATE, dateTime); weatherValues.put(WeatherEntry.COLUMN_HUMIDITY, humidity); weatherValues.put(WeatherEntry.COLUMN_PRESSURE, pressure); weatherValues.put(WeatherEntry.COLUMN_WIND_SPEED, windSpeed); weatherValues.put(WeatherEntry.COLUMN_DEGREES, windDirection); weatherValues.put(WeatherEntry.COLUMN_MAX_TEMP, high); weatherValues.put(WeatherEntry.COLUMN_MIN_TEMP, low); weatherValues.put(WeatherEntry.COLUMN_SHORT_DESC, description); weatherValues.put(WeatherEntry.COLUMN_WEATHER_ID, weatherId); cvVector.add(weatherValues); } // Add to database. if (cvVector.size() > 0) { ContentValues[] cvArray = new ContentValues[cvVector.size()]; cvVector.toArray(cvArray); getContext().getContentResolver().bulkInsert(WeatherEntry.CONTENT_URI, cvArray); // Delete old data so we don't build up an endless history. getContext().getContentResolver().delete(WeatherEntry.CONTENT_URI, WeatherEntry.COLUMN_DATE + " <= ?", new String[]{Long.toString(dayTime.setJulianDay(julianStartDay - 1))}); notifyWeather(); } Log.d(LOG_TAG, "Sync Complete! " + cvVector.size() + " Inserted!"); } catch (JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); e.printStackTrace(); } } /** * Helper method to handle insertion of a new location in the weather database. * * @param locationSetting The location string used to request updates from the server. * @param cityName A human-readable city name. e.g "Mountain View". * @param latitude The latitude of the city. * @param longitude The longitude of the city. * @return The row ID of the added location. */ private long addLocation(String locationSetting, String cityName, double latitude, double longitude) { long locationId; // First, check if the location with this city name exists in the database. Cursor locationCursor = getContext().getContentResolver().query( LocationEntry.CONTENT_URI, new String[]{LocationEntry._ID}, LocationEntry.COLUMN_LOCATION_SETTING + " = ?", new String[]{locationSetting}, null); if (locationCursor.moveToFirst()) { int locationIdIndex = locationCursor.getColumnIndex(LocationEntry._ID); locationId = locationCursor.getLong(locationIdIndex); } else { // Now that the content provider is set up, inserting rows of data is pretty simple. // First create a ContentValues object to hold the data you want to insert. ContentValues locationValues = new ContentValues(); // Then add the data, along with the corresponding name of the data type, // so the content provider knows what kind of value is being inserted. locationValues.put(LocationEntry.COLUMN_CITY_NAME, cityName); locationValues.put(LocationEntry.COLUMN_LOCATION_SETTING, locationSetting); locationValues.put(LocationEntry.COLUMN_COORD_LAT, latitude); locationValues.put(LocationEntry.COLUMN_COORD_LONG, longitude); // Finally, insert location data into the database. Uri insertedUri = getContext().getContentResolver().insert(LocationEntry.CONTENT_URI, locationValues); // The resulting URI contains the ID for the row. Extract the locationId from the Uri. locationId = ContentUris.parseId(insertedUri); } locationCursor.close(); // Wait, that worked? Yes! return locationId; } /** * Helper method to schedule the sync adapter periodic execution. * * @param context * @param syncInterval * @param flexTime */ public static void configurePeriodicSync(Context context, int syncInterval, int flexTime) { Account account = getSyncAccount(context); String authority = context.getString(R.string.content_authority); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { // We can enable inexact timers in our periodic sync. SyncRequest request = new SyncRequest.Builder() .syncPeriodic(syncInterval, flexTime) .setSyncAdapter(account, authority) .setExtras(new Bundle()) .build(); ContentResolver.requestSync(request); } else { ContentResolver.addPeriodicSync(account, authority, new Bundle(), syncInterval); } } public static void syncImmediately(Context context) { Bundle bundle = new Bundle(); bundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true); bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true); ContentResolver.requestSync(getSyncAccount(context), context.getString(R.string.content_authority), bundle); } /** * Helper method to get the fake account to be used with SyncAdapter, or make a new one * if the fake account doesn't exist yet. If we make a new account, we call the * onAccountCreated method so we can initialize things. * * @param context The context used to access the account service. * @return a fake account. */ public static Account getSyncAccount(Context context) { // Get an instance of the Android account manager. AccountManager accountManager = (AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE); // Create the account type and default account. Account newAccount = new Account(context.getString(R.string.app_name), context.getString(R.string.sync_account_type)); // If the password doesn't exist, the account doesn't exist. if (null == accountManager.getPassword(newAccount)) { /* * Add the account and account type, no password or user data * if successful, return the Account object, otherwise report an error. */ if (!accountManager.addAccountExplicitly(newAccount, "", null)) { return null; } /* * If you don't set `android:syncable="true"` in * your `<provider>` element in the manifest, * then call `ContentResolver.setIsSyncable(account, AUTHORITY, 1)` * here. */ onAccountCreated(newAccount, context); } return newAccount; } private static void onAccountCreated(Account newAccount, Context context) { /* * Since we've created an account. */ SunshineSyncAdapter.configurePeriodicSync(context, SYNC_INTERVAL, SYNC_FLEXTIME); /* * Without calling setSyncAutomatically, our periodic sync will not be enabled. */ ContentResolver.setSyncAutomatically(newAccount, context.getString(R.string.content_authority), true); /* * Finally, let's do a sync get things started. */ syncImmediately(context); } public static void initializeSyncAdapter(Context context) { getSyncAccount(context); } private void notifyWeather() { Context context = getContext(); // Checking the last update and notify if it' the first of the day. SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); // Grabs the preference to check notifications are on/off. String displayNotificationsKey = context.getString(R.string.pref_enable_notifications_key); boolean displayNotifications = prefs.getBoolean(displayNotificationsKey, Boolean.parseBoolean(context.getString(R.string.pref_enable_notifications_default))); // Check if notifications are disabled. if (!displayNotifications) { return; } String lastNotificationKey = context.getString(R.string.pref_last_notification); long lastSync = prefs.getLong(lastNotificationKey, 0); if (System.currentTimeMillis() - lastSync >= DAY_IN_MILLIS) { // Last sync was more than 1 day ago, let's send a notification with the weather. String locationQuery = Utility.getPreferredLocation(context); Uri weatherUri = WeatherEntry.buildWeatherLocationWithDate(locationQuery, System.currentTimeMillis()); // We'll query our ContentProvider, as always. Cursor cursor = context.getContentResolver().query(weatherUri, NOTIFY_WEATHER_PROJECTION, null, null, null); if (cursor.moveToFirst()) { int weatherId = cursor.getInt(INDEX_WEATHER_ID); double high = cursor.getDouble(INDEX_MAX_TEMP); double low = cursor.getDouble(INDEX_MIN_TEMP); String desc = cursor.getString(INDEX_SHORT_DESC); int iconId = Utility.getIconResourceForWeatherCondition(weatherId); String title = context.getString(R.string.app_name); // Define the text of the forecast. String contentText = String.format(context.getString(R.string.format_notification), desc, Utility.formatTemperature(context, high), Utility.formatTemperature(context, low)); // Build our notification here. buildNotification(context, iconId, title, contentText); // Refreshing last sync. SharedPreferences.Editor editor = prefs.edit(); editor.putLong(lastNotificationKey, System.currentTimeMillis()); editor.commit(); } cursor.close(); } } /** * Build your notification here. * * @param context * @param iconId * @param title * @param contentText */ private void buildNotification(Context context, int iconId, String title, String contentText) { // NotificationCompatBuilder is a very convenient way to build backward-compatible // notifications. Just throw in some data. NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context) .setSmallIcon(iconId) .setContentTitle(title) .setContentText(contentText); // Make something interesting happen when the user clicks on the notification. // In this case, opening the app is sufficient. Intent resultIntent = new Intent(getContext(), MainActivity.class); // The stack builder object will contain an artificial back stack for the // started Activity. // This ensures that navigating backward from the Activity leads out of // your application to the Home screen. TaskStackBuilder stackBuilder = TaskStackBuilder.create(context); // Adds the back stack for the Intent (but not the Intent itself). stackBuilder.addParentStack(MainActivity.class); // Adds the Intent that starts the Activity to the top of the stack. stackBuilder.addNextIntent(resultIntent); PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); mBuilder.setContentIntent(resultPendingIntent); // Call to NotificationManager now. NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); // WEATHER_NOTIFICATION_ID allows you to update the notification later on. mNotificationManager.notify(WEATHER_NOTIFICATION_ID, mBuilder.build()); } }
apache-2.0
niklasteichmann/gradoop
gradoop-flink/src/test/java/org/gradoop/flink/model/impl/operators/matching/common/query/predicates/compareables/ElementSelectorComparableTest.java
2619
/* * Copyright © 2014 - 2018 Leipzig University (Database Research Group) * * 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. */ package org.gradoop.flink.model.impl.operators.matching.common.query.predicates.compareables; import org.gradoop.common.model.impl.id.GradoopId; import org.gradoop.common.model.impl.properties.PropertyValue; import org.gradoop.flink.model.impl.operators.matching.common.query.predicates.comparables.ElementSelectorComparable; import org.gradoop.flink.model.impl.operators.matching.single.cypher.pojos.Embedding; import org.gradoop.flink.model.impl.operators.matching.single.cypher.pojos.EmbeddingMetaData; import org.gradoop.flink.model.impl.operators.matching.single.cypher.pojos.EmbeddingMetaData.EntryType; import org.junit.Test; import org.s1ck.gdl.model.comparables.ElementSelector; import java.util.NoSuchElementException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; public class ElementSelectorComparableTest { @Test public void testEvaluationReturnsPropertyValue() { ElementSelector selector = new ElementSelector("a"); ElementSelectorComparable wrapper = new ElementSelectorComparable(selector); Embedding embedding = new Embedding(); embedding.add(GradoopId.get()); PropertyValue reference = PropertyValue.create(embedding.getId(0)); EmbeddingMetaData metaData = new EmbeddingMetaData(); metaData.setEntryColumn("a", EntryType.VERTEX, 0); assertEquals(reference, wrapper.evaluate(embedding, metaData)); assertNotEquals(PropertyValue.create("42"), wrapper.evaluate(embedding, metaData)); } @Test(expected = NoSuchElementException.class) public void testThrowErrorIfElementNotPresent() { ElementSelector selector = new ElementSelector("a"); ElementSelectorComparable wrapper = new ElementSelectorComparable(selector); Embedding embedding = new Embedding(); embedding.add(GradoopId.get()); EmbeddingMetaData metaData = new EmbeddingMetaData(); metaData.setEntryColumn("b", EntryType.VERTEX, 0); wrapper.evaluate(embedding, metaData); } }
apache-2.0
b2ihealthcare/snow-owl
core/com.b2international.snowowl.core/src/com/b2international/snowowl/core/domain/ValueSetMembers.java
1383
/* * Copyright 2020-2021 B2i Healthcare Pte Ltd, http://b2i.sg * * 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. */ package com.b2international.snowowl.core.domain; import java.util.Collections; import java.util.List; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; /** * @since 7.7 */ public final class ValueSetMembers extends PageableCollectionResource<ValueSetMember> { private static final long serialVersionUID = 1L; public ValueSetMembers(int limit, int total) { super(Collections.emptyList(), null, limit, total); } @JsonCreator public ValueSetMembers( @JsonProperty("items") List<ValueSetMember> items, @JsonProperty("searchAfter") String searchAfter, @JsonProperty("limit") int limit, @JsonProperty("total") int total) { super(items, searchAfter, limit, total); } }
apache-2.0
cloudfoundry-incubator/bosh-vsphere-cpi-release
src/vsphere_cpi/lib/nsxt/nsxt_client/models/node_service_status_properties.rb
9033
=begin #NSX-T Manager API #VMware NSX-T Manager REST API OpenAPI spec version: 2.3.0.0.0 Generated by: https://github.com/swagger-api/swagger-codegen.git Swagger Codegen version: 2.3.1 =end require 'date' module NSXT # Node service status properties class NodeServiceStatusProperties # Link to this resource attr_accessor :_self # The server will populate this field when returing the resource. Ignored on PUT and POST. attr_accessor :_links # Schema for this resource attr_accessor :_schema # Service process ids attr_accessor :pids # Service runtime state attr_accessor :runtime_state # Service monitor runtime state attr_accessor :monitor_runtime_state # Service monitor process id attr_accessor :monitor_pid class EnumAttributeValidator attr_reader :datatype attr_reader :allowable_values def initialize(datatype, allowable_values) @allowable_values = allowable_values.map do |value| case datatype.to_s when /Integer/i value.to_i when /Float/i value.to_f else value end end end def valid?(value) !value || allowable_values.include?(value) end end # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { :'_self' => :'_self', :'_links' => :'_links', :'_schema' => :'_schema', :'pids' => :'pids', :'runtime_state' => :'runtime_state', :'monitor_runtime_state' => :'monitor_runtime_state', :'monitor_pid' => :'monitor_pid' } end # Attribute type mapping. def self.swagger_types { :'_self' => :'SelfResourceLink', :'_links' => :'Array<ResourceLink>', :'_schema' => :'String', :'pids' => :'Array<Integer>', :'runtime_state' => :'String', :'monitor_runtime_state' => :'String', :'monitor_pid' => :'Integer' } end # Initializes the object # @param [Hash] attributes Model attributes in the form of hash def initialize(attributes = {}) return unless attributes.is_a?(Hash) # convert string to symbol for hash key attributes = attributes.each_with_object({}){|(k,v), h| h[k.to_sym] = v} if attributes.has_key?(:'_self') self._self = attributes[:'_self'] end if attributes.has_key?(:'_links') if (value = attributes[:'_links']).is_a?(Array) self._links = value end end if attributes.has_key?(:'_schema') self._schema = attributes[:'_schema'] end if attributes.has_key?(:'pids') if (value = attributes[:'pids']).is_a?(Array) self.pids = value end end if attributes.has_key?(:'runtime_state') self.runtime_state = attributes[:'runtime_state'] end if attributes.has_key?(:'monitor_runtime_state') self.monitor_runtime_state = attributes[:'monitor_runtime_state'] end if attributes.has_key?(:'monitor_pid') self.monitor_pid = attributes[:'monitor_pid'] end end # Show invalid properties with the reasons. Usually used together with valid? # @return Array for valid properties with the reasons def list_invalid_properties invalid_properties = Array.new return invalid_properties end # Check to see if the all the properties in the model are valid # @return true if the model is valid def valid? runtime_state_validator = EnumAttributeValidator.new('String', ["running", "stopped"]) return false unless runtime_state_validator.valid?(@runtime_state) monitor_runtime_state_validator = EnumAttributeValidator.new('String', ["running", "stopped"]) return false unless monitor_runtime_state_validator.valid?(@monitor_runtime_state) return true end # Custom attribute writer method checking allowed values (enum). # @param [Object] runtime_state Object to be assigned def runtime_state=(runtime_state) validator = EnumAttributeValidator.new('String', ["running", "stopped"]) unless validator.valid?(runtime_state) fail ArgumentError, "invalid value for 'runtime_state', must be one of #{validator.allowable_values}." end @runtime_state = runtime_state end # Custom attribute writer method checking allowed values (enum). # @param [Object] monitor_runtime_state Object to be assigned def monitor_runtime_state=(monitor_runtime_state) validator = EnumAttributeValidator.new('String', ["running", "stopped"]) unless validator.valid?(monitor_runtime_state) fail ArgumentError, "invalid value for 'monitor_runtime_state', must be one of #{validator.allowable_values}." end @monitor_runtime_state = monitor_runtime_state end # Checks equality by comparing each attribute. # @param [Object] Object to be compared def ==(o) return true if self.equal?(o) self.class == o.class && _self == o._self && _links == o._links && _schema == o._schema && pids == o.pids && runtime_state == o.runtime_state && monitor_runtime_state == o.monitor_runtime_state && monitor_pid == o.monitor_pid end # @see the `==` method # @param [Object] Object to be compared def eql?(o) self == o end # Calculates hash code according to all attributes. # @return [Fixnum] Hash code def hash [_self, _links, _schema, pids, runtime_state, monitor_runtime_state, monitor_pid].hash end # Builds the object from hash # @param [Hash] attributes Model attributes in the form of hash # @return [Object] Returns the model itself def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| if type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) self.send("#{key}=", attributes[self.class.attribute_map[key]].map{ |v| _deserialize($1, v) } ) end elsif !attributes[self.class.attribute_map[key]].nil? self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) end # or else data not found in attributes(hash), not an issue as the data can be optional end self end # Deserializes the data based on type # @param string type Data type # @param string value Value to be deserialized # @return [Object] Deserialized data def _deserialize(type, value) case type.to_sym when :DateTime DateTime.parse(value) when :Date Date.parse(value) when :String value.to_s when :Integer value.to_i when :Float value.to_f when :BOOLEAN if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false end when :Object # generic object (usually a Hash), return directly value when /\AArray<(?<inner_type>.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } when /\AHash<(?<k_type>.+?), (?<v_type>.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| value.each do |k, v| hash[_deserialize(k_type, k)] = _deserialize(v_type, v) end end else # model temp_model = NSXT.const_get(type).new temp_model.build_from_hash(value) end end # Returns the string representation of the object # @return [String] String presentation of the object def to_s to_hash.to_s end # to_body is an alias to to_hash (backward compatibility) # @return [Hash] Returns the object in the form of hash def to_body to_hash end # Returns the object in the form of hash # @return [Hash] Returns the object in the form of hash def to_hash hash = {} self.class.attribute_map.each_pair do |attr, param| value = self.send(attr) next if value.nil? hash[param] = _to_hash(value) end hash end # Outputs non-array value in the form of hash # For object, use to_hash. Otherwise, just return the value # @param [Object] value Any valid value # @return [Hash] Returns the value in the form of hash def _to_hash(value) if value.is_a?(Array) value.compact.map{ |v| _to_hash(v) } elsif value.is_a?(Hash) {}.tap do |hash| value.each { |k, v| hash[k] = _to_hash(v) } end elsif value.respond_to? :to_hash value.to_hash else value end end end end
apache-2.0
NationalSecurityAgency/ghidra
Ghidra/Features/ByteViewer/src/main/java/ghidra/app/plugin/core/format/AsciiFormatModel.java
4511
/* ### * IP: GHIDRA * REVIEWED: YES * * 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. */ package ghidra.app.plugin.core.format; import ghidra.app.plugin.core.byteviewer.ByteViewerComponentProvider; import ghidra.util.HelpLocation; import java.math.BigInteger; /** * Converts byte values to Ascii representation. */ public class AsciiFormatModel implements UniversalDataFormatModel { private int symbolSize; public AsciiFormatModel() { symbolSize = 1; } /** * Get the name of this formatter. */ public String getName() { return "Ascii"; } /** * Get the number of bytes to make a unit; in this case it * takes 1 byte to make an Ascii value. */ public int getUnitByteSize() { return 1; } /** * Given a character position from 0 to data unit symbol size - 1 * it returns a number from 0 to unit byte size - 1 indicating which * byte the character position was obtained from. */ public int getByteOffset(ByteBlock block, int position) { return 0; } /** * Given the byte offset into a unit, get the column position. */ public int getColumnPosition(ByteBlock block, int byteOffset) { return 0; } /** * Gets the number of characters required to display a * unit. */ public int getDataUnitSymbolSize() { return symbolSize; } /** * Gets the string representation at the given index in the block. * @param block block to change * @param index byte index into the block * @throws ByteBlockAccessException if the block cannot be read * @throws IndexOutOfBoundsException if index is not valid for the * block */ public String getDataRepresentation(ByteBlock block, BigInteger index) throws ByteBlockAccessException { byte b = block.getByte(index); String str = null; if (b < 0x20 || b == 0x7f) { str = "."; } else { char[] charArray = { (char) b }; str = new String(charArray); } return (str); } /** * Returns true if the formatter allows values to be changed. */ public boolean isEditable() { return true; } /** * Overwrite a value in a ByteBlock. * @param block block to change * @param index byte index into the block * @param pos The position within the unit where c will be the * new character. * @param c new character to put at pos param * @return true if the replacement is legal, false if the * replacement value would not make sense for this format, e.g. * attempt to put a 'z' in a hex unit. * @throws ByteBlockAccessException if the block cannot be updated * @throws IndexOutOfBoundsException if index is not valid for the * block */ public boolean replaceValue(ByteBlock block, BigInteger index, int charPosition, char c) throws ByteBlockAccessException { if (charPosition != 0) { return false; } block.getByte(index); byte cb = (byte) c; if (cb < 0x20 || cb == 0x7f) { return false; } block.setByte(index, cb); return true; } /** * Get number of units in a group. A group may represent * multiple units shown as one entity. This format does not * support groups. * @throws UnsupportedOperationException */ public int getGroupSize() { return 0; } /** * Set the number of units in a group. This format does not * support groups. * @throws UnsupportedOperationException */ public void setGroupSize(int groupSize) { throw new UnsupportedOperationException("groups are not supported"); } /** * Get the number of characters separating units. */ public int getUnitDelimiterSize() { return 0; } /** * @see ghidra.app.plugin.core.format.DataFormatModel#validateBytesPerLine(int) */ public boolean validateBytesPerLine(int bytesPerLine) { return true; } /* (non-Javadoc) * @see ghidra.app.plugin.format.DataFormatModel#getHelpLocation() */ public HelpLocation getHelpLocation() { return new HelpLocation("ByteViewerPlugin", "Ascii"); } public void dispose() { } public boolean supportsProvider(ByteViewerComponentProvider provider) { return true; } }
apache-2.0