APPLE INC.

MACOS SDK AND XCODE AGREEMENT

 

PLEASE READ THIS MACOS SDK AND XCODE AGREEMENT ("LICENSE") CAREFULLY BEFORE USING THE DEVELOPER SOFTWARE (DEFINED BELOW). BY USING THE DEVELOPER SOFTWARE, YOU ARE AGREEING TO BE BOUND BY THE TERMS OF THIS LICENSE.  IF YOU ARE ACCESSING THE DEVELOPER SOFTWARE ELECTRONICALLY, SIGNIFY YOUR AGREEMENT TO BE BOUND BY THE TERMS OF THIS LICENSE BY CLICKING THE "AGREE " BUTTON.  IF YOU DO NOT AGREE TO THE TERMS OF THIS LICENSE, DO NOT USE THE DEVELOPER SOFTWARE AND CLICK “DISAGREE”. 

 

IMPORTANT NOTE: To the extent that this software may be used to reproduce materials, it is licensed to you only for reproduction of non-copyrighted materials, materials in which you own the copyright, or materials you are authorized or legally permitted to reproduce. If you are uncertain about your right to copy any material, you should contact your legal advisor.

 

1. General. 

A. The Apple software, tools, utilities, sample or example code, documentation, interfaces, content, data, and other materials accompanying this License, whether on disk, print or electronic documentation, in read only memory, or any other media or in any other form, (collectively, the "Developer Software") are licensed, not sold, to you by Apple Inc. ("Apple") for use only under the terms of this License.  Apple and/or Apple’s licensors retain ownership of the Developer Software itself and reserve all rights not expressly granted to you. The terms of this License will govern any software upgrades provided by Apple that replace and/or supplement the original Developer Software, unless such upgrade is accompanied by a separate license in which case the terms of that license will govern. 

 

B. Title and intellectual property rights in and to any content displayed by or accessed through the Developer Software belongs to the respective content owner. Such content may be protected by copyright or other intellectual property laws and treaties, and may be subject to terms of use of the third party providing such content. This License does not grant you any rights to use such content nor does it guarantee that such content will continue to be available to you.

 

2. Permitted License Uses and Restrictions.

A. License. Subject to the terms and conditions of this License, you are granted a limited, non-exclusive license to use the Developer Software on Apple-branded computers to develop and test application and other software. You may make only as many internal use copies of the Developer Software as reasonably necessary to use the Developer Software as permitted under this License and distribute such copies only to your employees whose job duties require them to so use the Developer Software; provided that you reproduce on each copy of the Developer Software or portion thereof, all copyright or other proprietary notices contained on the original. 

 

B. Other Use Restrictions. The grants set forth in this License do not permit you to, and you agree not to, install, use or run the Developer Software on any non-Apple-branded computer, or to enable others to do so. Except as otherwise expressly permitted by the terms of this License or as otherwise licensed by Apple: (i) only one user may use the Developer Software at a time, and (ii) you may not make the Developer Software available over a network where it could be run or used by multiple computers at the same time. You may not rent, lease, lend, sell, sublicense or otherwise redistribute the Developer Software or exploit any services provided by or through the Developer Software in any unauthorized way. 

 

C. No Reverse Engineering; Limitations. You may not, and you agree not to or to enable others to, copy (except as expressly permitted by this License), decompile, reverse engineer, disassemble, attempt to derive the source code of, decrypt, modify, create derivative works of the Developer Software or any services provided by or through the Developer Software or any part thereof (except as and only to the extent any foregoing restriction is prohibited by applicable law or to the extent as may be permitted by licensing terms governing use of the  Open-Sourced Components or Sample Code). 

 

D. Sample Code. Certain portions of the Developer Software consist of sample or example code provided by Apple ("Sample Code"). You may use, reproduce, modify and redistribute such Sample Code only in accordance with the licensing terms accompanying such Sample Code or related project(s).

 

E. QuickTime Development Software. You may use the QuickTime development software only to develop application software that is compatible with, and runs only on supported macOS and/or Windows platforms with QuickTime installed. Your software application may not interfere with the functionality of QuickTime Player or the QuickTime Plug-in, including but not limited to file type or MIME type associations that are registered to QuickTime.

 

F. Use of System-Provided Images. The system-provided images owned by Apple and documented as such in Apple's Human Interface Guidelines for macOS and iOS ("System-Provided Images") are licensed to you solely for the purpose of developing macOS and iOS applications, respectively, using the Developer Software. Upon termination of this License, you may continue to distribute the System-Provided Images as used within software you developed using the Developer Software; however, you agree to provide to Apple, at Apple's request, a copy of any software you developed using the Developer Software that incorporates any of the System-Provided Images so Apple may determine, in its sole discretion, whether your use of the System-Provided Images complies with these terms.

 

G. Location Services; Consents. 

1. Apple may enable you to access certain location-based application programming interfaces (APIs) (e.g., Core Location) documented by Apple (“Location APIs”) through the Developer Software.  Subject to these terms and conditions, you may use such APIs and services only to enable software programs you develop for use on macOS (“Applications”) to access location data (e.g. the real-time geographic location of a user’s computer) from users who consent to such access. For Applications that use Location APIs or otherwise provide location-based services, you agree that such Applications may not be designed or marketed for automatic or autonomous control of vehicle behavior, or for emergency or life-saving purposes. In addition, Applications that offer location-based services or functionality must notify and obtain consent from an individual before his or her location data is collected, transmitted or otherwise used by the Application. For Applications that use Location APIs for real-time navigation (including, but not limited to, turn-by-turn route guidance and other routing that is enabled through the use of a sensor), you must have an end-user license agreement that includes the following notice: YOUR USE OF THIS REAL TIME ROUTE GUIDANCE APPLICATION IS AT YOUR SOLE RISK. LOCATION DATA MAY NOT BE ACCURATE.

 

2. You agree that neither you nor your Applications will disable, override or otherwise interfere with any Apple-implemented system alerts, warnings, display panels, consent panels and the like, including, but not limited to, those that are intended to notify the user that the user's location data is being collected, transmitted, maintained, processed or used, or intended to obtain consent for such use.  If consent is denied or withdrawn, neither you nor your Applications may collect, transmit, maintain, process or utilize the user's location information or data through the Location APIs. You understand and agree that you and your Applications must comply with all applicable criminal, civil and statutory laws and regulations (including privacy, data collection and location service laws and regulations) in any jurisdictions in which your Applications may be delivered.  You shall be solely responsible for, and Apple shall have no responsibility or liability whatsoever with respect to, any and all claims, suits, liabilities, losses, damages, costs and expenses arising from, related or attributable to, or otherwise involving your Application, including but not limited to your Application’s use of the Location APIs.

 

H. Compliance with Laws. You agree to use the Developer Software and the services in compliance with all applicable laws, including local laws of the country or region in which you reside or in which you download or use the Developer Software or services.

 

3. Transfer. You may make a one-time permanent transfer of all of your license rights to the Developer Software (in its original form as provided by Apple) to another party, provided that: (a) the transfer must include all of the Developer Software, including all its component parts and this License; (b) you do not retain any copies of the Developer Software, full or partial, including copies stored on a computer or other storage device; and (c) the party receiving the Developer Software accepts the terms and conditions of this License. You may not transfer any Developer Software that has been modified or replaced under Section 13 below. All components of the Developer Software are provided as part of a bundle and may not be separated from the bundle and distributed as standalone applications.

 

4. Consent to Use of Data.

A. Diagnostic and Usage Data. If you choose to allow diagnostic and usage collection, you agree that Apple and its subsidiaries and agents may collect, maintain, process and use diagnostic, technical, usage and related information, including but not limited to unique system or hardware identifiers, information about your computer, system and application software, and peripherals, that is gathered periodically to provide and improve Apple’s products and services, facilitate the provision of software updates, product support and other services to you (if any) related to the Developer Software, and to verify compliance with the terms of this License. You may change your preferences for Diagnostics & Usage collection at any time by going to the Diagnostics & Usage setting on your computer and deselecting the checkbox. The Diagnostics & Usage setting is found in the Security & Privacy pane within System Preferences. Apple may use this information, as long as it is collected in a form that does not personally identify you, for the purposes described above. To enable Apple’s partners and third party developers to improve their software, hardware and services designed for use with Apple products, Apple may also provide any such partner or third party developer with a subset of diagnostic information that is relevant to that partner’s or developer’s software, hardware and/or services, as long as the diagnostic information is in a form that does not personally identify you. 

 

B. Privacy Policy. At all times your information will be treated in accordance with Apple’s Privacy Policy, which is incorporated by reference into this License and can be viewed at: http://www.apple.com/legal/privacy/.

 

5. Services; Mac Developer Program.

A. Apple may provide access to services by or through the Developer Software for you to use.  Use of these services may require an Apple ID, may require you to accept additional terms and may be subject to additional fees. If you elect to use such services in conjunction with the Developer Software, your usage of such services will be subject to those additional terms and conditions (e.g., your use of Developer IDs obtained from your Apple Developer Program account will be subject to the applicable Apple Developer Program terms for Developer IDs), but this License will continue to apply to your use of the Developer Software licensed hereunder. If you would like to submit Applications you develop to the Mac App Store, then you must apply to join the Mac Developer Program. More information about Apple’s Developer Programs is available at http://developer.apple.com/. Apple reserves the right to refuse admission to any of its Developer Programs at any time in its sole discretion. 

 

B. You agree that the services contain proprietary content, information and material that is owned by Apple and its licensors, and is protected by applicable intellectual property and other laws, and that you will not use such proprietary content, information or materials in any way whatsoever except for permitted use of the services or in any manner that is inconsistent with the terms of this License or that infringes any intellectual property rights of a third party or Apple. Except to the extent expressly permitted in the applicable terms for the services, You agree not to reproduce, modify, rent, lease, lend, sell, distribute, or create derivative works based on the services, in any manner, and you shall not exploit the services in any unauthorized way whatsoever, including but not limited to, using the services to transmit any malware, or by trespass or burdening network capacity. 

 

C. In addition, services that may be accessed, linked to or displayed through the Developer Software may not be available in all languages or in all countries. Apple makes no representation that any such services would be appropriate or available for use in any particular location. Apple reserves the right to change, suspend, remove, or disable access to any services at any time. In no event will Apple be liable for the removal of or disabling of access to any such services or for any updates, maintenance, warranty, technical or other support for such services. Apple may also impose limits or other restrictions on the use of or access to the services, in any case without notice or liability.  You acknowledge and agree that Apple reserves the right to revoke or remove your access to any services provided by or through the Developer Software at any time in its sole discretion.

 

6. Termination. This License is effective until terminated. Your rights under this License will terminate automatically or cease to be effective without notice from Apple if you fail to comply with any term(s) of this License. In addition, Apple reserves the right to terminate this License if a new version of Apple's operating system software or the Developer Software is released which is incompatible with this version of the Developer Software. Upon the termination of this License, you shall cease all use of the Developer Software and destroy all copies, full or partial, of the Developer Software. Section 2B, 2C, 4, 5B, and 6 through 13 of this License shall survive any termination.

 

7. Disclaimer of Warranties. 

A. YOU EXPRESSLY ACKNOWLEDGE AND AGREE THAT, TO THE EXTENT PERMITTED BY APPLICABLE LAW, USE OF THE DEVELOPER SOFTWARE AND ANY SERVICES PERFORMED BY OR ACCESSED THROUGH THE DEVELOPER SOFTWARE IS AT YOUR SOLE RISK AND THAT THE ENTIRE RISK AS TO SATISFACTORY QUALITY, PERFORMANCE, ACCURACY AND EFFORT IS WITH YOU. 

 

B. TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THE DEVELOPER SOFTWARE AND SERVICES ARE PROVIDED “AS IS” AND “AS AVAILABLE”, WITH ALL FAULTS AND WITHOUT WARRANTY OF ANY KIND, AND APPLE AND APPLE'S LICENSORS (COLLECTIVELY REFERRED TO AS “APPLE” FOR THE PURPOSES OF SECTIONS 7 AND 8) HEREBY DISCLAIM ALL WARRANTIES AND CONDITIONS WITH RESPECT TO THE DEVELOPER SOFTWARE AND SERVICES, EITHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES AND/OR CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A PARTICULAR PURPOSE, ACCURACY, QUIET ENJOYMENT, AND NON-INFRINGEMENT OF THIRD PARTY RIGHTS. 

 

C. APPLE DOES NOT WARRANT AGAINST INTERFERENCE WITH YOUR ENJOYMENT OF THE DEVELOPER SOFTWARE AND SERVICES, THAT THE FUNCTIONS CONTAINED IN, OR SERVICES PERFORMED OR PROVIDED BY, THE DEVELOPER SOFTWARE WILL MEET YOUR REQUIREMENTS, THAT THE OPERATION OF THE DEVELOPER SOFTWARE OR SERVICES WILL BE UNINTERRUPTED OR ERROR-FREE, THAT ANY SERVICES WILL CONTINUE TO BE MADE AVAILABLE, THAT THE DEVELOPER SOFTWARE OR SERVICES WILL BE COMPATIBLE OR WORK WITH ANY THIRD PARTY SOFTWARE, APPLICATIONS OR THIRD PARTY SERVICES, OR THAT DEFECTS IN THE DEVELOPER SOFTWARE OR SERVICES WILL BE CORRECTED. INSTALLATION OF THIS DEVELOPER SOFTWARE MAY AFFECT THE USABILITY OF THIRD PARTY SOFTWARE, APPLICATIONS OR THIRD PARTY SERVICES AS WELL AS OTHER APPLE PRODUCTS OR SERVICES.

 

D. YOU FURTHER ACKNOWLEDGE THAT THE DEVELOPER SOFTWARE AND SERVICES ARE NOT INTENDED OR SUITABLE FOR USE IN SITUATIONS OR ENVIRONMENTS WHERE THE FAILURE OR TIME DELAYS OF, OR ERRORS OR INACCURACIES IN THE CONTENT, DATA OR INFORMATION PROVIDED BY, THE DEVELOPER SOFTWARE OR SERVICES COULD LEAD TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE, INCLUDING WITHOUT LIMITATION THE OPERATION OF NUCLEAR FACILITIES, AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, LIFE SUPPORT OR WEAPONS SYSTEMS. 

 

E. NO ORAL OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE SHALL CREATE A WARRANTY. SHOULD THE DEVELOPER SOFTWARE OR SERVICES PROVE DEFECTIVE, YOU ASSUME THE ENTIRE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OF IMPLIED WARRANTIES OR LIMITATIONS ON APPLICABLE STATUTORY RIGHTS OF A CONSUMER, SO THE ABOVE EXCLUSION AND LIMITATIONS MAY NOT APPLY TO YOU. 

 

8. Limitation of Liability. TO THE EXTENT NOT PROHIBITED BY APPLICABLE LAW, IN NO EVENT SHALL APPLE BE LIABLE FOR PERSONAL INJURY, OR ANY INCIDENTAL, SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES WHATSOEVER, INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF PROFITS, CORRUPTION OR LOSS OF DATA, FAILURE TO TRANSMIT OR RECEIVE ANY DATA OR INFORMATION, BUSINESS INTERRUPTION OR ANY OTHER COMMERCIAL DAMAGES OR LOSSES, ARISING OUT OF OR RELATED TO YOUR USE OR INABILITY TO USE THE DEVELOPER SOFTWARE OR SERVICES OR ANY THIRD PARTY SOFTWARE, APPLICATIONS, OR SERVICES IN CONJUNCTION WITH THE DEVELOPER SOFTWARE OR SERVICES, HOWEVER CAUSED, REGARDLESS OF THE THEORY OF LIABILITY (CONTRACT, TORT OR OTHERWISE) AND EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OR LIMITATION OF LIABILITY FOR PERSONAL INJURY, OR OF INCIDENTAL OR CONSEQUENTIAL DAMAGES, SO THIS LIMITATION MAY NOT APPLY TO YOU. In no event shall Apple's total liability to you for all damages (other than as may be required by applicable law in cases involving personal injury) exceed the amount of fifty dollars ($50.00). The foregoing limitations will apply even if the above stated remedy fails of its essential purpose.

 

9. Export Control. You may not use or otherwise export or re-export the Developer Software except as authorized by United States law and the laws of the jurisdiction(s) in which the Developer Software was obtained. In particular, but without limitation, the Developer Software may not be exported or re-exported (a) into any U.S. embargoed countries or (b) to anyone on the U.S. Treasury Department's list of Specially Designated Nationals or the U.S. Department of Commerce Denied Person's List or Entity List. By using the Developer Software, you represent and warrant that you are not located in any such country or on any such list. You also agree that you will not use the Developer Software for any purposes prohibited by United States law, including, without limitation, the development, design, manufacture or production of missiles, nuclear, chemical or biological weapons.

 

10. Government End Users. The Developer Software and related documentation are "Commercial Items", as that term is defined at 48 C.F.R. §2.101, consisting of "Commercial Computer Software" and "Commercial Computer Software Documentation", as such terms are used in 48 C.F.R. §12.212 or 48 C.F.R. §227.7202, as applicable. Consistent with 48 C.F.R. §12.212 or 48 C.F.R. §227.7202-1 through 227.7202-4, as applicable, the Commercial Computer Software and Commercial Computer Software Documentation are being licensed to U.S. Government end users (a) only as Commercial Items and (b) with only those rights as are granted to all other end users pursuant to the terms and conditions herein. Unpublished-rights reserved under the copyright laws of the United States.

 

11. Controlling Law and Severability. This License will be governed by and construed in accordance with the laws of the State of California, excluding its conflict of law principles. This License shall not be governed by the United Nations Convention on Contracts for the International Sale of Goods, the application of which is expressly excluded. If for any reason a court of competent jurisdiction finds any provision, or portion thereof, to be unenforceable, the remainder of this License shall continue in full force and effect.  

 

12. Complete Agreement; Governing Language. This License constitutes the entire agreement between you and Apple relating to the use of the Developer Software licensed hereunder and supersedes all prior or contemporaneous understandings regarding such subject matter. No amendment to or modification of this License will be binding unless in writing and signed by Apple.  The parties hereto confirm that they have requested that this License and all related documents be drafted in English. Les parties ont exigé que le présent contrat et tous les documents connexes soient rédigés en anglais.

 

13. Third Party Acknowledgements. 

A. Certain components of the Developer Software, and third party open source programs included with the Developer Software, have been or may be made available by Apple on its Open Source web site (http://www.opensource.apple.com/) (collectively the "Open-Sourced Components"). You may modify or replace only these Open-Sourced Components; provided that: (i) the resultant modified Developer Software is used in accordance with the permitted uses set forth above; and (ii) you otherwise comply with the terms of this License and any applicable licensing terms governing use of the Open-Sourced Components. Apple is not obligated to provide any updates, maintenance, warranty, technical or other support, or services for the resultant modified Developer Software. You expressly acknowledge that if failure of or damage to Apple hardware results from modification of the Open-Sourced Components of the Developer Software, such failure or damage is excluded from the terms of the Apple hardware warranty.

 

B. Certain software libraries and other third party software included with the Developer Software are free software and licensed under the terms of the GNU General Public License (GPL) or the GNU Library/Lesser General Public License (LGPL), as the case may be. You may obtain a complete machine-readable copy of the source code for such free software under the terms of the GPL or LGPL, as the case may be, without charge except for the cost of media, shipping, and handling, upon written request to Apple. The GPL/LGPL software is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY, without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. A copy of the GPL and LGPL is included with the Developer Software.

 

C. The Developer Software includes certain software licensed under the IBM Public License Version 1.0 (IPL) or the Common Public License Version 1.0 (CPL). A copy of the source code for the IPL and CPL licensed software may be found in Apple’s Open Source repository. See Apple's Open Source web site (http://www.opensource.apple.com) for information on how to obtain the source code. THE IPL AND CPL SOFTWARE IS PROVIDED 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.  NEITHER APPLE, IBM NOR ANY OTHER CONTRIBUTOR TO THE  IPL AND CPL SOFTWARE SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, WITHOUT LIMITATION, LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE IPL AND CPL SOFTWARE OR THE EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.

 

EA1422

8/25/2016

 

 

APPLE INC.

MACOS SDK AND XCODE AGREEMENT

 

PLEASE READ THIS MACOS SDK AND XCODE AGREEMENT ("LICENSE") CAREFULLY BEFORE USING THE DEVELOPER SOFTWARE (DEFINED BELOW). BY USING THE DEVELOPER SOFTWARE, YOU ARE AGREEING TO BE BOUND BY THE TERMS OF THIS LICENSE.  IF YOU ARE ACCESSING THE DEVELOPER SOFTWARE ELECTRONICALLY, SIGNIFY YOUR AGREEMENT TO BE BOUND BY THE TERMS OF THIS LICENSE BY CLICKING THE "AGREE " BUTTON.  IF YOU DO NOT AGREE TO THE TERMS OF THIS LICENSE, DO NOT USE THE DEVELOPER SOFTWARE AND CLICK “DISAGREE”. 

 

IMPORTANT NOTE: To the extent that this software may be used to reproduce materials, it is licensed to you only for reproduction of non-copyrighted materials, materials in which you own the copyright, or materials you are authorized or legally permitted to reproduce. If you are uncertain about your right to copy any material, you should contact your legal advisor.

 

1. General. 

A. The Apple software, tools, utilities, sample or example code, documentation, interfaces, content, data, and other materials accompanying this License, whether on disk, print or electronic documentation, in read only memory, or any other media or in any other form, (collectively, the "Developer Software") are licensed, not sold, to you by Apple Inc. ("Apple") for use only under the terms of this License.  Apple and/or Apple’s licensors retain ownership of the Developer Software itself and reserve all rights not expressly granted to you. The terms of this License will govern any software upgrades provided by Apple that replace and/or supplement the original Developer Software, unless such upgrade is accompanied by a separate license in which case the terms of that license will govern. 

 

B. Title and intellectual property rights in and to any content displayed by or accessed through the Developer Software belongs to the respective content owner. Such content may be protected by copyright or other intellectual property laws and treaties, and may be subject to terms of use of the third party providing such content. This License does not grant you any rights to use such content nor does it guarantee that such content will continue to be available to you.

 

2. Permitted License Uses and Restrictions.

A. License. Subject to the terms and conditions of this License, you are granted a limited, non-exclusive license to use the Developer Software on Apple-branded computers to develop and test application and other software. You may make only as many internal use copies of the Developer Software as reasonably necessary to use the Developer Software as permitted under this License and distribute such copies only to your employees whose job duties require them to so use the Developer Software; provided that you reproduce on each copy of the Developer Software or portion thereof, all copyright or other proprietary notices contained on the original. 

 

B. Other Use Restrictions. The grants set forth in this License do not permit you to, and you agree not to, install, use or run the Developer Software on any non-Apple-branded computer, or to enable others to do so. Except as otherwise expressly permitted by the terms of this License or as otherwise licensed by Apple: (i) only one user may use the Developer Software at a time, and (ii) you may not make the Developer Software available over a network where it could be run or used by multiple computers at the same time. You may not rent, lease, lend, sell, sublicense or otherwise redistribute the Developer Software or exploit any services provided by or through the Developer Software in any unauthorized way. 

 

C. No Reverse Engineering; Limitations. You may not, and you agree not to or to enable others to, copy (except as expressly permitted by this License), decompile, reverse engineer, disassemble, attempt to derive the source code of, decrypt, modify, create derivative works of the Developer Software or any services provided by or through the Developer Software or any part thereof (except as and only to the extent any foregoing restriction is prohibited by applicable law or to the extent as may be permitted by licensing terms governing use of the  Open-Sourced Components or Sample Code). 

 

D. Sample Code. Certain portions of the Developer Software consist of sample or example code provided by Apple ("Sample Code"). You may use, reproduce, modify and redistribute such Sample Code only in accordance with the licensing terms accompanying such Sample Code or related project(s).

 

E. QuickTime Development Software. You may use the QuickTime development software only to develop application software that is compatible with, and runs only on supported macOS and/or Windows platforms with QuickTime installed. Your software application may not interfere with the functionality of QuickTime Player or the QuickTime Plug-in, including but not limited to file type or MIME type associations that are registered to QuickTime.

 

F. Use of System-Provided Images. The system-provided images owned by Apple and documented as such in Apple's Human Interface Guidelines for macOS and iOS ("System-Provided Images") are licensed to you solely for the purpose of developing macOS and iOS applications, respectively, using the Developer Software. Upon termination of this License, you may continue to distribute the System-Provided Images as used within software you developed using the Developer Software; however, you agree to provide to Apple, at Apple's request, a copy of any software you developed using the Developer Software that incorporates any of the System-Provided Images so Apple may determine, in its sole discretion, whether your use of the System-Provided Images complies with these terms.

 

G. Location Services; Consents. 

1. Apple may enable you to access certain location-based application programming interfaces (APIs) (e.g., Core Location) documented by Apple (“Location APIs”) through the Developer Software.  Subject to these terms and conditions, you may use such APIs and services only to enable software programs you develop for use on macOS (“Applications”) to access location data (e.g. the real-time geographic location of a user’s computer) from users who consent to such access. For Applications that use Location APIs or otherwise provide location-based services, you agree that such Applications may not be designed or marketed for automatic or autonomous control of vehicle behavior, or for emergency or life-saving purposes. In addition, Applications that offer location-based services or functionality must notify and obtain consent from an individual before his or her location data is collected, transmitted or otherwise used by the Application. For Applications that use Location APIs for real-time navigation (including, but not limited to, turn-by-turn route guidance and other routing that is enabled through the use of a sensor), you must have an end-user license agreement that includes the following notice: YOUR USE OF THIS REAL TIME ROUTE GUIDANCE APPLICATION IS AT YOUR SOLE RISK. LOCATION DATA MAY NOT BE ACCURATE.

 

2. You agree that neither you nor your Applications will disable, override or otherwise interfere with any Apple-implemented system alerts, warnings, display panels, consent panels and the like, including, but not limited to, those that are intended to notify the user that the user's location data is being collected, transmitted, maintained, processed or used, or intended to obtain consent for such use.  If consent is denied or withdrawn, neither you nor your Applications may collect, transmit, maintain, process or utilize the user's location information or data through the Location APIs. You understand and agree that you and your Applications must comply with all applicable criminal, civil and statutory laws and regulations (including privacy, data collection and location service laws and regulations) in any jurisdictions in which your Applications may be delivered.  You shall be solely responsible for, and Apple shall have no responsibility or liability whatsoever with respect to, any and all claims, suits, liabilities, losses, damages, costs and expenses arising from, related or attributable to, or otherwise involving your Application, including but not limited to your Application’s use of the Location APIs.

 

H. Compliance with Laws. You agree to use the Developer Software and the services in compliance with all applicable laws, including local laws of the country or region in which you reside or in which you download or use the Developer Software or services.

 

3. Transfer. You may make a one-time permanent transfer of all of your license rights to the Developer Software (in its original form as provided by Apple) to another party, provided that: (a) the transfer must include all of the Developer Software, including all its component parts and this License; (b) you do not retain any copies of the Developer Software, full or partial, including copies stored on a computer or other storage device; and (c) the party receiving the Developer Software accepts the terms and conditions of this License. You may not transfer any Developer Software that has been modified or replaced under Section 13 below. All components of the Developer Software are provided as part of a bundle and may not be separated from the bundle and distributed as standalone applications.

 

4. Consent to Use of Data.

A. Diagnostic and Usage Data. If you choose to allow diagnostic and usage collection, you agree that Apple and its subsidiaries and agents may collect, maintain, process and use diagnostic, technical, usage and related information, including but not limited to unique system or hardware identifiers, information about your computer, system and application software, and peripherals, that is gathered periodically to provide and improve Apple’s products and services, facilitate the provision of software updates, product support and other services to you (if any) related to the Developer Software, and to verify compliance with the terms of this License. You may change your preferences for Diagnostics & Usage collection at any time by going to the Diagnostics & Usage setting on your computer and deselecting the checkbox. The Diagnostics & Usage setting is found in the Security & Privacy pane within System Preferences. Apple may use this information, as long as it is collected in a form that does not personally identify you, for the purposes described above. To enable Apple’s partners and third party developers to improve their software, hardware and services designed for use with Apple products, Apple may also provide any such partner or third party developer with a subset of diagnostic information that is relevant to that partner’s or developer’s software, hardware and/or services, as long as the diagnostic information is in a form that does not personally identify you. 

 

B. Privacy Policy. At all times your information will be treated in accordance with Apple’s Privacy Policy, which is incorporated by reference into this License and can be viewed at: http://www.apple.com/legal/privacy/.

 

5. Services; Mac Developer Program.

A. Apple may provide access to services by or through the Developer Software for you to use.  Use of these services may require an Apple ID, may require you to accept additional terms and may be subject to additional fees. If you elect to use such services in conjunction with the Developer Software, your usage of such services will be subject to those additional terms and conditions (e.g., your use of Developer IDs obtained from your Apple Developer Program account will be subject to the applicable Apple Developer Program terms for Developer IDs), but this License will continue to apply to your use of the Developer Software licensed hereunder. If you would like to submit Applications you develop to the Mac App Store, then you must apply to join the Mac Developer Program. More information about Apple’s Developer Programs is available at http://developer.apple.com/. Apple reserves the right to refuse admission to any of its Developer Programs at any time in its sole discretion. 

 

B. You agree that the services contain proprietary content, information and material that is owned by Apple and its licensors, and is protected by applicable intellectual property and other laws, and that you will not use such proprietary content, information or materials in any way whatsoever except for permitted use of the services or in any manner that is inconsistent with the terms of this License or that infringes any intellectual property rights of a third party or Apple. Except to the extent expressly permitted in the applicable terms for the services, You agree not to reproduce, modify, rent, lease, lend, sell, distribute, or create derivative works based on the services, in any manner, and you shall not exploit the services in any unauthorized way whatsoever, including but not limited to, using the services to transmit any malware, or by trespass or burdening network capacity. 

 

C. In addition, services that may be accessed, linked to or displayed through the Developer Software may not be available in all languages or in all countries. Apple makes no representation that any such services would be appropriate or available for use in any particular location. Apple reserves the right to change, suspend, remove, or disable access to any services at any time. In no event will Apple be liable for the removal of or disabling of access to any such services or for any updates, maintenance, warranty, technical or other support for such services. Apple may also impose limits or other restrictions on the use of or access to the services, in any case without notice or liability.  You acknowledge and agree that Apple reserves the right to revoke or remove your access to any services provided by or through the Developer Software at any time in its sole discretion.

 

6. Termination. This License is effective until terminated. Your rights under this License will terminate automatically or cease to be effective without notice from Apple if you fail to comply with any term(s) of this License. In addition, Apple reserves the right to terminate this License if a new version of Apple's operating system software or the Developer Software is released which is incompatible with this version of the Developer Software. Upon the termination of this License, you shall cease all use of the Developer Software and destroy all copies, full or partial, of the Developer Software. Section 2B, 2C, 4, 5B, and 6 through 13 of this License shall survive any termination.

 

7. Disclaimer of Warranties. 

A. YOU EXPRESSLY ACKNOWLEDGE AND AGREE THAT, TO THE EXTENT PERMITTED BY APPLICABLE LAW, USE OF THE DEVELOPER SOFTWARE AND ANY SERVICES PERFORMED BY OR ACCESSED THROUGH THE DEVELOPER SOFTWARE IS AT YOUR SOLE RISK AND THAT THE ENTIRE RISK AS TO SATISFACTORY QUALITY, PERFORMANCE, ACCURACY AND EFFORT IS WITH YOU. 

 

B. TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THE DEVELOPER SOFTWARE AND SERVICES ARE PROVIDED “AS IS” AND “AS AVAILABLE”, WITH ALL FAULTS AND WITHOUT WARRANTY OF ANY KIND, AND APPLE AND APPLE'S LICENSORS (COLLECTIVELY REFERRED TO AS “APPLE” FOR THE PURPOSES OF SECTIONS 7 AND 8) HEREBY DISCLAIM ALL WARRANTIES AND CONDITIONS WITH RESPECT TO THE DEVELOPER SOFTWARE AND SERVICES, EITHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES AND/OR CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A PARTICULAR PURPOSE, ACCURACY, QUIET ENJOYMENT, AND NON-INFRINGEMENT OF THIRD PARTY RIGHTS. 

 

C. APPLE DOES NOT WARRANT AGAINST INTERFERENCE WITH YOUR ENJOYMENT OF THE DEVELOPER SOFTWARE AND SERVICES, THAT THE FUNCTIONS CONTAINED IN, OR SERVICES PERFORMED OR PROVIDED BY, THE DEVELOPER SOFTWARE WILL MEET YOUR REQUIREMENTS, THAT THE OPERATION OF THE DEVELOPER SOFTWARE OR SERVICES WILL BE UNINTERRUPTED OR ERROR-FREE, THAT ANY SERVICES WILL CONTINUE TO BE MADE AVAILABLE, THAT THE DEVELOPER SOFTWARE OR SERVICES WILL BE COMPATIBLE OR WORK WITH ANY THIRD PARTY SOFTWARE, APPLICATIONS OR THIRD PARTY SERVICES, OR THAT DEFECTS IN THE DEVELOPER SOFTWARE OR SERVICES WILL BE CORRECTED. INSTALLATION OF THIS DEVELOPER SOFTWARE MAY AFFECT THE USABILITY OF THIRD PARTY SOFTWARE, APPLICATIONS OR THIRD PARTY SERVICES AS WELL AS OTHER APPLE PRODUCTS OR SERVICES.

 

D. YOU FURTHER ACKNOWLEDGE THAT THE DEVELOPER SOFTWARE AND SERVICES ARE NOT INTENDED OR SUITABLE FOR USE IN SITUATIONS OR ENVIRONMENTS WHERE THE FAILURE OR TIME DELAYS OF, OR ERRORS OR INACCURACIES IN THE CONTENT, DATA OR INFORMATION PROVIDED BY, THE DEVELOPER SOFTWARE OR SERVICES COULD LEAD TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE, INCLUDING WITHOUT LIMITATION THE OPERATION OF NUCLEAR FACILITIES, AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, LIFE SUPPORT OR WEAPONS SYSTEMS. 

 

E. NO ORAL OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE SHALL CREATE A WARRANTY. SHOULD THE DEVELOPER SOFTWARE OR SERVICES PROVE DEFECTIVE, YOU ASSUME THE ENTIRE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OF IMPLIED WARRANTIES OR LIMITATIONS ON APPLICABLE STATUTORY RIGHTS OF A CONSUMER, SO THE ABOVE EXCLUSION AND LIMITATIONS MAY NOT APPLY TO YOU. 

 

8. Limitation of Liability. TO THE EXTENT NOT PROHIBITED BY APPLICABLE LAW, IN NO EVENT SHALL APPLE BE LIABLE FOR PERSONAL INJURY, OR ANY INCIDENTAL, SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES WHATSOEVER, INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF PROFITS, CORRUPTION OR LOSS OF DATA, FAILURE TO TRANSMIT OR RECEIVE ANY DATA OR INFORMATION, BUSINESS INTERRUPTION OR ANY OTHER COMMERCIAL DAMAGES OR LOSSES, ARISING OUT OF OR RELATED TO YOUR USE OR INABILITY TO USE THE DEVELOPER SOFTWARE OR SERVICES OR ANY THIRD PARTY SOFTWARE, APPLICATIONS, OR SERVICES IN CONJUNCTION WITH THE DEVELOPER SOFTWARE OR SERVICES, HOWEVER CAUSED, REGARDLESS OF THE THEORY OF LIABILITY (CONTRACT, TORT OR OTHERWISE) AND EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OR LIMITATION OF LIABILITY FOR PERSONAL INJURY, OR OF INCIDENTAL OR CONSEQUENTIAL DAMAGES, SO THIS LIMITATION MAY NOT APPLY TO YOU. In no event shall Apple's total liability to you for all damages (other than as may be required by applicable law in cases involving personal injury) exceed the amount of fifty dollars ($50.00). The foregoing limitations will apply even if the above stated remedy fails of its essential purpose.

 

9. Export Control. You may not use or otherwise export or re-export the Developer Software except as authorized by United States law and the laws of the jurisdiction(s) in which the Developer Software was obtained. In particular, but without limitation, the Developer Software may not be exported or re-exported (a) into any U.S. embargoed countries or (b) to anyone on the U.S. Treasury Department's list of Specially Designated Nationals or the U.S. Department of Commerce Denied Person's List or Entity List. By using the Developer Software, you represent and warrant that you are not located in any such country or on any such list. You also agree that you will not use the Developer Software for any purposes prohibited by United States law, including, without limitation, the development, design, manufacture or production of missiles, nuclear, chemical or biological weapons.

 

10. Government End Users. The Developer Software and related documentation are "Commercial Items", as that term is defined at 48 C.F.R. §2.101, consisting of "Commercial Computer Software" and "Commercial Computer Software Documentation", as such terms are used in 48 C.F.R. §12.212 or 48 C.F.R. §227.7202, as applicable. Consistent with 48 C.F.R. §12.212 or 48 C.F.R. §227.7202-1 through 227.7202-4, as applicable, the Commercial Computer Software and Commercial Computer Software Documentation are being licensed to U.S. Government end users (a) only as Commercial Items and (b) with only those rights as are granted to all other end users pursuant to the terms and conditions herein. Unpublished-rights reserved under the copyright laws of the United States.

 

11. Controlling Law and Severability. This License will be governed by and construed in accordance with the laws of the State of California, excluding its conflict of law principles. This License shall not be governed by the United Nations Convention on Contracts for the International Sale of Goods, the application of which is expressly excluded. If for any reason a court of competent jurisdiction finds any provision, or portion thereof, to be unenforceable, the remainder of this License shall continue in full force and effect.  

 

12. Complete Agreement; Governing Language. This License constitutes the entire agreement between you and Apple relating to the use of the Developer Software licensed hereunder and supersedes all prior or contemporaneous understandings regarding such subject matter. No amendment to or modification of this License will be binding unless in writing and signed by Apple.  The parties hereto confirm that they have requested that this License and all related documents be drafted in English. Les parties ont exigé que le présent contrat et tous les documents connexes soient rédigés en anglais.

 

13. Third Party Acknowledgements. 

A. Certain components of the Developer Software, and third party open source programs included with the Developer Software, have been or may be made available by Apple on its Open Source web site (http://www.opensource.apple.com/) (collectively the "Open-Sourced Components"). You may modify or replace only these Open-Sourced Components; provided that: (i) the resultant modified Developer Software is used in accordance with the permitted uses set forth above; and (ii) you otherwise comply with the terms of this License and any applicable licensing terms governing use of the Open-Sourced Components. Apple is not obligated to provide any updates, maintenance, warranty, technical or other support, or services for the resultant modified Developer Software. You expressly acknowledge that if failure of or damage to Apple hardware results from modification of the Open-Sourced Components of the Developer Software, such failure or damage is excluded from the terms of the Apple hardware warranty.

 

B. Certain software libraries and other third party software included with the Developer Software are free software and licensed under the terms of the GNU General Public License (GPL) or the GNU Library/Lesser General Public License (LGPL), as the case may be. You may obtain a complete machine-readable copy of the source code for such free software under the terms of the GPL or LGPL, as the case may be, without charge except for the cost of media, shipping, and handling, upon written request to Apple. The GPL/LGPL software is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY, without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. A copy of the GPL and LGPL is included with the Developer Software.

 

C. The Developer Software includes certain software licensed under the IBM Public License Version 1.0 (IPL) or the Common Public License Version 1.0 (CPL). A copy of the source code for the IPL and CPL licensed software may be found in Apple’s Open Source repository. See Apple's Open Source web site (http://www.opensource.apple.com) for information on how to obtain the source code. THE IPL AND CPL SOFTWARE IS PROVIDED 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.  NEITHER APPLE, IBM NOR ANY OTHER CONTRIBUTOR TO THE  IPL AND CPL SOFTWARE SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, WITHOUT LIMITATION, LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE IPL AND CPL SOFTWARE OR THE EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.

 

EA1422

8/25/2016

'Swift & Python 실무 > {APP} SOCANNER APP' 카테고리의 다른 글

game center icon  (0) 2021.06.04
Game Center transcript  (0) 2021.06.04
swift log level  (0) 2021.05.28
coredata 를 배열로 쓰기  (0) 2021.05.23
tableview 에 button 삽입 후 title 가져오기  (0) 2021.05.23

struct _logLevel: OptionSet {

        let rawValue: Int

        static let critical    = _logLevel(rawValue: 1 << 0)

        static let major  = _logLevel(rawValue: 1 << 1)

        static let minor   = _logLevel(rawValue: 1 << 2)

        static let just   = _logLevel(rawValue: 1 << 3)

        static let graph = _logLevel(rawValue: 1 << 4)

        static let current = _logLevel(rawValue: 1 << 5)

        static let fixing = _logLevel(rawValue: 1 << 6)

        static let motion = _logLevel(rawValue: 1 << 7)

        static let network = _logLevel(rawValue: 1 << 8)

        static let network2 = _logLevel(rawValue: 1 << 9)

        static let none = _logLevel(rawValue: 1 << 10)

        static let layer = _logLevel(rawValue: 1 << 11)

        static let json = _logLevel(rawValue: 1 << 12)

        static let share = _logLevel(rawValue: 1 << 13)

        static let guideline = _logLevel(rawValue: 1 << 14)

        static let calendar = _logLevel(rawValue: 1 << 15)

        static let refresh = _logLevel(rawValue: 1 << 16)

        static let location = _logLevel(rawValue: 1 << 17)

        static let all: _logLevel = [.critical, .major, .minor, .just, .graph, .current, .location, .fixing, .motion, .network, .network2, .layer, .json, .share, .guideline, .calendar, .refresh]

    }

 

class GS {

    

    static let s = GS()

    

    var totalScore : Int? = 0

    

    var logLevel: _logLevel = .current

 

 

if GS.s.logLevel == .motion { debugPrint("didSwipe Down") }

 

if GS.s.logLevel == .fixing {

 

 

if(!GS.s.logLevel.contains(.none)) {

 

 

나름 나의 고급 기술인데 오픈한다.

 

로그 레벨을 나눈 것과 아닌 프로젝트의 차이는 트러블슈팅에서 천지차이.

 

 

 

@property (nonatomic, strong) NSString    * _Nullable id_atch_file;

@property (nonatomic, strong) NSString    * _Nonnull cd_sub_sys;

 

혼자 전체 프로젝트 작업(서버 포함) 할 때는 무조건 Nullable...

 

인터페이스 만들어서 다른 사람에게 줄 때는 NonNull...

 

그게 정석인 것 같다.

'Objective-C, SQLite3' 카테고리의 다른 글

class 변수 쓰지 말자...  (0) 2021.06.11
UIAlertController  (0) 2021.05.31
select 구현 예제  (0) 2021.05.26
sqlite3 파일 생성  (0) 2021.05.26
sql 공통 .h, .m 작성법  (0) 2021.05.26

SELECT
    a.seq
  , a.nm_logi_file
  , a.nm_phys_file
  , a.yn_mbil_add
FROM ddtbt_atch_file_dtil2 a
INNER JOIN ddtbt_tppg b ON a.id_atch_file = b.id_dwg_atch_file
WHERE b.cd_tppg = '';

를 구현한다고 하면...

-(DDTBT_ATCH_FILE_DTIL *) hjhImageFileTitledMapReturn:(NSString *) param
{
    NSString *query = [NSString stringWithFormat:@"select a.seq, a.nm_logi_file, a.nm_phys_file, a.yn_mbil_add from ddtbt_atch_file_dtil2 a \
                       inner join ddtbt_tppg b on a.id_atch_file=b.id_dwg_atch_file \
                       where b.cd_tppg='%@';"
                       ,param
                       ];
    NSLog(@" hjhImageFileTitledMapReturn query = %@", query);
    [self checkBackDB];
    
    if (sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {  //성공적으로 열림
        const char *sqlStatement = [query cStringUsingEncoding:NSUTF8StringEncoding];
        sqlite3_stmt *compiledStatement;
        if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
            // Loop through the results and add them to the feeds array
            while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
                DDTBT_ATCH_FILE_DTIL *atch = [[DDTBT_ATCH_FILE_DTIL alloc] init];
                atch.seq = sqlite3_column_int(compiledStatement, 0);
                atch.nm_logi_file = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
                atch.nm_phys_file = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)];
                atch.yn_mbil_add = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 3)];
                
                NSLog(@"hjhImageFileTitledMapReturn2 %@ %ld %@ %@", atch.nm_logi_file, (long)atch.seq, atch.nm_phys_file, atch.yn_mbil_add);
                sqlite3_finalize(compiledStatement);
                [self checkBackDB];
                return atch;
            }
        }
        // Release the compiled statement from memory
        sqlite3_finalize(compiledStatement);
        [self checkBackDB];
    } else {
        [self checkBackDB];
    }
    
    return nil;
}

 

이렇게 한다.

'Objective-C, SQLite3' 카테고리의 다른 글

UIAlertController  (0) 2021.05.31
nullable, nonnull  (0) 2021.05.26
sqlite3 파일 생성  (0) 2021.05.26
sql 공통 .h, .m 작성법  (0) 2021.05.26
iOS Photokit  (0) 2021.05.26

  https://dudfufl.tistory.com/entry/23-SQLite-%EC%BF%BC%EB%A6%AC%EB%AC%B8-%EC%82%AC%EC%9A%A9%ED%95%98%EA%B8%B0

  본래 github에 있던 내용인데 사라졌다.


사용법은 이렇고.
  [SqlUtils checkAndCreateDatabase:true];
헤더와 
  + (void) checkAndCreateDatabase:(BOOL)flag;

구현은 이렇다.

#import "FileManager.h"

+ (void) checkAndCreateDatabase:(BOOL)flag {
    NSString *databaseName = @"mbass4.db";
    NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDir = [documentPaths objectAtIndex:0];
    NSString *databasePath = [documentsDir stringByAppendingPathComponent:databaseName];
    BOOL success;
    // Create a FileManager object, we will use this to check the status
    // of the database and to copy it over if required
    NSFileManager *fileManager = [NSFileManager defaultManager];
    // Check if the database has already been created in the users filesystem
    success = [fileManager fileExistsAtPath:databasePath];
    // If the database already exists then return without doing anything
    
    if(success && flag) return;
    
    // If not then proceed to copy the database from the application to the users filesystem
    // Get the path to the database in the application package
    NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];
    
    // Copy the database from the package to the users filesystem
    [fileManager removeItemAtPath:databasePath error:nil];
    [fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];
    NSLog(@"databasePathFromApp %@ To %@", databasePathFromApp, databasePath);
    
}

https://gist.github.com/tuxcanfly/1205986

 

나 같은 경우 DB 업데이트 할 때마다 db 파일 번호를 올리는데...

DB 구조 변화시 에러를 방지하기 위해서이다. 삼성전자에서 FOTA 할 때는 DB 버전별로 sql 구문을 따로 넣어줬었다.(진짜 개고생...)

물론, 사용자 데이터 보호를 위함이었지만 필드 늘어나고 관계 깨지면 서버에서 걍 다시 다운로드 받는게 맞다.

'Objective-C, SQLite3' 카테고리의 다른 글

nullable, nonnull  (0) 2021.05.26
select 구현 예제  (0) 2021.05.26
sql 공통 .h, .m 작성법  (0) 2021.05.26
iOS Photokit  (0) 2021.05.26
ViewController 자료 교환 방식 수정  (0) 2021.05.20

기본형은

 

sqlite3 *database;
    NSString *databaseName = @"mbass4.db";
    NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDir = [documentPaths objectAtIndex:0];
    NSString *databasePath = [documentsDir stringByAppendingPathComponent:databaseName];
    NSString *currentProgressString = @"";
    
    if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
    NSString *query = @"select nm_prgs_phs \
           from ddtbt_site;";
           const char *sqlStatement = [query cStringUsingEncoding:NSASCIIStringEncoding];
           sqlite3_stmt *compiledStatement;
           if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
               // Loop through the results and add them to the feeds array
               while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
                   currentProgressString = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 0)];
                   break;
               }
           }
        sqlite3_finalize(compiledStatement);
       }
    sqlite3_close(database);
이게 완결이다.

SqlUtils *db = [[SqlUtils alloc] init];

이렇게 쓰게 하기 위해서

- (id) init
{
    if (self = [super init]) {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        databasePath = [documentsDirectory stringByAppendingPathComponent:@"mbass4.db"];
    }
    return 
}
init을 만든다.- (id) init;
- (void) selectSite:(DDTBT_SITE *)data {
    [self checkBackDB];
    [data clear];
    
    // Open the database from the users filessytem
    if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
        // Setup the SQL Statement and compile it for faster access
        
        NSString *query = @"select cd_site \
        ,nm_site \
        ,nm_site_abrv \
        ,cd_prgs_phs \
        ,nm_prgs_phs \
        ,yn_adtn_phs \
        ,cd_rcpt_phs \
        ,nm_rcpt_phs \
        from ddtbt_site;";
        
        const char *sqlStatement = [query cStringUsingEncoding:NSASCIIStringEncoding];
        sqlite3_stmt *compiledStatement;
        if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
            // Loop through the results and add them to the feeds array
            while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
                
                data.cd_site = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 0)];
                data.nm_site = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
                data.nm_site_abrv = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)];
                data.cd_prgs_phs = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 3)];
                data.nm_prgs_phs = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 4)];
                data.yn_adtn_phs = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 5)];
                data.cd_rcpt_phs = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 6)];
                data.nm_rcpt_phs = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 7)];
                
                break;
            }
        }
        // Release the compiled statement from memory
        sqlite3_finalize(compiledStatement);
        
    }
    [self checkBackDB];
}

기본형과 별 다른게 없다. 그냥 DB 가져오는 부분만 공통이니 뺏을 뿐.
-(void) checkBackDB {
    if(database != nil)  {
        if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
            sqlite3_finalize;
            sqlite3_close(database);
        } else {
            sqlite3_finalize;
            sqlite3_close(database);
        }
    }

sqlite3는 느리고 다른데서 쓰고 있을 때 계속 문제가 생겨서 finalize 와 close를 하나 만들었다.

 

이제 기본형은

//
//  sql3hjh.h
//
//  Created by Junho HA on 2021/05/26.
//  Copyright © 2021 hajunho.com All rights reserved.
//


#ifndef sql3hjh_h
#define sql3hjh_h


#import <sqlite3.h>


@interface sql3hjh : NSObject
{
    sqlite3 *database;
}


@property (nonatomic, strong, readwrite) NSString *databasePath;


- (id) init;


@end


#endif /* sql3hjh_h */
//
//  sql3hjh.m
//
//  Created by Junho HA on 2021/05/26.
//  Copyright © 2021 hajunho.com All rights reserved.
//


#import <Foundation/Foundation.h>
#import "sql3hjh.h"


@implementation sql3hjh
@synthesize databasePath;


- (id) init
{
    if (self = [super init]) {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        databasePath = [documentsDirectory stringByAppendingPathComponent:@"mbass4.db"];
    }
    return self;
}
@end

'Objective-C, SQLite3' 카테고리의 다른 글

select 구현 예제  (0) 2021.05.26
sqlite3 파일 생성  (0) 2021.05.26
iOS Photokit  (0) 2021.05.26
ViewController 자료 교환 방식 수정  (0) 2021.05.20
잘 되던게, 갑자기 안되는 문제 해결.  (0) 2021.05.20

TypeError: 'type' object is not subscriptable

 

첨자 가능한(subscriptable)이라는 개념입니다. []는 첨자 연산자(subscript operator)라고 부릅니다.

a = [1,2,3,4]가 있다면 a[0]처럼 첫 번째 원소를 가리키는 것이 첨자 연산자의 역할입니다. 파이썬은 슬라이스를 사용해 범위까지 가르킬 수 있습니다.



IndexError: list index out of range

 

if(a)

try:

exception

 

# 올바른 값을 넣지 않으면 에러를 발생시키고 적당한 문구를 표시한다.

def rsp(mine, yours):

    allowed = ['가위','바위', '보']

    if mine not in allowed:

        raise ValueError

    if yours not in allowed:

        raise ValueError

 

try:

    rsp('가위', '바')

except ValueError:

    print('잘못된 값을 넣었습니다!')



# 190이 넘는 학생을 발견하면 반복을 종료한다.

school = {'1반' : [150, 156, 179, 191, 199], '2반' : [150, 195, 179, 191, 199]}

 

try:

    for class_number, students in school.items():

        for student in students:

            if student > 190:

                print(class_number, '190을 넘는 학생이 있습니다.')

                # break # 바로 상위 for문은 종료되지만 최고 상위 for문은 종료되지 않는다.

                raise StopIteration

                # 예외가 try 문 안에 있지 않으면 에러 발생시 프로그램이 멈춘다.

except StopIteration:

    print('정상종료') 



# 모든 에러 처리

try:

    list = []

    print(list[0])  # 에러가 발생할 가능성이 있는 코드

 

    text = 'abc'

    number = int(text)

except:

    print('에러발생')

 

# 에러 이름 확인

try:

    list = []

    print(list[0])  # 에러가 발생할 가능성이 있는 코드

 

except Exception as ex: # 에러 종류

    print('에러가 발생 했습니다', ex) # ex는 발생한 에러의 이름을 받아오는 변수

    # 에러가 발생 했습니다 list index out of range



try:

    import your_module

except ImportError:

    print('모듈이 없습니다.')




 

항상 새롭네...

'{BE} Python 3.1x' 카테고리의 다른 글

파이썬을 쉘로 써보기  (0) 2021.05.26
파이썬 수 체계  (0) 2021.05.26
python 빌드해서 에러 문구 교체해 봄.  (0) 2021.05.26
how to see the encoding  (0) 2021.05.26
AI 기본은 필수...  (0) 2021.05.20

>>> import os

 

>>> os.getcwd()

'/Users/junhoha'




 

 

>>> os.system('ls')
Applications             PycharmProjects          gotoC
Applications (Parallels) TakeIT                   ios_bridge

 

>>> os.chdir("~/Documents/GitHub")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
FileNotFoundError: [Errno 2] No such file or directory: '~/Documents/GitHub'
>>> os.chdir("/Users/junhoha/Documents/GitHub")

 

>>> os.system('git clone git@github.com:hajunho/takeTouch.git')
Cloning into 'takeTouch'...
remote: Enumerating objects: 5, done.
remote: Counting objects: 100% (5/5), done.
remote: Compressing objects: 100% (4/4), done.
Receiving objects: 100% (5/5), 5.47 KiB | 5.47 MiB/s, done.
remote: Total 5 (delta 0), reused 0 (delta 0), pack-reused 0
0

 

>>> os.chdir('./takeTouch')
>>> os.getcwd()
'/Users/junhoha/Documents/GitHub/takeTouch'
>>> os.listdir()
['LICENSE', 'README.md', '.gitignore', '.git']

 




>>> os.system('open .')
0
>>> os.system('git add *')
0
>>> os.system('git commit -a')

 

>>> os.system('git push')
Enumerating objects: 52, done.
Counting objects: 100% (52/52), done.
Delta compression using up to 16 threads
Compressing objects: 100% (50/50), done.
Writing objects: 100% (51/51), 6.48 MiB | 534.00 KiB/s, done.
Total 51 (delta 3), reused 0 (delta 0)
remote: Resolving deltas: 100% (3/3), done.
To github.com:hajunho/takeTouch.git
   214d7fa..e2c8791  main -> main
0
>>> 

 

>>> def a(f):
...     os.system(f)
... 
>>> 

 

>>> def a():
...     a = input()
...     os.system(str(a))
... 
>>> a()
ls
LICENSE                            README.md
LICENSE 복사본                TakeTouch
README 복사본.md              Touch.xcodeproj

 

( :; LIBDEPS="${LIBDEPS:--Wl,-search_paths_first -L.. -lssl -L.. -lcrypto  }"; LDCMD="${LDCMD:-cc}"; LDFLAGS="${LDFLAGS:--DOPENSSL_THREADS -D_REENTRANT -DDSO_DLFCN -DHAVE_DLFCN_H -arch x86_64 -O3 -DL_ENDIAN -Wall -DOPENSSL_IA32_SSE2 -DOPENSSL_BN_ASM_MONT -DOPENSSL_BN_ASM_MONT5 -DOPENSSL_BN_ASM_GF2m -DSHA1_ASM -DSHA256_ASM -DSHA512_ASM -DMD5_ASM -DAES_ASM -DVPAES_ASM -DBSAES_ASM -DWHIRLPOOL_ASM -DGHASH_ASM -DECP_NISTZ256_ASM}"; LIBPATH=`for x in $LIBDEPS; do echo $x; done | sed -e 's/^ *-L//;t' -e d | uniq`; LIBPATH=`echo $LIBPATH | sed -e 's/ /:/g'`; LD_LIBRARY_PATH=$LIBPATH:$LD_LIBRARY_PATH ${LDCMD} ${LDFLAGS} -o ${APPNAME:=dummytest} dummytest.o  ${LIBDEPS} )
making all in tools...
make[1]: Nothing to be done for `all'.

 

sudo make install


쉽진 않네.

'{BE} Python 3.1x' 카테고리의 다른 글

기본 에러 정리  (0) 2021.05.26
파이썬 수 체계  (0) 2021.05.26
python 빌드해서 에러 문구 교체해 봄.  (0) 2021.05.26
how to see the encoding  (0) 2021.05.26
AI 기본은 필수...  (0) 2021.05.20
√ ~ % python3
Python 3.7.9 (default, Nov 20 2020, 23:58:42) 
[Clang 12.0.0 (clang-1200.0.32.27)] on darwin
Type "help", "copyright", "credits" or "license" for more information.

 

기본자료형(Built-in Types, Primitive Types, Base Types)


숫자형(Numeric Type)

숫자형에는 정수형(Integer type), 부동 소수점형(fixed point, floating point), 복소수형(complex type)이 있다. 수학의 수의 체계에서 실수는 유리수와 무리수로 이루어진다. 유리수는 정수와 정수가 아닌 유리수로 이루어 진다. 수학의 수의 체계를 그대로 옮겨 놓은 것이 파이썬의 숫자형(Numeric Type) 이다.

 

파이썬 정수형의 한계(limitation)는 다음과 같이 알아 볼 수 있다.

√ ~ % python3 -c 'import sys; print(sys.maxsize)'
9223372036854775807

 

파이썬 실수형 정보는 다음과 같이 알 수 있다.

√ ~ % python3
Python 3.7.9 (default, Nov 20 2020, 23:58:42) 
[Clang 12.0.0 (clang-1200.0.32.27)] on darwin
Type "help", "copyright", "credits" or "license" for more information.

>>> import sys
>>> sys.float_info
sys.float_info(max=1.7976931348623157e+308, max_exp=1024, max_10_exp=308, min=2.2250738585072014e-308, min_exp=-1021, min_10_exp=-307, dig=15, mant_dig=53, epsilon=2.220446049250313e-16, radix=2, rounds=1)

 

프로그래머에게는 의미있는 몇 개의 숫자들이 있다.

 



 


 

파이썬의 수 체계는 64비트를 따른다는 것을 알 수 있다.

 

'{BE} Python 3.1x' 카테고리의 다른 글

기본 에러 정리  (0) 2021.05.26
파이썬을 쉘로 써보기  (0) 2021.05.26
python 빌드해서 에러 문구 교체해 봄.  (0) 2021.05.26
how to see the encoding  (0) 2021.05.26
AI 기본은 필수...  (0) 2021.05.20
√ ~/Documents/GitHub/pythoncore/Python-3.8.8 % ./configure 
checking build system type... x86_64-apple-darwin20.3.0
checking host system type... x86_64-apple-darwin20.3.0
checking for python3.8... python3.8
checking for --enable-universalsdk... no
checking for --with-universal-archs... no
checking MACHDEP... "darwin"
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/Applications/Xcode.app/C



make

 

Could not build the ssl module

 

Error: openssl@1.1 1.1.1i is already installed.
To upgrade to 1.1.1j, run:
  brew upgrade openssl@1.1
√ ~/Documents/GitHub/pythoncore/Python-3.8.8 % brew upgrade openssl@1.1
==> Upgrading 1 outdated package:
openssl@1.1 1.1.1i -> 1.1.1j
==> Upgrading openssl@1.1 1.1.1i -> 1.1.1j 
==> Downloading https://homebrew.bintray.com/bottles/openssl%401.1-1.1.1j.big_su
==> Downloading from https://d29vzk4ow07wi7.cloudfront.net/5725361adcd088a5b4fb2
######################################################################## 100.0%
==> Pouring openssl@1.1-1.1.1j.big_sur.bottle.tar.gz
√ ~/Documents/GitHub/pythoncore/Python-3.8.8 % brew reinstall openssl

 

 

 

https://github.com/libressl-portable/portable/issues/381
https://wiki.unify.com/wiki/openssl-1.0.2k.tar.gz_V1R0

 

  $ ./config
   $ make
   $ make test
   $ make install

 

ld: symbol(s) not found for architecture i386

 

WARNING! If you wish to build 64-bit library, then you have to
         invoke './Configure darwin64-x86_64-cc' *manually*.
         You have about 5 seconds to press Ctrl-C to abort.

 

./Configure darwin64-x86_64-cc

 

make clean
make

 

sudo make install

 

./configure again in python 3.8.8

 

make clean

 

make

 

To find the necessary bits, look in setup.py in detect_modules() for the module's name.


The following modules found by detect_modules() in setup.py, have been
built by the Makefile instead, as configured by the Setup files:
_abc                  atexit                pwd                
time                                                           


Failed to build these modules:
_tkinter     

 

brew install tcl-tk

 

√ ~/Documents/GitHub/pythoncore/Python-3.8.8 % brew install tcl-tk
Updating Homebrew...
Warning: tcl-tk 8.6.11_1 is already installed and up-to-date.
To reinstall 8.6.11_1, run:
  brew reinstall tcl-tk

 

If you need to have tcl-tk first in your PATH, run:
  echo 'export PATH="/usr/local/opt/tcl-tk/bin:$PATH"' >> ~/.zshrc

For compilers to find tcl-tk you may need to set:
  export LDFLAGS="-L/usr/local/opt/tcl-tk/lib"
  export CPPFLAGS="-I/usr/local/opt/tcl-tk/include"

For pkg-config to find tcl-tk you may need to set:
  export PKG_CONFIG_PATH="/usr/local/opt/tcl-tk/lib/pkgconfig"

 

X11/Xlib.h' file not found

 

xcode-select: error: command line tools are already installed, use "Software Update" to install updates

 

?1 ~/Documents/GitHub/pythoncore/Python-3.8.8 % softwareupdate --list
Software Update Tool

Finding available software
Software Update found the following new or updated software:
* Label: macOS Big Sur 11.2.2-20D80
Title: macOS Big Sur 11.2.2, Version: 11.2.2, Size: 2123844K, Recommended: YES, Action: restart, 
√ ~/Documents/GitHub/pythoncor

 

√ ~/Documents/GitHub/pythoncore/Python-3.8.8 % softwareupdate --install -a

 

https://www.tcl.tk/software/tcltk/

 

https://www.tcl.tk/software/tcltk/download.html

 

cd macosx ; ./configure ; make ; make test ; sudo make install

 

scanning section [incr Tcl] Package C API, version 4.2.1
......
scanning section TDBC Package C API, version 1.1.2
.
Assembling index
Rescanning 271 pages to build cross links and write out
...............................................................................................................................................................................................................................................................................
Done

 

'X11/Xlib.h' file not found

xcode-select --install

 

?127 ~/Documents/GitHub/pythoncore/Python-3.8.8 % ln -s /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/System/Library/Frameworks/Tk.framework/Versions/8.5/Headers/X11/ /usr/local/include/X11

 

/usr/bin/install -c ./install-sh /usr/local/lib/python3.8/config-3.8-darwin/install-sh
/usr/bin/install -c python-config.py /usr/local/lib/python3.8/config-3.8-darwin/python-config.py
/usr/bin/install -c python-config /usr/local/bin/python3.8-config
./python.exe -E ./setup.py install \
  --prefix=/usr/local \
--install-scripts=/usr/local/bin \
--install-platlib=/usr/local/lib/python3.8/lib-dynload \
--root=/
running install
running build
running build_ext

Python build finished successfully!

 

~/Documents/GitHub/pythoncore/Python-3.8.8 % grep -Risn "Type \"help\", \"copyright\", \"credits\" or \"license\" for more information." *
Doc/tutorial/interpreter.rst:103:   Type "help", "copyright", "credits" or "license" for more information.
Doc/install/index.rst:245:   Type "help", "copyright", "credits" or "license" for more information.
Doc/install/index.rst:647:   Type "help", "copyright", "credits" or "license" for more information.
Doc/faq/windows.rst:69:   Type "help", "copyright", "credits" or "license" for more information.
Doc/library/sys.rst:1663:      Type "help", "copyright", "credits" or "license" for more information.
Doc/whatsnew/3.8.rst:643:    Type "help", "copyright", "credits" or "license" for more information.
Lib/code.py:212:        cprt = 'Type "help", "copyright", "credits" or "license" for more information.'
Binary file Modules/main.o matches
Binary file Programs/_testembed matches
Binary file libpython3.8.a matches
Binary file python.exe matches

 

        cprt = 'Type "help", "copyright", "credits" or "license" for more information.'
         if banner is None:
             self.write("Python %s on %s\n%s\n(%s)\n" %
                        (sys.version, sys.platform, cprt,
                         self.__class__.__name__))

 

vim ./Modules/main.c

 

203     if (!config->verbose && (config_run_code(config) || !                       stdin_is_interactive(config))) {
 204         return;
 205     }
 206 
 207     fprintf(stderr, "Junho's Python %s on %s\n", Py_GetVersion(),               Py_GetPlatform());
 208     if (config->site_import) {
 209         fprintf(stderr, "%s\n", COPYRIGHT);
 210     }
 211 }

 

√ ~/Documents/GitHub/pythoncore/Python-3.8.8 % grep -Risn "is not defined" * | grep name

 

√ ~/Documents/GitHub/pythoncore/Python-3.8.8 % vim Python/ceval.c

 

#define NAME_ERROR_MSG \
     "hjh name '%.200s' is not defined"

 

√ ~/Documents/GitHub/pythoncore/Python-3.8.8 % ./python.exe -c "ls"
Traceback (most recent call last):
  File "<string>", line 1, in <module>
NameError: hjh name 'ls' is not defined


'{BE} Python 3.1x' 카테고리의 다른 글

파이썬을 쉘로 써보기  (0) 2021.05.26
파이썬 수 체계  (0) 2021.05.26
how to see the encoding  (0) 2021.05.26
AI 기본은 필수...  (0) 2021.05.20
python에서 아쉬운 점 private, protected, public...  (0) 2021.04.06
# python3 -m venv temppy
# cd temppy
# source ./bin/activate
(temppy)  junhoha  ~/Documents/Github/temppy>  deactivate
 junhoha  ~/Documents/Github/temp/temppy

 

>>> import sys
>>> print(sys.stdin.encoding)
utf-8
>>> print(sys.stdout.encoding)
utf-8


https://developer.apple.com/documentation/photokit

 

Apple Developer Documentation

 

developer.apple.com

 

Installing PhotoEditorSDK (10.23.1)

Installing imglyKit (10.23.1)

 

포토킷 예제는

 

https://github.com/imgly/pesdk-ios-examples

 

imgly/pesdk-ios-examples

A fully customizable photo editor for your app. Contribute to imgly/pesdk-ios-examples development by creating an account on GitHub.

github.com

objective-C , Swift 코드 둘 다 있어서 비교하기도 좋고...

 

오브젝티브 C 의 경우 정상 동작 확인했다.

 

pod 'PhotoEditorSDK'

 

참, 좋다. 그러나 역시 유료...

 

https://img.ly/pricing/configure-your-product

 

Price Calculator | IMG.LY

Not ready to get started yet? Why don't you take our editors for a test drive with a free trial or browse the FAQs?

img.ly

 

git 에도 안 올라가네...

Enumerating objects: 771, done.

Counting objects: 100% (771/771), done.

Delta compression using up to 16 threads

Compressing objects: 100% (746/746), done.

Writing objects: 100% (749/749), 77.75 MiB | 702.00 KiB/s, done.

Total 749 (delta 47), reused 0 (delta 0)

remote: Resolving deltas: 100% (47/47), completed with 18 local objects.

remote: error: GH001: Large files detected. You may want to try Git Large File Storage - https://git-lfs.github.com.

remote: error: Trace: ce5efb725d2417032acef77cd0abc232f6791cef39146cc2cbac700024735657

remote: error: See http://git.io/iEPt8g for more information.

remote: error: File Pods/imglyKit/ImglyKit.framework/ImglyKit is 150.33 MB; this exceeds GitHub's file size limit of 100.00 MB

 

 

git rm --cached Pods/imglyKit/ImglyKit.framework/ImglyKit

git commit --amend -CHEAD

[rel03 15a5da4] .

 Date: Wed May 26 17:27:21 2021 +0900

 3 files changed, 65 insertions(+), 4 deletions(-)

 delete mode 100755 Pods/imglyKit/ImglyKit.framework/ImglyKit

 

git push

Enumerating objects: 780, done.

Counting objects: 100% (780/780), done.

Delta compression using up to 16 threads

Compressing objects: 100% (755/755), done.

Writing objects:  13% (105/758), 1Writing objects:  14% (107/758), 1Writing objectsWriting objects: 100% (758/758), 77.75 MiB | 1.03 MiB/s, done.

Total 758 (delta 54), reused 0 (delta 0)

remote: Resolving deltas: 100% (54/54), completed with 18 local objects.

remote: error: GH001: Large files detected. You may want to try Git Large File Storage - https://git-lfs.github.com.

remote: error: Trace: 62cf00ddea2368d0eb0fd133d3fa8e9fb309b3448be13de070c88c33b000d361

remote: error: See http://git.io/iEPt8g for more information.

remote: error: File Pods/imglyKit/ImglyKit.framework/ImglyKit is 150.33 MB; this exceeds GitHub's file size limit of 100.00 MB

 

뭐야...

https://stackoverflow.com/questions/19573031/cant-push-to-github-because-of-large-file-which-i-already-deleted

 

Can't push to GitHub because of large file which I already deleted

Currently I have Empty GitHub repo SSH server repo (main) Local Repo SSH server repo was the most up-to-date repo (production site) so I did a Git clone from there to local. I then tried to do a ...

stackoverflow.com

안되잖아.

 

 

git filter-branch --tree-filter 'rm Pods/imglyKit/ImglyKit.framework/ImglyKit' HEAD

WARNING: git-filter-branch has a glut of gotchas generating mangled history

rewrites.  Hit Ctrl-C before proceeding to abort, then use an

alternative filtering tool such as 'git filter-repo'

(https://github.com/newren/git-filter-repo/) instead.  See the

filter-branch manual page for more details; to squelch this warning,

set FILTER_BRANCH_SQUELCH_WARNING=1.

 

Proceeding with filter-branch...

 

Rewrite 6a758d6dca2bdef2f13f60d2d494f411f7168604 (1/133) (0 seconds passed, remaining 0 predicted)    rm: Pods/imglyKit/ImglyKit.framework/ImglyKit: No such file or directory

tree filter failed: rm Pods/imglyKit/ImglyKit.framework/ImglyKit

 

 

git push origin master --force

Total 0 (delta 0), reused 0 (delta 0)

To github.com:hajunho/hanaMaster.git

 + 84e7d84...d45c23c master -> master (forced update)

 

이걸로 해결...

 

에혀... 반쪽짜리 git이다. 이 경험으로 이미지 라이브러리 넣기 전에 고민 좀 하고 넣어야 할 듯.

'Objective-C, SQLite3' 카테고리의 다른 글

sqlite3 파일 생성  (0) 2021.05.26
sql 공통 .h, .m 작성법  (0) 2021.05.26
ViewController 자료 교환 방식 수정  (0) 2021.05.20
잘 되던게, 갑자기 안되는 문제 해결.  (0) 2021.05.20
ImageButton  (0) 2021.05.18

'{3D} 가상 세계' 카테고리의 다른 글

icons  (0) 2021.06.01
썬더토큰 백서  (0) 2021.05.30
블랜더 강좌  (0) 2021.05.24
중요한 로그  (0) 2021.05.23
XR, AI, IoT, 블록체인  (0) 2021.03.21

개발자는 디자이너가 없어서 디자인을 배우고... 디자이너는 개발자가 없어서 개발을 배우는 것 같다.

https://www.youtube.com/watch?v=OCUHYvnGPKY&ab_channel=%EA%B9%8C%EB%A7%9D%EA%B3%A0%EB%8B%88%EA%B9%8C%EB%A7%9D%EA%B3%A0%EB%8B%88

 

내 경우는 아는 3D 디자이너들이 다들 바빠서... ㅠㅠ

'{3D} 가상 세계' 카테고리의 다른 글

썬더토큰 백서  (0) 2021.05.30
3D Models License Information  (0) 2021.05.24
중요한 로그  (0) 2021.05.23
XR, AI, IoT, 블록체인  (0) 2021.03.21
https://hajunho.com 컨설팅 취미  (0) 2020.12.27

2021-05-23 19:00:15.547127+0900 Touch[44871:4072399] [Session] ARSession <0x123d5d970>: did fail with error: Error Domain=com.apple.arkit.error Code=102 "Required sensor failed." UserInfo={NSLocalizedFailureReason=A sensor failed to deliver the required input., NSUnderlyingError=0x280670780 {Error Domain=AVFoundationErrorDomain Code=-11800 "The operation could not be completed" UserInfo={NSLocalizedFailureReason=An unknown error occurred (-12785), NSLocalizedDescription=The operation could not be completed, NSUnderlyingError=0x28180d290 {Error Domain=NSOSStatusErrorDomain Code=-12785 "(null)"}}}, NSLocalizedRecoverySuggestion=Make sure that the application has the required privacy settings., NSLocalizedDescription=Required sensor failed.}

"applicationDidEnterBackground"

 

unknown error 로그는 항상 소중함.

 

로그 나오는게 어디야 ㅋㅋㅋ

 

'{3D} 가상 세계' 카테고리의 다른 글

3D Models License Information  (0) 2021.05.24
블랜더 강좌  (0) 2021.05.24
XR, AI, IoT, 블록체인  (0) 2021.03.21
https://hajunho.com 컨설팅 취미  (0) 2020.12.27
한 사람의 힘  (0) 2020.10.29

list4c = getCentaur()

currentAnimal = list4c[row].name?.description ?? ""

 

ORM 은 정말 편하다. Objective-C에서는 sql을 직접 다루느라 힘들었는데 말이다.

 

'Swift & Python 실무 > {APP} SOCANNER APP' 카테고리의 다른 글

agreements  (0) 2021.05.29
swift log level  (0) 2021.05.28
tableview 에 button 삽입 후 title 가져오기  (0) 2021.05.23
한 번은 사용해 봐야할 iOS 기술 스택  (0) 2021.05.21
Snapkit 실무 코드  (0) 2021.05.20

let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! HomeTableViewCell

        cell.selectionStyle = .none

        let image = UIImage(named:"twodimg_"+"\(indexPath.row+1)")

        cell.feedImageView.image = image

 

        let button = UIButton(frame: CGRect(x: 0, y: 0, width: cellFrame.width, height: cellFrame.height))

        button.setTitle("fff", for: .normal)

        button.titleLabel?.layer.opacity = 0.0;

        button.addTarget(self, action: #selector(onClickCheck(_:)), for: .touchUpInside)

        cell.addSubview(button)

        

        return cell

 

debugPrint("title is", (sender as? UIButton)?.titleLabel?.text)

 

기본 코드다. 이미지만 쓰는 테이블 뷰를 만들고 데이터를 title 로 보내는 것을 만들고 있다. button에 extension을 달아도 되지만 title자체를 쓰지 않으니 타이틀을 텍스트에 실어 보내는.

이미지 번호를 row로 세팅하는 것처럼 객체 배열 번호를 넣어주면 된다.

인터넷 보니 tag 밖에 없어 int 만 전달할 수 없으니 내가 만드는 제품에는 불편해서 생각해 본 아이디어.

UPBIT company is helping the khan, I thought.

And. Notifications automatically to the 700000 Korean users by default app setting

 UPBIT is a South Korean company, and people died of suicide cause of coin.

 

The company helps the people who control the market price manipulation. 

1000% UP(x10) and 95%(-x10) down. (Synthetix, SNX)

 

Man commits suicide after loss on cryptocurrency

 

news link

https://biz.chosun.com/topics/topics_social/2021/04/29/UKFU5VKQPFFYJHMLOVPK4MCGBY/

 

news link

https://www.yna.co.kr/view/AKR20210428159900062

 

 

It's more than three people ages are around 20 to 30.

 

비트코인(가상화폐) 투자 실패한 여성, 수천만원 빚으로 독촉 시달리다 결국 투신 자살 가상화폐(비트코인)와 주식에 수천만원을 투자했다가 손해를 본 20대 여성이 스스로 목숨을 끊었다. 6일 청주상당경찰서에 따르면 전날 오후 5시20분께 청주시 상당구 한 아파트 화단에 A(26·여)씨가 피를 흘린 채 쓰러져 있는 것을 주민이 발견해 119에 신고했다.  머리 등을 크게 다친 A씨는 인근 병원으로 옮겨졌으나

숨졌다.

 http://www.topstarnews.net/news/articleView.html?idxno=477604

 

청주분 ..      

 

 

 

'가즈아' 또 비극…"비트코인 투자" 30대, 숨진채 발견

 

경찰이 30대 남성이 가상통화 투자 실패를 비관해 스스로 목숨을 끊은 것으로 보고 조사에 나섰다.

서울 동작경찰서는 지난달 21일 오후 2시 동작구 한 주택 방 안에서 A씨(30)가 숨진 채 발견됐다고 7일 밝혔다.

경찰은 지인들의 진술을 토대로 A씨가 비트코인 투자 실패를 이유로 스스로 목숨을 끊은 것으로 보고 조사 중이다.

A씨 지인들은 "최근 A씨가 가상통화 비트코인에 투자했다가 원금 손실을 보는 등의 이유로 극단적 선택을 한 것 같다"고 경찰에 진술했다. A씨의 유서는 발견되지 않았다.

https://n.news.naver.com/article/008/0004005242

 

서울분 ..

 

 

 

 

 

    

 

 

 

 

 

 

가상화폐 투자로 거액 잃은 20살 대학생 자살

 

 

  •  
  •  



한국에서 가상화폐에 투자했다가 거액을 잃은 20살 대학생이 우울한 감정을 호소하다가 방안에서 숨진 채 발견됐다. 

 

 

1일 부산진경찰서에 따르면 31일 아침 7시 50분쯤 부산의 한 주택에서 A씨가 방 안에서 숨져 있는 것을 A씨의 어머니가 발견해 경찰에 신고했다. 경찰은 A씨가 최근 가상화폐 투자 실패로 크게 낙담했다는 유족의 진술을 확보했다. 

A씨는 가상화폐에 투자해 한때 2억여 원까지 금액을 불리는 등 투자에 성공했지만 지난해 말 가상화폐 가치가 폭락하면서 대부분을 잃은 것으로 조사됐다. A씨는 이후 가족에게 우울감을 호소해 왔고 병원에서 수면유도제 등을 처방받아 복용해 왔던 것으로 알려졌다.

https://koreadailytimes.com/social/14884

부산분..

 

 

 

 

 

 

 

 

 

 

 

120AHT 추가

8B4BDA

 

그래도 서비스가 있는 아하... 아하가 잘 되었으면 좋겠다. 원금 찾을 수 있게...

https://haningya.tistory.com/33

 

뱅크 샐러드는 어떤 라이브러리를 쓸까?(iOS 유용한 라이브러리)

많고 많은 라이브러리~ 뱅크 샐러드를 쓰다가 재밌는 걸 발견했다ㅋㅋㅋ 개인설정 --> 오픈소스 라이센스 이용고지 --> 스크롤 하면 채용정보가 나타난다ㅋㅋㅋ 커여운 이모티콘과 함께 뱅크 샐

haningya.tistory.com

Alamofire 

AlignedCollectionView

FlowLayout 

Async 

Carte 

ChameleonFramework/Swift 

CSV.swift Firebase/Core 

Firebase/Database 

JTAppleCalendar 

KakaoLink 

NVActivityIndicatorView 

ObjectMapper 

PinLayout 

RealmSwift 

RLMRealm 

RxCocoa 

RxSwift 

SnapKit 

SQLite 

SwiftyJSON 

Then

AS-IS : NSMutableDictionary

TO-BE : @property

 

이유... 직전에 세팅값이 넘어 왔다는 직관성은 옳으나 어차피 그 자료 그대로 넘겨 받아서 이용하는 경우 딱히...

다수가 여러개의 모듈로 작업할 때는 커뮤니케이션에 좋겠지만... 또 네트웍 연결 상태일 때도...

혼자서 하는 경우 필요 없다는 결론....

 

 

NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:0];

    [dic setValue:data.cd_dong forKey:@"cd_dong"];

    if ([data.cd_dong isEqualToString:@""]) {

        [dic setValue:@"전체동" forKey:@"nm_dong"];

    }

    else {

        [dic setValue:data.nm_dong forKey:@"nm_dong"];

    }

    [dic setValue:data1.cd_flor forKey:@"cd_flor"];

    if ([data.cd_dong isEqualToString:@""]) {

        [dic setValue:@"전체층" forKey:@"nm_flor"];

    }

    else {

        [dic setValue:data1.nm_flor forKey:@"nm_flor"];

    }

    

    if(self.mSegmentedControl.selectedSegmentIndex ==0) {

    

    [dic setValue:data2.nohs forKey:@"nohs"];

    [dic setValue:data2.cd_loc_clsf forKey:@"cd_loc_clsf"];

    [dic setValue:data2.ho forKey:@"ho"];

    [dic setValue:data2.cd_tppg forKey:@"cd_tppg"];

'Objective-C, SQLite3' 카테고리의 다른 글

sql 공통 .h, .m 작성법  (0) 2021.05.26
iOS Photokit  (0) 2021.05.26
잘 되던게, 갑자기 안되는 문제 해결.  (0) 2021.05.20
ImageButton  (0) 2021.05.18
List  (0) 2021.05.18

 

종료 이유는 간단하다.

 

우선, 내가 얻을 지식은 다 얻었고. 다들 안 된다는 것이 왜 되는지에 대한 소명은 충분히 했으며,

 

그럼에도 불구하고 기술 저항력은 엄청나다는 것.

 

웹 개발자 뽑을 때는 정말 신기술을 받아 들일 수 있는 사람인지

그런 이력이 있는지(단순히 다른 분야 자격증이라도)

알아보고 뽑지 않으면

 

회사는 아마 망할거라는 확실한 논리를 세웠다.

 

기타 소스 백업도 지우고 나면, 덕분에 하드 디스크 남아 돌겠네.

 

SnapKit 으로 실무 변환 코드를 써 놓으니 아마 도움 되실 분이 계실 것 같다.




Code 로 View 를 그리기 위한 필수 Pod 이다. SnapKit을 이용하면 코드량이 줄고 가독성이 좋아진다. pod 'SnapKit' 설치 후, import SnapKit 이면 코드 전환이 가능하다.

 

NSLayoutConstraint.activate([

            btnAddDefect.widthAnchor.constraint(equalToConstant: 64),

            btnAddDefect.heightAnchor.constraint(equalToConstant: 64),

            btnAddDefect.leadingAnchor.constraint(equalTo: self.mainView.leadingAnchor, constant: 8),

            btnAddDefect.bottomAnchor.constraint(equalTo: bottomView.topAnchor, constant: -8),

        ])

 

이 코드를 SnapKit을 이용하여, 간결하며 보다 나은 가독성의 코드로 바꿀 수 있다.

 

btnAddDefect.snp.makeConstraints {

            $0.width.equalTo(64)

            $0.height.equalTo(64)

            $0.left.equalTo(self.mainView.snp.left).offset(8)

            $0.bottom.equalTo(bottomView.snp.top).offset(-8)

        }

 

 

Tip : 다국어 적용이 아니면, leading 보다 left를, trailing보다 right를 쓰는 것이 좋다. leading/trailing 의 경우 오른쪽에서 왼쪽으로 쓰는 언어(히브리어, 아랍어) 인 경우 우측 정렬을 우선시 하게 해 준다.

 

그 외 변환 된 다양한 실무 코드를 보자.

 

NSLayoutConstraint.activate([
           slider.widthAnchor.constraint(equalToConstant: 256),
           hjhSlider.heightAnchor.constraint(equalToConstant: 30),
           hjhSlider.leadingAnchor.constraint(equalTo: minusImage.trailingAnchor, constant: 12),
           hjhSlider.trailingAnchor.constraint(equalTo: plusImage.leadingAnchor, constant: -12),
           hjhSlider.centerYAnchor.constraint(equalTo: viewAngleLabel.centerYAnchor),
        ])
      hjhSlider.snp.makeConstraints {
            $0.width.equalTo(256)
            $0.height.equalTo(30)
            $0.left.equalTo(minusImage.snp.left).offset(12)
            $0.right.equalTo(plusImage.snp.right).offset(-12)
            $0.centerY.equalTo(viewAngleLabel.snp.centerY)
        }



NSLayoutConstraint.activate([
            minusImage.widthAnchor.constraint(equalToConstant: 16),
            minusImage.heightAnchor.constraint(equalToConstant: 2.7),
            minusImage.leadingAnchor.constraint(equalTo: viewAngleLabel.trailingAnchor, constant: 4),
            minusImage.centerYAnchor.constraint(equalTo: viewAngleLabel.centerYAnchor),
        ])
        

minusImage.snp.makeConstraints {
            $0.width.equalTo(16)
            $0.height.equalTo(2.7)
            $0.left.equalTo(viewAngleLabel.snp.right).offset(4)
            $0.centerY.equalTo(viewAngleLabel.snp.centerY)
        }

Tip : 레거시 코드 수동 변환 시에는 ^⌘T 로 옆에 탭을 하나 더 열고 작업하는 것이 좋다.

 

NSLayoutConstraint.activate([
            plusImage.widthAnchor.constraint(equalToConstant: 16),
            plusImage.heightAnchor.constraint(equalToConstant: 16),
            plusImage.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -12),
            plusImage.centerYAnchor.constraint(equalTo: viewAngleLabel.centerYAnchor),
        ])
plusImage.snp.makeConstraints {
            $0.width.equalTo(16)
            $0.height.equalTo(16)
            $0.right.equalToSuperview().offset(-12)
            $0.centerY.equalTo(viewAngleLabel.snp.centerY)
        }

Tip : 상위 뷰가 self.view라면 .equalToSuperview를 쓸 수 있다.



NSLayoutConstraint.activate([
            dropDown.heightAnchor.constraint(equalToConstant: 32),
            dropDown.leadingAnchor.constraint(equalTo: self.mtkView.leadingAnchor, constant: 8),
            dropDown.trailingAnchor.constraint(equalTo: self.mtkView.trailingAnchor, constant: -8),
        ])
dropDown.snp.makeConstraints {
            $0.height.equalTo(32)
            $0.left.equalToSuperview().offset(8)
            $0.right.equalToSuperview().offset(-8)
        }





NSLayoutConstraint.activate([
            viewAngleLabel.widthAnchor.constraint(equalToConstant: 30),
            viewAngleLabel.heightAnchor.constraint(equalToConstant: 24),
            viewAngleLabel.leadingAnchor.constraint(equalTo: self.mtkView.leadingAnchor, constant: 12),
            viewAngleLabel.bottomAnchor.constraint(equalTo: self.mtkView.bottomAnchor, constant: -8),
        ])
viewAngleLabel.snp.makeConstraints {
            $0.width.equalTo(30)
            $0.height.equalTo(24)
            $0.left.equalToSuperview().offset(12)
            $0.bottom.equalToSuperview().offset(-8)
        }





NSLayoutConstraint.activate([
            hjh_currentLocation.widthAnchor.constraint(equalTo: self.mtkView.widthAnchor, multiplier:0.4),
            hjh_currentLocation.heightAnchor.constraint(equalToConstant: 32),
            hjh_currentLocation.leadingAnchor.constraint(equalTo: self.mtkView.leadingAnchor),
            hjh_currentLocation.topAnchor.constraint(equalTo: emptyView.bottomAnchor)
        ])
        hjh_currentLocation.snp.makeConstraints({ (ConstraintMaker) in
            ConstraintMaker.width.equalTo(view.frame.width * 0.4)
            ConstraintMaker.height.equalTo(32)
            ConstraintMaker.left.equalToSuperview()
            ConstraintMaker.top.equalTo(bottomView.snp.bottom)
        })




거의 몇 년 동안 하루에 한 번 이상은 보는 테이블 뷰

 

#pragma mark -

#pragma mark TableView Delegate



if (YES == [mDfct.mode isEqualToString:@"U"] && (YES ==[mDfct.cd_hndl_stat isEqualToString:@"E"] || YES ==[mDfct.cd_hndl_stat isEqualToString:@"X"]))




- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

 

- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

 

지겹다…




sqliteFlow 에서는 제대로 나오는 쿼리가

 

SELECT

    cd_tppg

  , id_loc

  , id_uper_loc

  , nm_loc

FROM ddtbt_site_tppg_loc

WHERE cd_tppg = '70A_J'

ORDER BY

    oder_mkar

  , nm_loc;



갑자기 화면에서 나오지 않는다. 서버에서 뭐가 바뀌었다고 한다 ㅡㅡ;

 

 while(sqlite3_step(compiledStatement) == SQLITE_ROW) {

                DDTBT_SITE_TPPG_LOC *data = [[DDTBT_SITE_TPPG_LOC alloc] init];

                data.cd_tppg = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 0)];

                data.id_loc = sqlite3_column_int(compiledStatement, 1);

                data.id_uper_loc = sqlite3_column_int(compiledStatement, 2);

                data.nm_loc = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 3)];

                [array addObject:data];

            }

 

hmm.. 별 문제 없어 보이는데… BP 찍어보니 sql 에서 채워졌어야 할 data array 에 element가 0이다.




@interface QualityControl2 : BaseViewController<UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate, UIActionSheetDelegate, UIImagePickerControllerDelegate, BaseViewDelegate, MTSpeechRecognizerDelegate> {

    MTSpeechRecognizerClient *speechRecognizerClient;

    

    UITableView *mTableViewLoc;

    NSMutableArray *mListLoc;

 

    @property (nonatomic, strong) NSMutableArray *mListLoc;



    @synthesize mListLoc;



잘 되던 코드가 안되니 프로퍼티로 바꾸어 보았다.

 

똑같다.

 

웃긴 건





  array = [[NSMutableArray alloc] init];



가 들어가면...

 

2021-05-20 10:01:32.937461+0900 MBASS[18252:4236337] 810707 result 70A_J 12442 13 현관1 count: 1

2021-05-20 10:01:32.937579+0900 MBASS[18252:4236337] 810707 result 70A_J 10 9 공용욕실1 count: 2

2021-05-20 10:01:32.937671+0900 MBASS[18252:4236337] 810707 result 70A_J 3 1 침실1 count: 3

2021-05-20 10:01:32.937763+0900 MBASS[18252:4236337] 810707 result 70A_J 4 1 침실2 count: 4

2021-05-20 10:01:32.937848+0900 MBASS[18252:4236337] 810707 result 70A_J 5 1 침실3 count: 5

2021-05-20 10:01:32.937934+0900 MBASS[18252:4236337] 810707 result 70A_J 12967 12 거실1 count: 6

2021-05-20 10:01:32.938029+0900 MBASS[18252:4236337] 810707 result 70A_J 6 2 발코니1 count: 7

2021-05-20 10:01:32.938109+0900 MBASS[18252:4236337] 810707 result 70A_J 12533 19 주방/식당 count: 8

2021-05-20 10:01:32.938193+0900 MBASS[18252:4236337] 810707 result 70A_J 12523 31 다용도실 count: 9

2021-05-20 10:01:32.938277+0900 MBASS[18252:4236337] 810707 result 70A_J 8022 26 드레스룸 count: 10

2021-05-20 10:01:32.938363+0900 MBASS[18252:4236337] 810707 result 70A_J 102 14 부부욕실1 count: 11

2021-05-20 10:01:32.938444+0900 MBASS[18252:4236337] 810707 result 70A_J 15638 29 대피공간1 count: 12

2021-05-20 10:01:32.938627+0900 MBASS[18252:4236337] 810707 result 70A_J 13352 30 실외기실1 count: 13



들어간 array에 카운트가 나온다.

 

빼면...

 

2021-05-20 10:02:46.587067+0900 MBASS[18257:4237001] 810707 result 70A_J 12442 13 현관1 count: 0

2021-05-20 10:02:46.587261+0900 MBASS[18257:4237001] 810707 result 70A_J 10 9 공용욕실1 count: 0

2021-05-20 10:02:46.587414+0900 MBASS[18257:4237001] 810707 result 70A_J 3 1 침실1 count: 0

2021-05-20 10:02:46.587556+0900 MBASS[18257:4237001] 810707 result 70A_J 4 1 침실2 count: 0

2021-05-20 10:02:46.587706+0900 MBASS[18257:4237001] 810707 result 70A_J 5 1 침실3 count: 0

2021-05-20 10:02:46.587851+0900 MBASS[18257:4237001] 810707 result 70A_J 12967 12 거실1 count: 0

2021-05-20 10:02:46.587988+0900 MBASS[18257:4237001] 810707 result 70A_J 6 2 발코니1 count: 0

2021-05-20 10:02:46.588170+0900 MBASS[18257:4237001] 810707 result 70A_J 12533 19 주방/식당 count: 0

2021-05-20 10:02:46.588313+0900 MBASS[18257:4237001] 810707 result 70A_J 12523 31 다용도실 count: 0

2021-05-20 10:02:46.588482+0900 MBASS[18257:4237001] 810707 result 70A_J 8022 26 드레스룸 count: 0

2021-05-20 10:02:46.588620+0900 MBASS[18257:4237001] 810707 result 70A_J 102 14 부부욕실1 count: 0

2021-05-20 10:02:46.588790+0900 MBASS[18257:4237001] 810707 result 70A_J 15638 29 대피공간1 count: 0

2021-05-20 10:02:46.588934+0900 MBASS[18257:4237001] 810707 result 70A_J 13352 30 실외기실1 count: 0



안나온다.

 

            [array addObject:data];

가 안되는 것이다.

 

신기한 것은 지금까지 잘 되던 코드인데 갑자기 안된다는 것.



- (NSMutableArray*) RETNselectSiteTppgLoc:(NSMutableArray *)array withTppgCd:(NSString *)tppgCd {

 

포인트 파라미터 방식을 리턴 방식으로 바꾸어서 해결…



에혀… 참 별의 별개 갑자기 안된다.

 

빨리 Swift 세상이 되길…


'Objective-C, SQLite3' 카테고리의 다른 글

iOS Photokit  (0) 2021.05.26
ViewController 자료 교환 방식 수정  (0) 2021.05.20
ImageButton  (0) 2021.05.18
List  (0) 2021.05.18
UIViewController 중첩  (0) 2021.05.18

Python 으로 행렬 만들기

 

Vector & Matrix

 

벡터와 행렬도 숫자처럼 덧셈, 뺄셈, 곱셈 등의 연산을 있다. 벡터와 행렬의 연산을 이용하면 대량의 데이터에 대한 계산을 간단한 수식으로 나타낼 있다. 물론 벡터와 행렬에 대한 연산은 숫자의 사칙 연산과는 가지 다른 점이 있으므로 이러한 차이를 알아야 한다.

절에서는 넘파이를 이용하여 벡터와 행렬의 연산을 실행하는 법도 공부한다. 다음처럼 넘파이와 맷플롯립 패키지가 임포트되어 있어야 한다.

In [1]:

import numpy as np

import matplotlib.pylab as plt

벡터/행렬의 덧셈과 뺄셈

같은 크기를 가진 개의 벡터나 행렬은 덧셈과 뺄셈을 있다. 벡터와 행렬에서 같은 위치에 있는 원소끼리 덧셈과 뺄셈을 하면 된다. 이러한 연산을 요소별(element-wise) 연산이라고 한다.

예를 들어 벡터 𝑥x 𝑦y 다음과 같으면,

𝑥=⎡⎣⎢⎢101112⎤⎦⎥⎥,𝑦=⎡⎣⎢⎢012⎤⎦⎥⎥(2.2.1)(2.2.1)x=[101112],y=[012]

벡터 𝑥x 𝑦y 덧셈 𝑥+𝑦x+y 뺄셈 𝑥−𝑦x−y 다음처럼 계산한다.

𝑥+𝑦=⎡⎣⎢⎢101112⎤⎦⎥⎥+⎡⎣⎢⎢012⎤⎦⎥⎥=⎡⎣⎢⎢10+011+112+2⎤⎦⎥⎥=⎡⎣⎢⎢101214⎤⎦⎥⎥(2.2.2)(2.2.2)x+y=[101112]+[012]=[10+011+112+2]=[101214]

𝑥−𝑦=⎡⎣⎢⎢101112⎤⎦⎥⎥−⎡⎣⎢⎢012⎤⎦⎥⎥=⎡⎣⎢⎢10−011−112−2⎤⎦⎥⎥=⎡⎣⎢⎢101010⎤⎦⎥⎥(2.2.3)(2.2.3)x−y=[101112]−[012]=[10−011−112−2]=[101010]

벡터의 덧셈과 뺄셈을 넘파이로 계산하면 다음과 같다. 여기에서는 편의상 1차원 배열로 벡터를 표시하였다.

In [2]:

x = np.array([10, 11, 12, 13, 14])

y = np.array([0, 1, 2, 3, 4])

In [3]:

x + y

array([10, 12, 14, 16, 18])

In [4]:

x - y

array([10, 10, 10, 10, 10])

행렬도 같은 방법으로 덧셈과 뺄셈을 있다.

[5768]+[10302040]−[1324]=[14342444](2.2.4)(2.2.4)[5678]+[10203040]−[1234]=[14243444]

In [5]:

np.array([[5, 6], [7, 8]]) + np.array([[10, 20], [30, 40]]) - \

np.array([[1, 2], [3, 4]])

array([[14, 24],

    [34, 44]])

스칼라와 벡터/행렬의 곱셈

벡터 𝑥x 또는 행렬 𝐴A 스칼라값 𝑐c 곱하는 것은 벡터 𝑥x 또는 행렬 𝐴A 모든 원소에 스칼라값 𝑐c 곱하는 같다.

𝑐[𝑥1𝑥2]=[𝑐𝑥1𝑐𝑥2](2.2.5)(2.2.5)c[x1x2]=[cx1cx2]

𝑐[𝑎11𝑎21𝑎12𝑎22]=[𝑐𝑎11𝑐𝑎21𝑐𝑎12𝑐𝑎22](2.2.6)(2.2.6)c[a11a12a21a22]=[ca11ca12ca21ca22]

브로드캐스팅

원래 덧셈과 뺄셈은 크기(차원) 같은 벡터에 대해서만 있다. 하지만 벡터와 스칼라의 경우에는 관례적으로 다음처럼 1-벡터를 사용하여 스칼라를 벡터로 변환한 연산을 허용한다. 이를 브로드캐스팅(broadcasting)이라고 한다.

⎡⎣⎢⎢101112⎤⎦⎥⎥−10=⎡⎣⎢⎢101112⎤⎦⎥⎥−10⋅1=⎡⎣⎢⎢101112⎤⎦⎥⎥−⎡⎣⎢⎢101010⎤⎦⎥⎥(2.2.7)(2.2.7)[101112]−10=[101112]−10⋅1=[101112]−[101010]

데이터 분석에서는 원래의 데이터 벡터 𝑥x 아니라 데이터 벡터의 원소의 평균값을 평균제거(mean removed) 벡터 혹은 0-평균(zero-mean) 벡터 사용하는 경우가 많다.

𝑥=⎡⎣⎢⎢⎢⎢𝑥1𝑥2⋮𝑥𝑁⎤⎦⎥⎥⎥⎥→𝑥−𝑚=⎡⎣⎢⎢⎢⎢𝑥1−𝑚𝑥2−𝑚⋮𝑥𝑁−𝑚⎤⎦⎥⎥⎥⎥(2.2.8)(2.2.8)x=[x1x2⋮xN]→x−m=[x1−mx2−m⋮xN−m]

식에서 𝑚m 샘플 평균이다.

𝑚=1𝑁∑𝑖=1𝑁𝑥𝑖(2.2.9)(2.2.9)m=1N∑i=1Nxi

선형조합

벡터/행렬에 다음처럼 스칼라값을 곱한 더하거나 것을 벡터/행렬의 선형조합(linear combination)이라고 한다. 벡터나 행렬을 선형조합해도 크기는 변하지 않는다.

𝑐1𝑥1+𝑐2𝑥2+𝑐3𝑥3+⋯+𝑐𝐿𝑥𝐿=𝑥(2.2.10)(2.2.10)c1x1+c2x2+c3x3+⋯+cLxL=x

𝑐1𝐴1+𝑐2𝐴2+𝑐3𝐴3+⋯+𝑐𝐿𝐴𝐿=𝐴(2.2.11)(2.2.11)c1A1+c2A2+c3A3+⋯+cLAL=A

𝑐1,𝑐2,…,𝑐𝐿𝐑(2.2.12)(2.2.12)c1,c2,…,cL∈R

𝑥1,𝑥2,…,𝑥𝐿,𝑥∈𝐑𝑀(2.2.13)(2.2.13)x1,x2,…,xL,x∈RM

𝐴1,𝐴2,…,𝐴𝐿,𝐴∈𝐑𝑀×𝑁(2.2.14)(2.2.14)A1,A2,…,AL,A∈RM×N

벡터나 행렬의 크기를 직사각형으로 표시하면 다음과 같다.

𝑐1𝑥1+𝑐2𝑥2+⋯+𝑐𝐿𝑥𝐿(2.2.15)(2.2.15)c1(x1(+c2(x2(+⋯+cL(xL(

𝑐1𝐴1+𝑐2𝐴2+⋯+𝑐𝐿𝐴𝐿(2.2.16)(2.2.16)c1A1+c2A2+⋯+cLAL

벡터와 벡터의 곱셈

행렬의 곱셈을 정의하기 전에 우선 벡터의 곱셈을 알아보자. 벡터를 곱셈하는 방법은 여러 가지가 있지만 여기서는 내적(inner product) 대해서만 다룬다. 벡터 𝑥x 벡터 𝑦y 내적은 다음처럼 표기한다.

𝑥𝑇𝑦(2.2.17)(2.2.17)xTy

내적은 다음처럼 (dot)으로 표기하는 경우도 있어서 프로덕트(dot product)라고도 부르고 < 𝑥,𝑦x,y > 기호로 나타낼 수도 있다.

𝑥⋅𝑦=<𝑥,𝑦>=𝑥𝑇𝑦(2.2.18)(2.2.18)x⋅y=<x,y>=xTy

벡터를 내적하려면 다음과 같은 조건이 만족되어야 한다.

1. 우선 벡터의 차원(길이) 같아야 한다.

2. 앞의 벡터가 벡터이고 뒤의 벡터가 벡터여야 한다.

이때 내적의 결과는 스칼라값이 되며 다음처럼 계산한다. 우선 같은 위치에 있는 원소들을 요소별 곱셈처럼 곱한 다음, 값들을 다시 모두 더해서 하나의 스칼라값으로 만든다.

𝑥𝑇𝑦=[𝑥1𝑥2⋯𝑥𝑁]⎡⎣⎢⎢⎢⎢𝑦1𝑦2⋮𝑦𝑁⎤⎦⎥⎥⎥⎥=𝑥1𝑦1+⋯+𝑥𝑁𝑦𝑁=∑𝑖=1𝑁𝑥𝑖𝑦𝑖(2.2.19)(2.2.19)xTy=[x1x2⋯xN][y1y2⋮yN]=x1y1+⋯+xNyN=∑i=1Nxiyi

𝑥∈𝐑𝑁×1(2.2.20)(2.2.20)x∈RN×1

𝑦∈𝐑𝑁×1(2.2.21)(2.2.21)y∈RN×1

𝑥𝑇𝑦∈𝐑(2.2.22)(2.2.22)xTy∈R

다음은 벡터의 내적의 예다.

𝑥=⎡⎣⎢⎢123⎤⎦⎥⎥,𝑦=⎡⎣⎢⎢456⎤⎦⎥⎥(2.2.23)(2.2.23)x=[123],y=[456]

𝑥𝑇𝑦=[123]⎡⎣⎢⎢456⎤⎦⎥⎥=1⋅4+2⋅5+3⋅6=32(2.2.24)(2.2.24)xTy=[123][456]=1⋅4+2⋅5+3⋅6=32

넘파이에서 벡터와 행렬의 내적은 dot()이라는 명령 또는 @(at이라고 읽는다)이라는 연산자로 계산한다. 2차원 배열로 표시한 벡터를 내적했을 때는 결과값이 스칼라가 아닌 2차원 배열이다.

In [6]:

x = np.array([[1], [2], [3]])

y = np.array([[4], [5], [6]])

 

x.T @ y  # 또는 np.dot(x.T, y)

array([[32]])

넘파이에서는 1차원 배열끼리도 내적을 계산한다. 이때는 넘파이가 앞의 벡터는 벡터이고 뒤의 벡터는 벡터라고 가정한다.

In [7]:

x = np.array([1, 2, 3])

y = np.array([4, 5, 6])

 

x @ y  # 또는 np.dot(x, y)

32

벡터의 내적은 덧셈이나 뺄셈과 달리 이렇게 복잡하게 정의된 것일까? 이유는 데이터 분석을 이러한 연산이 필요하기 때문이다. 벡터의 내적을 사용하여 데이터를 분석하는 가지 예를 살펴보자.

가중합

벡터의 내적은 가중합을 계산할 쓰일 있다. 가중합(weighted sum)이란 복수의 데이터를 단순히 합하는 것이 아니라 각각의 수에 어떤 가중치 값을 곱한 곱셈 결과들을 다시 합한 것을 말한다.

만약 데이터 벡터가 𝑥=[𝑥1,⋯,𝑥𝑁]𝑇x=[x1,⋯,xN]T이고 가중치 벡터가 𝑤=[𝑤1,⋯,𝑤𝑁]𝑇w=[w1,⋯,wN]T이면 데이터 벡터의 가중합은 다음과 같다.

𝑤1𝑥1+⋯+𝑤𝑁𝑥𝑁=∑𝑖=1𝑁𝑤𝑖𝑥𝑖(2.2.25)(2.2.25)w1x1+⋯+wNxN=∑i=1Nwixi

값을 벡터 𝑥x 𝑤w 곱으로 나타내면 𝑤𝑇𝑥wTx 또는 𝑥𝑇𝑤xTw 라는 간단한 수식으로 표시할 있다.

𝑖=1𝑁𝑤𝑖𝑥𝑖=[𝑤1𝑤2⋯𝑤𝑁]⎡⎣⎢⎢⎢⎢𝑥1𝑥2⋮𝑥𝑁⎤⎦⎥⎥⎥⎥=[𝑥1𝑥2⋯𝑥𝑁]⎡⎣⎢⎢⎢⎢𝑤1𝑤2⋮𝑤𝑁⎤⎦⎥⎥⎥⎥=𝑤𝑇𝑥=𝑥𝑇𝑤(2.2.26)(2.2.26)∑i=1Nwixi=[w1w2⋯wN][x1x2⋮xN]=wTx=[x1x2⋯xN][w1w2⋮wN]=xTw

예를 들어 쇼핑을 물건의 가격은 데이터 벡터, 물건의 수량은 가중치로 생각하여 내적을 구하면 총금액을 계산할 있다.

만약 가중치가 모두 1이면 일반적인 (sum) 계산한다.

𝑤1=𝑤2=⋯=𝑤𝑁=1(2.2.27)(2.2.27)w1=w2=⋯=wN=1

또는

𝑤=1𝑁(2.2.28)(2.2.28)w=1N

이면

𝑖=1𝑁𝑥𝑖=1𝑇𝑁𝑥(2.2.29)(2.2.29)∑i=1Nxi=1NTx

연습 문제 2.2.1
A, B, C 회사의 주식은 각각 100만원, 80만원, 50만원이다. 주식을 각각 3, 4, 5주를 매수할 필요한 금액을 구하고자 한다.
(1) 주식의 가격과 수량을 각각 𝑝p 벡터, 𝑛n 벡터로 표시하고 넘파이로 코딩한다.
(2) 주식을 매수할 필요한 금액을 곱셈으로 표시하고 넘파이 연산으로 값을 계산한다.

가중평균

가중합의 가중치값을 전체 가중치값의 합으로 나누면 가중평균(weighted average) 된다. 가중평균은 대학교의 평균 성적 계산 등에 사용할 있다.

예를 들어 고등학교에서는 국어, 영어, 과목의 평균 점수를 구할 단순히 과목의 점수(숫자) 더한 2으로 나눈다. 그러나 대학교에서는 중요한 과목과 중요하지 않는 과목을 구분하는 학점(credit)이라는 숫자가 있다. 일주일에 시간만 수업하는 과목은 1학점짜리 과목이고 일주일에 시간씩 수업하는 중요한 과목은 3학점짜리 과목이다. 1학점과 3학점 과목의 점수가 각각 100, 60점이면 학점을 고려한 가중 평균(weighted average) 성적은 다음과 같이 계산한다.

11+3×100+31+3×60=70(2.2.30)(2.2.30)11+3×100+31+3×60=70

벡터로 표현된 𝑁N개의 데이터의 단순 평균은 다음처럼 생각할 있다.

𝑥¯=1𝑁∑𝑖=1𝑁𝑥𝑖=1𝑁1𝑇𝑁𝑥(2.2.31)(2.2.31)x¯=1N∑i=1Nxi=1N1NTx

수식에서 보인 것처럼 𝑥x 데이터의 평균은 보통 𝑥¯라는 기호로 표기하고 "엑스 (x bar)" 라고 읽는다.

다음은 넘파이로 평균을 계산하는 방법이다.

In [8]:

x = np.arange(10)

N = len(x)

 

np.ones(N) @ x / N

4.5

현실적으로는 mean()이라는 메서드를 사용하는 것이 편하다.

In [9]:

x.mean()

4.5

연습 문제 2.2.2
벡터 𝑥x 평균 제거 벡터는 다음과 같이 계산함을 증명하라.
𝑥−1𝑁1𝑇𝑁𝑥1𝑁(2.2.32)(2.2.32)x−1N1NTx1N

유사도

벡터의 곱셈(내적) 벡터 간의 유사도를 계산하는 데도 이용할 있다. 유사도(similarity) 벡터가 닮은 정도를 정량적으로 나타낸 으로 벡터가 비슷한 경우에는 유사도가 커지고 비슷하지 앟은 경우에는 유사도가 작아진다. 내적을 이용하면 코사인 유사도(cosine similarity)라는 유사도를 계산할 있다. 추후 선형대수의 기하학적 의미를 공부할 코사인 유사도에 대해 살펴볼 것이다.

예를 들어 0 1 나타내는 MNIST 이미지에 대해 내적을 계산해보자.

In [10]:

from sklearn.datasets import load_digits

import matplotlib.gridspec as gridspec

 

digits = load_digits()

d1 = digits.images[0]

d2 = digits.images[10]

d3 = digits.images[1]

d4 = digits.images[11]

v1 = d1.reshape(64, 1)

v2 = d2.reshape(64, 1)

v3 = d3.reshape(64, 1)

v4 = d4.reshape(64, 1)

 

plt.figure(figsize=(9, 9))

gs = gridspec.GridSpec(1, 8, height_ratios=[1],

                    width_ratios=[9, 1, 9, 1, 9, 1, 9, 1])

for i in range(4):

plt.subplot(gs[2 * i])

plt.imshow(eval("d" + str(i + 1)), aspect=1,

            interpolation='nearest', cmap=plt.cm.bone_r)

plt.grid(False)

plt.xticks([])

plt.yticks([])

plt.title("image {}".format(i + 1))

plt.subplot(gs[2 * i + 1])

plt.imshow(eval("v" + str(i + 1)), aspect=0.25,

            interpolation='nearest', cmap=plt.cm.bone_r)

plt.grid(False)

plt.xticks([])

plt.yticks([])

plt.title("vector {}".format(i + 1))

plt.tight_layout()

plt.show()

"0" 이미지와 "0" 이미지, 또는 "1" 이미지와 "1" 이미지의 내적값은 다음과 같다.

In [11]:

(v1.T @ v2)[0][0], (v3.T @ v4)[0][0]

(3064.0, 3661.0)

상대적으로 "0" 이미지와 "1" 이미지, 또는 "1" 이미지와 "0" 이미지의 내적값은 작다.

In [12]:

(v1.T @ v3)[0][0], (v1.T @ v4)[0][0], (v2.T @ v3)[0][0], (v2.T @ v4)[0][0]

(1866.0, 1883.0, 2421.0, 2479.0)

연습 문제 2.2.3
다음 코드를 실행하면 MNIST 숫자 이미지 전체 데이터를 모두 벡터로 변환하여 하나의 넘파이 행렬 X 만든다. 행렬을 이용하여 다음 문제를 풀어라.
from sklearn.datasets import load_digits
X = load_digits().data
(1) 내적을 이용하여 번째 이미지와 10번째 이미지의 유사도를 구하라.
(2) 내적을 이용하여 모든 이미지의 조합에 대해 유사도를 구하라. 어떻게 구현하는 것이 효율적일까? (힌트 : 문제는 뒤에서 배울 행렬과 행렬의 곱셈을 이용한다.)

선형회귀 모형

선형회귀 모형(linear regression model)이란 독립변수 𝑥x에서 종속변수 𝑦y 예측하는 방법의 하나로 독립변수 벡터 𝑥x 가중치 벡터 𝑤w와의 가중합으로 𝑦y 대한 예측값 𝑦̂ y^ 계산하는 수식을 말한다.

𝑦̂ =𝑤1𝑥1+⋯+𝑤𝑁𝑥𝑁(2.2.33)(2.2.33)y^=w1x1+⋯+wNxN

수식에서 기호 ^ "캐럿(caret)"이라는 기호이다. 𝑦̂ y^ "와이 (y hat)"이라고 읽는다.

수식은 다음처럼 벡터의 내적으로 나타낼 있다.

𝑦̂ =𝑤𝑇𝑥(2.2.34)(2.2.34)y^=wTx

선형회귀 모형은 가장 단순하면서도 가장 널리 쓰이는 예측 모형이다.

예를 들어 어떤 아파트 단지의 아파트 가격을 조사하였더니 아파트 가격은 (1)면적, (2)층수, (3)한강이 보이는지의 여부, 가지 특징에 의해 달라진다는 사실을 알게 되었다. 이때 단지 내의 아파트 가격을 예측하는 예측 모형을 다음과 같이 만들 있다.

·   면적(𝑚2m2) 입력 데이터 𝑥1x1라고 한다.

·   층수를 입력 데이터 𝑥2x2라고 한다

·   한강이 보이는지의 여부를 입력 데이터 𝑥3x3라고 하며 한강이 보이면 𝑥3=1x3=1, 보이지 않으면 𝑥3=0x3=0이라고 한다.

·   출력 데이터 𝑦̂ y^ 해당 아파트의 예측 가격이다.

위와 같이 입력 데이터와 출력 데이터를 정의하고 회귀분석을 결과, 아파트값이 다음과 같은 선형회귀 모형으로 나타난다고 가정하자. 이러한 모형을 실제로 찾는 방법은 나중에 회귀분석 파트에서 공부하게 된다.

𝑦̂ =500𝑥1+200𝑥2+1000𝑥3(2.2.35)(2.2.35)y^=500x1+200x2+1000x3

모형은 다음과 같이 해석할 있다.

·   면적이 1𝑚2m2 증가할수록 가격은 500 원이 증가한다.

·   층수가 1 높아질수록 가격은 200 원이 증가한다.

·   한강이 보이는 집은 1,000 원의 웃돈(프리미엄) 존재한다.

식은 다음과 같이 벡터의 내적으로 고쳐 있다.

𝑦̂ =[5002001000]⎡⎣⎢⎢𝑥1𝑥2𝑥3⎤⎦⎥⎥=𝑤𝑇𝑥(2.2.36)(2.2.36)y^=[5002001000][x1x2x3]=wTx

, 선형회귀 모형은 다음 가중치 벡터로 대표된다.

𝑤𝑇=[5002001000](2.2.37)(2.2.37)wT=[5002001000]

인공신경망(artificial neural network)에서는 선형회귀 모형을 다음과 같은 그림으로 표현한다. 데이터는 노드(node) 혹은 뉴런(neuron)이라는 동그라미로 표시하고 곱셈은 선분(line)위에 곱할 숫자를 써서 나타낸다. 덧셈은 여러 개의 선분이 만나는 것으로 표시한다.

그림 2.2.1 인공신경망으로 표현한 선형회귀 모형

선형회귀 모형의 단점

선형회귀 모형은 비선형적인 현실 세계의 데이터를 예측하지 못할 있다는 단점이 있다. 예를 들어 집값은 면적에 단순 비례하지 않는다. 소형 면적의 집과 대형 면적의 집은 단위 면적당 집값의 증가율이 다를 있다. 또한 저층이 보통 고층보다 집값이 싸지만 층수가 올라갈수록 정확히 층수에 비례하여 가격이 증가하지도 않는다.

이러한 현실 세계의 데이터와 선형회귀 모형의 괴리를 줄이기 위해 선형회귀 모형이 아닌 완전히 다른 모형을 쓰기보다는 선형회귀 모형을 기반으로 여러 기법을 사용해 수정한 모형을 사용하는 것이 일반적이다. 이러한 수정 선형회귀 모형에 대해서는 나중에 공부하게 된다.

제곱합

데이터의 분산(variance)이나 표준 편차(standard deviation) 등을 구하는 경우에는 각각의 데이터를 제곱한 값을 모두 더한 제곱합(sum of squares) 계산해야 한다. 경우에도 벡터의 내적을 사용하여 𝑥𝑇𝑥xTx 있다.

𝑥𝑇𝑥=[𝑥1𝑥2⋯𝑥𝑁]⎡⎣⎢⎢⎢⎢𝑥1𝑥2⋮𝑥𝑁⎤⎦⎥⎥⎥⎥=∑𝑖=1𝑁𝑥2𝑖(2.2.38)(2.2.38)xTx=[x1x2⋯xN][x1x2⋮xN]=∑i=1Nxi2

행렬과 행렬의 곱셈

벡터의 곱셈을 정의한 후에는 이를 이용하여 행렬의 곱셈을 정의할 있다. 행렬과 행렬을 곱하면 행렬이 된다. 방법은 다음과 같다.

𝐴A 행렬과 𝐵B 행렬을 곱한 결과가 𝐶C 행렬이 된다고 하자. 𝐶C 𝑖i번째 , 𝑗j번째 열의 원소 𝑐𝑖𝑗cij 값은 𝐴A 행렬의 𝑖i번째 벡터 𝑎𝑇𝑖aiT 𝐵B 행렬의 𝑗j번째 벡터 𝑏𝑗bj 곱이다.

𝐶=𝐴𝐵→𝑐𝑖𝑗=𝑎𝑇𝑖𝑏𝑗(2.2.39)(2.2.39)C=AB→cij=aiTbj

정의가 성립하려면 앞의 행렬 𝐴A 열의 수가 뒤의 행렬 𝐵B 행의 수와 일치해야만 한다.

𝐴∈𝐑𝑁×𝐿,𝐵∈𝐑𝐿×𝑀→𝐴𝐵∈𝐑𝑁×𝑀(2.2.40)(2.2.40)A∈RN×L,B∈RL×M→AB∈RN×M

다음은 4×34×3 행렬과 3×23×2 곱하여 4×24×2 계산하는 예다.

⎡⎣⎢⎢⎢⎢𝑎11𝑎21𝑎31𝑎41𝑎12𝑎22𝑎32𝑎42𝑎13𝑎23𝑎33𝑎43⎤⎦⎥⎥⎥⎥⎡⎣⎢⎢𝑏11𝑏21𝑏31𝑏12𝑏22𝑏32⎤⎦⎥⎥=⎡⎣⎢⎢⎢⎢(𝑎11𝑏11+𝑎12𝑏21+𝑎13𝑏31)(𝑎21𝑏11+𝑎22𝑏21+𝑎23𝑏31)(𝑎31𝑏11+𝑎32𝑏21+𝑎33𝑏31)(𝑎41𝑏11+𝑎42𝑏21+𝑎43𝑏31)(𝑎11𝑏12+𝑎12𝑏22+𝑎13𝑏32)(𝑎21𝑏12+𝑎22𝑏22+𝑎23𝑏32)(𝑎31𝑏12+𝑎32𝑏22+𝑎33𝑏32)(𝑎41𝑏12+𝑎42𝑏22+𝑎43𝑏32)⎤⎦⎥⎥⎥⎥(2.2.41)(2.2.41)[a11a12a13a21a22a23a31a32a33a41a42a43][b11b12b21b22b31b32]=[(a11b11+a12b21+a13b31)(a11b12+a12b22+a13b32)(a21b11+a22b21+a23b31)(a21b12+a22b22+a23b32)(a31b11+a32b21+a33b31)(a31b12+a32b22+a33b32)(a41b11+a42b21+a43b31)(a41b12+a42b22+a43b32)]

다음은 실제 행렬을 사용한 곱셈의 예다.

𝐴=[142536](2.2.42)(2.2.42)A=[123456]

𝐵=⎡⎣⎢⎢135246⎤⎦⎥⎥(2.2.43)(2.2.43)B=[123456]

𝐶=𝐴𝐵=[22492864](2.2.44)(2.2.44)C=AB=[22284964]

넘파이를 이용하여 행렬의 곱을 구할 때도 @ 연산자 또는 dot() 명령을 사용한다.

In [13]:

A = np.array([[1, 2, 3], [4, 5, 6]])

B = np.array([[1, 2], [3, 4], [5, 6]])

C = A @ B

C

array([[22, 28],

    [49, 64]])

연습 문제 2.2.4
(1) 𝐴A 𝐵B 위와 같을 𝐴𝐵AB 연습장에 손으로 계산하고 넘파이의 계산 결과와 맞는지 확인한다.
(2) 순서를 바꾸어 𝐵𝐴BA 손으로 계산하고 넘파이의 계산 결과와 맞는지 확인한다. 𝐵𝐴BA 𝐴𝐵AB 같은가?
(3) 𝐴A, 𝐵B 다음과 같을 , 𝐴𝐵AB, 𝐵𝐴BA (계산이 가능하다면) 손으로 계산하고 넘파이의 계산 결과와 맞는지 확인한다. 𝐴𝐵AB, 𝐵𝐴BA 모두 계산 가능한가?
𝐴=[123](2.2.45)(2.2.45)A=[123]
𝐵=⎡⎣⎢⎢456789⎤⎦⎥⎥(2.2.46)(2.2.46)B=[475869]
(4) 𝐴A, 𝐵B 다음과 같을 , 𝐴𝐵AB, 𝐵𝐴BA (계산이 가능하다면) 손으로 계산하고 넘파이의 계산 결과와 맞는지 확인한다. 𝐴𝐵AB, 𝐵𝐴BA 모두 계산 가능한가? 𝐵𝐴BA 결과가 𝐴𝐵AB 같은가?
𝐴=[1324](2.2.47)(2.2.47)A=[1234]
𝐵=[5768](2.2.48)(2.2.48)B=[5678]
(5) 𝐴A 다음과 같을 , 𝐴𝐴𝑇AAT 𝐴𝑇𝐴ATA 손으로 계산하고 넘파이의 계산 결과와 맞는지 확인한다. 𝐴𝐴𝑇AAT 𝐴𝑇𝐴ATA 크기는 어떠한가? 항상 정방행렬이 되는가?
𝐴=⎡⎣⎢⎢135246⎤⎦⎥⎥(2.2.49)(2.2.49)A=[123456]
(6) 𝑥x 다음과 같을 , 𝑥𝑇𝑥xTx 𝑥𝑥𝑇xxT 손으로 계산하고 넘파이의 계산 결과와 맞는지 확인한다. 𝑥𝑇𝑥xTx 𝑥𝑥𝑇xxT 크기는 어떠한가? 어떤 것이 스칼라이고 어떤 것이 정방행렬인가?
𝑥=⎡⎣⎢⎢123⎤⎦⎥⎥(2.2.50)(2.2.50)x=[123]

인공 신경망은 내부적으로 다음과 같이 여러 개의 선형회귀 모형을 사용한다. 구조는 행렬과 벡터의 곱으로 나타낼 있다.

그림 2.2.2 인공신경망의 기본 구조

그림을 행렬식으로 표현하면 다음과 같다.

[𝑦̂ 1𝑦̂ 2]=[𝑤11𝑤21𝑤12𝑤22𝑤13𝑤23]⎡⎣⎢⎢𝑥1𝑥2𝑥3⎤⎦⎥⎥(2.2.51)(2.2.51)[y^1y^2]=[w11w12w13w21w22w23][x1x2x3]

𝑦̂ =𝑊𝑥(2.2.52)(2.2.52)y^=Wx

교환 법칙과 분배 법칙

행렬의 곱셈은 곱하는 행렬의 순서를 바꾸는 교환 법칙이 성립하지 않는다. 그러나 덧셈에 대한 분배 법칙은 성립한다.

𝐴𝐵≠𝐵𝐴(2.2.53)(2.2.53)AB≠BA

𝐴(𝐵+𝐶)=𝐴𝐵+𝐴𝐶(2.2.54)(2.2.54)A(B+C)=AB+AC

(𝐴+𝐵)𝐶=𝐴𝐶+𝐵𝐶(2.2.55)(2.2.55)(A+B)C=AC+BC

𝐴A, 𝐵B, 𝐶C 다음과 같을 법칙을 넘파이로 살펴보자.

𝐴=[1324](2.2.56)(2.2.56)A=[1234]

𝐵=[5768](2.2.57)(2.2.57)B=[5678]

𝐶=[9786](2.2.58)(2.2.58)C=[9876]

In [14]:

A = np.array([[1, 2], [3, 4]])

B = np.array([[5, 6], [7, 8]])

C = np.array([[9, 8], [7, 6]])

𝐴𝐵AB 𝐵𝐴BA 값은 다음처럼 다른 값이 나오므로 교환법칙이 성립하지 않음을 있다.

In [15]:

A @ B

array([[19, 22],

    [43, 50]])

In [16]:

B @ A

array([[23, 34],

    [31, 46]])

분배법칙은 다음과 같이 성립한다.

In [17]:

A @ (B + C)

array([[42, 42],

    [98, 98]])

In [18]:

A @ B + A @ C

array([[42, 42],

    [98, 98]])

In [19]:

(A + B) @ C

array([[110,  96],

    [174, 152]])

In [20]:

A @ C + B @ C

array([[110,  96],

    [174, 152]])

전치 연산도 마찬가지로 덧셈/뺄셈에 대해 분배 법칙이 성립한다.

(𝐴+𝐵)𝑇=𝐴𝑇+𝐵𝑇(2.2.59)(2.2.59)(A+B)T=AT+BT

전치 연산과 곱셈의 경우에는 분배 법칙이 성립하기는 하지만 전치 연산이 분배되면서 곱셈의 순서가 바뀐다.

(𝐴𝐵)𝑇=𝐵𝑇𝐴𝑇(2.2.60)(2.2.60)(AB)T=BTAT

(𝐴𝐵𝐶)𝑇=𝐶𝑇𝐵𝑇𝐴𝑇(2.2.61)(2.2.61)(ABC)T=CTBTAT

마찬가지로 넘파이로 법칙이 성립하는지 살펴보자.

In [21]:

(A + B).T

array([[ 6, 10],

    [ 8, 12]])

In [22]:

A.T + B.T

array([[ 6, 10],

    [ 8, 12]])

In [23]:

(A @ B).T

array([[19, 43],

    [22, 50]])

In [24]:

B.T @ A.T

array([[19, 43],

    [22, 50]])

연습 문제 2.2.5
(1) 길이가 같은 일벡터 1𝑁𝐑𝑁1N∈RN 행벡터 𝑥∈𝐑𝑁x∈RN 곱은 행벡터 𝑥x 반복하여 가지는 행렬과 같음을 보여라.
1𝑁𝑥𝑇=⎡⎣⎢⎢⎢⎢𝑥𝑇𝑥𝑇⋮𝑥𝑇⎤⎦⎥⎥⎥⎥(2.2.62)(2.2.62)1NxT=[xTxT⋮xT]
(2) 행렬 𝑋(𝑋∈𝐑𝑁×𝑀)X(X∈RN×M) 있을 , 행렬의 열의 평균으로 이루어진 벡터 𝑥¯(𝑥¯∈𝐑𝑀)x¯(x¯∈RM) 다음과 같음을 보여라.
𝑥¯=1𝑁𝑋𝑇1𝑁(2.2.63)(2.2.63)x¯=1NXT1N
(3) 행렬 𝑋¯ (𝑋¯∈𝐑𝑁×𝑀)X¯ (X¯∈RN×M) 동일한 벡터 𝑥¯𝑇x¯T 𝑁N 누적하여 만든 행렬이다. 열의 모든 값이 열의 평균으로 이루어진 행렬이다.
𝑋¯=⎡⎣⎢⎢⎢⎢𝑥¯𝑇𝑥¯𝑇⋮𝑥¯𝑇⎤⎦⎥⎥⎥⎥(2.2.64)(2.2.64)X¯=[x¯Tx¯T⋮x¯T]
이때 𝑋¯ 다음과 같음을 보여라.
𝑋¯=1𝑁1𝑁1𝑇𝑁𝑋(2.2.65)(2.2.65)X¯=1N1N1NTX
(4) 다음 코드를 실행하면 붓꽃 전체 데이터를 모두 벡터로 변환하여 하나의 넘파이 행렬 X 만든다.
from sklearn.datasets import load_iris
X = load_iris().data
데이터로 행렬 𝑋¯ 값을 계산하라. 행렬은 번째 열의 값이 모두 같은 값으로 붓꽃의 꽃받침의 길이(sepal length) 평균이고 번째 열의 값이 모두 같은 값으로 붓꽃의 꽃받침의 (sepal width) 평균, 이런 식으로 계산된 행렬이다.

곱셈의 연결

연속된 행렬의 곱셈은 계산 순서를 임의의 순서로 해도 상관없다.

𝐴𝐵𝐶=(𝐴𝐵)𝐶=𝐴(𝐵𝐶)(2.2.66)(2.2.66)ABC=(AB)C=A(BC)

𝐴𝐵𝐶𝐷=((𝐴𝐵)𝐶)𝐷=(𝐴𝐵)(𝐶𝐷)=𝐴(𝐵𝐶𝐷)=𝐴(𝐵𝐶)𝐷(2.2.67)(2.2.67)ABCD=((AB)C)D=(AB)(CD)=A(BCD)=A(BC)D

연습 문제 2.2.6
다음 행렬의 곱셈을 순서를 바꾸어 가지 방법으로 해본다.
[12][1324][56](2.2.68)(2.2.68)[12][1234][56]

항등행렬의 곱셈

어떤 행렬이든 항등행렬을 곱하면 행렬의 값이 변하지 않는다.

𝐴𝐼=𝐼𝐴=𝐴(2.2.69)(2.2.69)AI=IA=A

넘파이로 다음과 같이 확인한다.

In [25]:

A = np.array([[1, 2], [3, 4]])

I = np.eye(2)

In [26]:

A @ I

array([[1., 2.],

    [3., 4.]])

In [27]:

I @ A

array([[1., 2.],

    [3., 4.]])

행렬과 벡터의

그럼 이러한 행렬의 곱셈은 데이터 분석에서 어떤 경우에 사용될까? 행렬의 곱셈 가장 널리 쓰이는 것은 다음과 같은 형태의 행렬 𝑀M 벡터 𝑣v 곱이다.

𝑀𝑣(2.2.70)(2.2.70)Mv

벡터와 행렬의 크기를 직사각형으로 표시하면 다음과 같다.

𝑀𝑣=𝑀𝑣(2.2.71)(2.2.71)M(v(=Mv

행렬과 벡터의 곱을 사용하는 몇가지 예를 살펴보자.

벡터의 선형조합

행렬 𝑋X 벡터 𝑤w 곱은 행렬 𝑋X 이루는 열벡터 𝑐1,𝑐2,…,𝑐𝑀c1,c2,…,cM 뒤에 곱해지는 벡터 𝑤w 성분 𝑤1,𝑤2,…,𝑤𝑀w1,w2,…,wM으로 선형조합(linear combination) 결과 벡터와 같다.

𝑋𝑤=[𝑐1𝑐2⋯𝑐𝑀]⎡⎣⎢⎢⎢⎢𝑤1𝑤2⋮𝑤𝑀⎤⎦⎥⎥⎥⎥=𝑤1𝑐1+𝑤2𝑐2+⋯+𝑤𝑀𝑐𝑀(2.2.72)(2.2.72)Xw=[c1c2⋯cM][w1w2⋮wM]=w1c1+w2c2+⋯+wMcM

벡터의 크기를 직사각형으로 표시하면 다음과 같다.

⎡⎣⎢⎢⎢⎢⎢𝑐1𝑐2⋯𝑐𝑀⎤⎦⎥⎥⎥⎥⎥⎡⎣⎢⎢⎢⎢𝑤1𝑤2⋮𝑤𝑀⎤⎦⎥⎥⎥⎥=𝑤1𝑐1+𝑤2𝑐2+⋯+𝑤𝑀𝑐𝑀(2.2.73)(2.2.73)[(c11((c21(⋯(cM(][w1w2⋮wM]=w1(c11(+w2(c21(+⋯+wM(cM(

연습 문제 2.2.7
다음 행렬 𝑋X 벡터 𝑤w 대해 𝑋𝑤Xw 열벡터 𝑐1,𝑐2,𝑐3c1,c2,c3 선형조합 𝑤1𝑐1+𝑤2𝑐2+𝑤3𝑐3w1c1+w2c2+w3c3 됨을 실제 계산으로 증명하라.
𝑋=[142536],𝑤=⎡⎣⎢⎢234⎤⎦⎥⎥(2.2.74)(2.2.74)X=[123456],w=[234]
연습 문제 2.2.8
벡터 𝑣1,𝑣2,𝑣3v1,v2,v3 이루어진 행렬 𝑉V 벡터 𝜆λ 대해 다음 식이 성립함을 증명하라. 식에서 𝜆1λ1 스칼라이다.
𝑉𝜆=[𝑣1𝑣2𝑣3]⎡⎣⎢⎢𝜆100⎤⎦⎥⎥=𝜆1𝑣1(2.2.75)(2.2.75)Vλ=[v1v2v3][λ100]=λ1v1

벡터의 선형조합은 다양한 분야에 응용된다. 예를 들어 이미지 벡터의 선형조합은 이미지를 섞어놓은 모핑(morphing) 효과를 얻는 사용할 있다.

In [28]:

from sklearn.datasets import fetch_olivetti_faces

 

faces = fetch_olivetti_faces()

 

f, ax = plt.subplots(1, 3)

 

ax[0].imshow(faces.images[6], cmap=plt.cm.bone)

ax[0].grid(False)

ax[0].set_xticks([])

ax[0].set_yticks([])

ax[0].set_title("image 1: $x_1$")

 

ax[1].imshow(faces.images[10], cmap=plt.cm.bone)

ax[1].grid(False)

ax[1].set_xticks([])

ax[1].set_yticks([])

ax[1].set_title("image 2: $x_2$")

 

new_face = 0.7 * faces.images[6] + 0.3 * faces.images[10]

ax[2].imshow(new_face, cmap=plt.cm.bone)

ax[2].grid(False)

ax[2].set_xticks([])

ax[2].set_yticks([])

ax[2].set_title("image 3: $0.7x_1 + 0.3x_2$")

 

plt.show()

여러 개의 벡터에 대한 가중합 동시 계산

벡터 하나의 가중합은 𝑤𝑇𝑥wTx 또는 𝑥𝑇𝑤xTw 표시할 있다는 것을 배웠다. 그런데 만약 이렇게 𝑤w 가중치를 사용한 가중합을 하나의 벡터 𝑥x 아니라 여러 벡터 𝑥1,⋯,𝑥𝑀x1,⋯,xM 개에 대해서 모두 계산해야 한다면 어떻게 해야 할까? 예를 들어 위와 같이 선형 회귀 모형을 사용하여 여러 데이터 𝑥1,𝑥2,𝑥3,⋯,𝑥𝑁x1,x2,x3,⋯,xN 개의 데이터 모두에 대해 예측값 𝑦1,𝑦2,𝑦3,⋯,𝑦𝑁y1,y2,y3,⋯,yN 한꺼번에 계산하고 싶다면 다음처럼 데이터 행렬 𝑋X 사용하여 𝑦̂ =𝑋𝑤y^=Xw라는 수식으로 간단하게 표시할 있다.

𝑦̂ =⎡⎣⎢⎢⎢⎢𝑦̂ 1𝑦̂ 2⋮𝑦̂ 𝑀⎤⎦⎥⎥⎥⎥=⎡⎣⎢⎢⎢⎢𝑤1𝑥1,1+𝑤2𝑥1,2+⋯+𝑤𝑁𝑥1,𝑁𝑤1𝑥2,1+𝑤2𝑥2,2+⋯+𝑤𝑁𝑥2,𝑁⋮𝑤1𝑥𝑀,1+𝑤2𝑥𝑀,2+⋯+𝑤𝑁𝑥𝑀,𝑁⎤⎦⎥⎥⎥⎥=⎡⎣⎢⎢⎢⎢𝑥1,1𝑥2,1⋮𝑥𝑀,1𝑥1,2𝑥2,2⋮𝑥𝑀,2⋯⋯⋮⋯𝑥1,𝑁𝑥2,𝑁⋮𝑥𝑀,𝑁⎤⎦⎥⎥⎥⎥⎡⎣⎢⎢⎢⎢𝑤1𝑤2⋮𝑤𝑁⎤⎦⎥⎥⎥⎥=⎡⎣⎢⎢⎢⎢⎢𝑥𝑇1𝑥𝑇2⋮𝑥𝑇𝑀⎤⎦⎥⎥⎥⎥⎥⎡⎣⎢⎢⎢⎢𝑤1𝑤2⋮𝑤𝑁⎤⎦⎥⎥⎥⎥=𝑋𝑤(2.2.76)(2.2.76)y^=[y^1y^2⋮y^M]=[w1x1,1+w2x1,2+⋯+wNx1,Nw1x2,1+w2x2,2+⋯+wNx2,N⋮w1xM,1+w2xM,2+⋯+wNxM,N]=[x1,1x1,2⋯x1,Nx2,1x2,2⋯x2,N⋮⋮⋮⋮xM,1xM,2⋯xM,N][w1w2⋮wN]=[x1Tx2T⋮xMT][w1w2⋮wN]=Xw

.

𝑦̂ =𝑋𝑤(2.2.77)(2.2.77)y^=Xw

연습 문제 2.2.9
𝑥1x1, 𝑥2x2 다음과 같을 ,
𝑥1=⎡⎣⎢⎢𝑥11𝑥21𝑥31⎤⎦⎥⎥𝑥2=⎡⎣⎢⎢𝑥12𝑥22𝑥32⎤⎦⎥⎥(2.2.78)(2.2.78)x1=[x11x21x31]x2=[x12x22x32]
다음 등식이 성립함을 보인다.
𝑋𝑤=[𝑥𝑇1𝑥𝑇2]⎡⎣⎢⎢𝑤1𝑤2𝑤3⎤⎦⎥⎥=[𝑥𝑇1𝑤𝑥𝑇2𝑤](2.2.79)(2.2.79)Xw=[x1Tx2T][w1w2w3]=[x1Twx2Tw]

잔차

선형 회귀분석(linear regression) 결과는 가중치 벡터 𝑤w라는 형태로 나타나고 예측치는 가중치 벡터를 사용한 독립변수 데이터 레코드 , 벡터 𝑥𝑖xi 가중합 𝑤𝑇𝑥𝑖wTxi 된다고 했다. 예측치와 실젯값(target) 𝑦𝑖yi 차이를 오차(error) 혹은 잔차(residual) 𝑒𝑖ei라고 한다. 이러한 잔찻값을 모든 독립변수 벡터에 대해 구하면 잔차 벡터 𝑒e 된다.

𝑒𝑖=𝑦𝑖−𝑦̂ 𝑖=𝑦𝑖−𝑤𝑇𝑥𝑖(2.2.80)(2.2.80)ei=yi−y^i=yi−wTxi

잔차 벡터는 다음처럼 𝑦−𝑋𝑤y−Xw 간단하게 표기할 있다.

𝑒=⎡⎣⎢⎢⎢⎢𝑒1𝑒2⋮𝑒𝑀⎤⎦⎥⎥⎥⎥=⎡⎣⎢⎢⎢⎢𝑦1𝑦2⋮𝑦𝑀⎤⎦⎥⎥⎥⎥−⎡⎣⎢⎢⎢⎢⎢𝑥𝑇1𝑤𝑥𝑇2𝑤⋮𝑥𝑇𝑀𝑤⎤⎦⎥⎥⎥⎥⎥=𝑦−𝑋𝑤(2.2.81)(2.2.81)e=[e1e2⋮eM]=[y1y2⋮yM]−[x1Twx2Tw⋮xMTw]=y−Xw

𝑒=𝑦−𝑋𝑤(2.2.82)(2.2.82)e=y−Xw

잔차 제곱합

잔차의 크기는 잔차 벡터의 원소를 제곱한 더한 잔차 제곱합(RSS: Residual Sum of Squares) 이용하여 구한다. 값은 𝑒𝑇𝑒eTe 간단하게 있으며 값은 다음처럼 계산한다.

𝑖=1𝑁𝑒2𝑖=∑𝑖=1𝑁(𝑦𝑖−𝑤𝑇𝑥𝑖)2=𝑒𝑇𝑒=(𝑦−𝑋𝑤)𝑇(𝑦−𝑋𝑤)(2.2.83)(2.2.83)∑i=1Nei2=∑i=1N(yi−wTxi)2=eTe=(y−Xw)T(y−Xw)

연습 문제 2.2.10
분배 법칙을 사용하여 (𝑦−𝑋𝑤)𝑇(𝑦−𝑋𝑤)(y−Xw)T(y−Xw) 풀어쓰면 다음과 같아짐을 보여라.
(𝑦−𝑋𝑤)𝑇(𝑦−𝑋𝑤)=𝑦𝑇𝑦−𝑤𝑇𝑋𝑇𝑦−𝑦𝑇𝑋𝑤+𝑤𝑇𝑋𝑇𝑋𝑤(2.2.84)(2.2.84)(y−Xw)T(y−Xw)=yTy−wTXTy−yTXw+wTXTXw

이차형식

위의 연습 문제에서 마지막 항은 𝑤𝑇𝑋𝑇𝑋𝑤wTXTXw라는 형태다. 식에서 𝑋𝑇𝑋XTX 정방행렬이 되므로 정방행렬을 𝐴A라고 이름 붙이면 마지막 항은 𝑤𝑇𝐴𝑤wTAw 같은 형태가 된다.

벡터의 이차형식(Quadratic Form)이란 이처럼 어떤 벡터와 정방행렬이 '행벡터 x 정방행렬 x 열벡터' 형식으로 되어 있는 것을 말한다.

수식을 풀면 𝑖=1,…,𝑁,𝑗=1,…,𝑁i=1,…,N,j=1,…,N 대해 가능한 모든 𝑖,𝑗i,j 쌍의 조합을 구한 다음 𝑖i, 𝑗j 해당하는 원소 𝑥𝑖xi, 𝑥𝑗xj 가중치 𝑎𝑖,𝑗ai,j 같이 곱한 𝑎𝑖,𝑗𝑥𝑖𝑥𝑗ai,jxixj 총합이 된다.

𝑥𝑇𝐴𝑥=[𝑥1𝑥2⋯𝑥𝑁]⎡⎣⎢⎢⎢⎢𝑎1,1𝑎2,1⋮𝑎𝑁,1𝑎1,2𝑎2,2⋮𝑎𝑁,2⋯⋯⋱⋯𝑎1,𝑁𝑎2,𝑁⋮𝑎𝑁,𝑁⎤⎦⎥⎥⎥⎥⎡⎣⎢⎢⎢⎢𝑥1𝑥2⋮𝑥𝑁⎤⎦⎥⎥⎥⎥=∑𝑖=1𝑁𝑗=1𝑁𝑎𝑖,𝑗𝑥𝑖𝑥𝑗(2.2.85)(2.2.85)xTAx=[x1x2⋯xN][a1,1a1,2⋯a1,Na2,1a2,2⋯a2,N⋮⋮⋱⋮aN,1aN,2⋯aN,N][x1x2⋮xN]=∑i=1N∑j=1Nai,jxixj

연습 문제 2.2.11
다음 3차원 벡터와 행렬에 대해 이차형식을 쓰고 값을 계산하라.
𝑥=⎡⎣⎢⎢𝑥1𝑥2𝑥3⎤⎦⎥⎥(2.2.86)(2.2.86)x=[x1x2x3]
𝐴=⎡⎣⎢⎢𝑎11𝑎21𝑎31𝑎12𝑎22𝑎32𝑎13𝑎23𝑎33⎤⎦⎥⎥(2.2.87)(2.2.87)A=[a11a12a13a21a22a23a31a32a33]

예를 들어 𝑥=[1,2,3]𝑇x=[1,2,3]T 이고 A 다음과 같다면

𝐴=⎡⎣⎢⎢147258369⎤⎦⎥⎥(2.2.88)(2.2.88)A=[123456789]

넘파이 에서 벡터의 이차형식은 다음처럼 계산한다.

In [29]:

x = np.array([1, 2, 3])

x

array([1, 2, 3])

In [30]:

A = np.arange(1, 10).reshape(3, 3)

A

array([[1, 2, 3],

    [4, 5, 6],

    [7, 8, 9]])

In [31]:

x.T @ A @ x

228

연습 문제 2.2.12
다음 식이 성립함을 증명하라.
𝑥𝑇𝐴𝑥=12𝑥𝑇(𝐴+𝐴𝑇)𝑥(2.2.89)(2.2.89)xTAx=12xT(A+AT)x

부분행렬

다음과 같은 2차원 정방행렬 𝐴A, 𝐵B 있다.

𝐴=[𝑎11𝑎21𝑎12𝑎22],𝐵=[𝑏11𝑏21𝑏12𝑏22](2.2.90)(2.2.90)A=[a11a12a21a22],B=[b11b12b21b22]

이때 행렬의 𝐴𝐵AB 𝐴A, 𝐵B 부분행렬(submatrix) 이용하여 여러 방법으로 계산할 있다.

(1) 우선 앞에 곱해지는 행렬을 행벡터로 나누어 계산해도 된다.

𝐴=⎡⎣⎢⎢𝑎𝑇1𝑎𝑇2⎤⎦⎥⎥(2.2.91)(2.2.91)A=[a1Ta2T]

,

𝑎𝑇1=[𝑎11𝑎12],𝑎𝑇2=[𝑎21𝑎22](2.2.92)(2.2.92)a1T=[a11a12],a2T=[a21a22]

이면

𝐴𝐵=⎡⎣⎢⎢𝑎𝑇1𝑎𝑇2⎤⎦⎥⎥𝐵=⎡⎣⎢⎢𝑎𝑇1𝐵𝑎𝑇2𝐵⎤⎦⎥⎥(2.2.93)(2.2.93)AB=[a1Ta2T]B=[a1TBa2TB]

(2) 아니면 뒤에 곱해지는 행렬을 열벡터로 나누어 계산해도 된다.

𝐵=⎡⎣⎢⎢⎢𝑏1𝑏2⎤⎦⎥⎥⎥(2.2.94)(2.2.94)B=[(b1((b2(]

,

𝑏1=[𝑏11𝑏21],𝑏2=[𝑏21𝑏22](2.2.95)(2.2.95)b1=[b11b21],b2=[b21b22]

이면

𝐴𝐵=𝐴⎡⎣⎢⎢⎢𝑏1𝑏2⎤⎦⎥⎥⎥=⎡⎣⎢⎢⎢𝐴𝑏1𝐴𝑏2⎤⎦⎥⎥⎥(2.2.96)(2.2.96)AB=A[(b1((b2(]=[(Ab1((Ab2(]

(3) 앞에 곱해지는 행렬을 열벡터로, 뒤에 곱해지는 행렬을 행벡터로 나누어 스칼라처럼 계산해도 된다.

𝐴𝐵=[𝑎1𝑎2][𝑏𝑇1𝑏𝑇2]=𝑎1𝑏𝑇1+𝑎2𝑏𝑇2(2.2.97)(2.2.97)AB=[a1a2][b1Tb2T]=a1b1T+a2b2T

벡터의 크기를 직사각형으로 표시하면 다음과 같다.

𝐴𝐵=⎡⎣⎢⎢⎢𝑎1𝑎2⎤⎦⎥⎥⎥⎡⎣⎢⎢𝑏𝑇1𝑏𝑇2⎤⎦⎥⎥=𝑎1𝑏𝑇1+𝑏1𝑏𝑇2(2.2.98)(2.2.98)AB=[(a1((a2(][b1Tb2T]=(a1(b1T+(b1(b2T

여기에서는 2차원 행렬의 예를 들었지만 일반적인 𝑁N차원 행렬에서도 관계는 성립한다.

연습 문제 2.2.13
행렬 𝑉V 열벡터 𝑣𝑖(𝑖=1,…,𝑁)vi(i=1,…,N) 이루어진 정방행렬이다. 𝑉V 크기가 같은 다른 정방행렬 𝐴A, ΛΛ 있을 다음 식이 성립한다.
𝐴𝑉=𝐴[𝑣1⋯𝑣𝑁]=[𝐴𝑣1⋯𝐴𝑣𝑁](2.2.99)(2.2.99)AV=A[v1⋯vN]=[Av1⋯AvN]
𝑉Λ=[𝑣1⋯𝑣𝑁]⎡⎣⎢⎢⎢⎢𝜆10⋮00𝜆2⋮0⋯⋯⋱⋯00⋮𝜆𝑁⎤⎦⎥⎥⎥⎥=[𝜆1𝑣1⋯𝜆𝑁𝑣𝑁](2.2.100)(2.2.100)VΛ=[v1⋯vN][λ10⋯00λ2⋯0⋮⋮⋱⋮00⋯λN]=[λ1v1⋯λNvN]
𝑁=3N=3 경우에 식이 성립함을 보여라.
연습 문제 2.2.14
부분행렬 공식 (3)으로부터 𝐴A 행벡터 𝑎𝑇𝑖(𝑖=1,…,𝑁)aiT(i=1,…,N) 이루어진 𝑁N 정방행렬일
𝐴=⎡⎣⎢⎢⎢⎢⎢𝑎𝑇1𝑎𝑇2⋮𝑎𝑇𝑁⎤⎦⎥⎥⎥⎥⎥(2.2.101)(2.2.101)A=[a1Ta2T⋮aNT]
다음 관계가 성립한다.
𝐴𝑇𝐴=[𝑎1𝑎2⋯𝑎𝑁]⎡⎣⎢⎢⎢⎢⎢𝑎𝑇1𝑎𝑇2⋮𝑎𝑇𝑁⎤⎦⎥⎥⎥⎥⎥=∑𝑖=1𝑁𝑎𝑖𝑎𝑇𝑖(2.2.102)(2.2.102)ATA=[a1a2⋯aN][a1Ta2T⋮aNT]=∑i=1NaiaiT
𝑁=3N=3 경우에 식이 성립함을 보여라.

질문/덧글

dot연산된 2차원 배열 벡터 hamj*** 2017 3 24 9:42 오후 답변

안녕하세요. numpy 관련 문서를 찾다가 압도적인 튜토리얼을 발견했네요 ! 요새 딥러닝관련 문서들을 보는데, 문꽈 출신으로 첩첩산중이라 애로사항이 많슴다... 위에서 2차원 벡터의 dot 연산된 "결과값이 스칼라가 아닌 2차원 배열이라는 점에 유의한다."

array([[32]]) 이게 무슨 의미인지 이해하기가 힘듭니다. 얼마 전에 수학교과서에서는 "내적(inner product = dot product)연산은 결과값이 스칼라이므로 scalar product라고도 부른다"라고 봤거든요. 외적은 결과값도 벡터이므로 벡터곱이라고 부른다고 하구요. 수학적인 결과값은 스칼라이지만, 파이썬의 자료형으로 2차원 배열이라는 의미인지요 ?

답변: dot연산된 2차원 배열 벡터 관리자 2017 3 27 8:29 오후 답변

, 말씀하신대로 수학적인 결과값은 스칼라이지만, 파이썬의 자료형으로 2차원 배열이라는 의미입니다.

본문의 평균 부분 beom*** 2017 9 3 8:22 오후 답변

본문의 평균 부분에서 N = len(x) np.dot(np.ones(N), x) / N 아래에 나오는 결과값이 잘못 같습니다. x.mean() 결과값과 동일하게 4.5 수정되어야 같습니다.

답변: 본문의 평균 부분 관리자 2017 9 4 1:38 오후 답변

수정하였습니다. 지적 감사드립니다.

본문의 문장 '벡터로 표현된 N 개의 데이터의 단순 평균은 가중치값이 모두 1/N 가중 평균과 같다'에서 가중 평균이 가중 합으로 바뀌어하는게 아닌지요? beom*** 2017 9 8 4:25 오후 답변

답변: 본문의 문장 '벡터로 표현된 N 개의 데이터의 단순 평균은 가중치값이 모두 1/N 가중 평균과 같다'에서 가중 평균이 가중 합으로 바뀌어하는게 아닌지요? 관리자 2017 9 8 5:56 오후 답변

수정하였습니다. 지적 감사드립니다.

사용자에 의해 삭제되었습니다. eddy*** 2017 9 23 8:12 오후 답변

사용자에 의해 삭제되었습니다.

교열맨 roh.*** 2018 9 18 9:37 오전 답변

행렬과 행렬의 곱셈) 다음은 실제 행렬을 사용한 '곱셍' 예이다. -> 곱셈

벡터의 선형조합) 이미지를 섞어놓은 모핑(morhping) 효과 -> morphing 감사합니다!!

답변: 교열맨 관리자 2018 9 19 9:49 오전 답변

지적 감사드립니다. 수정하겠습니다.

사용자에 의해 삭제되었습니다. shul*** 2019 5 6 8:48 오후 답변

사용자에 의해 삭제되었습니다.

사용자에 의해 삭제되었습니다. shul*** 2019 5 6 9:13 오후 답변

사용자에 의해 삭제되었습니다.

의문 혹은 질문들 shul*** 2019 5 6 11:27 오후 답변

· 내적을 표현할 각괄호<> 사용하는데, 각괄호는 위치벡터를 표현할 때도 사용하는 걸로 압니다. 혹시 사이에 어떤 연관성이 있기에 같은 기호를 사용하는 걸까요?

· 절에서 Numpy에서는 1차원 배열의 전치 연산이 계산되지 않는다고 했는데, 내적은 행벡터와 열벡터를 가정해가면서까지 자동으로 구할 있게 해놨네요. 그렇게 만들어진 걸까요?

· 문서와 연습문제들로 , 행렬간의 곱셈에서는 교환법칙이 성립하지 않지만, 벡터와 행렬의 곱셈에서는 교환법칙이 성립한다고 이해했는데 맞을까요?

답변: 의문 혹은 질문들 관리자 2019 5 10 9:32 오전 답변

(1) 참고 자료나 링크를 제시해주시면 좋겠습니다. (2) 사용자 편의를 위한 것입니다. (3) 아닙니다. 벡터도 행렬이므로 교환법칙이 일반적으로 성립하지 않습니다.

연습문제 해설을 보다가 질문 드립니다. sgus*** 2020 3 18 2:03 오후 답변

연습문제 2.2.1에서 내적 곱을 , p.T @ n으로 끝나지 않고, p.T @ n [0][0] 들어가 있는 확인하였습니다. [0][0] 넣은 것은 2차원 배열을 1차원 배열로 변형하기 위해서인가요?

답변: 연습문제 해설을 보다가 질문 드립니다. 관리자 2020 3 25 7:12 오후 답변

2차원 배열에서 스칼라를 뽑기 위해서입니다.

 


파일 설치

  • python opencv/platforms/ios/build_framework.py ios
  • python opencv/platforms/ios/build_framework.py ios --contrib opencv_contrib
  • python opencv/platforms/ios/build_framework.py ios --contrib opencv_contrib --iphoneos_archs arm64 --iphonesimulator_archs x86_64



- (IBAction)onClickSegmentedControl:(id)sender {

    self.mNmTppg=@"";

    if(self.mDokkaebi.selectedSegmentIndex ==0) {

        mCanYouSeeThisSword = @"H";

    } else if(self.mDokkaebi.selectedSegmentIndex ==1) {

        mCanYouSeeThisSword = @"P";

    }

    [self initializeData];

}




 HPQualityControl2 *v = [[HPQualityControl2 alloc] initWithNibName:@"HPQualityControl2" bundle:[NSBundle mainBundle]];

        if(self.mDokkaebi.selectedSegmentIndex ==0) {

            v.previousSegment = false;

        } else if(self.mDokkaebi.selectedSegmentIndex ==1) {

            v.previousSegment = true;

        }

            if(self.mDokkaebi.selectedSegmentIndex ==0) {

                v.mNm_tppg = _mCdTppg; } else {

                                v.mNm_tppg = _mNmTppg;

                }



  if(self.mDokkaebi.selectedSegmentIndex ==0) {

            [mLblHosh setText:[NSString stringWithFormat:@"→%@ %@호(%@)→%@%ld건", dongNm, nohs, tppgCd, mvin, (long)cntB]];

            [GlobalVar saveToUserDefaults:tppgCd forKey:@"HP_CD_TPPG"];

            } else if(self.mDokkaebi.selectedSegmentIndex ==1) {




'Swift & Python 실무 > {APP} SOCANNER APP' 카테고리의 다른 글

한 번은 사용해 봐야할 iOS 기술 스택  (0) 2021.05.21
Snapkit 실무 코드  (0) 2021.05.20
POD  (0) 2021.05.20
List  (0) 2021.05.18
UINavigationBar  (0) 2021.05.18

iOS에서 지난 10년간 히스토리로 POD은 필수가 되어 버렸다.

 

junhoha  ~/Documents/Github/takeTouch   main  pod init
 junhoha  ~/Documents/Github/takeTouch   main  pod install
Analyzing dependencies
Downloading dependencies
Generating Pods project
Integrating client project

[!] Please close any current Xcode sessions and use `Touch.xcworkspace` for this project from now on.
Pod installation complete! There are 0 dependencies from the Podfile and 0 total pods installed.

[!] The Podfile does not contain any dependencies.

[!] Automatically assigning platform `iOS` with version `13.0` on target `Touch` because no platform was specified. Please specify a platform for this target in your Podfile. See `https://guides.cocoapods.org/syntax/podfile.html#platform`.
 junhoha  ~/Documents/Github/takeTouch   main ●

 

'Swift & Python 실무 > {APP} SOCANNER APP' 카테고리의 다른 글

Snapkit 실무 코드  (0) 2021.05.20
iOS용 openCV 라이브러리 나왔으면 좋겠다.  (0) 2021.05.20
List  (0) 2021.05.18
UINavigationBar  (0) 2021.05.18
오늘자 troubleshooting  (0) 2020.04.08

#It's a simple tron sending source.
#python3 - m pip install tronpy
#python3 - m pip install rsa
#python3 - m pip install openpyxl

from tronpy import Tron
from tronpy.keys import PrivateKey
import time
import pandas as pd

class SendTron:
def sendTo(self, address):
client = Tron()
priv_key = PrivateKey(bytes.fromhex("YOUR_PRIVATE_KEY"))
txn = (
client.trx.transfer("TTfsJKVRDmFXRSYtp2QTGwEzjZvuWe7Fmj",
address, 1) # 1 is 0.000001 tron
.memo("sending using tronpy")
.build()
.inspect()
.sign(priv_key)
.broadcast()
)

print(txn)
print(txn.wait())



if __name__ == '__main__':
sendTron = SendTron()
time.sleep(2)
# 1person exam sendTron.sendTo("TTY9pSXAhQuJJyiKp15AixGUD4mMagRfGY")
# 1person exam sendTron.sendTo("TC5R1dy34Mb1VnVrUYSxPRka8gV1DYJoQY")
df = pd.read_excel('./event1.xlsx', sheet_name='recv_address', header=None, index_col=None, usecols=[1])
list4participants = df.values

for i in list4participants:
print("send To", i[0])
time.sleep(3)
sendTron.sendTo(i[0])

# TODO : adding try exception block
# W: Exceed the user daily usage (100000), the maximum query frequency is 1 time per second
# in case of bad wallet address.

일부 코드는 깃헙에 머지 했다.

https://github.com/andelf/tronpy

 

andelf/tronpy

TRON Python Client Library. Contribute to andelf/tronpy development by creating an account on GitHub.

github.com

복/붙 하니 제대로 안 붙네 파일로 첨부함.

tron_send.py
0.00MB

+ Recent posts