text
stringlengths 15
59.8k
| meta
dict |
|---|---|
Q: Bookmarklet to change zoom level works fine on base elements but not on elements that appear after a button is clicked I wish to change the zoom level of an element on a webpage using a bookmarklet which can be written using this URL: https://mcdlr.com/css-inject/
It's work ok on one element but not another.
This worked as expected.
javascript: (function(){ var style = document.createElement('style'), styleContent = document.createTextNode('.cards-panel--6LapW2x8n7IkQX8 {zoom: 0.8!important;}'); style.appendChild(styleContent); var caput = document.getElementsByTagName('head'); caput[0].appendChild(style); })();
but this didn't:
javascript: (function(){ var style = document.createElement('style'), styleContent = document.createTextNode('.notifications-list--cMVsqVbKkaXV4SQ {zoom: 0.8!important;}'); style.appendChild(styleContent); var caput = document.getElementsByTagName('head'); caput[0].appendChild(style); })();
The first element is a normal element that appears on load. The second element only appears after you click a button. However when you go into developer tools you can edit the class manually and the zoom function works as expected. When using these types of bookmarklets is there a limitation in that it will only work on what is available on initial load of the webpage and not what is dynamically shown after you click a button? I don't see any difference in the elements so I'm rather confused.
The odd thing is that in JS Fiddle and using the JS code function here in stackoverflow, using the HTML part of the troublesome element and the bookmarklet as is (the second one), it works fine.
So it seems to work from a JS point of view but not a bookmark button. Any help getting this working would be greatly appreciated.
Thanks
PS - keeping this example simple but my intention is once owrking to inject some CSS on the list which has a count number next to each line.
Run the snippet below and it will reduce the zoom as expected
(function(){ var style = document.createElement('style'), styleContent = document.createTextNode('.notifications-list--cMVsqVbKkaXV4SQ {zoom: 0.8!important;}'); style.appendChild(styleContent); var caput = document.getElementsByTagName('head'); caput[0].appendChild(style); })();
<div class="notifications-view--lC37J1MN7CXS1GR" data-testid="notificationsView"><div class="header--ulyJ0SomVeEE4j0"><div class="text--s39Y3jwGS6b6Iqq">Notifications</div><button data-testid="notifications-header-context-menu" aria-label="Notifications, more options" tabindex="0" role="button" id="a31f4e9e-d8ee-408c-a1a7-ce8f1faadb68" aria-haspopup="menu" aria-disabled="false" type="button" class="button--ZcJjbhoWNM0Sk5Y _24M7m _3fLjY"><svg class="_3t9Dk" width="24" height="24" focusable="false" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" data-icontype="EllipsisHorizontal"><path fill-rule="evenodd" clip-rule="evenodd" d="M5.675 13.975C6.73815 13.975 7.6 13.1131 7.6 12.05C7.6 10.9869 6.73815 10.125 5.675 10.125C4.61185 10.125 3.75 10.9869 3.75 12.05C3.75 13.1131 4.61185 13.975 5.675 13.975Z"></path><path fill-rule="evenodd" clip-rule="evenodd" d="M18.3249 13.975C19.3881 13.975 20.2499 13.1131 20.2499 12.05C20.2499 10.9869 19.3881 10.125 18.3249 10.125C17.2618 10.125 16.3999 10.9869 16.3999 12.05C16.3999 13.1131 17.2618 13.975 18.3249 13.975Z"></path><path fill-rule="evenodd" clip-rule="evenodd" d="M12.0002 13.975C13.0633 13.975 13.9252 13.1131 13.9252 12.05C13.9252 10.9869 13.0633 10.125 12.0002 10.125C10.937 10.125 10.0752 10.9869 10.0752 12.05C10.0752 13.1131 10.937 13.975 12.0002 13.975Z"></path><path d="M5.675 13.975C6.73815 13.975 7.6 13.1131 7.6 12.05C7.6 10.9869 6.73815 10.125 5.675 10.125C4.61185 10.125 3.75 10.9869 3.75 12.05C3.75 13.1131 4.61185 13.975 5.675 13.975Z"></path><path d="M18.325 13.975C19.3882 13.975 20.25 13.1131 20.25 12.05C20.25 10.9869 19.3882 10.125 18.325 10.125C17.2619 10.125 16.4 10.9869 16.4 12.05C16.4 13.1131 17.2619 13.975 18.325 13.975Z"></path><path d="M13.9248 12.05C13.9248 13.1131 13.063 13.975 11.9998 13.975C10.9367 13.975 10.0748 13.1131 10.0748 12.05C10.0748 10.9869 10.9367 10.125 11.9998 10.125C13.063 10.125 13.9248 10.9869 13.9248 12.05Z"></path></svg></button><div><button data-testid="close-feed-button" aria-label="Close notifications" type="button" class="_30V1q" aria-disabled="false"><svg class="_3t9Dk" width="24" height="24" focusable="false" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" data-icontype="Close" aria-hidden="true"><path d="M17.781 7.27855C18.0735 6.986 18.0729 6.51224 17.7797 6.22037C17.4865 5.9285 17.0116 5.92906 16.7191 6.22161L12 10.9407L7.28095 6.22161C6.9884 5.92906 6.51353 5.9285 6.22029 6.22037C5.92705 6.51224 5.9265 6.986 6.21905 7.27855L10.9406 12.0001L6.21905 16.7216C5.9265 17.0142 5.92705 17.4879 6.22029 17.7798C6.51353 18.0717 6.9884 18.0711 7.28095 17.7785L12 13.0595L16.7191 17.7785C17.0116 18.0711 17.4865 18.0717 17.7797 17.7798C18.0729 17.4879 18.0735 17.0142 17.781 16.7216L13.0594 12.0001L17.781 7.27855Z"></path></svg></button></div></div><div class="wrapper--dgb6f9MRKbnyZ1P"><ul data-testid="notifications-list" class="notifications-list--cMVsqVbKkaXV4SQ"><li data-testid="notification-container" class="notification-container--cmGv8ll9qjdnKcX" tabindex="-1"><div class="notification--vbNM7UCgkZrvGQ3 hover-inside--niik2J95IhaF11K" data-testid="notification" tabindex="0" aria-label="Widget ready for download (1 of 11)"><div class="header--PbUSpYtqAmDetOQ"><h3 class="header-text--TaaKMDumePzcO7v">Widget ready for download</h3><button aria-label="Widget ready for download, more options" data-prevent-card-click="true" data-testid="notification-context-menu-button" tabindex="0" role="button" id="0e8cb8ac-bd2f-44ee-ab38-fa77895b7e95" aria-haspopup="menu" type="button" class="context-menu--HFjqStz2y1JDY3z _30V1q" aria-disabled="false"><svg class="_3t9Dk" width="24" height="24" focusable="false" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" data-icontype="EllipsisHorizontal" aria-hidden="true"><path fill-rule="evenodd" clip-rule="evenodd" d="M5.675 13.975C6.73815 13.975 7.6 13.1131 7.6 12.05C7.6 10.9869 6.73815 10.125 5.675 10.125C4.61185 10.125 3.75 10.9869 3.75 12.05C3.75 13.1131 4.61185 13.975 5.675 13.975Z"></path><path fill-rule="evenodd" clip-rule="evenodd" d="M18.3249 13.975C19.3881 13.975 20.2499 13.1131 20.2499 12.05C20.2499 10.9869 19.3881 10.125 18.3249 10.125C17.2618 10.125 16.3999 10.9869 16.3999 12.05C16.3999 13.1131 17.2618 13.975 18.3249 13.975Z"></path><path fill-rule="evenodd" clip-rule="evenodd" d="M12.0002 13.975C13.0633 13.975 13.9252 13.1131 13.9252 12.05C13.9252 10.9869 13.0633 10.125 12.0002 10.125C10.937 10.125 10.0752 10.9869 10.0752 12.05C10.0752 13.1131 10.937 13.975 12.0002 13.975Z"></path><path d="M5.675 13.975C6.73815 13.975 7.6 13.1131 7.6 12.05C7.6 10.9869 6.73815 10.125 5.675 10.125C4.61185 10.125 3.75 10.9869 3.75 12.05C3.75 13.1131 4.61185 13.975 5.675 13.975Z"></path><path d="M18.325 13.975C19.3882 13.975 20.25 13.1131 20.25 12.05C20.25 10.9869 19.3882 10.125 18.325 10.125C17.2619 10.125 16.4 10.9869 16.4 12.05C16.4 13.1131 17.2619 13.975 18.325 13.975Z"></path><path d="M13.9248 12.05C13.9248 13.1131 13.063 13.975 11.9998 13.975C10.9367 13.975 10.0748 13.1131 10.0748 12.05C10.0748 10.9869 10.9367 10.125 11.9998 10.125C13.063 10.125 13.9248 10.9869 13.9248 12.05Z"></path></svg></button></div><div class="content--yAxWmleMR96C4gK"><div class="content-container--vIxELlAcP7WPxyY"><div class="hidden--ZBT5BZ9jdORbOjA"><span aria-hidden="true" width="0"><span><span>Your Widget export is now available. Select this</span><br><span>notification to download.</span></span><span style="position: fixed; visibility: hidden; top: 0px; left: 0px;">… show more</span></span></div><span>Your Widget export is now available. Select this
notification to download.</span></div></div><div class="source--g6JqykPjdKIaZhX"><span class="source-type--nqwcmKQ9T_yzxL6">Dashboards</span><span>19 hours ago</span></div><div class="container--SS6PDdT5VC1e4yJ actions-container--CN2v4IpQZ0ES5rh"><button tabindex="0" data-prevent-card-click="true" aria-disabled="false" type="button" class="action-button--PvQ0yPlS_UiHhYy _24M7m _3fLjY">See more</button></div></div></li><li data-testid="notification-container" class="notification-container--cmGv8ll9qjdnKcX" tabindex="-1"><div class="notification--vbNM7UCgkZrvGQ3" data-testid="notification" tabindex="-1" aria-label="Widget ready for download (2 of 11)"><div class="header--PbUSpYtqAmDetOQ"><h3 class="header-text--TaaKMDumePzcO7v">Widget ready for download</h3><button aria-label="Widget ready for download, more options" data-prevent-card-click="true" data-testid="notification-context-menu-button" tabindex="-1" role="button" id="1090fc99-2d92-4356-b456-bf47dc73f088" aria-haspopup="menu" type="button" class="context-menu--HFjqStz2y1JDY3z _30V1q" aria-disabled="false"><svg class="_3t9Dk" width="24" height="24" focusable="false" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" data-icontype="EllipsisHorizontal" aria-hidden="true"><path fill-rule="evenodd" clip-rule="evenodd" d="M5.675 13.975C6.73815 13.975 7.6 13.1131 7.6 12.05C7.6 10.9869 6.73815 10.125 5.675 10.125C4.61185 10.125 3.75 10.9869 3.75 12.05C3.75 13.1131 4.61185 13.975 5.675 13.975Z"></path><path fill-rule="evenodd" clip-rule="evenodd" d="M18.3249 13.975C19.3881 13.975 20.2499 13.1131 20.2499 12.05C20.2499 10.9869 19.3881 10.125 18.3249 10.125C17.2618 10.125 16.3999 10.9869 16.3999 12.05C16.3999 13.1131 17.2618 13.975 18.3249 13.975Z"></path><path fill-rule="evenodd" clip-rule="evenodd" d="M12.0002 13.975C13.0633 13.975 13.9252 13.1131 13.9252 12.05C13.9252 10.9869 13.0633 10.125 12.0002 10.125C10.937 10.125 10.0752 10.9869 10.0752 12.05C10.0752 13.1131 10.937 13.975 12.0002 13.975Z"></path><path d="M5.675 13.975C6.73815 13.975 7.6 13.1131 7.6 12.05C7.6 10.9869 6.73815 10.125 5.675 10.125C4.61185 10.125 3.75 10.9869 3.75 12.05C3.75 13.1131 4.61185 13.975 5.675 13.975Z"></path><path d="M18.325 13.975C19.3882 13.975 20.25 13.1131 20.25 12.05C20.25 10.9869 19.3882 10.125 18.325 10.125C17.2619 10.125 16.4 10.9869 16.4 12.05C16.4 13.1131 17.2619 13.975 18.325 13.975Z"></path><path d="M13.9248 12.05C13.9248 13.1131 13.063 13.975 11.9998 13.975C10.9367 13.975 10.0748 13.1131 10.0748 12.05C10.0748 10.9869 10.9367 10.125 11.9998 10.125C13.063 10.125 13.9248 10.9869 13.9248 12.05Z"></path></svg></button></div><div class="content--yAxWmleMR96C4gK"><div class="content-container--vIxELlAcP7WPxyY"><div class="hidden--ZBT5BZ9jdORbOjA"><span aria-hidden="true" width="0"><span><span>Your Widget export is now available. Select this</span><br><span>notification to download.</span></span><span style="position: fixed; visibility: hidden; top: 0px; left: 0px;">… show more</span></span></div><span>Your Widget export is now available. Select this
notification to download.</span></div></div><div class="source--g6JqykPjdKIaZhX"><span class="source-type--nqwcmKQ9T_yzxL6">Dashboards</span><span>19 hours ago</span></div><div class="container--SS6PDdT5VC1e4yJ actions-container--CN2v4IpQZ0ES5rh"><button tabindex="-1" data-prevent-card-click="true" aria-disabled="false" type="button" class="action-button--PvQ0yPlS_UiHhYy _24M7m _3fLjY">See more</button></div></div></li><li data-testid="notification-container" class="notification-container--cmGv8ll9qjdnKcX" tabindex="-1"><div class="notification--vbNM7UCgkZrvGQ3" data-testid="notification" tabindex="-1" aria-label="Widget ready for download (3 of 11)"><div class="header--PbUSpYtqAmDetOQ"><h3 class="header-text--TaaKMDumePzcO7v">Widget ready for download</h3><button aria-label="Widget ready for download, more options" data-prevent-card-click="true" data-testid="notification-context-menu-button" tabindex="-1" role="button" id="2ebbd579-597e-4e75-a012-c01d20599f4a" aria-haspopup="menu" type="button" class="context-menu--HFjqStz2y1JDY3z _30V1q" aria-disabled="false"><svg class="_3t9Dk" width="24" height="24" focusable="false" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" data-icontype="EllipsisHorizontal" aria-hidden="true"><path fill-rule="evenodd" clip-rule="evenodd" d="M5.675 13.975C6.73815 13.975 7.6 13.1131 7.6 12.05C7.6 10.9869 6.73815 10.125 5.675 10.125C4.61185 10.125 3.75 10.9869 3.75 12.05C3.75 13.1131 4.61185 13.975 5.675 13.975Z"></path><path fill-rule="evenodd" clip-rule="evenodd" d="M18.3249 13.975C19.3881 13.975 20.2499 13.1131 20.2499 12.05C20.2499 10.9869 19.3881 10.125 18.3249 10.125C17.2618 10.125 16.3999 10.9869 16.3999 12.05C16.3999 13.1131 17.2618 13.975 18.3249 13.975Z"></path><path fill-rule="evenodd" clip-rule="evenodd" d="M12.0002 13.975C13.0633 13.975 13.9252 13.1131 13.9252 12.05C13.9252 10.9869 13.0633 10.125 12.0002 10.125C10.937 10.125 10.0752 10.9869 10.0752 12.05C10.0752 13.1131 10.937 13.975 12.0002 13.975Z"></path><path d="M5.675 13.975C6.73815 13.975 7.6 13.1131 7.6 12.05C7.6 10.9869 6.73815 10.125 5.675 10.125C4.61185 10.125 3.75 10.9869 3.75 12.05C3.75 13.1131 4.61185 13.975 5.675 13.975Z"></path><path d="M18.325 13.975C19.3882 13.975 20.25 13.1131 20.25 12.05C20.25 10.9869 19.3882 10.125 18.325 10.125C17.2619 10.125 16.4 10.9869 16.4 12.05C16.4 13.1131 17.2619 13.975 18.325 13.975Z"></path><path d="M13.9248 12.05C13.9248 13.1131 13.063 13.975 11.9998 13.975C10.9367 13.975 10.0748 13.1131 10.0748 12.05C10.0748 10.9869 10.9367 10.125 11.9998 10.125C13.063 10.125 13.9248 10.9869 13.9248 12.05Z"></path></svg></button></div><div class="content--yAxWmleMR96C4gK"><div class="content-container--vIxELlAcP7WPxyY"><div class="hidden--ZBT5BZ9jdORbOjA"><span aria-hidden="true" width="0"><span><span>Your Widget export is now available. Select this</span><br><span>notification to download.</span></span><span style="position: fixed; visibility: hidden; top: 0px; left: 0px;">… show more</span></span></div><span>Your Widget export is now available. Select this
notification to download.</span></div></div><div class="source--g6JqykPjdKIaZhX"><span class="source-type--nqwcmKQ9T_yzxL6">Dashboards</span><span>19 hours ago</span></div><div class="container--SS6PDdT5VC1e4yJ actions-container--CN2v4IpQZ0ES5rh"><button tabindex="-1" data-prevent-card-click="true" aria-disabled="false" type="button" class="action-button--PvQ0yPlS_UiHhYy _24M7m _3fLjY">See more</button></div></div></li><li data-testid="notification-container" class="notification-container--cmGv8ll9qjdnKcX" tabindex="-1"><div class="notification--vbNM7UCgkZrvGQ3" data-testid="notification" tabindex="-1" aria-label="Widget ready for download (4 of 11)"><div class="header--PbUSpYtqAmDetOQ"><h3 class="header-text--TaaKMDumePzcO7v">Widget ready for download</h3><button aria-label="Widget ready for download, more options" data-prevent-card-click="true" data-testid="notification-context-menu-button" tabindex="-1" role="button" id="4d935aea-eb97-4628-a6c2-b21789d33cd8" aria-haspopup="menu" type="button" class="context-menu--HFjqStz2y1JDY3z _30V1q" aria-disabled="false"><svg class="_3t9Dk" width="24" height="24" focusable="false" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" data-icontype="EllipsisHorizontal" aria-hidden="true"><path fill-rule="evenodd" clip-rule="evenodd" d="M5.675 13.975C6.73815 13.975 7.6 13.1131 7.6 12.05C7.6 10.9869 6.73815 10.125 5.675 10.125C4.61185 10.125 3.75 10.9869 3.75 12.05C3.75 13.1131 4.61185 13.975 5.675 13.975Z"></path><path fill-rule="evenodd" clip-rule="evenodd" d="M18.3249 13.975C19.3881 13.975 20.2499 13.1131 20.2499 12.05C20.2499 10.9869 19.3881 10.125 18.3249 10.125C17.2618 10.125 16.3999 10.9869 16.3999 12.05C16.3999 13.1131 17.2618 13.975 18.3249 13.975Z"></path><path fill-rule="evenodd" clip-rule="evenodd" d="M12.0002 13.975C13.0633 13.975 13.9252 13.1131 13.9252 12.05C13.9252 10.9869 13.0633 10.125 12.0002 10.125C10.937 10.125 10.0752 10.9869 10.0752 12.05C10.0752 13.1131 10.937 13.975 12.0002 13.975Z"></path><path d="M5.675 13.975C6.73815 13.975 7.6 13.1131 7.6 12.05C7.6 10.9869 6.73815 10.125 5.675 10.125C4.61185 10.125 3.75 10.9869 3.75 12.05C3.75 13.1131 4.61185 13.975 5.675 13.975Z"></path><path d="M18.325 13.975C19.3882 13.975 20.25 13.1131 20.25 12.05C20.25 10.9869 19.3882 10.125 18.325 10.125C17.2619 10.125 16.4 10.9869 16.4 12.05C16.4 13.1131 17.2619 13.975 18.325 13.975Z"></path><path d="M13.9248 12.05C13.9248 13.1131 13.063 13.975 11.9998 13.975C10.9367 13.975 10.0748 13.1131 10.0748 12.05C10.0748 10.9869 10.9367 10.125 11.9998 10.125C13.063 10.125 13.9248 10.9869 13.9248 12.05Z"></path></svg></button></div><div class="content--yAxWmleMR96C4gK"><div class="content-container--vIxELlAcP7WPxyY"><div class="hidden--ZBT5BZ9jdORbOjA"><span aria-hidden="true" width="0"><span><span>Your Widget export is now available. Select this</span><br><span>notification to download.</span></span><span style="position: fixed; visibility: hidden; top: 0px; left: 0px;">… show more</span></span></div><span>Your Widget export is now available. Select this
notification to download.</span></div></div><div class="source--g6JqykPjdKIaZhX"><span class="source-type--nqwcmKQ9T_yzxL6">Dashboards</span><span>19 hours ago</span></div><div class="container--SS6PDdT5VC1e4yJ actions-container--CN2v4IpQZ0ES5rh"><button tabindex="-1" data-prevent-card-click="true" aria-disabled="false" type="button" class="action-button--PvQ0yPlS_UiHhYy _24M7m _3fLjY">See more</button></div></div></li><li data-testid="notification-container" class="notification-container--cmGv8ll9qjdnKcX" tabindex="-1"><div class="notification--vbNM7UCgkZrvGQ3" data-testid="notification" tabindex="-1" aria-label="Widget ready for download (5 of 11)"><div class="header--PbUSpYtqAmDetOQ"><h3 class="header-text--TaaKMDumePzcO7v">Widget ready for download</h3><button aria-label="Widget ready for download, more options" data-prevent-card-click="true" data-testid="notification-context-menu-button" tabindex="-1" role="button" id="0f98b373-8db7-48c3-b89e-238e9f33fea4" aria-haspopup="menu" type="button" class="context-menu--HFjqStz2y1JDY3z _30V1q" aria-disabled="false"><svg class="_3t9Dk" width="24" height="24" focusable="false" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" data-icontype="EllipsisHorizontal" aria-hidden="true"><path fill-rule="evenodd" clip-rule="evenodd" d="M5.675 13.975C6.73815 13.975 7.6 13.1131 7.6 12.05C7.6 10.9869 6.73815 10.125 5.675 10.125C4.61185 10.125 3.75 10.9869 3.75 12.05C3.75 13.1131 4.61185 13.975 5.675 13.975Z"></path><path fill-rule="evenodd" clip-rule="evenodd" d="M18.3249 13.975C19.3881 13.975 20.2499 13.1131 20.2499 12.05C20.2499 10.9869 19.3881 10.125 18.3249 10.125C17.2618 10.125 16.3999 10.9869 16.3999 12.05C16.3999 13.1131 17.2618 13.975 18.3249 13.975Z"></path><path fill-rule="evenodd" clip-rule="evenodd" d="M12.0002 13.975C13.0633 13.975 13.9252 13.1131 13.9252 12.05C13.9252 10.9869 13.0633 10.125 12.0002 10.125C10.937 10.125 10.0752 10.9869 10.0752 12.05C10.0752 13.1131 10.937 13.975 12.0002 13.975Z"></path><path d="M5.675 13.975C6.73815 13.975 7.6 13.1131 7.6 12.05C7.6 10.9869 6.73815 10.125 5.675 10.125C4.61185 10.125 3.75 10.9869 3.75 12.05C3.75 13.1131 4.61185 13.975 5.675 13.975Z"></path><path d="M18.325 13.975C19.3882 13.975 20.25 13.1131 20.25 12.05C20.25 10.9869 19.3882 10.125 18.325 10.125C17.2619 10.125 16.4 10.9869 16.4 12.05C16.4 13.1131 17.2619 13.975 18.325 13.975Z"></path><path d="M13.9248 12.05C13.9248 13.1131 13.063 13.975 11.9998 13.975C10.9367 13.975 10.0748 13.1131 10.0748 12.05C10.0748 10.9869 10.9367 10.125 11.9998 10.125C13.063 10.125 13.9248 10.9869 13.9248 12.05Z"></path></svg></button></div><div class="content--yAxWmleMR96C4gK"><div class="content-container--vIxELlAcP7WPxyY"><div class="hidden--ZBT5BZ9jdORbOjA"><span aria-hidden="true" width="0"><span><span>Your Widget export is now available. Select this</span><br><span>notification to download.</span></span><span style="position: fixed; visibility: hidden; top: 0px; left: 0px;">… show more</span></span></div><span>Your Widget export is now available. Select this
notification to download.</span></div></div><div class="source--g6JqykPjdKIaZhX"><span class="source-type--nqwcmKQ9T_yzxL6">Dashboards</span><span>19 hours ago</span></div><div class="container--SS6PDdT5VC1e4yJ actions-container--CN2v4IpQZ0ES5rh"><button tabindex="-1" data-prevent-card-click="true" aria-disabled="false" type="button" class="action-button--PvQ0yPlS_UiHhYy _24M7m _3fLjY">See more</button></div></div></li><li data-testid="notification-container" class="notification-container--cmGv8ll9qjdnKcX" tabindex="-1"><div class="notification--vbNM7UCgkZrvGQ3" data-testid="notification" tabindex="-1" aria-label="Widget ready for download (11 of 11)"><div class="header--PbUSpYtqAmDetOQ"><h3 class="header-text--TaaKMDumePzcO7v">Widget ready for download</h3><button aria-label="Widget ready for download, more options" data-prevent-card-click="true" data-testid="notification-context-menu-button" tabindex="-1" role="button" id="1cf96ab6-29f6-4800-999a-14774fb0a184" aria-haspopup="menu" type="button" class="context-menu--HFjqStz2y1JDY3z _30V1q" aria-disabled="false"><svg class="_3t9Dk" width="24" height="24" focusable="false" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" data-icontype="EllipsisHorizontal" aria-hidden="true"><path fill-rule="evenodd" clip-rule="evenodd" d="M5.675 13.975C6.73815 13.975 7.6 13.1131 7.6 12.05C7.6 10.9869 6.73815 10.125 5.675 10.125C4.61185 10.125 3.75 10.9869 3.75 12.05C3.75 13.1131 4.61185 13.975 5.675 13.975Z"></path><path fill-rule="evenodd" clip-rule="evenodd" d="M18.3249 13.975C19.3881 13.975 20.2499 13.1131 20.2499 12.05C20.2499 10.9869 19.3881 10.125 18.3249 10.125C17.2618 10.125 16.3999 10.9869 16.3999 12.05C16.3999 13.1131 17.2618 13.975 18.3249 13.975Z"></path><path fill-rule="evenodd" clip-rule="evenodd" d="M12.0002 13.975C13.0633 13.975 13.9252 13.1131 13.9252 12.05C13.9252 10.9869 13.0633 10.125 12.0002 10.125C10.937 10.125 10.0752 10.9869 10.0752 12.05C10.0752 13.1131 10.937 13.975 12.0002 13.975Z"></path><path d="M5.675 13.975C6.73815 13.975 7.6 13.1131 7.6 12.05C7.6 10.9869 6.73815 10.125 5.675 10.125C4.61185 10.125 3.75 10.9869 3.75 12.05C3.75 13.1131 4.61185 13.975 5.675 13.975Z"></path><path d="M18.325 13.975C19.3882 13.975 20.25 13.1131 20.25 12.05C20.25 10.9869 19.3882 10.125 18.325 10.125C17.2619 10.125 16.4 10.9869 16.4 12.05C16.4 13.1131 17.2619 13.975 18.325 13.975Z"></path><path d="M13.9248 12.05C13.9248 13.1131 13.063 13.975 11.9998 13.975C10.9367 13.975 10.0748 13.1131 10.0748 12.05C10.0748 10.9869 10.9367 10.125 11.9998 10.125C13.063 10.125 13.9248 10.9869 13.9248 12.05Z"></path></svg></button></div><div class="content--yAxWmleMR96C4gK"><div class="content-container--vIxELlAcP7WPxyY"><div class="hidden--ZBT5BZ9jdORbOjA"><span aria-hidden="true" width="0"><span><span>Your Widget export is now available. Select this</span><br><span>notification to download.</span></span><span style="position: fixed; visibility: hidden; top: 0px; left: 0px;">… show more</span></span></div><span>Your Widget export is now available. Select this
notification to download.</span></div></div><div class="source--g6JqykPjdKIaZhX"><span class="source-type--nqwcmKQ9T_yzxL6">Dashboards</span><span>19 hours ago</span></div><div class="container--SS6PDdT5VC1e4yJ actions-container--CN2v4IpQZ0ES5rh"><button tabindex="-1" data-prevent-card-click="true" aria-disabled="false" type="button" class="action-button--PvQ0yPlS_UiHhYy _24M7m _3fLjY">See more</button></div></div></li></ul></div></div>
Update - I've just looked at the HTML before and after clicking the button and is looks like that there are two and tags. When you click the button to show the list the second lot appears that the botttom. So I guess the javascript is looking for the first tag and looking within that. Is there a way to get round this?
A: found a solution. The tricky bit was to get the bookmarklet to see inside an iframe! see this link: How to pick element inside iframe using document.getElementById
so to manage the zoom in the iframe list this is the working example. In the link above I developed this further to make it a numbered list but the code is below:
javascript:(function(){ var style = document.createElement('style'), styleContent = document.createTextNode('.notifications-list--cMVsqVbKkaXV4SQ {zoom: 0.8!important;}'); style.appendChild(styleContent); var caput = document.getElementById('xm-feed-iframe').contentWindow.document.getElementsByTagName('head'); caput[0].appendChild(style); })();
to create a numbered list:
javascript:(function(){ var style = document.createElement('style'), styleContent = document.createTextNode('ul.notifications-list--cMVsqVbKkaXV4SQ li {zoom: 1.0!important; counter-increment: my-counter !important; } ul.notifications-list--cMVsqVbKkaXV4SQ li::before { content: counter(my-counter) \". \" !important; color: red !important; font-weight: bold !important; margin-left: 10px}'); style.appendChild(styleContent); var caput = document.getElementById('xm-feed-iframe').contentWindow.document.getElementsByTagName('head'); caput[0].appendChild(style); })();
Just for awareness, I've tried to do this using TamperMonkey but struggled and gave up upon finding a bookmarklet option (see this thread: Use Tampermonkey to add or append a number to each line of a list). I will loop back to this thread though and see if I can get it working (with the aid of stackoverflow users!).
resulting picture:
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75386435",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: No data to display GridView Asp Net DevExpress i try to make gridview in devexpress and its work but if i click next page, page get message No data to display.
i try to make from asp net, but same problem no data display.
How to fix that ? sorry im newbie for this.
This is my code for aspx :
<dx:BootstrapGridView runat="server" ID="GVcity" AutoGenerateColumns="False" >
<SettingsEditing Mode="Inline"></SettingsEditing>
<SettingsDataSecurity AllowEdit="true" AllowDelete="true" AllowInsert="true" />
<SettingsBehavior AllowSelectSingleRowOnly="true" AllowSelectByRowClick="true" />
<Columns>
<dx:BootstrapGridViewTextColumn FieldName="localRegionName" VisibleIndex="0" Caption="Regional"></dx:BootstrapGridViewTextColumn>
<dx:BootstrapGridViewTextColumn FieldName="localRegionCode" VisibleIndex="1" Caption="Code"></dx:BootstrapGridViewTextColumn>
<dx:BootstrapGridViewTextColumn FieldName="CityName" VisibleIndex="2" Caption="City"></dx:BootstrapGridViewTextColumn>
</Columns>
<Settings ShowFilterRow="true" ShowFilterRowMenu="true" />
</dx:BootstrapGridView>
and this is my code for cs :
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
this.BindGrid();
}
private void BindGrid()
{
string constr = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
using (MySqlConnection con = new MySqlConnection(constr))
{
using (MySqlCommand cmd = new MySqlCommand("SELECT tblcity.localRegionCode, tblcity.CityName, tbllocalregion.localRegionName FROM tblcity, tbllocalregion where tblcity.localRegionCode = tbllocalregion.localRegionCode"))
{
using (MySqlDataAdapter sda = new MySqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
GVcity.DataSource = dt;
GVcity.DataBind();
}
}
}
}
}
protected void OnPageIndexChanging(object sender, GridViewPageEventArgs e)
{
GVcity.PageIndex = e.NewPageIndex;
this.BindGrid();
}
i try to show data from mysql, and i dont know what i miss ???
A:
<dx:BootstrapGridView runat="server" ID="GVcity" AutoGenerateColumns="False" AllowPaging="True" OnPageIndexChanging="OnPageIndexChanging" OnPageIndexChanged="GVcity_PageIndexChanged">
<Columns>
<dx:BootstrapGridViewTextColumn FieldName="localRegionName" VisibleIndex="0" Caption="Regional"></dx:BootstrapGridViewTextColumn>
<dx:BootstrapGridViewTextColumn FieldName="localRegionCode" VisibleIndex="1" Caption="Code"></dx:BootstrapGridViewTextColumn>
<dx:BootstrapGridViewTextColumn FieldName="CityName" VisibleIndex="2" Caption="City"></dx:BootstrapGridViewTextColumn>
<dx:BootstrapGridViewCommandColumn ShowClearFilterButton="true" ShowApplyFilterButton="true" VisibleIndex="3" />
</Columns>
</dx:BootstrapGridView>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/68647382",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to iterate through a hash of hashes which contains an array of hashes in Perl? I am getting an output to a query in the format below. I need to get all the values for itemthree.
After trying a lot of different things I was able to extract only the first value. I couldn't figure out how to run it in a loop so as to get the values of all itemthree in the items element.
This is a dump of my data
$VAR1 = {
one => { msgSize => 103 },
two => {
items => [
{ itemOne => -1, itemthree => "AB_CD_EF", itemtwo => 0 },
{ itemOne => -1, itemthree => "XY_YZ_AB", itemtwo => 10 },
],
},
someOtherStuff => "abc",
}
A: Assuming you have a hash:
my @item3s;
for my $item (@{ $hash{two}{items} }){
push @item3s, $item->{itemthree};
}
print "$_\n" for @item3s;
If it's in fact a hash reference, change $hash{two}{items} to $hash->{two}{items}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/36580377",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Scons and dmd error: unrecognized file extension o I am trying to build a "hello world" D project with SConstruct and getting this output:
D:\projects\test>scons
scons: Reading SConscript files ...
scons: done reading SConscript files.
scons: warning: No version of Visual Studio compiler found - C/C++ compilers most likely not set correctly
File "C:\Python27\Scripts\scons.py", line 192, in <module>
scons: Building targets ...
dmd -I. -c -ofsrc\main.o src\main.d
dmd -ofhello.exe src\main.o
Error: unrecognized file extension o
scons: *** [hello.exe] Error 1
scons: building terminated because of errors.
Further I discovered that dmd compiler generates object files with the *.obj extension, rather then *.o and it is not able to handle with *.o files.
Is there a way to make SCons to use default output for dmd object files or to pass *.obj files extension for them? Or this is just a bug?
My SConstruct file:
import os
env = Environment(ENV=os.environ)
env.Object(target = 'hello', source = 'src/main.d')
My platform is Windows 7 x86_64.
dmd vervion is 2.064.2.
A: You need to tell SCons to use the D compiler, as I dont believe it does so by default. This does more than just load the compiler, it also sets the corresponding Construction Variables, which among other things sets the object file extension that you are asking about.
If you create your environment as follows, then the D compiler and related construction variables will be loaded.
env=Environment(tools=['default', 'dmd'])
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/21085786",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: EXIM4 configuration not working for only 1 machine. Here is the deal.
We have a printer and all our machines have debian in our office. I've configured the printer to send mails to the server (pc00) via its IP (which is static). I created a hubbed_hosts file that tells exim each machine, which IP it has. So my own personal mahcine is ariela@pc01 since I have pc01 and my username is ariela. This should get received in the mbox file. This works in every other machine except mine.
If I print the exim log I get:
ariela@pc01 R=hubbed_hosts T=remote_smtp defer (-44): SMTP error from remote mail server after RCPT TO:<ariela@pc01>: host 192.168.2.101 [192.168.2.101]: 451 Temporary local problem - please try later
It seems as if the problem is in my client machine, howerver I've runned the exim4-config with dpkg-reconfigure for my machine and It is the exact same things as the others that do work. I'm clueless.
Any help would be appreciated.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/24872880",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Integrating php in shell scripts for a cronjob? I would like to execute a cronjob for a routine task every X hours. The cronjob basically executes a shell script which in turn uses a WGET command to download files from a remote server. However, before I run this shell script I want the cronjob to execute a php script which will check whether the update's available (there's no point in wasting BW and downloading the same file over and over again) and if it is, it should pass on the update URL to the shell script which in turn uses the WGET command.
The cronjobs are set from the hosts Admin Panel. There is no other way around it. Being a shared hosting service, I am not allowed access to other functions on PHP which might do the task for me either.
Is this possible? I am Linux illiterate. I have installed a few RPM's on Fedora but that's about it. Please bear with me. Thanks!
A: Just pass --timestamping to your wget command.
Alternatively if you are more familiar with PHP's ways you can check this question for a usable method.
Use a curl HEAD request to get the file's headers and parse out the Last-Modified: header.
To use a php script as a regular command line executable use this as a starting point:
#!/bin/env php
<?php
echo "Hello World\n";
Save the file without the .php and tuck it somewhere that your server won't serve it.
Next, set the executable bit so that you can execute the script like a regular program
(u+x in the following command means grant the [u]ser e[x]ecute privileges for helloworld, and chmod is the command that unix variants use to set file permissions)
Omit the $ in the following sequence, as it represents the command prompt
$ chmod u+x helloworld
now you can execute your commandline script by calling it in the bash prompt:
$ ls
helloworld
$ ./helloworld
Hello World
$
From here you can get the full path of the executable script:
$ readlink -f helloworld
/home/SPI/helloworld
And now you can install the cronjob using the path to your executable script.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/12294951",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to check if field ID exists? I'm trying to write a code that will look if certain text field (and drop-down boxes) IDs exists.
I'm working with a page where, depending on what options are selected, the available boxes will be changed. For example, starting with the blank page, "form" and "comments" may appear or "Division" and "Comments" may be present.
I have all of the field ID names, and I know how to grab the value from them.
My question is: how would I write the If statement to see if it exists?
A: Assuming that you're still working on an HTA, something like this should work:
id = "Division"
If window.document.getElementById(id) Is Nothing Then
MsgBox "Element not found."
Else
MsgBox "Element found."
End If
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/24697000",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why do "page-break-inside:avoid' added element overlapping with other element after page break in PDF? I'm using 'page-break-inside:avoid' to break div to next page in PDF and its perfectly working but overlapping with other element when page break
HTML image
PDF image
i am using 'wkhtmltopdf' to convert html to PDF
<div style="page-break-inside:avoid;>
Portable Document Format (PDF) is a file format used to present and exchange
documents reliably
</div>
This is the div which is overlapping with other in PDF
I expect it will not overlap with other element when page break, but its overlapping
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/55321978",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Discover devices plugged in via ethernet cables? I have a controller which I hardwire an ethernet cable into. What I would like to do is find all devices connected via an ethernet cable or something similar and what those devices are. Eg:
>>> ???
[{
host: "192.168.1.4",
port: 23,
device: 'Galil DMC-4143'
}]
Is this possible to do via python?
A: Take a look at netifaces. It should help.
Here is example from their documentation:
>>> netifaces.interfaces()
['lo0', 'gif0', 'stf0', 'en0', 'en1', 'fw0']
>>> netifaces.ifaddresses('lo0')
{18: [{'addr': ''}], 2: [{'peer': '127.0.0.1', 'netmask': '255.0.0.0', 'addr': '127.0.0.1'}], 30: [{'peer': '::1', 'netmask': 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff', 'addr': '::1'}, {'peer': '', 'netmask': 'ffff:ffff:ffff:ffff::', 'addr': 'fe80::1%lo0'}]}
And it should work on OS X, Linux and Windows.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/32097551",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Loading Banner Ads in View Controller With SKScene Glitches Game? I'm currently developing a game where the objective is to survive as long as possible (i.e. Doodle Jump, Flappy Bird, Jetpack Joyride, etc) and there's no pause button. Anyways, I have a view controller that presents an SKScene. The moment I integrated banner ads, glitches began to occur.
For example, the game is good (fps is awesome) but as soon as banner ads low, it gets bad, the game drops to half the speed and its pretty hard to play. Obviously that's counter-productive.
I'm using a third party library called LARSAdController that alternates between iAds, Admobs, and Mopubs. Could it be something to do with threads? How can I call the ads on the main thread so that they don't glitch the game, or is that the opposite of what I should do? What's wrong here?
I have linked to the library, in case anyone is curious.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/23238238",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: javascript unbind dom events I'm working on a web framework and am trying to build XSS prevention into it. I have set it up so it will escape incoming data for storage in the database, but sometimes you want to save html that the user generates. I am trying to make a custom tag that will prevent any javascript from executing, here is my first hack at it:
<html>
<head>
<script type="text/javascript" src="/js/jquery.min.js"></script>
</head>
<body>
<preventjs>
<div id="user-content-area">
<!-- evil user content -->
<p onclick="alert('evil stuff');">I'm not evil, promise.</p>
<p onmouseover="alert('evil stuff');">Neither am I.</p>
<!-- end user content -->
</div>
</preventjs>
<script type="text/javascript">
// <preventjs> tags are supposed to prevent any javascript events
// but this does not unbined DOM events
$("preventjs").find("*").unbind();
</script>
</body>
</html>
I tried using jQuery to unbind everything, but it doesn't unbind events in the DOM, which is exactly what I'm trying to do. Is it possible to unbind all events for a DOM element?
A: You're problem is that you are doing this on the wrong end of things -- you should be filtering all user input of potentially hostile content when you receive it.
The first rule of thumb when doing this is "always whitelist, never blacklist". Rather than allowing any and all attributes in your user-generated HTML, simply keep a list of allowed attributes and strip away all others when you receive the HTML (possibly on the client side -- definitely on the server side.)
Oh, and HTML is not a regular language. You'll want to use an HTML parser, not a regular expression for this task.
A: .unbind will only unbind events attached using jQuery. You can get rid of inline event handler code by setting them to null, e.g.:
$("preventjs *").removeAttr("onclick").removeAttr("onmouseover");
Demo.
EDIT: Here's an evil solution, you can remove all attributes starting with "on":
$("preventjs *").each(function() {
var attribs = this.attributes;
var that = this;
$.each(attribs, function(i, attrib) {
if(attrib.name.indexOf("on") === 0) {
$(that).removeAttr(attrib.name);
}
});
});
Demo.
A: The problem is that you've inline handlers. unbind cannot remove inline handlers.
<p onclick="alert('evil stuff'...
^^^^
To remove inline handlers, use removeAttr
$("preventjs").find("*").removeAttr('onclick');
$("preventjs").find("*").removeAttr('onmouseover');
A: You can unbind the events individually:
$('p').each(function(){ this.onclick = this.onmouseover = undefined; });
If you want to unbind other events like mouseout you have to add them to that list:
$('p').each(function(){ this.onclick =
this.onmouseover =
this.onmouseout = undefined; });
Of course you'll want to use a selector other than $('p'), I just didn't want to put your other one because preventjs is not an HTML tag
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7196003",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Trying to create a theme for blogspot using WYSIWYG web builder, it runs on https://www.w3schools.com/ but not on blogger HTML theme editor <!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Page</title>
</head>
<body>
<div id="wb_Text1" style="position:absolute;left:458px;top:19px;width:156px;height:16px;z-index:1;">
<span style="color:#000000;font-family:Arial;font-size:13px;">This is My First Post</span></div>
<div id="wb_Text2" style="position:absolute;left:338px;top:60px;width:509px;height:32px;z-index:2;">
<span style="color:#000000;font-family:Arial;font-size:13px;">If i am looking at it<br>that means i
am able to create the theme correctly using webbuilder</span></div>
</body>
</html>
it runs perfectly
but fails to run on Blogger
What should i do?
A: Yes your code is perfect but, in blogger theme design with html you need to add "b:skin and b:section" inside that code.
And this is the sample code for blogger from your code :
Sorry if i wrong but thats all i know :)
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Page</title>
<b:skin>
<!-- Your CSS Code Here -->
</b:skin>
</head>
<body>
<b:section id='Unique-Id'>
<!-- Your section content -->
</b:section>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/63300323",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Makefile Linking Issues - Not Found Here is our current Makefile; the test file we're attempting to run includes "phase1.h".
TARGET = libphase1.a
CFLAGS = -Wall -g
TESTDIR = ./tests
TESTS = forkInvalidParmsTest
LIBS = -lphase1 -lusloss
$(TARGET): phase1.c
ar -r $@ phase1.c
$(TESTS): $(TARGET) $(TESTDIR)/$@
gcc $(CFLAGS) -c -I./usloss/build/include $(TARGET) $(TESTDIR)/$@.c
gcc $(LDFLAGS) -o forkInvalidParmsTest forkInvalidParmsTest.o $(LIBS) ./usloss/lib/linux/libusloss2.8.a
And here is the error we recieve after attempting to run the make forkInvalidParmsTest (after successfully generating the libphase1.a).
gcc -Wall -g -c -I./usloss/build/include libphase1.a ./tests/forkInvalidParmsTest.c
./tests/forkInvalidParmsTest.c:2:20: fatal error: phase1.h: No such file or directory
#include "phase1.h"
Any ideas?
UPDATE
The error has changed since adding -I. to the cflags:
make forkInvalidParmsTest 2 ↵ ✖ ✹master
gcc -Wall -g -I. -c -I./usloss/build/include libphase1.a ./tests/forkInvalidParmsTest.c
gcc: warning: libphase1.a: linker input file unused because linking not done
gcc -o forkInvalidParmsTest forkInvalidParmsTest.o -lphase1 -lusloss ./usloss/lib/linux/libusloss2.8.a
/usr/bin/ld: cannot find -lphase1
/usr/bin/ld: cannot find -lusloss
collect2: error: ld returned 1 exit status
make: *** [forkInvalidParmsTest] Error 1
.
├── children_list.c
├── children_list.h
├── children_list_test.c
├── forkInvalidParmsTest.c
├── forkInvalidParmsTest.o
├── kernel.c
├── libphase1.a
├── Makefile
├── phase1.c
├── phase1.h
├── queue.c
├── queue.h
├── tests
│ ├── children_list_test.c
│ └── forkInvalidParmsTest.c
├── usloss
│ ├──
│
└── usyscall.h
A: I shared you my example makefile(I can't type all of them in comment section, if not answer your question, pls let me know):
Here is my folder view:
./
├── debug
│ ├── debug.c
│ ├── debug.h
│ └── uart_print.c
├── driver
│ ├── driver.c
│ └── driver.h
├── include
│ └── common.h
├── Makefile
├── root
│ └── main.c
├── tc
│ ├── boot.c
│ ├── boot.h
│ ├── connect.c
│ ├── connect.h
│ ├── ffs.c
│ ├── ffs.h
│ ├── gpio.c
│ ├── gpio.h
│ ├── i2c.c
│ ├── i2c.h
│ ├── network.c
│ ├── network.h
│ ├── power.c
│ ├── power.h
│ ├── product.c
│ ├── product.h
│ ├── spi.c
│ └── spi.h
└── utility
├── utility.c
└── utility.h
Makefile1, did not generate lib
CC := gcc
LD := gcc
COLOR_ON := color
COLOR_OFF :=
PROGRAM = gSmokeTest
MAKE_DIR = $(PWD)
MODULES := debug driver utility tc root
SRC_DIR := $(addprefix $(MAKE_DIR)/,$(MODULES))
BUILD_DIR := $(MAKE_DIR)/output
SRC := $(foreach sdir,$(SRC_DIR),$(wildcard $(sdir)/*.c))
OBJ := $(patsubst %.c,%.o,$(SRC))
INCLUDES := $(addprefix -I,$(SRC_DIR))
INCLUDES += -I$(MAKE_DIR)/include
CFLAGS :=
CFLAGS += -Wall -O -ggdb -Wstrict-prototypes -Wno-pointer-sign #-Werror# -finstrument-functions -fdump-rtl-expand
#CFLAGS += -D_DEBUG_ -D_REENTRANT
TC_DEF :=
#TC_DEF += -D_POWER_SOS_
#TC_DEF += -D_PRODUCT_
#TC_DEF += -D_CONNECT_
TC_DEF += -D_SPI_
#TC_DEF += -D_I2C_
#TC_DEF += -D_POWER_
#TC_DEF += -D_BOOT_
#TC_DEF += -D_NETWORK_
vpath %.c $(SRC_DIR)
define make-goal
$1/%.o: %.c
@$(COLOR_ON)$(CC) $(TC_DEF) $(CFLAGS) $(INCLUDES) -c $$< -o $$@
@echo "Compile $$*.c"
endef
.PHONY: all checkdirs clean help flowchart
all: checkdirs $(BUILD_DIR)/$(PROGRAM)
$(BUILD_DIR)/$(PROGRAM): $(OBJ)
@$(LD) $^ -o $@
@echo "Generate $(PROGRAM)"
checkdirs: $(BUILD_DIR)
$(BUILD_DIR):
mkdir -p $@
clean:
rm -f $(OBJ) $(BUILD_DIR)/$(PROGRAM)
rm -rf $(BUILD_DIR)
help:
@echo "SRC DIR: $(SRC_DIR)"
@echo "Build DIR: $(BUILD_DIR)"
@echo "Source: $(SRC)"
@echo "Obj: $(OBJ)"
@echo "Includes: $(INCLUDES)"
flowchart:
@cflow2dot pdf ${SRC}
$(foreach sdir,$(SRC_DIR),$(eval $(call make-goal,$(sdir))))
Then, I setup another folder structure(make it simple, delete some files) and this time I generated lib:
./
├── debug
│ ├── debug.h
│ └──debug.mk
├── driver
│ ├── driver.h
│ ├── driver.mk
│ └── driver.o
├── include
│ └── common.h
├── libs
│ ├── libdebug.a
│ ├── libdrv.a
│ ├── libtc.a
│ └── libutility.a
├── make
│ ├── connect.d
│ ├── debug.d
│ ├── driver.d
│ ├── makefile
│ ├── network.d
│ ├── uart_print.d
│ └── utility.d
├── Makefile
├── prog
│ └── DEMO.map
├── root
│ ├── main.c
│ └── root.mk
├── rules.mk
├── tc
│ ├── connect.h
│ ├── network.h
│ └── tc.mk
├── tools.mk
└── utility
├── utility.h
└──utility.mk
Makefile2.1, top makefile:
CC := gcc
LD := gcc
MAKE_DIR = $(PWD)
MODULES := root tc utility driver debug
SRC_DIR := $(addprefix ${MAKE_DIR}/,$(MODULES))
#BUILD_DIR := $(addprefix ${MAKE_DIR}/,$(MODULES))
SRC := $(foreach sdir,$(SRC_DIR),$(wildcard $(sdir)/*.c))
#OBJ := $(patsubst ${SRC_DIR}/%.c,${BUILD_DIR}/%.o,$(SRC))
#OBJ := $(foreach sdir,$(SRC_DIR),$(patsubst $(sdir)/%.c,$(BUILD_DIR)/%.o,$(filter $(sdir)/%,$(SRC))))
OBJ := $(patsubst %.c,%.o,$(SRC))
INCLUDES := $(addprefix -I,$(SRC_DIR))
vpath %.c $(SRC_DIR)
#SRC_F = $(foreach sdir,$(SRC_DIR),$(filter $(SRC_DIR)/%,$(SRC)))
#OBJ_F = $(patsubst $(SRC_F)/%.c, $(BUILD_DIR)/%.o, $(SRC_F))
default:
@echo "SRC DIR: ${SRC_DIR}"
# @echo "Build DIR: ${BUILD_DIR}"
@echo "Source: ${SRC}"
@echo "Obj: ${OBJ}"
@echo "Includes: ${INCLUDES}"
# @echo "SRC_F: ${SRC_F}"
# @echo "OBJ_F: ${OBJ_F}"
define make-goal
$1/%.o: %.c
$(CC) $(INCLUDES) -c $$< -o $$@
endef
all: test
test: $(OBJ)
$(LD) $^ -o $@
#$(foreach sdir,$(SRC_DIR),$(eval $(call make-goal,$(sdir))))
#.PHONY: all checkdirs clean
#
#all: checkdirs build/test
#
#build/test: $(OBJ)
# $(LD) $^ -o $@
#
#
#checkdirs: $(BUILD_DIR)
#
#$(BUILD_DIR):
# @mkdir -p $@
#
clean:
rm -f $(OBJ) test
#
$(foreach sdir,$(SRC_DIR),$(eval $(call make-goal,$(sdir))))
#
and in each module, I have individual mk file, generated self lib:
#you just need change this MODULE name
MODULE = debug
LIB = $(LIB_DIR)/lib$(MODULE).a
SRCS = $(wildcard *.c)
OBJS = $(patsubst %.c, %.o, $(SRCS))
DEPS = $(patsubst %.c, %.d, $(SRCS))
$(LIB): $(OBJS)
@mkdir -p ../libs
@$(AR) cr $@ $^
@echo " Archive $(notdir $@)"
#$(OBJS): $(SRCS)
%.o: %.c
@$(CC) $(CFLAGS) -o $@ -c $<
@echo " CC $@"
# Automatic dependency magic:
#%.d: %.c
# $(CC) -MM $(CFLAGS) $@ > $<
#-include (SRCS:%.c=%.d)
.PHONY: clean
clean:
@$(RM) -f $(LIB) $(OBJS) $(DEPS)
@$(RM) -f *.expand
@echo " Remove Objects: $(OBJS)"
@echo " Remove Libraries: $(notdir $(LIB))"
@echo " Remove Dependency: $(DEPS)"
.PHONY: lint
lint:
$(LINT) $(INC_SRCH_PATH) $(SRCS)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/28424777",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Android Sha1 Hash username and password not hashing correctly I have a little problem with hashing a username and password.I need to find a way to hash the data with java as the server did with mysql.Here is a mysql hashing :
and I'm trying to get the same result in Java like this :
String userName_input = txtUserName.getText().toString();
String password_input = txtPassword.getText().toString();
try {
String userName_hash;
String password_hash;
String username = SHA1.Sha1Hash(userName_input);
String password = SHA1.Sha1Hash(password_input);
String username1 = SHA1.Sha1Hash((username.concat(password)).substring(20, 35));
String password1 = SHA1.Sha1Hash((password.concat(username)).substring(10, 35));
userName_hash = SHA1.Sha1Hash(username1.concat(username));
password_hash = SHA1.Sha1Hash(password1.concat(password));
//THE RESULT WHICH SERVER RETURNS AND THE RESULT OF JAVA HASH
UsernameHash (fcd86e8cc9fc7596f102de7b2b922e80c6e6fac9) : dd1ed59ebab6c420d750046539fcb60e7a1f9162
PasswordHash (b66936348bd0bd44fa44f5ca7dcceb909545e47f) : cde70a6416e061d00b4247b73c54c73fee7116ab
But the result that I get is not the same as in mysql hash.I'm using this SHA1 code :
public class SHA1 {
private static String convertToHex(byte[] data) {
StringBuffer buf = new StringBuffer();
for (int i = 0; i < data.length; i++) {
int halfbyte = (data[i] >>> 4) & 0x0F;
int two_halfs = 0;
do {
if ((0 <= halfbyte) && (halfbyte <= 9))
buf.append((char) ('0' + halfbyte));
else
buf.append((char) ('a' + (halfbyte - 10)));
halfbyte = data[i] & 0x0F;
} while(two_halfs++ < 1);
}
return buf.toString();
}
public static String Sha1Hash(String text)
throws NoSuchAlgorithmException, UnsupportedEncodingException {
MessageDigest md;
md = MessageDigest.getInstance("SHA-1");
byte[] sha1hash = new byte[40];
md.update(text.getBytes("iso-8859-1"), 0, text.length());
sha1hash = md.digest();
return convertToHex(sha1hash);
}
}
Any ideas/suggestions where is my mistake and how to get the hashing work exactly as in mysql?
Thanks in advance!!!
A: Depending on the source that you give this should work properly :
String hashUser = SHA1.Sha1Hash(username);
String hashPass = SHA1.Sha1Hash(password);
/**
* HASH USERNAME
* sha1(concat(sha1(substr(concat(sha1('username'),sha1('password')),20,35)),sha1('username')))
*/
String userPLUSpass = hashUser+hashPass;
String userConcat = "";
String subStringUserHash = userConcat.concat(userPLUSpass);
String userHashSubStr = SHA1.Sha1Hash(subStringUserHash.substring(19, 54));
String luser = userHashSubStr+hashUser;
String uConcat = "";
lastUser = SHA1.Sha1Hash(uConcat.concat(luser));
/**
* HASH PASSWORD
* sha1(concat(sha1(substr(concat(sha1('password'),sha1('username')),10,35)),sha1('password')))
*/
String passPLUSuser = hashPass+hashUser;
String passConcat = "";
String subStringPassHash = passConcat.concat(passPLUSuser);
String passHashSubStr = SHA1.Sha1Hash(subStringPassHash.substring(9, 44));
String lpass = passHashSubStr+hashPass;
String pConcat = "";
lastPass = SHA1.Sha1Hash(pConcat.concat(lpass));
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7571485",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: ASP .Net MVC/WebApi with Angular 4/5 Visual Studio Template I'm using Visual Studio 2017 Community Edition and looking for an Angular with Web Api 2.0 (or MVC with Web Api) Template but not able to find one. When I try to google I get only links to Asp .Net Core related topics, no mention of identical template for older versions of ASP .Net. By older I mean any other than Core.
When I try to change the version of .Net to .Net Framework I still see only .Net Core templates:
Only available ASP .Net versions are Core.
There exists a template for single page application but it does not create an angular application:
If to look online, there is a template for Angular2 though:
But:
*
*It is not an official microsoft template
*I will need to upgrade the Angular version
*It has no generated api controllers with authorization
*No OWIN support
*No file nesting for component files in solution explorer
*All links to documentation or git hub are broken and response with 404
It's a nice and in some cases usefull template but still a lot of thing that would be nice to have in a template I will need to do manually, basically from scratch. Does there exist some powerful and rich template for Angular5 and Web Api 2.0 like there is for .NET Core?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/48950658",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to integrate google analytics for calculate visitor to my specific item i am developing an ecommerce site. i want to calculate how many time my item viewed, calculate new visitors, total visitors number of click to purchase. And detail of visitor.
i have read documentation of google analytics and have search on many sites. but there is no easier and step by step guide available to calculate these things kindly guide me.
A: Google Analytics offers a feature called "event tracking". You can use this feature to track clicks on specific HTML Dom Elements (Buttons, Links, Images etc.) and generate analytics data for your website.
Read more about GA Event Tracking
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/60956551",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Can't scrape customized property links from zillow using requests I'm trying to parse different property links which are populated when I select two dropdowns from zillow. When I'm done choosing the options, I can see the results in json in dev tools. However, when I do the same using the script below, I get some weird text.
Manual actions:
*
*Navigated to that site
*Chose options from first dropdown
*Chose options from second dropdown
This is how I've tried to automate:
import json
import requests
from pprint import pprint
link = 'https://www.zillow.com/search/GetSearchPageState.htm?'
params = {
'searchQueryState': {"pagination":{},"usersSearchTerm":"Vista, CA","mapBounds":{"west":-117.44051346728516,"east":-116.99488053271484,"south":33.126944633035116,"north":33.27919773006566},"regionSelection":[{"regionId":41517,"regionType":6}],"isMapVisible":True,"filterState":{"doz":{"value":"6m"},"isForSaleByAgent":{"value":False},"isForSaleByOwner":{"value":False},"isNewConstruction":{"value":False},"isForSaleForeclosure":{"value":False},"isComingSoon":{"value":False},"isAuction":{"value":False},"isPreMarketForeclosure":{"value":False},"isPreMarketPreForeclosure":{"value":False},"isRecentlySold":{"value":True},"isAllHomes":{"value":True},"hasPool":{"value":True},"hasAirConditioning":{"value":True},"isApartmentOrCondo":{"value":False}},"isListVisible":True,"mapZoom":11},
'wants': {"cat1":["listResults","mapResults"]},
'requestId': 2
}
with requests.Session() as s:
s.headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36'
res = s.get(link,params=json.dumps(params))
pprint(res.content)
This is the output it produces:
b'<!-- This page outputs JSON instead of anything written here. -->'
How can I parse customized property links from zillow using requests?
A: You have to encode the query string as it appears in the request URL.
To do so you need:
urllib.parse.urlencode()
Here's a working example:
import json
import urllib.parse
import requests
link = 'https://www.zillow.com/search/GetSearchPageState.htm?'
params = {
'searchQueryState': {
"pagination": {},
"usersSearchTerm": "Vista, CA",
"mapBounds": {
"west": -117.44051346728516,
"east": -116.99488053271484,
"south": 33.126944633035116,
"north": 33.27919773006566
},
"regionSelection": [{"regionId": 41517, "regionType": 6}],
"isMapVisible": True,
"filterState": {
"doz": {"value": "6m"}, "isForSaleByAgent": {"value": False},
"isForSaleByOwner": {"value": False}, "isNewConstruction": {"value": False},
"isForSaleForeclosure": {"value": False}, "isComingSoon": {"value": False},
"isAuction": {"value": False}, "isPreMarketForeclosure": {"value": False},
"isPreMarketPreForeclosure": {"value": False},
"isRecentlySold": {"value": True}, "isAllHomes": {"value": True},
"hasPool": {"value": True}, "hasAirConditioning": {"value": True},
"isApartmentOrCondo": {"value": False}
},
"isListVisible": True,
"mapZoom": 11
},
'wants': {"cat1": ["listResults"]},
'requestId': 2
}
with requests.Session() as s:
s.headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36'
s.headers["x-requested-session"] = "BE6D8DA620E60010D84B55EB18DC9DC8"
s.headers["cookie"] = f"JSESSIONID={s.headers['x-requested-session']}"
data = json.dumps(
json.loads(s.get(f"{link}{urllib.parse.urlencode(params)}").content),
indent=2
)
print(data)
Output:
{
"user": {
"isLoggedIn": false,
"hasHousingConnectorPermission": false,
"savedSearchCount": 0,
"savedHomesCount": 0,
"personalizedSearchGaDataTag": null,
"personalizedSearchTraceID": "607a9ecb5aabe489c361c1d91f368b37",
"searchPageRenderedCount": 0,
"guid": "33b7add3-bfd3-4d85-a88a-d9d99256d2a2",
"zuid": "",
"isBot": false,
"userSpecializedSEORegion": false
},
"mapState": {
"customRegionPolygonWkt": null,
"schoolPolygonWkt": null,
"isCurrentLocationSearch": false,
"userPosition": {
"lat": null,
"lon": null
},
"regionBounds": {
"north": 33.275284,
"east": -117.145153,
"south": 33.130865,
"west": -117.290241
}
},
and much much more ...
Note: Go easy on that site as they have a pretty sensitive anti-bot measures and if you keep requesting the data too quickly, they'll throw a CAPTCHA at you.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/67130173",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to italicise part of correlation coefficient annotation in ggplot2 I cannot figure out how the make the letter "R" in the annotate() function below italicised on my plot. I've tried adding in expression() before paste(), and using italic(), but that then pastes the section starting "round(cor..." as text, rather than the result of the calculation.
ggplot(subset(crossnat, !is.na(homicide) & !is.na(gdppercapita)),
aes(x = gdppercapita, y = homicide)) +
geom_point(alpha = 0.4) +
ggtitle("Figure 3: Relationship between GDP per capita ($) and homicide rate") +
labs(subtitle = "n = 177 (17 countries removed as either GDP per capita or homicide data unavailable",
x = "GDP per capita ($)",
y = "Number of homicides in 2013 (per 100k of population)") +
scale_y_continuous(breaks = c(0,15,30,45,60,75,90)) +
geom_smooth(method = "loess",
formula = y ~ x,
colour = "red",
size = 0.5) +
annotate(x = 50000, y = 75,
label = paste("R = ", round(cor(crossnat$gdppercapita, crossnat$homicide, use = "complete.obs"),3)),
geom = "text", size = 4)
Thanks
EDIT - the suggested possible duplicate does not seem to work for me. I think this might be due to the calculation of the correlation being embedded inside the annotate()?
A: This type of formatting is tricky. You need to pay attention to the white spaces when the parse=TRUE is used. To format the text you need proceed in two steps of pasting. Let's create a simple reproducible example:
ggData <- data.frame(x=rnorm(100), y=rnorm(100) )
I recommend you to store the text AND the correlation value R outside of the ggplot function for readability of the code:
textPart1 <- "paste(italic(R), \" =\")" # check the ?annotate example for \" =\"
corVal <- round(cor(ggData$x, ggData$y, use = "complete.obs"), 3)
The trick is to paste the two variables with the sep="~" instead of the white space.
ggplot(ggData, aes(x = x, y = y) ) +
geom_point(alpha = 0.4) +
annotate("text", x = 2, y = 1.5,
label = paste(textPart1, corVal, sep="~"), size = 4 , parse=TRUE)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/52661393",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: UITapGestureRecognizer partially works on UIImageView inside UITableViewCell I have a table view. Some cells could have images, and I add those images to cells through UIImageView. Those images have react and open new view controller if a user taps it (not a cell). Images are of different size.
I added UITapGestureRecognizer to UIImageView, but it acts weird. I thought the whole area of imageView will respond to gestures, but I see only some smaller areas, and on all images this area is located differently.
Here is the code from cell init:
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
UIImageView *thumbnailImageView = [[[UIImageView alloc] init] autorelease];
thumbnailImageView.tag = CELL_THUMBNAIL_TAG;
thumbnailImageView.userInteractionEnabled = YES;
[self.contentView addSubview:thumbnailImageView];
UITapGestureRecognizer *pictureTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handlePictureTap:)];
[thumbnailImageView addGestureRecognizer:pictureTap];
[pictureTap release];
All the cells with images are displayed correctly in different orientation
Location of images and texts inside cells is done through layoutSubviews method:
- (void)layoutSubviews
if (thumbnail) {
CGRect thumbnailFrame = CGRectMake(contentOrigin.x, contentOrigin.y, thumbnail.size.width, thumbnail.size.height);
thumbnailImageView = (UIImageView *)[self.contentView viewWithTag:CELL_THUMBNAIL_TAG];
thumbnailImageView.frame = thumbnailFrame;
thumbnailImageView.image = thumbnail;
}
In tableView: cellForRowAtIndexPath: method I just pass all the required data to the cell, so the whole configuration is going in layoutSubviews
Could you please help me identify why the area that reacts on tap gesture is defined randomly and strange for all imageViews, despite that all content is displayed correctly?
A: After long list of ideas I finally found the reason of that strange behavior. It might help anybody with similar problem.
In this project I subclass UITableViewCell. Since all cells could be of different size, I provide correct height in tableView: heightForRowAtIndexPath: method.
HOWEVER, in my custom cell init method I didn't set proper autoresizing mask. That lead to UITableViewCellContenView view had constant height of 44pt. And this view is a superview for all cell content.
I don't know why despite of it all cell content was displayed correctly and with proper sizes, but all gestures reached imageView only within this 44pt height area.
Setting
self.contentView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
in custom UITableViewCell init method I solved this issue.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/9801231",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: SQL query to fetch all Auctions for whom a particular user has not submitted a Bid I am working on a project where I want to fetch from my postgres database all the auctions where a particular user has not submitted any bid for the auctions. I am trying to write the query for this.
The schema is as follows -
Auction Table
auction_id (PK)
auction_data
A1
a1_data
A2
a2_data
A3
a3_data
Bids Table
bid_id (PK)
auction_id (FK)
user_id
bid_price
B1
A1
U1
P1
B2
A2
U1
P2
B3
A1
U2
P3
B4
A2
U2
P4
B5
A3
U2
P5
The constraint is that for each auction any user can submit only a single bid.
So ideally the query should return Auction id as A3 if the input to it is find auctions where user U1 has not submitted a bid.
How to accomplish this? I know we can do multiple joins to find the result but I am looking for something a little straight forward. Not sure if there is any in-built function to make the query a little less complex. I don't have much experience so struggling to come up with a solution.
A: SELECT A.AUCTION_ID
FROM AUCTION_TABLE A
EXCEPT
SELECT B.AUCTION_ID
FROM BIDS_TABLE B WHERE B.USER_ID='U1'
Could you please try this
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72992390",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Extending SQLiteStatement, is there a tested wrapper class available? The class cannot subclass the final class SQLiteStatement cannot be extended.
That together with the fact that java does not support extension methods brings me here.
There does not seem to be any smooth way to do extensions for that class.
I do not have the time to write and test a class that wraps the class SQLiteStatement. I'm thus asking if there is a trusted wrapper class out there for this?
What I've done right now is a class with methods that I send the reference to SQLiteStatement and the values I want to add to the SQLiteStatement but that is not as smooth as extending the class.
A: In lack of better alternatives or if none else answers my question this will be my solution.
This is the start of a class with the methods this far to avoid repeated null check statements etc.
public class SQLiteStatementExtension {
public static void BindNullable(SQLiteStatement statement, int index, String value)
{
if(value == null){
statement.bindNull(index);
} else {
statement.bindString(index, value);
}
}
public static void BindNullable(SQLiteStatement statement, int index, Calendar value)
{
if(value == null){
statement.bindNull(index);
} else {
statement.bindLong(index, value.getTimeInMillis());
}
}
public static void BindNullable(SQLiteStatement statement, int index, byte[] value)
{
if(value == null){
statement.bindNull(index);
} else {
statement.bindBlob(index, value);
}
}
public static void Bind(SQLiteStatement satement, int index, boolean value) {
satement.bindLong(index, value ? 1 : 0);
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/21283883",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Image upload with Knockout and webapi c# I am trying to upload an image using Knokout JS and web api. This my code
<div class="row">
<div class="col-sm-4">
<h3>Send Feedback</h3>
<form data-bind="submit: sendFeedback">
<div class="form-group">
<label>Feedback</label>
<textarea class="form-control" data-bind="value: feedbackText"></textarea>
</div>
<div class="form-group">
<label>Version Id</label>
<input class="form-control" type="text" data-bind="value: versionId" />
</div>
<div class="form-group">
<label>Image</label>
<input class="form-control" type="file"
data-bind="file: {data: fileInput, name: fileName, reader: someReader}" />
</div>
<div class="form-group">
<button type="submit" class="btn btn-default">Submit</button>
</div>
</form>
</div>
I am using this custom binding
https://github.com/TooManyBees/knockoutjs-file-binding
Then in my script code I am doing this
self.sendFeedback = function () {
self.result('');
var feedBackData = {
versionId: self.versionId(),
text: self.feedbackText(),
screenShot: self.fileInput
};
$.ajax({
type: 'POST',
url: apiUrl + '/Feedback/Add',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(feedBackData)
}).done(function (data) {
self.result("Done!");
}).fail(showError);
}
I am uncertain about the server part of the code. I have written this so far
public void Add(HttpPostedFileBase screenShot, String versionId, String text)
{
String imgId = null;
int count = HttpContext.Current.Request.Files.Count;
if (screenShot != null && screenShot.ContentLength > 0)
{
Images img = Images.Create().Save();
imgId = img.Id;
BlobHelper.PutFile(imgId, screenShot.InputStream);
}
Feedback.Create(versionId, text, imgId).Save();
}
Any thoughts on how to do this?
A: The fileInput contains the base64-encoded file data. It's a string, so HttpPostedFileBase would not work.
Change the form HTML:
<input class="form-control" type="file"
data-bind="file: {data: fileInput}" />
Change the viewmodel code as follows:
// store file data here
self.fileInput = ko.observable(); // is this present already?
var feedBackData = {
versionId: self.versionId(),
text: self.feedbackText(),
screenShot: self.fileInput()
};
$.ajax({
type: 'POST',
url: apiUrl + '/Feedback/Add',
contentType: 'application/json; charset=utf-8',
data: ko.toJSON(feedBackData)
}).done(function (data) {
self.result("Done!");
}).fail(showError);
If the controller method is in an API controller it should accept JSON and the model binder will extract the values:
public void Add(String screenShot, String versionId, String text)
{
String imgId = null;
if(!String.IsNullOrEmpty(screenShot))
{
Byte[] data = Convert.FromBase64String(screenShot);
// rest of code omitted
Sorry have not been able to test this for syntax etc. but should put you on the right track.
A good tip for debugging Knockout pages is to use this line while developing so you can see what is happening in your viewModel:
<pre data-bind="text: ko.toJSON($data, null, 2)"></pre>
See http://www.knockmeout.net/2013/06/knockout-debugging-strategies-plugin.html for more help.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/34809513",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: batch delete certain lines of paragraphs in .srt files I have .srt files that consist out of paragraphs with the same pattern.
the amount of paragraphs in each document is different.
I wanna keep the number of the paragraph, keep the time in the second line, and then basically only keep the "BAROMETER:" and the number next to that.
the last line can also go out.
Every help is much appreciated!
I am running a mac and would like to do it in automator or any other program that
this is how the paragraphs look like now
1
00:00:01,000 --> 00:00:02,000
HOME(11.6488,51.7185) 2016.06.02 13:19:11
GPS(11.6488,51.7185,18) BAROMETER:3.5
ISO:100 Shutter:400 A:63 AA:63 EV: Fnum:6.3
2
00:00:02,000 --> 00:00:03,000
HOME(11.6488,51.7185) 2016.06.02 13:19:12
GPS(11.6488,51.7185,17) BAROMETER:3.5
ISO:100 Shutter:400 A:63 AA:63 EV: Fnum:6.3
and this is how i would like them to look like afterwards
3
00:00:03,000 --> 00:00:04,000
BAROMETER:4.3
4
00:00:04,000 --> 00:00:05,000
BAROMETER:5.3
A: grep -oE "^[0-9].*$|^$|BAROMETER.*$" input-file
EDIT: Based on your comment it seems that you want to do it for every file in a folder and replace in-place. In this case it is better to use find and sed, e.g.
find "$@" -type f -name "*.srt" -exec \
sed -i.bak '/^[0-9]\|BAROMETER\|^$/!d;s/^.*\(BAROMETER\)/\1/' {} \;
I have never used Automator for anything really, but there is quite detailed examples in the documentation.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/37730902",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Find the number of players cannot win the game? We are given n players, each player has 3 values assigned A, B and C.
A player i cannot win if there exists another player j with all 3 values A[j] > A[i], B[j] > B[i] and C[j] > C[i]. We are asked to find number of players cannot win.
I tried this problem using brute force, which is a linear search over players array. But it's showing TLE.
For each player i, I am traversing the complete array to find if there exists any other player j for which the above condition holds true.
Code :
int count_players_cannot_win(vector<vector<int>> values) {
int c = 0;
int n = values.size();
for(int i = 0; i < n; i++) {
for(int j = 0; j!= i && j < n; j++) {
if(values[i][0] < values[j][0] && values[i][1] < values[j][1] && values[i][2] < values[j][2]) {
c += 1;
break;
}
}
}
return c;
}
And this approach is O(n^2), as for every player we are traversing the complete array. Thus it is giving the TLE.
Sample testcase :
Sample Input
3(number of players)
A B C
1 4 2
4 3 2
2 5 3
Sample Output :
1
Explanation :
Only player1 cannot win as there exists player3 whose all 3 values(A, B and C) are greater than that of player1.
Contraints :
n(number of players) <= 10^5
What would be optimal way to solve this problem?
Solution:
int n;
const int N = 4e5 + 1;
int tree[N];
int get_max(int i, int l, int r, int L) { // range query of max in range v[B+1: n]
if(r < L || n <= l)
return numeric_limits<int>::min();
else if(L <= l)
return tree[i];
int m = (l + r)/2;
return max(get_max(2*i+1, l, m, L), get_max(2*i+2, m+1, r, L));
}
void update(int i, int l, int r, int on, int v) { // point update in tree[on]
if(r < on || on < l)
return;
else if(l == r) {
tree[i] = max(tree[i], v);
return;
}
int m = (l + r)/2;
update(2*i+1, l, m, on, v);
update(2*i+2, m + 1, r, on, v);
tree[i] = max(tree[2*i+1], tree[2*i+2]);
}
bool comp(vector<int> a, vector<int> b) {
return a[0] != b[0] ? a[0] > b[0] : a[1] < b[1];
}
int solve(vector<vector<int>> &v) {
n = v.size();
vector<int> b(n, 0); // reduce the scale of range from [0,10^9] to [0,10^5]
for(int i = 0; i < n; i++) {
b[i] = v[i][1];
}
for(int i = 0; i < n; i++) {
cin >> v[i][2];
}
// sort on 0th col in reverse order
sort(v.begin(), v.end(), comp);
sort(b.begin(), b.end());
int ans = 0;
for(int i = 0; i < n;) {
int j = i;
while(j < n && v[j][0] == v[i][0]) {
int B = v[j][1];
int pos = lower_bound(b.begin(), b.end(), B) - b.begin(); // position of B in b[]
int mx = get_max(0, 0, n - 1, pos + 1);
if(mx > v[j][2])
ans += 1;
j++;
}
while(i < j) {
int B = v[i][1];
int C = v[i][2];
int pos = lower_bound(b.begin(), b.end(), B) - b.begin(); // position of B in b[]
update(0, 0, n - 1, pos, C);
i++;
}
}
return ans;
}
This solution uses segment tree, and thus solves the problem in
time O(n*log(n)) and space O(n).
Approach is explained in the accepted answer by @Primusa.
A: First lets assume that our input comes in the form of a list of tuples T = [(A[0], B[0], C[0]), (A[1], B[1], C[1]) ... (A[N - 1], B[N - 1], C[N - 1])]
The first observation we can make is that we can sort on T[0] (in reverse order). Then for each tuple (a, b, c), to determine if it cannot win, we ask if we've already seen a tuple (d, e, f) such that e > b && f > c. We don't need to check the first element because we are given that d > a* since T is sorted in reverse.
Okay, so now how do we check this second criteria?
We can reframe it like so: out of all tuples (d, e, f), that we've already seen with e > b, what is the maximum value of f? If the max value is greater than c, then we know that this tuple cannot win.
To handle this part we can use a segment tree with max updates and max range queries. When we encounter a tuple (d, e, f), we can set tree[e] = max(tree[e], f). tree[i] will represent the third element with i being the second element.
To answer a query like "what is the maximum value of f such that e > b", we do max(tree[b+1...]), to get the largest third element over a range of possible second elements.
Since we are only doing suffix queries, you can get away with using a modified fenwick tree, but it is easier to explain with a segment tree.
This will give us an O(NlogN) solution, for sorting T and doing O(logN) work with our segment tree for every tuple.
*Note: this should actually be d >= a. However it is easier to explain the algorithm when we pretend everything is unique. The only modification you need to make to accommodate duplicate values of the first element is to process your queries and updates in buckets of tuples of the same value. This means that we will perform our check for all tuples with the same first element, and only then do we update tree[e] = max(tree[e], f) for all of those tuples we performed the check on. This ensures that no tuple with the same first value has updated the tree already when another tuple is querying the tree.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/65057363",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: External page back to local app in PhoneGap I have read through numerous posts and articles regarding this, but still can't find a good solution. I am trying to:
*
*Start app on a local page
*Go to an external page triggered using window.location.href after an AJAX event.
*Return to the local app from external page when a close button is clicked using window.location.href = "appURL://".
I have the URL_SCHEME plugin setup with my custom url (appURL://). That URL works from the browser directly, but not within the app. It seems to just ignore it and move on to other code.
Now I have read about InAppBrowser and ChildBrowser. I tried InAppBrowser, but it doesn't keep the settings I need like the appendUserAgent and AllowInlineMediaPlayback. I know I can set the latter, but didn't see a way for the former. I also want to make sure it stays in landscape only and don't want to have two different places for configuration settings. Even without that, I still couldn't get it to link back to the app.
Is there not a way to link back to the local app from an external site without a browser plugin or if not, how do I make it work well using a browser plugin? I have full control over the external site.
The main device I am testing with is an iPhone 6 on iOS 9.2.1 and I am using PhoneGap Build.
A: I don't think its possible to do what I asked at this point, but if you keep it local, you can do something similar and have more flexibility. The best thing to do is load the contents you need inside the local page. In my case, I need the whole site, including all things in the head, so I used an iframe. Keep in mind that the iframe won't be able to access the window above due to different domains, so what I did was setup an onload event in the local page to check the iframe changes. When it had the URL I was looking for, I would handle differently and load a different page in the local app.
Here is an example. I am using jQuery with this and setup so that the URL's to check for are /app/LOCALPAGEPATH. So if the URL found is /app/index.html it would go to index.html.
$('iframe').load(function(){
var url = $(this).get(0).contentWindow.location.href;
var appIndex = url.indexOf('/app/');
if (appIndex > -1) {
var appURL = url.substr(appIndex+5);
window.location.href = appURL;
}
});
A: You can make your close button execute
window.history.go(-(window.history.length - 1));
That should go back to the local index.html as it was the first page it loaded.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/35782286",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: c# websocket console application on windows server 2012 r2 I have a c# websocket code that will do the handshake and after successful, take the input from the client and return it back to the client again.
The code is working on localhost:8080 on my local machine.
I have an azure VM running Windows Server 2012 R2. I have created an Inbound Firewall Rule to allow connections on port 8080 on the server, and in azure. My questions are:
*
*Is it possible to run(or host) c# console application on my server?
*If yes, is there anything I am missing besides creating inbound firewall rule?
*If no, what are the other options (windows service maybe)?
Right now, when I run the console app and run the client on my server, onOpen() function gets fired and the console app gets the message. However, the message is not the first GET request for websocket connection. Its something else, it gibberish. Hence I dont get the key and nothing works.
What am I doing wrong or missing? Please help!
Also, I have to be able to send message from the client to the server via websocket from the outside world.
Thank you
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/38156837",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Spring Boot in Intellij won't load image I'm just starting to learn Spring reading "Spring In Action" and I cannot get my image to load on anything other than port 8080 (where tomcat launches). This would be fine normally, but I have to keep restarting the program to load any changes to my webpage.
Intellij tries to run my web program on port 63342, but no images load, only text. I believe this is an issue with Thymeleaf. I tried pointing tomcat to port 63342 but it won't load (port is in use?)
I would like it to where I can get the reload on save feature to work, and especially being able to use the shortcuts in intellij to launch the web page.
Any suggestions?
A: Basically the problem is, as I understand, that you're trying to open your .html template directly from IDEA. Which means you're not using the thymeleaf engine to render it - you're just opening the template itself and not the resulting page. If you open the source code of this page using your browser's dev tools, you will see that all your expressions stay unprocessed which leads to it trying to fetch the resources on the wrong port (e.g. 63342 instead of 8080 where your application is really running and is ready to serve the resources).
Thus, you cannot edit your templates like this. But Thymeleaf does have an option to do that. If you're running your Spring Boot application from the IDE directly (e.g. a profile in Intellij IDEA Ultimate) you can add the following to your application.properties:
spring.thymeleaf.cache=false
This will tell your Spring template resolver that you do not want to cache your .html templates and it will load the files from disk every time, so if you modify your template and then hit IDE's build button it should re-package your template and when you refresh your page in browser it will load (and process!) the edited one.
Caution! Only use this for development builds, set value to true for production environments to prevent unnecessary re-reading.
See Spring Boot Docs on Hot Swapping for more.
A: if you want intelj to display your image you have to add a regular src and add a th:src to show the image when the program is run. Try adding both
<img th:src="@{/assets/img/image.svg}" src="../static/assets/img/image.svg"/>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/70311772",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to have different color for alternate row for MUI v4 Table? Below are my code. I tried setting the tableRowRoot in the style.js but the row background color for alternate row did not change. I hope to just set the root for table row so I do not need to add any class or logic to the rows etc. Hope you guys can show me the correct way to do this.
import { makeStyles } from '@material-ui/core/styles';
export default makeStyles((theme) => ({
tableRowRoot: {
'&:nth-of-type(odd)': {
backgroundColor: theme.palette.action.hover,
},
},
}));
import useStyles from './styles';
const Event = ({ pendingEvents, handleUpdateEvent }) => {
const classes = useStyles();
return (
<Container className={classes.content}>
<div className={classes.toolbar} />
<Typography className={classes.title} variant='h3' gutterBottom>
List of Pending Request
</Typography>
<TableContainer component={Paper}>
<Table className={classes.table} aria-label='simple table'>
<TableHead>
<TableRow>
<TableCell className={classes.th}>Email</TableCell>
<TableCell className={classes.th}>Name</TableCell>
<TableCell className={classes.th}>Reason</TableCell>
<TableCell className={classes.th}>Start Date</TableCell>
<TableCell className={classes.th}>End Date</TableCell>
<TableCell className={classes.th}>Approve / Reject</TableCell>
</TableRow>
</TableHead>
<TableBody>
{pendingEvents.map((event) => (
<TableRow key={event.id}>
<TableCell component='th' scope='row'>
{event.email}
</TableCell>
<TableCell>{event.name}</TableCell>
<TableCell>{event.reason}</TableCell>
<TableCell>{new Date(event.start).toDateString()}</TableCell>
<TableCell>{new Date(event.end).toDateString()}</TableCell>
<TableCell>
<IconButton
aria-label='Approve'
color='inherit'
onClick={() => handleUpdateEvent(event, 'approved')}
>
<ThumbUpIcon color='primary' />
</IconButton>
<IconButton
aria-label='Reject'
color='inherit'
onClick={() => handleUpdateEvent(event, 'rejected')}
>
<ThumbDownIcon color='secondary' />
</IconButton>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</TableContainer>
</Container>
);
};
export default Event;
A: You have a tableRowRoot rule, but I don't see you set the className in the TableRow to apply the custom styles:
<TableRow key={event.id} className={classes.tableRowRoot} /* <------- Add this */>
From the docs, you can also use withStyles to create a styled component from the original one:
const StyledTableRow = withStyles((theme) => ({
root: {
'&:nth-of-type(odd)': {
backgroundColor: theme.palette.action.hover,
},
},
}))(TableRow);
<TableBody>
{pendingEvents.map((event) => (
<StyledTableRow key={event.id}>
{...}
</StyledTableRow>
))}
</TableBody>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/69751510",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Program Working On C:\ But Not E:\ I wrote a simple program in VB 2017 that is meant to gather data about my computer's internet connection to be used in a later script, in an attempt to fix an ip issue. The program is meant to be run from my Desktop, which is on my E:\ Drive instead of C:\ On the main drive (C:), the program executes perfectly and outputs the wanted information into a text file, but on E:, the program simply creates the text files, but leaves them blank. The code is as follows:
Imports System.IO
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'Creates path for output file & cmd process
Dim path As String = My.Application.Info.DirectoryPath() & "\ExIpOutput.txt"
Dim path1 As String = My.Application.Info.DirectoryPath() & "\Ipconfig.txt"
Dim pathSub As String = path.Substring(2, 3)
Dim path1Sub As String = path1.Substring(2, 3)
'Creates output files
Dim fs As FileStream = File.Create(path)
fs.Close()
Dim fs1 As FileStream = File.Create(path1)
fs1.Close()
'Declares the ExIP Program
Dim psi As New ProcessStartInfo With {
.Verb = "runas",
.FileName = "Cmd",
.Arguments = "/c" & "nslookup myip.opendns.com. resolver1.opendns.com" & "> " & path
}
'Attempts to run the program
Process.Start(psi)
'Declares the IPConf Program
Dim psi1 As New ProcessStartInfo With {
.Verb = "runas",
.FileName = "Cmd",
.Arguments = "/c" & "ipconfig /all" & "> " & path1
}
'Attempts to run the program
Process.Start(psi1)
End Sub
End Class
What I've tried/Debugged:
I originally thought it was an issue with the path, being E:\\ Instead of E:\, but after writing an annoyingly complex Function to repair the path, the same result occurred. I am running in both locations with administrative permissions, and the same exact .exe file. The command prompt seems to run fine. Not sure what's up.
A: You are redirecting the output of nslookup and ipconfig to a path without quoting, so maybe your location on drive E:\ contains spaces, which would prevent nslookup to write to correct file.
Maybe it would good to provide the actual value of "path" and "path1".
If this is not the case, try to open a command prompt as administrator and try to execute the exact same command with the same paths to verify it works.
A: .Arguments = "/c" & "nslookup myip.opendns.com. resolver1.opendns.com" & "> " & path
shall look more like
.Arguments = "/c " & "nslookup myip.opendns.com resolver1.opendns.com " & "> " & path
and
.Arguments = "/c" & "ipconfig /all" & "> " & path1
shall look more like
.Arguments = "/c " & "ipconfig /all " & "> " & path1
Also I would follow the advise above to consider that spaces may be in the path.
A: Following the tips from both @AlessandroMandelli and @wech ... I wrote a (way too long) appending section of the program to put quotes into the path, making sure spaces won't screw up the program:
'Appends path1 string with quotes to fix spacing
Dim pathIns As String = """"
Dim path1F As String = path1.Insert(0, pathIns)
path1 = path1F
Dim path1FIns As Integer = path1.Length()
Dim path1FF As String = path1.Insert(path1FIns, pathIns)
path1 = path1FF
'Appends path string...
Dim pathF As String = path.Insert(0, pathIns)
path = pathF
Dim pathFIns As Integer = path.Length()
Dim pathFF As String = path.Insert(pathFIns, pathIns)
path = pathFF
And.. It worked! The program now yields the same results as it would from a path with no quotes! Final product/project can be viewed here
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/50830536",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Variable is not updating despite having good @Query I want to update one variable for user.
Method:
fun blockUser(username: String): Boolean {
val user = userRepository.findUserByUsername(username)
if (user == null) {
throw UsernameNotFoundException("User not found by username: $username")
} else {
userRepository.blockUser(username)
}
val justToCheckIfUserIsUpdated = userRepository.findUserByUsername(username) //to be removed
return true
}
Query
@Modifying
@Transactional
@Query("update UserEntity c set c.isBlocked = TRUE WHERE c.username = :username")
fun blockUser(@Param("username") username: String)
Test:
@Test
fun `should block user when user exists`() {
//given
val userEntity = UserEntity(
username = "user",
phoneNumber = "500200300",
isBlocked = false,
email = "kupaa@wp.pl"
)
val userService = UserService(userDetailsRepository, userRepository, passwordEncoder)
userRepository.save(userEntity);
//when
userService.blockUser(userEntity.username);
//then
val blockedUser = userRepository.findUserByUsername(userEntity.username);
assertThat(blockedUser!!.isBlocked).isTrue()
}
While debugging you can see that isblocked is always true despite I updated it to true value.
Test ends with:
Expected :true
Actual :false
What I do wrong? I'm really confused.
A: When you do updates using JPQL, the updates go directly to the database. Hibernate doesn't magically update corresponding entities in the persistence context (the first level cache).
This userRepository.findUserByUsername(username) should get a user from the database (without the cache). But if you have a query cache enabled, the result can be loaded from the cache. You need to enable SQL logging and check the logs for that.
Also keep in mind that @Transactional above blockUser() method does nothing because spring boot creates a transaction for each test method. It doesn't mean that you have to remove @Transactional of course.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/64484501",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: ImageMagick colors depth conversion I have several thousands of tga files (without palette) which contain RGBA4444 data (I know usualy tga files don't contain RGBA4444 data). I would like to convert them into RGBA8888 data. I use the following command line:
convert -depth 4 woody4.tga -depth 8 woody8.tga
In this case, woody4.tga is the original RGBA4444 file, and woody8.tga the target RGBA8888 file but it doesn't change the colors of my pictures, what am I missing?
Thanks,
Pierre
Edit:
Thanks very much Mark, I have successfully converted more than 10 000 TGA with your program, the result is very good and correct to the original TGA ! this would has been impossible without the parallel command ! Just a last point, I have around 50 TGA larger (the backgrounds of the game) which are coded with RGBA5650 and not RGBA4444, how can I modify your program to manage the RGBA5650 ? Thanks very much !
A: Updated answer.
After reading a few documents about TARGA format. I've revised + simplified a C program to convert.
// tga2img.c
#include <stdio.h>
#include <stdlib.h>
#include <wand/MagickWand.h>
typedef struct {
unsigned char idlength;
unsigned char colourmaptype;
unsigned char datatypecode;
short int colourmaporigin;
short int colourmaplength;
unsigned char colourmapdepth;
short int x_origin;
short int y_origin;
short int width;
short int height;
unsigned char bitsperpixel;
unsigned char imagedescriptor;
} HEADER;
typedef struct {
int extensionoffset;
int developeroffset;
char signature[16];
unsigned char p;
unsigned char n;
} FOOTER;
int main(int argc, const char * argv[]) {
HEADER tga_header;
FOOTER tga_footer;
FILE
* fd;
size_t
tga_data_size,
tga_pixel_size,
i,
j;
unsigned char
* tga_data,
* buffer;
const char
* input,
* output;
if (argc != 3) {
printf("Usage:\n\t %s <input> <output>\n", argv[0]);
return 1;
}
input = argv[1];
output = argv[2];
fd = fopen(input, "rb");
if (fd == NULL) {
fprintf(stderr, "Unable to read TGA input\n");
return 1;
}
/********\
* TARGA *
\*********/
#pragma mark TARGA
// Read TGA header
fread(&tga_header.idlength, sizeof(unsigned char), 1, fd);
fread(&tga_header.colourmaptype, sizeof(unsigned char), 1, fd);
fread(&tga_header.datatypecode, sizeof(unsigned char), 1, fd);
fread(&tga_header.colourmaporigin, sizeof( short int), 1, fd);
fread(&tga_header.colourmaplength, sizeof( short int), 1, fd);
fread(&tga_header.colourmapdepth, sizeof(unsigned char), 1, fd);
fread(&tga_header.x_origin, sizeof( short int), 1, fd);
fread(&tga_header.y_origin, sizeof( short int), 1, fd);
fread(&tga_header.width, sizeof( short int), 1, fd);
fread(&tga_header.height, sizeof( short int), 1, fd);
fread(&tga_header.bitsperpixel, sizeof(unsigned char), 1, fd);
fread(&tga_header.imagedescriptor, sizeof(unsigned char), 1, fd);
// Calculate sizes
tga_pixel_size = tga_header.bitsperpixel / 8;
tga_data_size = tga_header.width * tga_header.height * tga_pixel_size;
// Read image data
tga_data = malloc(tga_data_size);
fread(tga_data, 1, tga_data_size, fd);
// Read TGA footer.
fseek(fd, -26, SEEK_END);
fread(&tga_footer.extensionoffset, sizeof( int), 1, fd);
fread(&tga_footer.developeroffset, sizeof( int), 1, fd);
fread(&tga_footer.signature, sizeof( char), 16, fd);
fread(&tga_footer.p, sizeof(unsigned char), 1, fd);
fread(&tga_footer.n, sizeof(unsigned char), 1, fd);
fclose(fd);
buffer = malloc(tga_header.width * tga_header.height * 4);
#pragma mark RGBA4444 to RGBA8888
for (i = 0, j=0; i < tga_data_size; i+= tga_pixel_size) {
buffer[j++] = (tga_data[i+1] & 0x0f) << 4; // Red
buffer[j++] = tga_data[i ] & 0xf0; // Green
buffer[j++] = (tga_data[i ] & 0x0f) << 4; // Blue
buffer[j++] = tga_data[i+1] & 0xf0; // Alpha
}
free(tga_data);
/***************\
* IMAGEMAGICK *
\***************/
#pragma mark IMAGEMAGICK
MagickWandGenesis();
PixelWand * background;
background = NewPixelWand();
PixelSetColor(background, "none");
MagickWand * wand;
wand = NewMagickWand();
MagickNewImage(wand,
tga_header.width,
tga_header.height,
background);
background = DestroyPixelWand(background);
MagickImportImagePixels(wand,
0,
0,
tga_header.width,
tga_header.height,
"RGBA",
CharPixel,
buffer);
free(buffer);
MagickWriteImage(wand, argv[2]);
wand = DestroyMagickWand(wand);
return 0;
}
Which can be compiled with clang $(MagickWand-config --cflags --libs) -o tga2im tga2im.c, and can be executed simply by ./tga2im N_birthday_0000.tga N_birthday_0000.tga.png.
Original answer.
The only way I can think of converting the images is to author a quick program/script to do the bitwise color-pixel logic.
This answer offers a quick way to read the image data; so combining with MagickWand, can be converted easily. (Although I know there'll be better solutions found on old game-dev forums...)
#include <stdio.h>
#include <stdbool.h>
#include <wand/MagickWand.h>
typedef struct
{
unsigned char imageTypeCode;
short int imageWidth;
short int imageHeight;
unsigned char bitCount;
unsigned char *imageData;
} TGAFILE;
bool LoadTGAFile(const char *filename, TGAFILE *tgaFile);
int main(int argc, const char * argv[]) {
const char
* input,
* output;
if (argc != 3) {
printf("Usage:\n\t%s <input> <output>\n", argv[0]);
}
input = argv[1];
output = argv[2];
MagickWandGenesis();
TGAFILE header;
if (LoadTGAFile(input, &header) == true) {
// Build a blank canvas image matching TGA file.
MagickWand * wand;
wand = NewMagickWand();
PixelWand * background;
background = NewPixelWand();
PixelSetColor(background, "NONE");
MagickNewImage(wand, header.imageWidth, header.imageHeight, background);
background = DestroyPixelWand(background);
// Allocate RGBA8888 buffer
unsigned char * buffer = malloc(header.imageWidth * header.imageHeight * 4);
// Iterate over TGA image data, and convert RGBA4444 to RGBA8888;
size_t pixel_size = header.bitCount / 8;
size_t total_bytes = header.imageWidth * header.imageHeight * pixel_size;
for (int i = 0, j = 0; i < total_bytes; i+=pixel_size) {
// Red
buffer[j++] = (header.imageData[i ] & 0x0f) << 4;
// Green
buffer[j++] = (header.imageData[i ] & 0xf0);
// Blue
buffer[j++] = (header.imageData[i+1] & 0xf0) << 4;
// Alpha
buffer[j++] = (header.imageData[i+1] & 0xf0);
}
// Import image data over blank canvas
MagickImportImagePixels(wand, 0, 0, header.imageWidth, header.imageHeight, "RGBA", CharPixel, buffer);
// Write image
MagickWriteImage(wand, output);
wand = DestroyMagickWand(wand);
} else {
fprintf(stderr, "Could not read TGA file %s\n", input);
}
MagickWandTerminus();
return 0;
}
/*
* Method copied verbatim from https://stackoverflow.com/a/7050007/438117
* Show your love by +1 to Wroclai answer.
*/
bool LoadTGAFile(const char *filename, TGAFILE *tgaFile)
{
FILE *filePtr;
unsigned char ucharBad;
short int sintBad;
long imageSize;
int colorMode;
unsigned char colorSwap;
// Open the TGA file.
filePtr = fopen(filename, "rb");
if (filePtr == NULL)
{
return false;
}
// Read the two first bytes we don't need.
fread(&ucharBad, sizeof(unsigned char), 1, filePtr);
fread(&ucharBad, sizeof(unsigned char), 1, filePtr);
// Which type of image gets stored in imageTypeCode.
fread(&tgaFile->imageTypeCode, sizeof(unsigned char), 1, filePtr);
// For our purposes, the type code should be 2 (uncompressed RGB image)
// or 3 (uncompressed black-and-white images).
if (tgaFile->imageTypeCode != 2 && tgaFile->imageTypeCode != 3)
{
fclose(filePtr);
return false;
}
// Read 13 bytes of data we don't need.
fread(&sintBad, sizeof(short int), 1, filePtr);
fread(&sintBad, sizeof(short int), 1, filePtr);
fread(&ucharBad, sizeof(unsigned char), 1, filePtr);
fread(&sintBad, sizeof(short int), 1, filePtr);
fread(&sintBad, sizeof(short int), 1, filePtr);
// Read the image's width and height.
fread(&tgaFile->imageWidth, sizeof(short int), 1, filePtr);
fread(&tgaFile->imageHeight, sizeof(short int), 1, filePtr);
// Read the bit depth.
fread(&tgaFile->bitCount, sizeof(unsigned char), 1, filePtr);
// Read one byte of data we don't need.
fread(&ucharBad, sizeof(unsigned char), 1, filePtr);
// Color mode -> 3 = BGR, 4 = BGRA.
colorMode = tgaFile->bitCount / 8;
imageSize = tgaFile->imageWidth * tgaFile->imageHeight * colorMode;
// Allocate memory for the image data.
tgaFile->imageData = (unsigned char*)malloc(sizeof(unsigned char)*imageSize);
// Read the image data.
fread(tgaFile->imageData, sizeof(unsigned char), imageSize, filePtr);
// Change from BGR to RGB so OpenGL can read the image data.
for (int imageIdx = 0; imageIdx < imageSize; imageIdx += colorMode)
{
colorSwap = tgaFile->imageData[imageIdx];
tgaFile->imageData[imageIdx] = tgaFile->imageData[imageIdx + 2];
tgaFile->imageData[imageIdx + 2] = colorSwap;
}
fclose(filePtr);
return true;
}
The order of the color channels may need to be switch around.
A: Oh, I see Eric beat me to it:-)
Hey ho! I did it a different way anyway and got a different answer so you can see which one you like best. I also wrote some C but I didn't rely on any libraries, I just read the TGA and converted it to a PAM format and let ImageMagick make that into PNG afterwards at command-line.
I chose PAM because it is the simplest file to write which supports transparency - see Wikipedia on PAM format.
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
int main(int argc,char* argv[]){
unsigned char buf[64];
FILE* fp=fopen(argv[1],"rb");
if(fp==NULL){
fprintf(stderr,"ERROR: Unable to open %s\n",argv[1]);
exit(1);
}
// Read TGA header of 18 bytes, extract width and height
fread(buf,1,18,fp); // 12 bytes junk, 2 bytes width, 2 bytes height, 2 bytes junk
unsigned short w=buf[12]|(buf[13]<<8);
unsigned short h=buf[14]|(buf[15]<<8);
// Write PAM header
fprintf(stdout,"P7\n");
fprintf(stdout,"WIDTH %d\n",w);
fprintf(stdout,"HEIGHT %d\n",h);
fprintf(stdout,"DEPTH 4\n");
fprintf(stdout,"MAXVAL 255\n");
fprintf(stdout,"TUPLTYPE RGB_ALPHA\n");
fprintf(stdout,"ENDHDR\n");
// Read 2 bytes at a time RGBA4444
while(fread(buf,2,1,fp)==1){
unsigned char out[4];
out[0]=(buf[1]&0x0f)<<4;
out[1]=buf[0]&0xf0;
out[2]=(buf[0]&0x0f)<<4;
out[3]=buf[1]&0xf0;
// Write the 4 modified bytes out RGBA8888
fwrite(out,4,1,stdout);
}
fclose(fp);
return 0;
}
I the compile that with gcc:
gcc targa.c -o targa
Or you could use clang:
clang targa.c -o targa
and run it with
./targa someImage.tga > someImage.pam
and convert the PAM to PNG with ImageMagick at the command-line:
convert someImage.pam someImage.png
If you want to avoid writing the intermediate PAM file to disk, you can pipe it straight into convert like this:
./targa illu_evolution_01.tga | convert - result.png
You can, equally, make a BMP output file if you wish:
./targa illu_evolution_01.tga | convert - result.bmp
If you have thousands of files to do, and you are on a Mac or Linux, you can use GNU Parallel and get them all done in parallel much faster like this:
parallel --eta './targa {} | convert - {.}.png' ::: *.tga
If you have more than a couple of thousand files, you may get "Argument list too long" errors, in which case, use the slightly harder syntax:
find . -name \*tga -print0 | parallel -0 --eta './targa {} | convert - {.}.png'
On a Mac, you would install GNU Parallel with homebrew using:
brew install parallel
For your RGBA5650 images, I will fall back to PPM as my intermediate format because the alpha channel of PAM is no longer needed. The code will now look like this:
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
int main(int argc,char* argv[]){
unsigned char buf[64];
FILE* fp=fopen(argv[1],"rb");
if(fp==NULL){
fprintf(stderr,"ERROR: Unable to open %s\n",argv[1]);
exit(1);
}
// Read TGA header of 18 bytes, extract width and height
fread(buf,1,18,fp); // 12 bytes junk, 2 bytes width, 2 bytes height, 2 bytes junk
unsigned short w=buf[12]|(buf[13]<<8);
unsigned short h=buf[14]|(buf[15]<<8);
// Write PPM header
fprintf(stdout,"P6\n");
fprintf(stdout,"%d %d\n",w,h);
fprintf(stdout,"255\n");
// Read 2 bytes at a time RGBA5650
while(fread(buf,2,1,fp)==1){
unsigned char out[3];
out[0]=buf[1]&0xf8;
out[1]=((buf[1]&7)<<5) | ((buf[0]>>3)&0x1c);
out[2]=(buf[0]&0x1f)<<3;
// Write the 3 modified bytes out RGB888
fwrite(out,3,1,stdout);
}
fclose(fp);
return 0;
}
And will compile and run exactly the same way.
A: I have been thinking about this some more and it ought to be possible to reconstruct the image without any special software - I can't quite see my mistake for the moment by maybe @emcconville can cast your expert eye over it and point out my mistake! Pretty please?
So, my concept is that ImageMagick has read in the image size and pixel data correctly but has just allocated the bits according to the standard RGB5551 interpretation of a TARGA file rather than RGBA4444. So, we rebuild the 16-bits of data it read and split them differently.
The first line below does the rebuild into the original 16-bit data, then each subsequent line splits out one of the RGBA channels and then we recombine them:
convert illu_evolution_01.tga -depth 16 -channel R -fx "(((r*255)<<10) | ((g*255)<<5) | (b*255) | ((a*255)<<15))/255" \
\( -clone 0 -channel R -fx "((((r*255)>>12)&15)<<4)/255" \) \
\( -clone 0 -channel R -fx "((((r*255)>>8 )&15)<<4)/255" \) \
\( -clone 0 -channel R -fx "((((r*255) )&15)<<4)/255" \) \
-delete 0 -set colorspace RGB -combine -colorspace sRGB result.png
# The rest is just debug so you can see the reconstructed channels in [rgba].png
convert result.png -channel R -separate r.png
convert result.png -channel G -separate g.png
convert result.png -channel B -separate b.png
convert result.png -channel A -separate a.png
So, the following diagram represents the 16-bits of 1 pixel:
A R R R R R G G G G G B B B B B <--- what IM saw
R R R R G G G G B B B B A A A A <--- what it really meant
Yes, I have disregarded the alpha channel for the moment.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/42629143",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Python/Pyramid - Wrapping Cornice response with extra data when raising HTTP Exception I'm using Pyramid and Cornice to write some RESTful Python app and I made a simple Cornice resource:
@resource(collection_path='/users/', path='/users/{id}')
class UsersResource(object):
def __init__(self, request):
self.request = request
@view(renderer='json', content_type=content_type)
@my_wrapper
def get(self):
return {'user_id': self.request.matchdict['id']}
As you may have noticed, along with Cornice's view decorator, I also added an extra decorator here (my_decorator), which I intended to use as an wrapper to add some extra information to the response:
def my_wrapper(method):
def wrapper(*args, **kw):
time_start = time()
profiler = sqltap.start()
fn_result = method(*args, **kw)
stats = profiler.collect()
time_end = time()
result = {
'info': {
'api_version': args[0].request.registry.settings.api_version,
'request_path': args[0].request.path_info,
'request_method': args[0].request.method,
'current_time': datetime.datetime.now(pytz.utc).strftime('%Y-%m-%dT%H:%M:%SZ'),
'execution_time': time_end - time_start,
'total_queries': len(stats),
'query_time': stats[0].duration if len(stats) > 0 else 0,
},
}
result.update(fn_result)
return result
return wrapper
This works fine unless I define Cornice validators in my view decorator:
from validators import validate_int
@resource(collection_path='/users/', path='/users/{id}')
class UsersResource(object):
def __init__(self, request):
self.request = request
@view(renderer='json', content_type=content_type, validators=validate_int) # added validators
@my_wrapper
def get(self):
return {'user_id': self.request.matchdict['id']}
validators.py
import responses
def validate_int(request):
should_be_int = request.matchdict['id']
try:
int(should_be_int)
except:
raise responses._400('This doesn\'t look like a valid ID.')
responses.py
class _400(exc.HTTPError):
def __init__(self, desc):
body = {'status': 400, 'message': 'Bad Request', 'description': desc}
Response.__init__(self, json.dumps(body))
With a code like this, my_wrapper wraps a response only if the validation passes (which is completely understandable), but I wonder how can I still wrap the response with some extra information when the default HTTPException is raised (because in that case the code never reaches my_wrapper at all)?
A: In a short discussion with a brilliant Pyramid IRC community, I decided to do this with Pyramid's tweens, rather than using the wrapper.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/31142344",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: What is the difference between making android game with hand or some game engine? I want to know what is the difference between making game with game engine and code that you write yourself. in other words how the game engine help us to develop a game.
and can introduce me some good game engines for android platform?
A: An engine is going to help you because it already has some basic functionalities, like: collision handling, sprites and so on! In other words you don't need to be concerned about coding in order to solve basic problems that every single game has in common!(you will write fewer lines of code) Look I'm not an expert in this subject but you can try: Cocos 2D and AndEngine, take a look at the links bellow:
http://cocos2d.org/
http://www.andengine.org/
I hope it will be usefull!
see you!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/30245700",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
}
|
Q: Variable stage keeps coming back undefined Hi I am trying to get the result from function test() and use it to set variable stageIs however it keeps coming back undefined. Any help would be greatly appreciated I have been trying to figure it out for hours now.
var stage;
import { CONTRACT } from '../contract'
import _ from 'lodash'
export default {
data () {
return {
stageIs: null,
amount: null
}
},
mounted () {
this.coinbase = CONTRACT._eth.coinbase
this.test()
},
methods: {
test () {
CONTRACT.name1(function(err, res) {
stage = (res);
});
alert(stage);
this.stageIs= (stage)
}
When I do the alert inside the test() it works however it will not set {{ stageIs }} for some reason.
test () {
CONTRACT.name1(function(err, res) {
stage = (res);
alert(stage)
this.stageIs = (stage)
})
A: You have an anonymous function as an argument to CONTRACT.name1. By the signature of this anonymous function, name1 seems to be asynchronous.
As a result, the call to name1 will return immediately, while the work that is supposed to be done by name1 will execute later in the event loop (or it is waiting for IO). As a result, stage would always be undefined.
What you want to do is this:
test () {
let that = this;
CONTRACT.name1(function(err, res) {
stage = (res);
alert(stage)
that.stageIs = stage;
});
}
There are two things happening here. We are assigning a value to stage when the callback is invoked by the asynchronous function name1. We are also assigning a reference to this inside test, because the anonymous function will execute in a different context (and therefore the anonymous function's this would point to something else).
Or you could also use arrow functions to get rid of the this binding problem.
test () {
CONTRACT.name1((err, res) => {
stage = (res);
alert(stage)
this.stageIs = stage;
});
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/51886714",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to differenciate indexPath of first cell with indexPath of empty space at the end of table? I use the following code to detect a click on a UITableView and take action depending on which cell is clicked, and which element in the cell was clicked, with a default action for any element that doesn't match.
-(void)addTapRecognizer {
// this is called when the view is created
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
singleTap.delegate = self;
singleTap.numberOfTapsRequired = 1;
singleTap.numberOfTouchesRequired = 1;
[self.tableView addGestureRecognizer:singleTap];
}
- (void)handleTap:(UITapGestureRecognizer *)tap {
NSLog(@"tap detected!");
if (UIGestureRecognizerStateEnded != tap.state) {
return;
}
UITableView *tableView = (UITableView *)tap.view;
CGPoint p = [tap locationInView:tap.view];
NSIndexPath* indexPath = [tableView indexPathForRowAtPoint:p];
[tableView deselectRowAtIndexPath:indexPath animated:NO];
NSLog(@"selectedIndex = %ld", (long)indexPath.row);
// take action depending where the cell was clicked
// with a default action if no element matches
MyTableViewCell *cell = (MyTableViewCell *) [self.tableView cellForRowAtIndexPath:indexPath];
CGPoint pointInCell = [tap locationInView:cell];
if(CGRectContainsPoint(cell.someImage.frame,pointInCell)) {
[self openItemID:[ItemList[indexPath.row] valueForKey:ID_ITEM]];
return;
}
if (...) {
...
return;
}
[self openItemID:[ItemList[indexPath.row] valueForKey:ID_ITEM]];
return;
}
My problem is that when there aren't enough cells to fill the screen (so for instance the table contains 2 cells and then blank space below), when the user clicks below the last cell, this is treated as a click on the first cell (the console logs "selectedIndex = 0" in both cases).
Is there a way to tell the difference between such a click, in the empty space at the end of the table, and a click on a "proper" cell of the table?
A:
Is there a way to tell the difference between such a click, in the empty space at the end of the table, and a click on a "proper" cell of the table?
Yes. For the cheap and easy solution only do what you are trying to do if you actually get an indexPath:
NSIndexPath *indexPath = [tableView indexPathForRowAtPoint:p];
if(indexPath != nil){
// do everything in here
}
Basically, your indexPath is returning nil because it can't find a row. From the docs:
An index path representing the row and section associated with point, or nil if the point is out of the bounds of any row.
You could do it the way that you're currently doing it but is there any reason why you aren't using:
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
This is a much more standard way of detecting the cell that the user tapped on.
This method won't be called if you tap on something that isn't a cell and has a number of other benefits. Firstly you get a reference to the tableView and the indexPath for free. But you also won't need any gesture recognisers this way either.
Try something like this:
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
// Do stuff with cell here...
}
Obviously this all assumes that you have correctly set a class as your table view's delegate.
NB: It's very easy to mistakenly write didDeselectRowAtIndexPath instead of didSelectRowAtIndexPath when using Xcode's autocompletion to do this. I always do this and then inevitably realise my mistake 20 minutes later.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/37457321",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Java Regular Expression for Syslog Message not working I'm trying to develop a Java program that matches syslog messages.
The pattern is like this:
"%FACILITY-[SUBFACILITY-]SEVERITY-MNEMONIC: description"
At first I did this regex and it worked for some messages:
(%[a-zA-Z_-]+-[0-6]-[a-zA-Z_-]+[^\r\t\n]+)
Now I need to match only the part before the ":" (i.e, %FACILITY-[SUBFACILITY-]SEVERITY-MNEMONIC) so I'm doing the following, which does not work:
(%[a-zA-Z_-]+-[0-6]-[a-zA-Z_-]+)
I've found some online test pages and the surprising thing is that on the first one the string matches, but not the second (this one is for Java code).
http://www.regexr.com/ -> Match
http://www.regexplanet.com/advanced/java/index.html -> Does not match
This are the strings I'm trying to match:
%HA-REDCON-4-FAILOVER_REQUEST[0x767443be74] Record Reboot History, reboot cause = 0x4000004, descr = Cause: Initiating switch-over.
%ROUTING-FIB-3-ASSERT error message may occur when doing a RCC check.
Anyone has any idea about this? What am I missing?
Thanks in advance.
A: To match everything before :, use ^[^:]+ regex.
See demo (it will work with Java, too, with find()).
The matches() in Java just must match the whole string, that is why regexplanet.com says there is no match (but find() shows success).
If you want to use matches(), you need to extend the regex to the string end, and only grab the first capturing group: ([^:]+):.*.
Here is a link to a sample program showing how to capture multiple matches.
String str = "%ROUTING-FIB-3-ASSERT more words here\n%HA-REDCON-4-FAILOVER_REQUEST[0x767443be74] Record Reboot History, reboot cause = 0x4000004, descr = Cause: Initiating switch-over.";
String rx = "(?i)(%[a-z_-]+-[0-6]-[a-z_-]+)";
Pattern ptrn = Pattern.compile(rx);
Matcher m = ptrn.matcher(str);
while (m.find()) {
System.out.println(m.group(0));
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/29769775",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Preview Camera HTC-One cuts image I'm using a custom camera preview on my app, it works fine in almost all devices, for HTC-One I'm getting a bad cut, the original photo doesn't match what the preview shows on the top.
It only happens on this device, this is the code of my preview camera and the picture about what's going on.
Thanks in advance for any help someone can give me.
public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
private final String TAG = "CameraPreview";
private SurfaceHolder mHolder;
private Camera mCamera;
private Context context;
private Camera.Size mPreviewSize;
private List<Camera.Size> mSupportedPreviewSizes;
public CameraPreview(Context context) {
super(context);
this.context = context;
mHolder = getHolder();
mHolder.addCallback(this);
}
public void setCamera(Camera camera) {
mCamera = camera;
if (mCamera != null) {
mSupportedPreviewSizes = mCamera.getParameters().getSupportedPreviewSizes();
for (Camera.Size str : mSupportedPreviewSizes) {
Log.e(TAG, str.width + "/" + str.height);
}
mHolder = getHolder();
mHolder.addCallback(this);
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
final int width = resolveSize(getSuggestedMinimumWidth(), widthMeasureSpec);
final int height = resolveSize(getSuggestedMinimumHeight(), heightMeasureSpec);
if (mSupportedPreviewSizes != null) {
mPreviewSize = getOptimalPreviewSize(mSupportedPreviewSizes, width, height);
}
float ratio;
if (mPreviewSize.height >= mPreviewSize.width) {
ratio = (float) mPreviewSize.height / (float) mPreviewSize.width;
} else {
ratio = (float) mPreviewSize.width / (float) mPreviewSize.height;
}
setMeasuredDimension(width, (int) (width * ratio));
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
if (mHolder.getSurface() == null) {
// preview surface does not exist
return;
}
// stop preview before making changes
try {
mCamera.stopPreview();
} catch (Exception e) {
// ignore: tried to stop a non-existent preview
}
// set preview size and make any resize, rotate or reformatting changes here
// start preview with new settings
try {
Camera.Parameters parameters = mCamera.getParameters();
parameters.setPreviewSize(mPreviewSize.width, mPreviewSize.height);
parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
mCamera.setParameters(parameters);
mCamera.setDisplayOrientation(90);
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
} catch (Exception e) {
Log.d(TAG, "Error starting camera preview: " + e.getMessage());
}
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
public void setFlash(String flashMode) {
Camera.Parameters params = mCamera.getParameters();
params.setFlashMode(flashMode);
mCamera.setParameters(params);
}
private Camera.Size getOptimalPreviewSize(List<Camera.Size> sizes, int w, int h) {
final double ASPECT_TOLERANCE = 0.1;
double targetRatio = (double) h / w;
if (sizes == null) {
return null;
}
Camera.Size optimalSize = null;
double minDiff = Double.MAX_VALUE;
for (Camera.Size size : sizes) {
double ratio = (double) size.height / size.width;
if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE)
continue;
if (Math.abs(size.height - h) < minDiff) {
optimalSize = size;
minDiff = Math.abs(size.height - h);
}
}
if (optimalSize == null) {
minDiff = Double.MAX_VALUE;
for (Camera.Size size : sizes) {
if (Math.abs(size.height - h) < minDiff) {
optimalSize = size;
minDiff = Math.abs(size.height - h);
}
}
}
return optimalSize;
}
public void switchCamera(Camera camera) {
Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
if (display.getRotation() == Surface.ROTATION_0) {
camera.setDisplayOrientation(90);
} else if (display.getRotation() == Surface.ROTATION_270) {
camera.setDisplayOrientation(180);
}
setCamera(camera);
try {
camera.setPreviewDisplay(mHolder);
} catch (IOException exception) {
Log.e(TAG, "IOException caused by setPreviewDisplay()", exception);
}
}
}
A: Camera preview size and picture size are two different parameters, which you can update through setPictureSize() and setPreviewSize() APIs. But if user doesn't change these sizes, it will use default values.
In this case you are updating the preview size by calculating optimum preview size based on some aspect ratio. But you are not updating picture size, so it will be using default picture size.
If picture size and preview size aspect ratios are different, definitely the captured image looks different from preview. So update the picture size also by calculating optimum picture size with same aspect ratio as preview size.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/27690298",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is the Chrome Driver Management module downloading the latest version or is it downloading the correct version of my Chrome version? I know this code allows you to download and use the most recent version of the chrome driver.
driver = webdriver.Chrome(ChromeDriverManager().install(), chrome_options=options)
If my version of chrome is an older version, does that code matter? Or does that code download a chrome driver for my version of Chrome?
A: here what official doc says :
Python module to facilitate downloading and deploying WebDriver
binaries. The classes in this module can be used to automatically
search for and download the latest version (or a specific version) of
a WebDriver binary and then extract it and place it by copying or
symlinking it to the location where Selenium or other tools should be
able to find it then.
Reference link
Read more about chromedriver-autoinstaller
Installation
pip install chromedriver-autoinstaller
Usage
Just type import chromedriver_autoinstaller in the module you want to use chromedriver.
Example
from selenium import webdriver
import chromedriver_autoinstaller
chromedriver_autoinstaller.install() # Check if the current version of chromedriver exists
# and if it doesn't exist, download it automatically,
# then add chromedriver to path
driver = webdriver.Chrome()
driver.get("http://www.python.org")
assert "Python" in driver.title
Reference Link here
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/67527961",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: gtkmm display file contents I am quite new to gtkmm please be soft, I need to read a file contents and display it.
I have referred to this tut https://developer.gnome.org/gtkmm-tutorial/stable/sec-buildapp-opening-files.html.en, but not sure how to tailor these example to my scenario, I am reading Gtk::TextView, GtkWidget. Can someone point to any simple examples to start.
A: Have a look at this, it's in PHP but understandable https://www.kksou.com/php-gtk2/sample-codes/read-a-text-file-into-GtkTextView.php
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62763585",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: JBoss-provided libraries in Maven-managed Java EE app It's actually pretty unlikely for me, but it seems that there is no direct answer over the net about importing JBoss-provided dependencies into Maven-managed Java EE application to be deployed within it.
AFAIK there are 2 things somehow related to the problem, that is jboss-as-client artifact for external (in sense of JVM) JBoss clients and jboss-as-component-matrix artifact with huge <dependencyManagement> block defining version of the libraries that JBoss uses. The latter artifact is pretty useful since I can use Maven's import scope to have all version properly set up. The one that is missing (AFAIK) i something like jboss-as-client but for deployed Java EE application. Something, that I can depend on with provided scope and have all stuff in the classpath, including platform-related APIs (like EJB or JMS) and AS-specific stuff (like EJB-ext or jboss-messaging) and possibly some other stuff from lib, lib/endorsed and (mainly) common/lib directories. I know that probably a better practice (and religion-compatible) would be to be explicit with dependencies used in modules but the way I'm asking about is much more pragmatic for me (sorry), at least for Java EE applications that really use many standard APIs.
I'm really curious about your way of dealing with such challange. I'm using 5.1.0.GA version of the AS.
A: You have to provide your own (infrastructure) maven project which just packages all the mentioned dependencies and all your JBoss projects depend on this infrastructure project with scope provided.
But shouldn't you compile just against the specification jars instead of the concrete implementation?
Like
<dependency>
<groupId>org.jboss.spec</groupId>
<artifactId>jboss-javaee-6.0</artifactId>
<version>1.0.0.Final</version>
<type>pom</type>
<scope>provided</scope>
</dependency>
Jump to the first occurrence of "Java EE 6 API" on http://arquillian.org/guides/getting_started/.
A: You won't like this answer, but as the libraries are provided at run-time by JBoss, other than using a provided scope, it is not really your affair. The classes of any unstated transitive dependency will be loaded by a different class loader (presumably), and live nicely together with the application classes.
For the not so nice coupled classes, what @MichalKalinowski said is true.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/9839689",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: react native Table GridView how to build table gridview in react native like in picture or in code snippet
<table border=1>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
</table>
A: You can use ListView component, the first row would be your header (renderHeader), others are rows (renderRow).
Both row and header would be the same component containing a parent View with flexDirection: 'row' with 4 Text components. Each Text component would have a flex: 1 if you want them to be of the same widths.
A: import React from "react";
import { registerComponent } from "react-native-playground";
import { StatusBar, StyleSheet, Text, View } from "react-native";
class App extends React.Component {
render() {
return (
<View>
<View
style={{
height: 50,
flexDirection: "row",
flex: 1,
borderWidth: 1,
padding: 2,
justifyContent: "space-around"
}}
>
<View
style={{
flex: 1,
borderWidth: 1,
alignItems: "center",
justifyContent: "center"
}}
>
<Text>Jill</Text>
</View>
<View
style={{
flex: 1,
borderWidth: 1,
alignItems: "center",
justifyContent: "center"
}}
>
<Text>Smith</Text>
</View>
<View
style={{
flex: 1,
borderWidth: 1,
alignItems: "center",
justifyContent: "center"
}}
>
<Text>50</Text>
</View>
</View>
<View
style={{
height: 50,
flexDirection: "row",
flex: 1,
borderWidth: 1,
padding: 2,
justifyContent: "space-around"
}}
>
<View
style={{
flex: 1,
borderWidth: 1,
alignItems: "center",
justifyContent: "center"
}}
>
<Text>Eve</Text>
</View>
<View
style={{
flex: 1,
borderWidth: 1,
alignItems: "center",
justifyContent: "center"
}}
>
<Text>Jackson</Text>
</View>
<View
style={{
flex: 1,
borderWidth: 1,
alignItems: "center",
justifyContent: "center"
}}
>
<Text>94</Text>
</View>
</View>
<View
style={{
height: 50,
flexDirection: "row",
flex: 1,
borderWidth: 1,
padding: 2,
justifyContent: "space-around"
}}
>
<View
style={{
flex: 1,
borderWidth: 1,
alignItems: "center",
justifyContent: "center"
}}
>
<Text>First Name</Text>
</View>
<View
style={{
flex: 1,
borderWidth: 1,
alignItems: "center",
justifyContent: "center"
}}
>
<Text>Last Name</Text>
</View>
<View
style={{
flex: 1,
borderWidth: 1,
alignItems: "center",
justifyContent: "center"
}}
>
<Text>Age</Text>
</View>
</View>
</View>
);
}
}
registerComponent(App);
Here's the working code https://rnplay.org/apps/e3MZAw
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/42157198",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to get data from the current row in INSTEAD OF trigger? For example, we have a table named 'Names':
id | name
-----+------
1 | Mary
2 | Sue
3 | John
and this trigger:
CREATE TRIGGER TRG_insofdel
ON Names
INSTEAD OF DELETE
AS
BEGIN
-- here I need to get some data from the current row
END
and then I call
DELETE FROM Names
WHERE id = 1
How can I get Mary's (id == 1) name in the trigger?
What is going on with the 'deleted' table in this case?
A: The MSDN documentation does explain but it isn't laid out very clearly.
In a trigger, SQL server automatically makes 2 special in-memory tables available to you:
*
*inserted: the data which was added to the table (for insert and update statements)
*deleted: the data which was removed from the table (for update and delete statements)
They have the same columns as the actual table, but are completely read-only - you cannot add columns or indexes to them or change the data inside them.
So in your example, to get the name of the person being removed, you can do the following inside the trigger:
DECLARE @name varchar(100);
SELECT @name = name from deleted;
Important note
Be aware tho that if multiple rows were deleted from the table, then deleted will contain multiple rows - the trigger is not called individually once for each row.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/52576340",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: replace NA with data from another column in R I know how to make the NA's blanks with the following code:
IMILEFT IMIRIGHT IMIAVG
NA NA NA
NA 71.15127 NA
72.18310 72.86607 72.52458
70.61460 68.00766 69.31113
69.39032 69.91261 69.65146
72.58609 72.75168 72.66888
70.85714 NA NA
NA 69.88203 NA
74.47109 73.07963 73.77536
70.44855 71.28647 70.86751
NA 72.33503 NA
69.82818 70.45144 70.13981
68.66929 69.79866 69.23397
72.46879 71.50685 71.98782
71.11888 71.98336 71.55112
NA 67.86667 NA
IMILEFT <- ((ASLCOMPTEST$LHML + ASLCOMPTEST$LRML)/(ASLCOMPTEST$LFML +
ASLCOMPTEST$LTML)*100)
IMILEFT <- sapply(IMILEFT, as.character)
IMILEFT[is.na(IMILEFT)] <- ""
But when I do that code, it won't allow me to do an average of "IMILEFT" and "IMIRIGHT" or make the "IMIAVG" the same as the other column that has a numerical value.
IMIAVG<-((IMILEFT + IMIRIGHT)/2)
Error in IMILEFT + IMIRIGHT : non-numeric argument to binary operator
It will also be the same error if I make it as.numeric
A: Try the following. Leave the NAs as they are
rowSums(M, na.rm=TRUE) / 2 - (is.na(L) + is.na(R))
## WHERE
M = cbind(IMILEFT, IMIRIGHT)
L = IMILEFT
R = IMIRIGHT
if you have rows were both columns are NA, then have the denominator be
pmin(1, 2 - (is.na(L) + is.na(R)))
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/30228989",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is it possible always to force a new thread with Task? I am trying to create a new thread each time Task.Factory.StartNew is called. The question is how to run the code bellow without throwing the exception:
static void Main(string[] args)
{
int firstThreadId = 0;
Task.Factory.StartNew(() => firstThreadId = Thread.CurrentThread.ManagedThreadId);
for (int i = 0; i < 100; i++)
{
Task.Factory.StartNew(() =>
{
while (true)
{
Thread.Sleep(1000);
if (firstThreadId == Thread.CurrentThread.ManagedThreadId)
throw new Exception("The first thread is reused.");
}
});
}
Console.Read();
}
EDIT: the new code if you comment the first for statement there is no problem. But if you have it, WOW, the message "Thread reused" is written to the console. Can you explain that because I am really confused.
static void Main(string[] args)
{
ConcurrentDictionary<int, int> startedThreads = new ConcurrentDictionary<int, int>();
for (int i = 0; i < 10; i++)
{
Task.Factory.StartNew(() =>
{
Task.Factory.StartNew(() =>
{
startedThreads.AddOrUpdate(Thread.CurrentThread.ManagedThreadId,
Thread.CurrentThread.ManagedThreadId, (a, b) => b);
}, TaskCreationOptions.LongRunning);
for (int j = 0; j < 100; j++)
{
Task.Factory.StartNew(() =>
{
while (true)
{
Thread.Sleep(10);
if (startedThreads.ContainsKey(
Thread.CurrentThread.ManagedThreadId))
Console.WriteLine("Thread reused");
}
}, TaskCreationOptions.LongRunning);
}
});
}
Console.Read();
}
A: Adding to Jon Skeet's answer, if you want to guarantee that a new thread is created every time, you can write your own TaskScheduler that creates a new thread.
A: Try this:
var taskCompletionSource = new TaskCompletionSource<bool>();
Thread t = new Thread(() =>
{
try
{
Operation();
taskCompletionSource.TrySetResult(true);
}
catch (Exception e)
{
taskCompletionSource.TrySetException(e);
}
});
void Operation()
{
// Some work in thread
}
t.Start();
await taskCompletionSource.Task;
You also can write extension methods for Action, Func and so on.
For example:
public static Task RunInThread(
this Action action,
Action<Thread> initThreadAction = null)
{
TaskCompletionSource<bool> taskCompletionSource = new TaskCompletionSource<bool>();
Thread thread = new Thread(() =>
{
try
{
action();
taskCompletionSource.TrySetResult(true);
}
catch (Exception e)
{
taskCompletionSource.TrySetException(e);
}
});
initThreadAction?.Invoke(thread);
thread.Start();
return taskCompletionSource.Task;
}
or
public static Task<TResult> RunInThread<T1, T2, TResult>(
this Func<T1, T2, TResult> function,
T1 param1,
T2 param2,
Action<Thread> initThreadAction = null)
{
TaskCompletionSource<TResult> taskCompletionSource = new TaskCompletionSource<TResult>();
Thread thread = new Thread(() =>
{
try
{
TResult result = function(param1, param2);
taskCompletionSource.TrySetResult(result);
}
catch (Exception e)
{
taskCompletionSource.TrySetException(e);
}
});
initThreadAction?.Invoke(thread);
thread.Start();
return taskCompletionSource.Task;
}
and use it like that:
var result = await some_function.RunInThread(param1, param2).ConfigureAwait(true);
A: Hello and thank you all for the answers. You all got +1. All suggested solution did not work for my case. The problem is that when you sleep a thread it will be reused at some point of time. The people above suggested:
*
*using LongRunning => This will not work if you have nested/child
tasks
*custom task scheduler => I tried to write my own and also tried this
ThreadPerTaskScheduler which also di not work.
*using pure threads => Still failing...
*you could also check this project at Multithreading.Scheduler github
My solution
I don't like it but it works. Basically I block the thread so it cannot be reused. Bellow are the extension methods and a working example. Again, thank you.
https://gist.github.com/4150635
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApplication
{
public static class ThreadExtensions
{
/// <summary>
/// Blocks the current thread for a period of time so that the thread cannot be reused by the threadpool.
/// </summary>
public static void Block(this Thread thread, int millisecondsTimeout)
{
new WakeSleepClass(millisecondsTimeout).SleepThread();
}
/// <summary>
/// Blocks the current thread so that the thread cannot be reused by the threadpool.
/// </summary>
public static void Block(this Thread thread)
{
new WakeSleepClass().SleepThread();
}
/// <summary>
/// Blocks the current thread for a period of time so that the thread cannot be reused by the threadpool.
/// </summary>
public static void Block(this Thread thread, TimeSpan timeout)
{
new WakeSleepClass(timeout).SleepThread();
}
class WakeSleepClass
{
bool locked = true;
readonly TimerDisposer timerDisposer = new TimerDisposer();
public WakeSleepClass(int sleepTime)
{
var timer = new Timer(WakeThread, timerDisposer, sleepTime, sleepTime);
timerDisposer.InternalTimer = timer;
}
public WakeSleepClass(TimeSpan sleepTime)
{
var timer = new Timer(WakeThread, timerDisposer, sleepTime, sleepTime);
timerDisposer.InternalTimer = timer;
}
public WakeSleepClass()
{
var timer = new Timer(WakeThread, timerDisposer, Timeout.Infinite, Timeout.Infinite);
timerDisposer.InternalTimer = timer;
}
public void SleepThread()
{
while (locked)
lock (timerDisposer) Monitor.Wait(timerDisposer);
locked = true;
}
public void WakeThread(object key)
{
locked = false;
lock (key) Monitor.Pulse(key);
((TimerDisposer)key).InternalTimer.Dispose();
}
class TimerDisposer
{
public Timer InternalTimer { get; set; }
}
}
}
class Program
{
private static readonly Queue<CancellationTokenSource> tokenSourceQueue = new Queue<CancellationTokenSource>();
static void Main(string[] args)
{
CancellationTokenSource tokenSource = new CancellationTokenSource();
tokenSourceQueue.Enqueue(tokenSource);
ConcurrentDictionary<int, int> startedThreads = new ConcurrentDictionary<int, int>();
for (int i = 0; i < 10; i++)
{
Thread.Sleep(1000);
Task.Factory.StartNew(() =>
{
startedThreads.AddOrUpdate(Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.ManagedThreadId, (a, b) => b);
for (int j = 0; j < 50; j++)
Task.Factory.StartNew(() => startedThreads.AddOrUpdate(Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.ManagedThreadId, (a, b) => b));
for (int j = 0; j < 50; j++)
{
Task.Factory.StartNew(() =>
{
while (!tokenSource.Token.IsCancellationRequested)
{
if (startedThreads.ContainsKey(Thread.CurrentThread.ManagedThreadId)) Console.WriteLine("Thread reused");
Thread.CurrentThread.Block(10);
if (startedThreads.ContainsKey(Thread.CurrentThread.ManagedThreadId)) Console.WriteLine("Thread reused");
}
}, tokenSource.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default)
.ContinueWith(task =>
{
WriteExceptions(task.Exception);
Console.WriteLine("-----------------------------");
}, TaskContinuationOptions.OnlyOnFaulted);
}
Thread.CurrentThread.Block();
}, tokenSource.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default)
.ContinueWith(task =>
{
WriteExceptions(task.Exception);
Console.WriteLine("-----------------------------");
}, TaskContinuationOptions.OnlyOnFaulted);
}
Console.Read();
}
private static void WriteExceptions(Exception ex)
{
Console.WriteLine(ex.Message);
if (ex.InnerException != null)
WriteExceptions(ex.InnerException);
}
}
}
A: If you specify TaskCreationOptions.LongRunning when starting the task, that provides a hint to the scheduler, which the default scheduler takes as an indicator to create a new thread for the task.
It's only a hint - I'm not sure I'd rely on it... but I haven't seen any counterexamples using the default scheduler.
A: Just start threads with new Thread() and then Start() them
static void Main(string[] args)
{
ConcurrentDictionary<int, int> startedThreads = new ConcurrentDictionary<int, int>();
for (int i = 0; i < 10; i++)
{
new Thread(() =>
{
new Thread(() =>
{
startedThreads.AddOrUpdate(Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.ManagedThreadId, (a, b) => b);
}).Start();
for (int j = 0; j < 100; j++)
{
new Thread(() =>
{
while (true)
{
Thread.Sleep(10);
if (startedThreads.ContainsKey(Thread.CurrentThread.ManagedThreadId))
Console.WriteLine("Thread reused");
}
}).Start();
}
}).Start();
}
Console.Read();
}
Tasks are supposed to be managed by the scheduler. The whole idea of Tasks is that the runtime will decide when a new thread is needed. On the other hand if you do need different threads chances are something else in the code is wrong like overdependency on Thread.Sleep() or thread local storage.
As pointed out you can create your own TaskScheduler and use tasks to create threads but then why use Tasks to begin with?
A: Here is a custom TaskScheduler that executes the tasks on a dedicated thread per task:
public class ThreadPerTask_TaskScheduler : TaskScheduler
{
protected override void QueueTask(Task task)
{
var thread = new Thread(() => TryExecuteTask(task));
thread.IsBackground = true;
thread.Start();
}
protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
{
return TryExecuteTask(task);
}
protected override IEnumerable<Task> GetScheduledTasks() { yield break; }
}
Usage example:
var parallelOptions = new ParallelOptions()
{
MaxDegreeOfParallelism = 3,
TaskScheduler = new ThreadPerTask_TaskScheduler()
};
Parallel.ForEach(Enumerable.Range(1, 10), parallelOptions, item =>
{
Console.WriteLine($"{DateTime.Now:HH:mm:ss.fff}" +
$" [{Thread.CurrentThread.ManagedThreadId}]" +
$" Processing #{item}" +
(Thread.CurrentThread.IsBackground ? ", Background" : "") +
(Thread.CurrentThread.IsThreadPoolThread ? ", ThreadPool" : ""));
Thread.Sleep(1000); // Simulate CPU-bound work
});
Output:
20:38:56.770 [4] Processing #3, Background
20:38:56.770 [5] Processing #2, Background
20:38:56.770 [1] Processing #1
20:38:57.782 [1] Processing #4
20:38:57.783 [8] Processing #5, Background
20:38:57.783 [7] Processing #6, Background
20:38:58.783 [1] Processing #7
20:38:58.783 [10] Processing #8, Background
20:38:58.787 [9] Processing #9, Background
20:38:59.783 [1] Processing #10
Try it on Fiddle.
This custom TaskScheduler allows the current thread to participate in the computations too. This is demonstrated in the above example by the thread [1] processing the items #1, #4, #7 and #10. If you don't want this to happen, just replace the code inside the TryExecuteTaskInline with return false;.
Another example, featuring the Task.Factory.StartNew method. Starting 100 tasks on 100 different threads:
var oneThreadPerTask = new ThreadPerTask_TaskScheduler();
Task[] tasks = Enumerable.Range(1, 100).Select(_ =>
{
return Task.Factory.StartNew(() =>
{
Thread.Sleep(1000); // Simulate long-running work
}, default, TaskCreationOptions.None, oneThreadPerTask);
}).ToArray();
In this case the current thread is not participating in the work, because all tasks are started behind the scenes by invoking their Start method, and not the
RunSynchronously.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/13570579",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
}
|
Q: How to order by time and time only in C#? I have this recorded in SQL Server:
1- startTime (datetime): 5/2/2009 08:30 (brazilian time format: d/m/y)
2- startTime (datetime): 4/2/2009 14:30 (brazilian time format: d/m/y)
My application just records time... the date it's SQL that generates by itself be getting the date of today.
When I ask VS 2008 to order this datetime fields, it returns me that code #2 is before #1, because 4/2/2009 comes before 5/2/2009.
But, actually I want it to order by time only and ignore the date.
Is it possible??
Thanks!!
André
A: You might also try fixing your app so it always saves the same base date with the time (like '01/01/1900' or whatever) and then you do not have to do all these slow and inefficient date stripping operations every time you need to do a query.
Or as Joel said, truncate or strip off the date portion before you do the insert or update.
A: from d in dates
orderby d.TimeOfDay
select d;
or
dates.OrderBy(d => d.TimeOfDay);
Note: This will work as long as this is plain LINQ and not LINQ-to-SQL. If you're using LINQ-to-SQL to query your database, you'll need something that will translate to SQL.
A: Well, you can't really store a datetime without a date, but you could just store the total seconds as an double (using @florian's method).
You'd have to add a second method to convert this back to a date in your object, if you still need a date, such as:
public class BusinessObjectWithDate
{
private string _someOtherDbField = "";
private double _timeInMS = 0; // save this to the database
// sort by this? in sql or in code. You don't really need this
// property, since TimeWithDate actually saves the _timeInMS field
public double TimeInMS {
get { return _timeInMS; }
}
public DateTime TimeWithDate { // sort by this too, if you want
get { return (new DateTime(1900,1,1).AddMilliseconds(_timeInMS)); }
set { _timeInMS = value.TimeOfDay.TotalMilliseconds; }
}
}
var f = new BusinessObjectWithDate();
MessageBox.Show( f.TimeWithDate.ToString() ); // 1/1/1900 12:00:00 AM
f.TimeWithDate = DateTime.Now;
MessageBox.Show( f.TimeWithDate.ToString() ); // 1/1/1900 1:14:57 PM
You could also just store the real date time, but always overwrite with 1/1/1900 when the value gets set. This would also work in sql
public class BusinessObjectWithDate
{
private DateTime _msStoredInDate;
public DateTime TimeWithDate
{
get { return _msStoredInDate; }
set {
var ms = value.TimeOfDay.TotalMilliseconds;
_msStoredInDate = (new DateTime(1900, 1, 1).AddMilliseconds(ms));
}
}
}
A: Try this in your sql:
ORDER BY startTime - CAST(FLOOR(CAST(startTime AS Float)) AS DateTime)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/517661",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Get Values From a Specific Column Into a Dropdown Want to ask if there's a quick way, an automated or using formulas for this scenario.
So I have "config" sheet, and each columns is a list used for a specific dropdown.
config!A:A = clientA
config!B:B = clientB
In a "summary" sheet, I need to add a dropdown in column C depending on the column A
For example summary!A2 contains "client A" so the dropdown in summary!C2 will show the list of clientA
And summary!A3 contains "client B" so the dropdown in summary!C3 will show the list of clientB
What I currently do is named the range each in the "config" then in "summary" I put the Data Validation for the specific name.
I was wondering if there's a custom formula that I can put in the Data Validation for Column C that depends on the value in column A. The only challenge is there are spaces so in the Named Range I remove the space. And since it depends on the column, the row number is moving.
Looking for a formula since I am avoiding App Script for this specific file. Thanks
Hopefully someone could help me on this.
Thanks much.
You are all awesome!
A: What you can do is set an Auxiliary sheet (or extra columns far in "Summary"). You can set Summary!C2 the next Data Validation:
=Auxiliary!A1:1
Open the settings of that data validation and make sure there are no anchors (no $, for example A$1). If there is some, delete them
Close it and then copy and paste special - Data Validation only to the rest of the cells
This way C2 will be associated with row 2 from Auxiliary, C3 with row 3 and so on
Then, you can go to Auxiliary and set a formula in each row to filter the values according to B2, B3 (or however you identify the client... (a Query, or Filter) --> You'll probably need to transpose the information, so the list becomes a row
With that done, each data validation will depend now on the value of that row
Re-reading your example, you can do the same but instead of filter you can transpose the entire Config sheet and you'll have a row per client
......
You have an example here: https://docs.google.com/spreadsheets/d/1jF5XoBkQll5tHEjADg508NMznmbuB43tyWv5R2S1mM8/edit?usp=sharing
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/74405910",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Entity Framework object graph deletion with Breeze I am encountering a recurring problem that just makes no sense, and hoping someone (in the Breeze team?) can shed some light.
The following model illustrates the entities in question.
As you can see, I'm adhering pretty strictly to Entity Framework conventions in my property names, and as a result, if I check in SQL the cascade on delete rules are set by EF code first when it creates the db.
Now, when I try to delete a BusUnit manually in SQL, the delete cascades correctly and the corresponding BusUnitDimensions are also deleted, as it should be. Likewise, if I delete a Dimension in SQL, the corresponding BusUnitDimensions are also deleted.
However, in my application, if I mark a BusUnit as setDeleted with Breeze and then try saveChanges, I get the following error.
The operation failed: The relationship could not be changed because one
or more of the foreign-key properties is non-nullable. When a change is
made to a relationship, the related foreign-key property is set to a null
value. If the foreign-key does not support null values, a new relationship
must be defined, the foreign-key property must be assigned another
non-null value, or the unrelated object must be deleted.
Strangely though, if I mark a Dimension for deletion and then save (within Breeze), the cascaded delete works correctly and both the Dimension and its corresponding BusUnitDimensions are deleted.
So, why the inconsistency? Why are the cascaded delete rules in SQL not being applied for BusUnits but yet they're working for Dimensions? I've read elsewhere that Breeze does not support cascaded deletes, but then why is my Dimensions case working?
EDIT:
I've removed my previous edits as they weren't relevant. The changes below follow on from Ward's answer...
My model now looks like this, and BusUnitDims now uses BusUnitId and DimId as a compound key, and I've added a bool, IsBud for the purposes of payload.
I haven't yet implemented deletes for BusUnits, but already if I try delete a Dim, I'm getting the same error message:
The operation failed: The relationship could not be changed because one
or more of the foreign-key properties is non-nullable. When a change is
made to a relationship, the related foreign-key property is set to a null
value. If the foreign-key does not support null values, a new relationship
must be defined, the foreign-key property must be assigned another
non-null value, or the unrelated object must be deleted.
I have noticed that cascaded deletes is no longer enabled, and in fact, to get EF to build the database I to add the following configuration:
modelBuilder.Entity<BusUnitDim>()
.HasRequired(bud => bud.BusUnit)
.WithMany(bu => bu.BusUnitDims)
.HasForeignKey(bud => bud.BusUnitId)
.WillCascadeOnDelete(false);
modelBuilder.Entity<BusUnitDim>()
.HasRequired(bud => bud.Dim)
.WithMany(d => d.BusUnitDims)
.HasForeignKey(bud => bud.DimId)
.WillCascadeOnDelete(false);
So, with cascading now explicitly not in place, I can understand why the error occurs. Does that imply that in the controller, one has to specifically mark each map for deletion when deleting a parent Dim or BusUnit and before saveChanges is called, or is there some way to configure EF to take advantage of cascaded deletes as this would hugely simplify the code in my controller?
(PS: it gets even more complex, because BusUnitDims ends up having a further join table of its own, MetricBusUnitDims to accommodate yet another entity in the model and their relationships. This is why I'm trying to get the principles right early on)
EDIT: (A CONTROLLER SOLUTION FOR BUSUNITS)
So, the following approach works for BusUnits:
function deleteBusUnit(busUnitVm) { // note that you pass in the item viewmodel, not the entity
var busUnit = busUnitVm.busUnit;
var mapVms = busUnitVm.dimMapVms;
var dimHash = createBusUnitDimHash(busUnit);
mapVms.forEach(function (mapVm) {
var map = dimHash[mapVm.dim.id];
if (map) {
datacontext.markDeleted(map);
}
});
datacontext.markDeleted(busUnit);
save().then(function() { getDBoardConfig(); });
}
}
Is this the correct approach? if so, I'll still have to figure out the following:
*
*How to approach Dims. These are different becuase the item viewmodel is defined for BusUnits.
*How to approach the situation where there is a join tabel one level down, e.g. MetricBusUnitDIm.
EDIT: (A CONTROLLER SOLUTION FOR DIMS)
function deleteDim(dim) {
return bsDialog.deleteDialog(dim.name, true)
.then(function () {
vm.busUnitVms.forEach(function (busUnitVm) {
busUnitVm.busUnit.busUnitDims.forEach(function (bud) {
if (bud.dimId === dim.id) {
datacontext.markDeleted(bud);
}
});
});
datacontext.markDeleted(dim);
save().then(function () { getDboardConfig(); });
});
}
A: I believe your problems are traceable to the fact that your mapping table BusUnitDimension has its own primary key, Id, as opposed to the more typical approach in which the BusUnitId and DimensionId FK properties together comprise the compound primary key of BusUnitDimension.
Observe that OrderDetails in Northwind and the HeroPoweMap in the Breeze many-to-many example have compound keys.
Your choice creates complications.
First, it becomes possible to create multiple BusUnitDimension entities representing the same association between BusUnit and Dimension (i.e., they all have the same pair of FKs). The database may be able to prevent this (it's been a long time since I looked) but whether it does or doesn't, it won't prevent you from creating those duplicates in Breeze ... and maybe not in EF either.
Secondly, it opens you up to the problem you're currently facing. If those mapping entities are in the DbContext when you perform the delete, EF may (apparently does) try to null their FK properties as it sets either BusUnit or Dimension to the deleted state.
You can get around this, as has been suggested, by making both the BusUnitId and DimensionId FK properties nullable. But that is contrary to the semantics as a BusUnitDimension must link a real BusUnit to a real Dimension; they aren't optional. The practical consequence may be that you don't get cascade delete from the EF perspective if you do this (not sure if the DB will enforce that either). That means you'd have orphaned BusUnitDimension rows in your database with one or both FKs being null. I speculate because I'm not used to getting into this kind of trouble.
Another approach would be to set their FK values to zero (I think Breeze does this for you). Of course this implies the existence of BusUnit and Dimension table rows with Id == 0, if only during the delete operation.
Btw, you could actually have such "sentinel entities" in your DB.
You must make sure that these BusUnitDimension are in the deleted state or EF (and the DB) will either reject them (referential integrity constraint) or orphan them (you'll have BusUnitDimension rows in your database with one or both FKs being zero).
Alternatively, if you know that the DB will cascade delete them, you can simply remove them from the DbContext (remove from the EntityInfoMap in the EFContextProvider). But now you have to tell the Breeze client to get rid of them too if it happens to have them hanging around.
Enough Already!
These wandering thoughts should tell you that you've got yourself in a jam here with way too much bookkeeping ... and all because you gave BusUnitDimension its own Id primary key.
It gets a lot easier if you give BusUnitDimension the compound key, {BusUnitId, DimensionId}. You must also give it a payload property (anything will do) to prevent EF from hiding it in its "many-to-many" implementation because Breeze doesn't handle that. Adding any nonsense property will do the trick.
HTH
A: That has nothing to do with Breeze.. The originating message is from Entity Framework..
inside BusUnitDimension Model update BusUnitId property to:
public Nullable<int> BusUnitId { get; set; }
Notice the Nullable struct..
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/21679073",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Rename iTunes files with AppleScript I've got this beautiful AppleScript inside iTunes which relocates selected files to my holy music folder. However I'd also like to rename the file to {Artist} - {Trackname}.extension (extension is mp3 99% of the time).
While artist and trackname are known earlier in the script I've got no clue how to also make them available in the move_the_files-function.
I hope any AppleScript (self-flagellating) enthusiasts can help me.
This is the script:
property my_title : "Re-Locate Selected"
global selectedTracks, originalLocs
global newDirectory
tell application "iTunes"
ok_v(get version) of me
set selectedTracks to selection
if selectedTracks is {} then return
if (get class of (item 1 of selectedTracks)) is not file track then return
set originalLocs to {}
repeat with i from 1 to (length of selectedTracks)
tell item i of selectedTracks to set {nom, loc, artist} to {get name, get location, get artist}
# log ("artis" & artist)
if loc is missing value then
display dialog "The file for \"" & nom & "\" appears to be missing. ..." buttons {"Cancel", "OK, Skip It"} default button 1 with icon 2 giving up after 30 with title "Need a decision..."
end if
set end of originalLocs to (loc as text)
end repeat
# OKAY to proceed
display dialog "This script will re-locate the files of the selected tracks to a new folder. All meta-data will be preserved." buttons {"Cancel", "Execute"} default button 2 with title my_title
# set newDirectory to (choose folder with prompt "Move files of selected tracks to:")
set newDirectory to "/Volumes/Daten/Musik/Tracks/2014/12"
# log ("rez: " & newDirectory)
my move_the_files()
tell application "iTunes" to if (get frontmost) then display dialog "Done, handsome <3!" buttons {"Cool"} default button 1 with title my_title giving up after 15
end tell
to move_the_files()
repeat with t from 1 to (length of selectedTracks)
try
with timeout of 300 seconds
set f to (item t of originalLocs) as text
do shell script "cp -p " & quofo(f) & space & quofo(newDirectory)
relocate((item t of selectedTracks), fig_new_loc(f))
tell application "Finder" to delete f
end timeout
on error m
logger(m)
end try
end repeat
end move_the_files
to fig_new_loc(f)
return (newDirectory & (last item of text_to_list(f, ":"))) as text
end fig_new_loc
on quofo(t)
return (quoted form of POSIX path of (t as text))
end quofo
on ok_v(v)
if (do shell script ("echo " & quoted form of (v as text) & "|cut -d . -f 1")) as integer < 10 then
display dialog return & "This script requires iTunes v10.0 or better..." buttons {"Cancel"} default button 1 with icon 0 giving up after 15 --with title my_title
end if
end ok_v
to relocate(t, nf)
tell application "iTunes" to set location of t to (nf as alias)
end relocate
on replace_chars(txt, srch, repl)
set text item delimiters to srch
set item_list to every text item of txt
set text item delimiters to repl
set txt to item_list as string
set text item delimiters to ""
return txt
end replace_chars
on text_to_list(txt, delim)
set saveD to text item delimiters
try
set text item delimiters to {delim}
set theList to every text item of txt
on error errStr number errNum
set text item delimiters to saveD
error errStr number errNum
end try
set text item delimiters to saveD
return (theList)
end text_to_list
on list_to_text(theList, delim)
set saveD to text item delimiters
try
set text item delimiters to {delim}
set txt to theList as text
on error errStr number errNum
set text item delimiters to saveD
error errStr number errNum
end try
set text item delimiters to saveD
return (txt)
end list_to_text
to logger(t)
log t
try
do shell script "logger -t" & space & quoted form of my_title & space & quoted form of (t as text)
end try
end logger
A: Using cp unix command, you can copy and rename at same time.
I changed a bit your script to reduce it and I set the copy/rename inside the main loop. remove the "--" before the "set location" and the do shell script "rm". I leave them to be more safe for debugging.
On first row, I assigned, for my tests, the Newdirectory to my desktop. you must adjust this.
set NewDirectory to (path to desktop folder from user domain) as string -- my desktop for example
tell application "iTunes"
ok_v(get version) of me
set selectedTracks to selection
if selectedTracks is {} then return
if (get class of (item 1 of selectedTracks)) is not file track then return
set originalLocs to {}
repeat with i from 1 to (count of selectedTracks)
tell item i of selectedTracks to set {TName, Tloc, Tartist} to {get name, get location, get artist}
if Tloc is missing value then
display dialog "The file for \"" & TName & "\" appears to be missing. ..." buttons {"Cancel", "OK, Skip It"} default button 1 with icon 2 giving up after 30 with title "Need a decision..."
end if
tell application "Finder" to set FExt to name extension of Tloc
set NewName to NewDirectory & Tartist & "_" & TName & "." & FExt
do shell script "cp " & quoted form of (POSIX path of Tloc) & " " & quoted form of (POSIX path of NewName)
--set location of (item i of selectedTracks) to NewName
--do shell script "rm " & quoted form of (posix path of Tloc)
end repeat
end tell
on ok_v(v)
if (do shell script ("echo " & quoted form of (v as text) & "|cut -d . -f 1")) as integer < 10 then
display dialog return & "This script requires iTunes v10.0 or better..." buttons {"Cancel"} default button 1 with icon 0 giving up after 15 --with title my_title
end if
end ok_v
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/32148744",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: React Router not working correctly I am new to react and have no idea why this wouldnt be working.
My router code is here:
import React from 'react';
import { Route, IndexRoute } from 'react-router';
import App from './components/App';
import HomePage from './components/home/HomePage';
export default (
<Route path="/" component={App}>
<IndexRoute component={HomePage} />
<Route path="example" component={HomePage} />
</Route>
);
So what happens with this code is:
localhost/ displays fine
localhost/example does not display
localhost/example link from the header on the homepage displays, but pressing refresh does not
Thanks for any help, I appreciate it!
here is my webpack config:
const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
context: path.join(__dirname, "/client"),
entry: [
'webpack-dev-server/client?http://127.0.0.0:5000/',
'webpack/hot/only-dev-server',
'react-hot-loader/patch',
'./src/index.js'
],
output: {
path: path.join(__dirname, "/client/dist"),
filename: '[name].js',
publicPath: '/'
},
resolve: {
extensions: ['.js', '.jsx', '.json']
},
devServer: {
historyApiFallback: true
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: [ 'babel-loader', 'react-hot-loader/webpack' ],
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: './static/template.html',
inject: 'body',
filename: 'index.html'
}),
new webpack.optimize.OccurrenceOrderPlugin(),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('development')
})
]
};
app.js snippet:
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(__dirname + 'client/dist'));
app.use(webpackDevMiddleware(compiler, {
publicPath: webpackConfig.output.publicPath,
hot: true,
historyApiFallback: true,
stats: {
colors: true
}
}));
I am using localhost:5000 . The question linked did not fix my problem
A: FYI, Starting in version 4.0, React Router no longer uses the IndexRoute.
Also for your path, change "example" to "/example"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/44426693",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Swift 3 xcode 8 failed to import Lock and RxSwift in to my project In my project, created by other, i have problems with some libraries that i'm "podding" them in my pod file, using cocoapod.
this is my pod file
# Uncomment this line to define a global platform for your project
platform :ios, "9.3"
target 'classme' do
use_frameworks!
inhibit_all_warnings!
pod 'Firebase/Core'
pod 'Firebase/Database'
pod 'Firebase/Storage'
pod 'Firebase/DynamicLinks'
pod 'Firebase/Auth'
pod 'Firebase/Messaging'
pod 'Lock'
pod 'RxSwift'
pod 'RxCocoa'
pod 'RxDataSources'
pod 'Auth0'
pod 'HockeySDK'
pod 'MaterialControls'
pod 'libPhoneNumber-iOS'
pod 'SwiftLint'
pod 'Mixpanel-swift'
pod ‘AppsFlyerFramework’
end
post_install do |installer|
installer.pods_project.targets.each do |target|
target.build_configurations.each do |config|
config.build_settings['SWIFT_VERSION'] = '3.0'
end
end
end
When trying to import the Lock i get the following message
No such module 'Lock'
Also for the RxSwift
How it can be solved?
A: I have used the myApp.xcworkspace instead of myApp.xcodeproj and the problem fixed.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/45857444",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can I mongoimport with Meteor? I made a mongoexport of some local data that I now want to mongoimport into production. I'm trying the following command:
mongoimport -h production-db-b2.meteor.io --port 27017 --username client --password password_that_expires_fast --collection collection_name --db prod_meteor_com --file ./mongo_import.json
This appears to be quite similar to the solution posted here: how to mongoimport data to deployed meteor app?
However, it's not working with the error couldn't connect to [production-db-b2.meteor.io:27017] couldn't connect to server production-db-b2.meteor.io:27017
How do I get around this?
(Note: I also tried concatenating the port and host into -h production-db-b2.meteor.io:27017 to no avail)
A: This is what worked for me in the past. I'm not exactly sure of why it works and your solution doesn't, but I think it has something to do with not specifying the collection or the file in a certain way.
mongoimport -u client -h production-db-b2.meteor.io:27017 -d myapp_meteor_com -p passwordthatexpiresreallyfast /pathtofile
A: check your port. the local meteor mongodb uses 3001 not 27017...
i'm using the following line successfully
mongoimport --host localhost:3001 -d meteor -c TestCollection --type csv --file /home/ubuntu/meteorMongoImportTest/results1.txt --headerline
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/19963166",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to access a form inside a material step template in AngularDart? I am trying to combine a material-stepper with a form in AngularDart. The continue button from the material-stepper should be disabled as long as some required inputs are missing from the form. When the form is completed, the continue button should trigger a submit on the form.
However, as the step is a template, it creates its own scope and the reference to form cannot be used outside this scope. Therefore, the following code will not compile with error The getter 'form' isn't defined for the class....
<material-stepper>
<template step
name="Personal data"
(continue)="form.submit()"
[canContinue]="form.valid"
>
<form #form="ngForm">
<material-input required
label="Name"
ngControl="name"
></material-input>
</form>
form complete: {{form.valid}}
</template>
</material-stepper>
Is there another way to access the form or another solution to accomplish the same behavior?
A: The way that templates work is that the components aren't instantiated until they are needed. In this case you are asking for the state of a form before the form is added to the component tree.
In terms of what you could do I suggest following Gunter's answer in the comments:
I'd use a shared service that you provide in the component that
contains above markup and add a component or directive to the
that injects that service and communicates from the
template with the parent using that service. The parent that provides
the service needs also to inject it so that both communication ends
have a reference to the same service instance. The service can use a
stream to allow one (or both) party to emit events and the other to
subscribe to them.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/52272510",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to remove 'My Approvals' tab from Approval screen (EP503010) in Acumatica? I am trying to remove My Approvals tab from Approval screen (EP503010). But challenge is its not like other pages. This screen built in with some automation steps and conditions. How to remove My Approval tab?
A: I found the solution for this question. We need to use filter in screen in top corner
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/66850269",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to solve the constant to the negative gurobi variable power in python I am using Gurobi with Python to solve the following problem:
max. (1-Var(3^{-VC})) * (mean(VC)) s. t. sum(C) <= 3 and C in {0,1}
Whereas, C is a binary decision vector of length n. V is a coefficient (information) matrix of size mxn (m<=n). Here is my python code:
from gurobipy import *
import numpy as np
# EXAMPLE DATA SET
# ----------------------------------------------
V = np.matrix((
(1,1,1,1,0,0),
(0,1,1,1,1,0),
(1,1,0,0,0,1),
(0,0,0,1,1,1)))
V = V.tolist()
# LOCAL FUNCTIONS
# ----------------------------------------------
# V times C
def V_x_C(V,C):
VC = {}
for i in range(np.shape(V)[0]):
ij_sum = 0;
for j in range(len(C)):
ij_sum += V[i][j]*C[j]
VC[i] = ij_sum
return VC
# Square
def sqr(vec):
sqr_vec = {}
for i in range(len(vec)):
sqr_vec[i] = vec[i]*vec[i]
return sqr_vec
# Variance
def variance(vec):
mean_vec = sum(vec)/len(vec)
diff_vec = vec-mean_vec
sqdf_vec = sqr(diff_vec)
var_vec = (sum(sqdf_vec))/len(vec)
return var_vec
# Power
def pwr(scalr,vec):
reslt = {}
for i in range(len(vec)):
reslt[i] = scalr**vec[i]
return reslt
# ObjVar
def objVar(V,C):
VC = V_x_C(V,C)
negVC = np.dot(-1,VC.values())
pwrVC = pwr(3,negVC)
varVC = variance(1-pwrVC)
return varVC
# ObjMean
def objMean(V,C):
VC = V_x_C(V,C)
sumVC = 0
for i in range(len(VC)):
sumVC += VC[i]
meanVC = float(sumVC)/len(VC)
return meanVC
# OPTIMIZATION
# ----------------------------------------------
# Create a new model
m = Model("My Model")
# Optimization Variables
C = {}
for i in range(np.shape(V)[1]):
C[i] = m.addVar(vtype=GRB.BINARY)
# The objective is to maximize the costs
m.modelSense = GRB.MAXIMIZE
# Integrate new variables
m.update()
# Objective Function
m.setObjective( (1-objVar(V,C))*(objMean(V,C)) )
# Constraint
m.addConstr( quicksum ([C[i] for i in range(np.shape(V)[1])]) <= 3)
m.optimize()
# Publish results
for v in m.getVars():
print('%s %g' % (v.varName, v.x))
I am getting following error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/asif/anaconda/lib/python2.7/site-packages/spyderlib/widgets/externalshell/sitecustomize.py", line 682, in runfile
execfile(filename, namespace)
File "/home/asif/anaconda/lib/python2.7/site-packages/spyderlib/widgets/externalshell/sitecustomize.py", line 78, in execfile
builtins.execfile(filename, *where)
File "/media/Win7/DATA/MPS-GSMR/PLANNER/TestPython/question_gurobi_form.py", line 83, in <module>
m.setObjective( (1-objVar(V,C))*(objMean(V,C)) )
File "/media/Win7/DATA/MPS-GSMR/PLANNER/TestPython/question_gurobi_form.py", line 52, in objVar
pwrVC = pwr(3,negVC)
File "/media/Win7/DATA/MPS-GSMR/PLANNER/TestPython/question_gurobi_form.py", line 45, in pwr
reslt[i] = scalr**vec[i]
TypeError: unsupported operand type(s) for ** or pow(): 'int' and 'LinExpr'
So apparently, the main issue is how to use gurobi variable as power on a constant. Please suggest me to address the bug in particular and the overall implementation in general.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/31382225",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: When creating a form in React .map() does not populate select > options correctly, but works for a normal div I am using React (and Redux) and have a form that I need to populate a dropdown with data via an API call.
When I use .map() within a standard div the list of results outputs correct. This is the code:
<div>
{categories &&
categories.map((category, i) => (
<option
key={i}
label={category.categoryName}
value={category._id}
name={category.categoryName}
category={category}
>
{category.categoryName}
</option>
))}
</div>
When I then try and map the same data within a select/option dropdown it only renders the first result. i.e. there is no dropdown. Here's this code:
<select
value={categoryName}
onChange={(e) => setCategoryName(e.target.value)}
>
{categories &&
categories.map((category, i) => (
<option
key={i}
label={category.categoryName}
value={category._id}
name={category.categoryName}
category={category}
>
{category.categoryName}
</option>
))}
Here's the full code for the component in a github gist
Thanks in advance for any additional insight you can provide.
Edited to add in actions and reducer:
export const getCategories = () => async (dispatch) => {
try {
const config = {
headers: {
"Content-Type": "application/json",
},
};
const res = await axios.get(
"http://localhost:5000/category/getallcategories",
config
);
dispatch({
type: GET_CATEGORIES,
payload: res.data,
});
console.log("2222" + res.data);
} catch (err) {
dispatch({
type: CATEGORY_ERROR,
payload: { msg: err.response.statusText, status: err.response.status },
});
}
};
And Reducer:
export default function (state = initialState, action) {
const { type, payload } = action;
switch (type) {
case GET_CATEGORIES:
return {
...state,
categories: payload,
loading: false,
};
A: <select> tag should contain the value. In your case it is the state: taskTitle. Onchange should also be under select.
In your code you use this useState:
const [taskTitle, setTaskTitle] = useState("");
So try to change the select to this:
<select
value={taskTitle}
onChange={(e) => setTaskTitle(e.target.value)}>
{categories &&
categories.map((category, i) => (
<option
key={i}
label={category.categoryName}
value={category._id}
name={category.categoryName}
category={category}
>
{category.categoryName}
</option>
))}
</select>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62066985",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Highstock scrollbar not covering the whole length in multiple series I'm having an issue with the scrollbar in multiple series line chart where x-axis is date.
Looks like the max length of the scrollbar is determined by the length of the first (older) series.
Although when pressing the 'All' button in range selector I can see all of the series, as the first series ends before the others, as soon as I touch the scrollbar the chart readjusts so that all I can see is the data contained in the first series' length period.
After that, if I want to see the series after the first one has ended, I need to drag the chart or click the 'All' button in range selector again.
I would really appreciate any help you could provide.
Thanks in advance!
jsFiddle: http://jsfiddle.net/8DdP4/2/
A: Indeed, it's not supported to cover all series. Here you can find workarund.
With demo: http://jsfiddle.net/highcharts/SD4XN/
In short: in callback add series to the navigator on your own:
function (chart) {
chart.addSeries({
data: seriesOptions[2].data,
xAxis: 1,
yAxis: 1
});
}
A: The scrollbar you refer to is called navigator.
There is a property in navigator called series which is defined as:
series: Object
Options for the navigator series. Available options are the same as
any series, documented at plotOptions and series.
Unless data is explicitly defined on navigator.series, the data is
borrowed from the first series in the chart.
You can see it here.
Im not sure if you can build your navigator from multiple series, i suppose it is posibles. In case it is not build build the navigator with the largest.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/23607273",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to get wallet of user if its delete once in hypeledger I need one help as I have confusion in one condition let's user register and enroll to the network and it's secret which is generate at time of registration saved in mongodb but somehow it's wallet got deleted so we need to register the user again or we can get wallet again just enroll user again with same secret?
A: Yes, you can enroll the Identity again using the same secret. Assuming that the max number of enrollments has not been exceeded - but the default is "-1" (unlimited).
FYI each time you enroll you get different credentials, but they are valid for the same Identity.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/57974362",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Avoid showing logger entries in console I have one "basic" logging configuration that logs to stdout in my project.
stream_handler = logging.StreamHandler()
stream_handler.setLevel(logging.INFO)
SERVER_FORMAT = "[%(asctime)s] %(levelname)s [%(name)s:%(filename)s:%(lineno)d] %(message)s"
DATETIME_FORMAT = "%d/%b/%Y %H:%M:%S"
logging.basicConfig(
level=logging.INFO,
format=SERVER_FORMAT,
datefmt=DATETIME_FORMAT,
handlers=[stream_handler])
I have also another logger user_logger that should not print anything. Instead, it should store log entries in a variable.
user_logger = logging.getLogger('user_logger')
user_logger.setLevel(logging.INFO)
log_capture_string = io.StringIO()
log_capture_string_handler = logging.StreamHandler(log_capture_string)
log_capture_string_handler.setLevel(logging.INFO)
log_capture_string_handler.setFormatter(logging.Formatter(USER_FORMAT))
user_logger.handlers = [log_capture_string_handler]
The problem is that when I call:
user_logger.info('This should only be in "log_capture_string"')
it prints it to the console.
Do you know how to avoid that?
A: You should set user_logger.propagate = False. logging.propagate docs
If this evaluates to false, logging messages are not passed to the handlers of ancestor loggers.
So, your root logger will not send any data to stderr.
This example outputs nothing
import io
import logging
stream_handler = logging.StreamHandler()
stream_handler.setLevel(logging.INFO)
SERVER_FORMAT = "[%(asctime)s] %(levelname)s [%(name)s:%(filename)s:%(lineno)d] %(message)s"
DATETIME_FORMAT = "%d/%b/%Y %H:%M:%S"
logging.basicConfig(
level=logging.INFO,
format=SERVER_FORMAT,
datefmt=DATETIME_FORMAT,
handlers=[stream_handler])
user_logger = logging.getLogger('user_logger')
user_logger.propagate = False
user_logger.setLevel(logging.INFO)
log_capture_string = io.StringIO()
log_capture_string_handler = logging.StreamHandler(log_capture_string)
log_capture_string_handler.setLevel(logging.INFO)
log_capture_string_handler.setFormatter(logging.Formatter(SERVER_FORMAT))
user_logger.handlers = [log_capture_string_handler]
user_logger.info('This should only be in "log_capture_string"')
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/70511274",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: why does LedoitWolf return zeros for off-diagonal elements? from sklearn.covariance import EmpiricalCovariance, LedoitWolf
a = np.array([[ 0.6278, -1.1273 ],
[ 0.2323, 0.4533 ],
[ 0.3234, 1.5356 ],
[1.7473 , -0.3113 ],
[-0.3525 , 0.2577 ]])
Empirical_cov = EmpiricalCovariance().fit(a)
Empirical_cov.covariance_
array([[ 0.48009421, -0.23144627],
[-0.23144627, 0.77341954]])
LedoitWolf_cov = LedoitWolf().fit(a)
LedoitWolf_cov.covariance_
array([[ 1., -0.],
[-0., 1.]])
Why is LedoitWolf giving me zeros for the off-diagonal elements? I have a few larger datasets in which this happens.
Is this a bug? The empirical covariance is non-zero, so shouldn't LedoitWolf also be non-zero? I read that using LedoitWolf would be slightly more accurate than empirical covariance, but what is the point if most covariance elements turn out to be zero?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/66782024",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Mapping entity to dto with interfaces I've my entity class I retrieve from database:
public class User{
public string Username {get; set;}
public List<IAddress> Addresses {get; set;}
}
public class Address: IAddress{
public string Line1 {get; set;}
public string Line2 {get; set;}
}
public class AddressExtended:Address, IAddress{
public string Line3 {get; set;}
public string Line4 {get; set;}
}
public interface IAddress{
}
I use Automapper to map this entity to the mirrored DTO:
public class UserDto{
[JsonProperty("username")]
public string Username { get; set; }
[JsonProperty("addresses")]
public List<IAddressDto> Addresses { get; set; }
}
public class AddressDto: IAddressDto{
[JsonProperty("line1")]
public string Line1 { get; set; }
[JsonProperty("line2")]
public string Line2 { get; set; }
}
public class AddressExtendedDto:AddressDto, IAddressDto{
[JsonProperty("line3")]
public string Line3 { get; set; }
[JsonProperty("line4")]
public string Line4 { get; set; }
}
public interface IAddressDto{
}
Automapper configuration is the following:
CreateMap<IAddress, IAddressDto>();
CreateMap<Address, AddressDto>();
CreateMap<AddressExtended, AddressExtendedDto>();
The problem is that when I run my application, if in the entity I have 2 addresses and 1 addressExtended, in DTO the Addresses property () is mapped like this:
[
{Proxy<MyProject.Models.Dto.IAddressDto_MyProject_Version=1.0.0.0_Culture=neutral_PublicKeyToken=null>},
{Proxy<MyProject.Models.Dto.IAddressDto_MyProject_Version=1.0.0.0_Culture=neutral_PublicKeyToken=null>},
{Proxy<MyProject.Models.Dto.IAddressDto_MyProject_Version=1.0.0.0_Culture=neutral_PublicKeyToken=null>}
]
The Username property it is correctly valued.
What I miss?
UPDATE
I added a fiddler here:
https://dotnetfiddle.net/ZkUZgp
A: As per my knowledge, one approach solving the issue is using Construct using below code
cfg.CreateMap<Address, AddressDto>();
cfg.CreateMap<AddressExtended, AddressExtendedDto>();
cfg.CreateMap<IAddress, IAddressDto>().ConstructUsing((IAddress addressDto) =>
{
if (addressDto is AddressExtended) return Mapper.Map<AddressExtendedDto>(addressDto);
return Mapper.Map<AddressDto>(addressDto);
});
Edit 1:
Here is the final answer and it solves your problem
cfg.CreateMap<Address, AddressDto>();
cfg.CreateMap<AddressExtended, AddressExtendedDto>();
cfg.CreateMap<IAddress, IAddressDto>().ConstructUsing((addressDto, ctx) =>
{
var destination = Mapper.Instance.ConfigurationProvider.GetAllTypeMaps()
.First(t => t.SourceType == addressDto.GetType());
return ctx.Mapper.Map(addressDto, addressDto.GetType(), destination.DestinationType) as IAddressDto;
});
Instead of getting destination type using LINQ you can build a dictionary and get from it for faster execution.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/52717294",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Encrypt and compress html-codes in iPhone app bundle, unpack on first start My client wants to encrypt/compress the html-code for their medical books in the iPhone bundle, to protect their IP.
Whats is a good way to prepare this file for the app bundle, and what complementary libraries (C, Obj-C) should I use to do the decryption and decompressing on the first launch of the app?
Copying the file to ~/Documents, then working on it seems like the best solution. Thoughts?
A: This is quite tricky... almost impossible to make it really unbreakable. Any reasonnably motivated person will be able to pierce through it. You'll only make it a little harder to do. In any case, you definitely can't store any secret key in the bundle itself. You'd need to securely obtain the decryption key over a secure channel from a server and use it as needed. Even then, someone doing jailbreak would probably be able to run GDB over your running program and extract the secret key in RAM + the secret key would be shared amongst all users of your app... You're essentially trying to implement a DRM scheme, which is inherently flawed by design... Unless you need offline access, you might want to pull the data as needed from a secure erver... at least you "could" throttle information leakage...
A: Here's a few thoughts.
If the book text is all alphanumeric data, then don't save the data as ASCII - save them in your own binary encoded format (for instance use 5 bits instead of 8 and pack into words). That gives you a bit of compression, slight obfuscation and a very cheap (in clock cycles) decompression. You would have a data format that is quick to access on the fly and will keep the casual curious hacker out of the text. Clock cycles would be my main concern and security second.
Another idea is store the decrypt key for a typical Blowfish encryption in obfuscated format in the app. Split into two or three constants that require some odd operation to restore for instance. But of course, now the overhead of Blowfish or whatever will be your concern.
Since you will not be able to implement perfect security (perfection is extremely expensive), the IP owners will have to use traditional copyright and trade secret techniques to fully protect their property. You've made it harder to hack, but it's still up to the lawyers to be diligent, just a book on the shelf in the reserved section of the library (no photocopies please!).
Cheers
A: I would keep the documents encrypted if I were you and just decrypt them as needed. One would easily be able to access the decrypted documents on a jailbroken device.
See the "Security Overview" document and the CryptoExercise sample code for encryption techniques
A: You probably won't like it, but the best way is to just not use HTML. Once you pass the decrypted HTML to UIWebView, it is very easy for a malicious user to steal it at that level, defeating any purpose your encryption algorithm had. A UIView subclass with custom drawing code and a custom encrypted backing format will be much more difficult to work around
A: From Mac OS X and iPhone OS Security Services:
You can use Keychain Services to
encrypt and store small amounts of
data (see Keychain Services Reference
and Keychain Services Programming
Guide). If you want to encrypt or
decrypt larger amounts of data in Mac
OS X, you can use the Common Security
Services Manager (CSSM) Cryptographic
Services Manager. This manager also
has functions to create and verify
digital signatures, generate
cryptographic keys, and create
cryptographic hashes. In iPhone OS,
the Certificate, Key, and Trust
Services API provides functions for
generating encryption keys, creating
and verifying digital signatures, and
encrypting blocks of data; see
Certificate, Key, and Trust Services
Reference.
It's always a choice between performance (encryption just doesn't come free) and security (security and everything else, really). But what else is new? If you keep the individual files small enough, maybe decryption doesn't slow you down much. Alternatively, you may consider predictive decryption such that you have certain files being decrypted in the background, say those linked from the currently viewed file, etc. I realize, however, that concurrancy on the iPhone may be pretty spotty (I don't know as I haven't dropped the cash for a license). You may also realize performance gains by only encrytping those files that really need it; does an index/table of contents or other often accessed file really need to be encrypted? Does that count as IP your client is worried about?
A: For compression I can recommend QuickLZ (fastest engine I saw, great compression ratio).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/612728",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Selecting all foreign key references on table I need to select all foreign key references on a table. I came up with a query that works, but takes 9 seconds to execute. It would be very nice if someone could help with optimizing it. Thank you very much!
Here is the query:
SELECT A.TABLE_NAME REFENCING_TABLE,
A.COLUMN_NAME REFENCING_COLUMN,
B.TABLE_NAME REFERENCED_TABLE,
B.COLUMN_NAME REFERENCED_COLUMN
from (select TABLE_NAME,
COLUMN_NAME,
REFERENCED_CONSTRAINT_NAME,
POSITION
from all_cons_columns C
join (select CONSTRAINT_NAME,
PK.REFERENCED_CONSTRAINT_NAME
from all_constraints FK
JOIN (select CONSTRAINT_NAME REFERENCED_CONSTRAINT_NAME
from all_constraints
where constraint_type in ('P','U') and
table_name = :tablename) PK
on FK.R_CONSTRAINT_NAME = PK.REFERENCED_CONSTRAINT_NAME
where constraint_type = 'R') FK
on C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME) A
join (select TABLE_NAME,
COLUMN_NAME,
CONSTRAINT_NAME,
POSITION
from all_cons_columns) B
on REFERENCED_CONSTRAINT_NAME = B.CONSTRAINT_NAME AND
A.POSITION = B.POSITION;
A: You may use this query to find all foreign key references on a table:
SELECT
fk.owner fk_schema_owner,fk.table_name fk_table,
fk.column_name fk_column, fk.constraint_name fk_constraint_name,
pk.r_owner pk_schema_owner,
c_pk.table_name pk_table_name, c_pk.constraint_name pk_constraint_name
FROM
all_cons_columns fk
JOIN all_constraints pk
ON fk.owner = pk.owner AND fk.constraint_name = pk.constraint_name
JOIN all_constraints c_pk
ON pk.r_owner = c_pk.owner AND pk.r_constraint_name = c_pk.constraint_name
WHERE pk.constraint_type = 'R' AND fk.table_name = :InputTableName
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/41625168",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to generate non-repeating Random Numbers in Unity I am trying to create a simple Bingo game and want to make sure the numbers are not repeating on the bingo card. I have a random number generator, but for some reason the code I'm using doesn't work as the same numbers will constantly repeat. Could somebody please take a look at my code below and either tell me what I need to fix or fix the code for me?
public Grid(int width, int height, float cellSize)
{
this.width = width;
this.height = height;
this.cellSize = cellSize;
gridArray = new int[width, height];
debugTextArray = new TextMesh[width, height];
for (int x = 0; x < gridArray.GetLength(0); x++)
{
for (int y = 0; y < gridArray.GetLength(1); y++)
{
debugTextArray[x, y] = UtilsClass.CreateWorldText(gridArray[x, y].ToString(), null, GetWorldPosition(x, y) + new Vector3(cellSize, cellSize) * .5f, 20, Color.white, TextAnchor.MiddleCenter);
Debug.DrawLine(GetWorldPosition(x, y), GetWorldPosition(x, y + 1), Color.white, 100f);
Debug.DrawLine(GetWorldPosition(x, y), GetWorldPosition(x + 1, y), Color.white, 100f);
}
}
Debug.DrawLine(GetWorldPosition(0, height), GetWorldPosition(width, height), Color.white, 100f);
Debug.DrawLine(GetWorldPosition(width, 0), GetWorldPosition(width, height), Color.white, 100f);
for (int x = 0; x <= 4; x++)
{
RandomValue(0, x);
RandomValue(1, x);
RandomValue(2, x);
RandomValue(3, x);
RandomValue(4, x);
}
}
private Vector3 GetWorldPosition(int x, int y)
{
return new Vector3(x, y) * cellSize;
}
public void RandomValue(int x, int y)
{
if (x >= 0 && y >= 0 && x < width && y < height)
{
list = new List<int>(new int[Lenght]);
for (int j = 0; j < 25; j++)
{
Rand = UnityEngine.Random.Range(1, 50);
while (list.Contains(Rand))
{
Rand = UnityEngine.Random.Range(1, 50);
}
list[j] = Rand;
gridArray[x, y] = list[j];
}
debugTextArray[x, y].text = gridArray[x, y].ToString();
debugTextArray[2, 2].text = "Free";
}
}
A: As mentioned in the comment on your question, it's probably the easiest to just shuffle the numbers in the range [1,50] and then take the first 25 or however many you want.
The reason your code isn't working properly and you see a lot of repeats is because you're calling the RandomValue() function multiple separate times and the list variable you're comparing against if a value is already on the chart is inside of that function. Meaning that it will only ever check the values it has generated in that call, in this case meaning only for one row.
Also, if you make a list that you know will always be the same size, you should use an array instead. Lists are for when you want the size to be adjustable.
Solution 1:
A very simple way to generate an array with the numbers 1-50 would be to do this:
//Initialize Array
int[] numbers = new int[50];
for (int i = 1; i <= numbers.Length; i++)
{
numbers[i] = i;
}
//Shuffle Array
for (int i = 0; i < numbers.Length; i++ )
{
int tmp = numbers[i];
int r = Random.Range(i, numbers.Length);
numbers[i] = numbers[r];
numbers[r] = tmp;
}
//Get first 'n' numbers
int[] result = Array.Copy(numbers, 0, result, 0, n);
return result;
I'm not sure if it's the most efficient way, but it would work.
Solution 2:
To change your code to check against the entire list, I would change this section:
for (int x = 0; x <= 4; x++)
{
RandomValue(0, x);
RandomValue(1, x);
RandomValue(2, x);
RandomValue(3, x);
RandomValue(4, x);
}
To something like this:
List<int> values = new List<int>();
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
int r = RandomValue(1, 50);
while (values.Contains(r))
{
r = RandomValue(1, 50);
}
values[y * width + x].Add(r);
gridArray[x, y] = r;
}
}
int RandomValue(int min, int max) {
return UnityEngine.Random.Range(min, max);
}
Hope this helps!
A: Basically your concept in function RandomValue() is correct, but problem is it only check in same column, so you have to bring the concept of RandomValue() to Grid() level. You need a List contain all approved value, then check Contains() at Grid().
But in fact you can do it in all one go.
Make sure your width*height not larger than maxValue.
Dictionary<Vector2Int, int> CreateBingoGrid(int width, int height, int maxValue)
{
var grid = new Dictionary<Vector2Int, int>();
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
var num = Random.Range(1, maxValue);
while (grid.ContainsValue(num))
{
num = Random.Range(1, maxValue);
}
grid.Add(new Vector2Int(x, y), num);
}
}
return grid;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62013122",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: error- dalvik.system.PathClassLoader [data/app/com.my.appname-2.apk] I searched a lot for similar kind of error, but I am not getting a solution for it. I am getting this error as soon as I start the app
03-21 10:33:08.100: E/AndroidRuntime(13098): FATAL EXCEPTION: main
03-21 10:33:08.100: E/AndroidRuntime(13098): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.airlife/com.example.airlife.MainActivity}: java.lang.ClassNotFoundException: com.example.airlife.MainActivity in loader dalvik.system.PathClassLoader[/data/app/com.example.airlife-2.apk]
03-21 10:33:08.100: E/AndroidRuntime(13098): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1785)
03-21 10:33:08.100: E/AndroidRuntime(13098): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1893)
03-21 10:33:08.100: E/AndroidRuntime(13098): at android.app.ActivityThread.access$1500(ActivityThread.java:135)
03-21 10:33:08.100: E/AndroidRuntime(13098): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1054)
03-21 10:33:08.100: E/AndroidRuntime(13098): at android.os.Handler.dispatchMessage(Handler.java:99)
03-21 10:33:08.100: E/AndroidRuntime(13098): at android.os.Looper.loop(Looper.java:150)
03-21 10:33:08.100: E/AndroidRuntime(13098): at android.app.ActivityThread.main(ActivityThread.java:4389)
03-21 10:33:08.100: E/AndroidRuntime(13098): at java.lang.reflect.Method.invokeNative(Native Method)
03-21 10:33:08.100: E/AndroidRuntime(13098): at java.lang.reflect.Method.invoke(Method.java:507)
03-21 10:33:08.100: E/AndroidRuntime(13098): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:849)
03-21 10:33:08.100: E/AndroidRuntime(13098): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:607)
03-21 10:33:08.100: E/AndroidRuntime(13098): at dalvik.system.NativeStart.main(Native Method)
03-21 10:33:08.100: E/AndroidRuntime(13098): Caused by: java.lang.ClassNotFoundException: com.example.airlife.MainActivity in loader dalvik.system.PathClassLoader[/data/app/com.example.airlife-2.apk]
03-21 10:33:08.100: E/AndroidRuntime(13098): at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:240)
03-21 10:33:08.100: E/AndroidRuntime(13098): at java.lang.ClassLoader.loadClass(ClassLoader.java:551)
03-21 10:33:08.100: E/AndroidRuntime(13098): at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
03-21 10:33:08.100: E/AndroidRuntime(13098): at android.app.Instrumentation.newActivity(Instrumentation.java:1040)
03-21 10:33:08.100: E/AndroidRuntime(13098): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1777)
03-21 10:33:08.100: E/AndroidRuntime(13098): ... 11 more
MainActivity.java is like this
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import android.os.Bundle;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
public class MainActivity extends MapActivity implements OnClickListener{
private ImageButton mVid,mAgebtn,mWeightbtn,mPicbtn,mMsgbtn,mReqbtn,mHelibtn,mDocbtn,mContextbtn;
private MapView mapView;
private MyLocationOverlay myLocationOverlay;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mapView = (MapView)findViewById(R.id.webview);
mapView.setBuiltInZoomControls(true);
myLocationOverlay = new MyLocationOverlay(this, mapView);
mapView.getOverlays().add(myLocationOverlay);
mapView.postInvalidate();
// call convenience method that zooms map on our location
zoomToMyLocation();
mAgebtn = (ImageButton) findViewById(R.id.imageView36);
mWeightbtn = (ImageButton) findViewById(R.id.imageView4);
mPicbtn = (ImageButton) findViewById(R.id.imageView5);
mMsgbtn = (ImageButton) findViewById(R.id.imageView6);
mReqbtn = (ImageButton) findViewById(R.id.imageView32);
mHelibtn = (ImageButton) findViewById(R.id.btnsearch);
mDocbtn = (ImageButton) findViewById(R.id.btnprovide);
mVid = (ImageButton) findViewById(R.id.btnpost);
mContextbtn = (ImageButton) findViewById(R.id.btnsettings);
mAgebtn.setOnClickListener(this);
mWeightbtn.setOnClickListener(this);
mPicbtn.setOnClickListener(this);
mMsgbtn.setOnClickListener(this);
mReqbtn.setOnClickListener(this);
mHelibtn.setOnClickListener(this);
mDocbtn.setOnClickListener(this);
mVid.setOnClickListener(this);
mContextbtn.setOnClickListener(this);
}
@Override
protected void onResume() {
super.onResume();
// when our activity resumes, we want to register for location updates
myLocationOverlay.enableMyLocation();
}
@Override
protected void onPause() {
super.onPause();
// when our activity pauses, we want to remove listening for location updates
myLocationOverlay.disableMyLocation();
}
/**
* This method zooms to the user's location with a zoom level of 10.
*/
private void zoomToMyLocation() {
GeoPoint myLocationGeoPoint = myLocationOverlay.getMyLocation();
if(myLocationGeoPoint != null) {
mapView.getController().animateTo(myLocationGeoPoint);
mapView.getController().setZoom(10);
}
else {
Toast.makeText(this, "Cannot determine location", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
@Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
Manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.airlife"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.airlife.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".playvid" />
<activity android:name=".Display" />
<activity android:name=".Video" />
<activity android:name=".Documents" />
<activity android:name=".Contact" />
<activity android:name=".FixedMyLocationOverlay" />
</application>
</manifest>
Please tell me why I am getting this error, and how to solve this.
A: Got the solution. I had missed this code in my manifest file
<uses-library android:name="com.google.android.maps"/>
A: Class not found exception in MainActivity.
I think you've the wrong package, or that your APK doesn't have what you think it has.This is your package name.
com.example.airlife
Maku sure that it is imported in all activities as.
package com.example.airlife;
and don't forget to add entry in manifest file for every new activity.
If so, then make this change in manifest file. No need to mention your package name and remove allowBackUp
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
A: if not this try adding any library files you are using. missing library files may also cause this exception. see this link
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo after SDK update
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/15540378",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: restart specific website in IIS6 via command line Does anyone know if I can restart a specific website within IIS 6 using the command line.
I don't want to use a blanket IISReset /restart command if I can avoid it.
I have a site that has an issue and is maxing out the server, I need to find a fix for it but in the meantime I also want to sleep so I'd like to just restart it every 10 minutes overnight to nurse it through.
A: Sounds like you actually want to recycle an Application pool rather than stop/start a website.
To do this you can use the IISAPP.vbs utility:
cscript c:\windows\system32\iisapp.vbs /a "My AppPool" /r
You can run the utility with a /? flag for full usage details and some sample commandlines.
If you really want to start/stop a website you can use the ADSUTIL.vbs utility:
cscript c:\inetpub\adminscripts\adsutil.vbs STOP_SERVER W3SVC/1
cscript c:\inetpub\adminscripts\adsutil.vbs START_SERVER W3SVC/1
For more information on ADSUTIL.vbs please see this page :
Using the Adsutil.vbs Administration Script (IIS 6.0)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/12832401",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Panel does not appear I have a panel with a really simple config:
Ext.define('MyApp.view.PanelPersonalData', {
extend: 'Ext.Panel',
alias: 'widget.panelpersonaldata',
requires: [
'Ext.Panel',
'Ext.Button',
'Ext.XTemplate'
],
config: {
items: [
{
xtype: 'panel',
styleHtmlContent: true,
items: [
{
xtype: 'panel',
tpl: [
'Data:',
'{salutation} {firstname} {lastname}<br />',
'Birthday: {birthday}<br />',
'{street} {number}<br />',
'{zip} {city}<br />',
'E-Mail: {email}',
'<p>Insurance: {priorInsurance}</p>',
'<p>',
'IBAN: {iban}<br />',
'BIC: {bic}',
'</p>',
'<p>Job: {occupationGroup}</p>'
]
}
]
}
]
}
The data for the placeholders is set correctly (I made a console log of it). But the pannel won't appear on the screen. If I remove the tpl config and add html: 'TEST' instead, I can see the correct output of TEST. What am I doing wrong here with the tpl config?
A: The problem was that I called setData() for the wrong panel. Instead of setting it to the panel with the placeholders, I used the parent panel. After changing this, everything works fine now.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/21454052",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: When do you need to use type annotations? While reading Data Types from the Rust Book I noticed that sometimes a variable is defined with a type annotation and sometimes not.
When should I use type annotations?
let tup: (i32, f64, u8) = (500, 6.4, 1);
let tup = (500, 6.4, 1);
let months = ["January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"];
let a: [i32; 5] = [1, 2, 3, 4, 5];
A: When types have to be specified
If the compiler cannot infer the type by itself, it must be specified:
let numbers: Vec<_> = (0..10).collect();
Types also cannot be omitted from items. In particular, consts and statics look very much like let statements, but the type must be specified:
const PI_SQUARED: i32 = 10;
// Not valid syntax
const HALF_PI = 1.5;
When types cannot be specified
When the type is anonymous, it cannot be specified
fn displayable() -> impl std::fmt::Display {
""
}
fn main() {
let foo = displayable();
// Not valid syntax:
let foo: impl std::fmt::Display = displayable();
}
When the types can be specified, but do not have too
But most of the time, the type can be specified but doesn't have to: The compiler can infer it from usage.
In Rust, it is usually considered good practice to omit simple types when they can. The bound where people will decide that something is not simple anymore and decide that it must be specified or not is however very opinion-based and out of scope for StackOverflow.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/61950263",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: React Router Dom redirects incorrectly upon building Goal: Reach http://localhost:3000/test.html?test=5
Problem: When run in development mode and prior to building, I can reach http://localhost:3000/test.html?test=5 just fine. However, after running 'react-scripts build', when navigating to http://localhost:3000/test.html?test=5, the page will redirect to http://localhost:3000/test with a status code 301 Moved Permanently.
App.js
import React from 'react';
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
import Test from "./Test";
function App() {
return (
<React.Fragment>
<Router>
<Route path="*" component={Test} />
</Router>
</React.Fragment>
);
}
export default App;
Test.js
import React, { Component } from 'react';
class Test extends Component {
render() {
return (
<React.Fragment>
<h1>{this.props.location.pathname+this.props.location.search}</h1>
</React.Fragment>
);
}
}
export default Test;
I believe it has something to do with the URL containing '.html?'. When I try to navigate to 'http://localhost:3000/test.html/test=5', it works just fine, but as soon as you try 'http://localhost:3000/test.html?test=5', it will redirect to 'http://localhost:3000/test'
I created a demo of the problem if anyone wants to test it.
Demo
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/58159754",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: how to put procedure inside package I have a package:
CREATE OR REPLACE PACKAGE pack1
AS
PROCEDURE details;
END pack1;
/
CREATE OR REPLACE PACKAGE BODY pack1
AS
CREATE OR REPLACE PROCEDURE details
IS
BEGIN
select *
FROM table1;
END details;
END;
/
But I am getting error message
Warning: Package Body created with compilation errors.
I am new to pl/sql, and trying to learn how to use package and procedure. I know my code might be far from correct. Tell me what changes i can do in my code to make it work
A: Use
PROCEDURE details
instead of
CREATE OR REPLACE PROCEDURE details
https://docs.oracle.com/cd/E11882_01/appdev.112/e25519/packages.htm#LNPLS00905
On the other hand, the SELECT statement needs a INTO statement. So the code could be:
CREATE OR REPLACE PACKAGE pack1
AS
PROCEDURE details;
END pack1;
/
CREATE OR REPLACE PACKAGE BODY pack1
AS
PROCEDURE details
IS
l_rec table1%ROWTYPE;
BEGIN
SELECT *
INTO l_rec
FROM table1;
END details;
END pack1;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/53402682",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: insert not functioning mysql php i got one problem with this . everytime i go insert it the page just refresh and blank. i dont know where is the problem but i checked my sql the data i use is the same. so i dont know where the problem is.
<form enctype="multipart/form-data" method="POST"> <tr>
<td> Generic Name:<input type="text" class="form-control" name = "gname"></td>
</tr>
<tr>
<td> Brand Name:<input type="text" class="form-control" name = "bname"></td>
</tr>
<tr>
<td> Quantity:<input type="number" min="0" class="form-control" name = "mqty"></td>
</tr>
<tr>
<td> Description:<input type="text" class="form-control" name = "mdesc"></td>
</tr>
<br>
<tr>
<td> <input type="submit" class="btn btn-info" name="add" Value="Add"></td>
</tr>
</form>
<?php
include "../../functions/connect.php";
error_reporting(0);
date_default_timezone_set('Singapore');
$date = date('m/d/Y h:i:s a', time());
?>
<?php
include "../../functions/connect.php";
extract($_POST);
if(isset($add)){
$sql = "INSERT INTO `tbl_meds`(`date`,`generic`,`brand`,`description`,`medqty`) VALUES ('$date','$gname','$bname','$mdesc','$mqty')";
$result = mysql_query($sql) or die("Verification Error: " . mysql_error());
}
?>
EDIT: Result of var_dump($_POST) -
array(5) {
["gname"]=> string(11) "Paracetamol"
["bname"]=> string(8) "Biogesic"
["mqty"]=> string(3) "100"
["mdesc"]=> string(71) "The most prescribed Headache and Fever brand that's Effective and Safe."
["add"]=> string(4) "Save"
}
A: if(isset($_POST["add"])){
this will work for you
your form has POST method. So on PHP side you have to handle it with $_POST global variable.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/28455701",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
}
|
Q: Postfix - Html emails contain random characters I'm storing my postfix emails into mysql.
I notice some weird characters showing up in some messages, while other emails don't have them. So, it's random.
Here's what I see:
--1001534069-1142425087-1366837456=:47630
Content-Type: text/plain; charset=utf-8
Content-Transfer-Encoding: quoted-printable
=0A=0AConfirmation: We received your membership (one-year) p=
ayment =0A=0A =0A =0A =0A =0A =0A =0A =0A=0A Confirmation:: We received =
your membership (one-year) payment=0AHi John Smith,=0AWe re=
............
--1001534069-1142425087-1366837456=:47630
Content-Type: text/html; charset=utf-8
Content-Transfer-Encoding: quoted-printable
<html><body><div style=3D"color:#000; background-color:#fff; font-family:ti=
mes new roman, new york, times, serif;font-size:12pt"><div><br></div><div s=
tyle=3D"font-family: 'times new roman', 'new york', times, serif; font-size=
: 12pt;"><div style=3D"font-family: 'times new roman', 'new york', times, s=
erif; font-size: 12pt;"><div class=3D"y_msg_container"><div id=3D"yiv684532=
7653"><div>=0A <div class=3D"yiv6845327653moz-forward-container">=0A =
=0A <title>Confirmation: We received your membership=
............................
I included both content-types, and the weird characters are rather noticable.
I'm saving each email into a column type: text, with a Collation: utf8_unicode_ci
And for those interested in what I'm using to extract my postfix emails, I'm using the PHP imap_* functions.
Anyways, does anyone know why those weird characters get interjected? (while other emails have perfect html or plain text?)
A: That's quoted printable encoding. You need to undo the content-transfer-encoding, which might be quoted printable or base64.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/16202827",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Show all capes/products when i filter them through price range // React imports
import { useCallback, useEffect, useState } from 'react'
import { GetServerSideProps } from 'next'
import Link from 'next/link'
import { ParsedUrlQuery } from 'querystring'
import { capesApi } from 'api'
import {
CapeCategoryEnum,
CapeTypeEnum,
GetCapesResponse
} from 'mantle-api-client'
// Component imports
import { ShopLayout } from '@components/Shop/ShopLayout'
import { Container, Text } from '@components/utils'
import { Pagination } from '@components/Pagination'
import { useRouter } from 'next/router'
import { RenderedMineman } from '@components/RenderedMineman'
import { capeTypes, capeCategories } from 'config'
import Checkbox from '@components/Checkbox/Checkbox'
import { toDollars } from '@helper/price'
// Types
interface Props {
query: ParsedUrlQuery
capeData: GetCapesResponse
}
/**
* The MVP shop page. This is a public page.
*/
const Shop = ({
capeData: initialCapeData,
query: { page: initialPage }
}: Props) => {
/**
* State
*/
const [page, setPage] = useState(initialPage ? Number(initialPage) : 1)
const [capeData, setCapeData] = useState(initialCapeData)
const [fetching, setFetching] = useState(false)
const [filterCategories, setFilterCategories] = useState<CapeCategoryEnum[]>([])
const [filterTypes, setFilterTypes] = useState<CapeTypeEnum[]>([])
/**
* Helpers
*/
// Access the router.
const router = useRouter()
// This helper will add or remove selected categories to the categories state.
const addOrRemoveCategoryToFilter = (categoryValue: CapeCategoryEnum) => {
if (filterCategories.includes(categoryValue)) {
setFilterCategories(
filterCategories.filter((value) => value !== categoryValue)
)
} else {
setFilterCategories(filterCategories.concat(categoryValue))
}
}
// This helper will add or remove selected types to the types state.
const addOrRemoveTypesToFilter = (typeValue: CapeTypeEnum) => {
if (filterTypes.includes(typeValue)) {
setFilterTypes(filterTypes.filter((value) => value !== typeValue))
} else {
setFilterTypes(filterTypes.concat(typeValue))
}
}
const { capes, totalPages, count } = capeData
// This client-side helper will fetch additional capes depending on filters passed to it.
const fetchCapes = useCallback(
async (page: number) => {
setPage(page)
setFetching(true)
const capesDataR = (
await capesApi.getCapes({
page,
sortBy: 'createdAt DESC',
categories: filterCategories,
types: filterTypes
})
).data
setCapeData(capesDataR)
setTimeout(() => setFetching(false), 100)
},
[filterCategories, filterTypes]
)
// This helper will perform a client-side re-render of the page.
const handlePageChange = (page: number) => {
router.push(`/shop?page=${page}`, undefined, { shallow: true })
}
// Whenever the route changes or if we are fetching more capes, make sure to fetch more capes.
useEffect(() => {
fetchCapes(router.query.page ? Number(router.query.page) : 1)
}, [router.query, fetchCapes])
const[checkVal1, setCheckVal1]= useState(false);
const[checkVal2, setCheckVal2]= useState(false);
const[checkVal3, setCheckVal3]= useState(false);
const[checkVal4, setCheckVal4]= useState(false);
const[checkVal5, setCheckVal5]= useState(false);
this handleCheckData ftn returns the filtered data of only 1 page. meaning if I click the checkbox of price range >2$ it will show the prices >2$ on page 1 only and not rest of the products and i have to go to page 2 to see the rest of the filtered products
const handleCheckData=(cape:any)=>{
if(checkVal1===true){
return cape.price>=1
}
else if(checkVal2===true){
return cape.price>=200 && cape.price<=300
}
else if(checkVal3===true){
return cape.price>=300 && cape.price<=400
}
else if(checkVal4===true){
return cape.price>=400 && cape.price<=500
}
else if(checkVal5===true){
return cape.price<=500
}
else{
return cape.price>=0
}
}
return (
<>
<Container>
<ShopLayout>
{/* sidebar*/}
<div id='sampleDiv' className='classOrignal'>
<div>
<div className='space-y-4 mb-5 pb-5'>
<div className='flex'>
<Text as='h4' tag='h2'>
Filter Capes
</Text>
</div>
</div>
<div className='space-y-4 mb-5 mt-5'>
<div className='flex'>
<Text as='h4' tag='h2'>
Price
</Text>
</div>
{/* 2nd: make the price checkbox a separate component */}
<div className='flex flex-col gap-2'>
{/* 1st checkbox */}
<div>
<label > {'>'} $1.99</label>
<input type='checkbox' onClick={()=>setCheckVal1(!checkVal1)} />
</div>
{/* 2nd checkbox */}
<div>
<label >$2.00 - $2.99</label>
<input type='checkbox' onClick={()=>setCheckVal2(!checkVal2)}/>
</div>
{/* 3rd checkbox */}
<div>
<label >$3.00 - $3.99</label>
<input type='checkbox' onClick={()=>setCheckVal3(!checkVal3)}/>
</div>
{/* 4th checkbox */}
<div>
<label >$4.00 - $4.99</label>
<input type='checkbox' onClick={()=>setCheckVal4(!checkVal4)}/>
</div>
{/* 5th checkbox */}
<div>
<label > {'<'} $5.00</label>
<input type='checkbox' onClick={()=>setCheckVal5(!checkVal5)}/>
</div>
</div>
</div>
{/*filtering by categories */}
<div className='space-y-4 mb-5 mt-5'>
<div className='flex'>
<Text as='h4' tag='h2'>
Categories
</Text>
</div>
<div className='flex flex-col gap-2'>
{capeCategories.map(
({ name, value }) => (
<div key={value}>
<Checkbox
labelClassName='text-sm text-gray-400 mr-4'
label={name}
handleClick={() =>
addOrRemoveCategoryToFilter(value)
}
className={`bg-gray-800 text-gray-400 rounded border border-stone-200 space-x-3 ${
filterCategories.includes(value)
}`}
/>
</div>
)
)}
</div>
</div>
</div>
<div>
{/*filtering by types*/}
<div className='space-y-4'>
<div className='flex'>
<Text as='h4' tag='h2'>
Types
</Text>
</div>
<div className='flex flex-col gap-2'>
{capeTypes.map(({ name, value }) => (
<div key={value}>
<Checkbox
labelClassName='text-sm text-gray-400 mr-4'
label={name}
handleClick={() =>addOrRemoveTypesToFilter(value)
}
className={`bg-gray-800 text-gray-400 rounded border border-stone-200 space-x-3 ${
filterTypes.includes(value)
}`}
/>
</div>
))}
</div>
</div>
</div>
</div>
the capes we will show plus the price filter ftn
<div className='flex-1 md:grid md:grid-cols-4 md:gap-4 justify-items-center'>
{capes.filter((cape) => handleCheckData(cape)).map((cape) => (
<div
key={cape.id}
className='text-white transition duration-300 ease-in-out group hover:text-orange-500'
>
<div className='flex flex-col items-center space-y-4 cursor-pointer'>
<div className='-ml-8 transition duration-300 ease-in-out group-hover:scale-110 transform-gpu'>
<RenderedMineman
capes={[cape]}
rotation={
cape.type ===
CapeTypeEnum.Cape
? 'back'
: 'front'
}
/>
</div>
<div className='space-y-1 text-center'>
<Text
as='h3'
tag='h3'
className='text-current'
>
{cape.name}
</Text>
</div>
<div className='space-y-1 text-center text-gray-700'>
<Text as='h4' tag='p'>
${toDollars(cape.price)}
</Text>
</div>
</div>
</Link>
</div>
))}{' '}
</div>
</div>
{/* This pagination allows users to filter through pages of products. */}
<Pagination
handlePageChange={handlePageChange}
pages={totalPages}
currentPage={page}
count={count}
perPage={16}
fetching={fetching}
displayNumberOfItems={false}
/>
</ShopLayout>
</Container>
</>
)}
export const getServerSideProps: GetServerSideProps = async ({ query }) => {
const capeData = (
await capesApi.getCapes({
page: query.page ? Number(query.page) : 1,
sortBy: 'createdAt DESC'
})
).data
return {
props: {
query,
capeData
}
}
}
export default Shop
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/71486169",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: String returned by pyodbc different than a normal string? I used pyodbc to get some data from an mssql db. The returned text contains \n whenever a newline is necessary. I loaded all the text into the "row" variable.
var=row.somecolumnfromdatabase
var2=str('Some text\nand the newline.')
print(RichText(var))
print(RichText(var2))
However, if I use a function like RichText (from docxtpl) to transform the string, I receive different results. In the case of "var" (text loaded from db), the \n symbol is preserved. In the case of var2 (where I input the text by hand), the \n is transformed correctly. Simply printing var and var2 without transformations shows no difference and I would expect the contained strings to be identical - e.g. the RichText function should receive the exact same input.
What am I missing?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/33440504",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Unable to I to display the list value in dropdown which I am passing as list from my java class in my JSP.My code works perfectly if I am using table I am passing list from my java class in my JSP where I want to display the list value in dropdown.
While debugging I checked that the list is containing desired values but not displaying in my JSP dropdown.
Though the values are coming if I am displaying in Table form.
Please, tell me where I am going wrong and how can I make my code to work?
Java Code:
// add the event list to the model
theModel.addAttribute("event", theEvents);
return "fundContributionCollectionListPage";
JSP Code:
<select name="eventSelected">
<c:forEach var="tempEvents" items="${event}">
<option value="tempEvents.eventName">${tempEvents.eventName}</option>
</c:forEach>
</select>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/51055539",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how send tinymce content using jquery method post I had a form.
like this
<form id=form ><input type='text' name='input1' ><textarea name='text' ></textarea></form>
when I do this
var $dados = $("#form").serialize()
I get all the values, to send via jquery post like this
$.ajax({
url: "action.php",
data: $dados,
type: 'POST',
timeout: 6000,
success: function (retorno) {
}
});
The beginning of the problem is, my textarea is a TinyMCE, and I get the val using this
$("#form").find('textarea').each(function(){
$dados = $dados + "&" + $(this).attr('name') + "=" + tinyMCE.get( $(this).attr('id') ).getContent();
});
My variable $dados is something likes this
field=value & filed2 = value ....
Now the problem..
when I put a text like this
"Olá mundão"
My value of the TinyeMCE is (whit the spaces to show ) Ol & #xE1; Mund ã ;o
The value is a value with HTML entity
So, I have this particular caracter "&" in the tinyMCE value.
and my variable $dados become like this
input1=value & input2 = val & ue
This particular caracter makes mess with my tinyMCE value,
So someone can help me?
A: Why don't you use something like this to generate your $dados object?
There is no need to build your data as a html ajax GET Parameter string.
var $dados = {};
$("#form").find('textarea').each(function(){
$dados[$(this).attr('name')] = tinyMCE.get($(this).attr('id')).getContent();
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/32913463",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: MySQL: Select between September and September I am showing the sales in my Database using this select
SELECT YEAR( ordered_date ) AS Jahr, SUM( preis ) AS Preis, count(*) as Anzahl FROM wccrm_orders where typ = 'Brautkleid' GROUP BY YEAR(ordered_date) ORDER BY ordered_date ASC
This is working fine, currently the output is year (1-12), the number and the price. Now I need to achieve the following:
The Price, Count(*) and Year should not be shown from Jan to Dec, but from Sep to Sep. Is this possible? How can I achieve this?
Kind Regards,
Stefan
A: Subtract 9 months or add 3 months (I'm not sure what you want to call "Jahr"):
SELECT YEAR( ordered_date + interval 3 month) AS Jahr,
SUM( preis ) AS Preis, count(*) as Anzahl
FROM wccrm_orders
WHERE typ = 'Brautkleid'
GROUP BY Jahr
ORDER BY Jahr ASC;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/43540678",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Set a Default Path in express.js app.set('views', path.join(__dirname,'views'))
What is the meaning of the line above? And what is the purpose of it?
A: That line of code indicates the main path of your views, for example if you have this hierarchy:
views/index.html
views/home/index.html
views/home/news/index.html
would render your views like this:
res.render('/index.html', /*...*/);
res.render('home/index.html', /*...*/);
res.render('home/news/index.html', /*...*/);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/67450332",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: jQuery stop custom function from working if width is a certain size How do I make the imagePopUp function stop executing if the screen goes smaller than 768px when resizing? Here is my code:
// Image pop up
function imagePopUp() {
$('.pop-up-img').click(function () {
var pizza_img = $(this).attr('src');
var close_button = "<span class='close-img-btn' onClick='closeImage()'><i class='fas fa-times'></i></span>";
var pop_up_dark_bg = "<div class='pop-up-bg-div' onClick='closeImage()'></div>";
var shown_img = "<div class='shown-img-div'><img id='shown-img' class='img-fluid mx-auto d-block' src='"+pizza_img+"'></div>";
$('body').append(close_button);
$('body').append(pop_up_dark_bg);
$('body').append(shown_img);
});
};
function closeImage() {
$('.pop-up-bg-div').remove();
$('.shown-img-div').remove();
$('.close-img-btn').remove();
};
$(document).ready(function() {
if ($(window).width() > 768) {
imagePopUp();
}
});
I tried:
$(window).resize(function() {
if ($(window).width() > 768) {
imagePopUp();
}
});
but the function doesn't start unless the screen is resized. Also it just keeps adding on the imagePopUp function every time the screen is resized, so if you drag the screen to resize it, it starts running the function like 20 times.
What I want and imagine should look like is something like this:
$(document).ready(function() {
if ($(window).width() > 768) {
on loading the page, check the width and run the function once if its more than 768px width
}
});
$(window).resize(function() {
if ($(window).width() > 768) {
run the function only once if it wasnt running already.
} else {
when the screen goes smaller than 768, stop the function from running completely
});
Right now I just "fixed" the problem by adding css display: none with @media to everything when the width is less than 768px. It still runs the code and adds the divs and images to the html after resizing but it just doesnt show them.
EDIT:
Thank you. I solved my problem. It's probably not the best way to do it but it works as intended. Here is the code if anyone else will need something similar in the future:
var running = false;
function imagePopUp() {
running = true;
$('.pop-up-img').click(function () {
var pizza_img = $(this).attr('src');
var close_button = "<span class='close-img-btn' onClick='closeImage()'><i class='fas fa-times'></i></span>";
var pop_up_dark_bg = "<div class='pop-up-bg-div' onClick='closeImage()'></div>";
var shown_img = "<div class='shown-img-div'><img id='shown-img' class='img-fluid mx-auto d-block' src='"+pizza_img+"'></div>";
$('body').append(close_button);
$('body').append(pop_up_dark_bg);
$('body').append(shown_img);
});
};
function closeImage() {
$('.pop-up-bg-div').remove();
$('.shown-img-div').remove();
$('.close-img-btn').remove();
};
$(document).ready(function() {
if ($(window).width() > 768 && running == false) {
imagePopUp();
}
});
$(window).resize(function () {
if ($(window).width() < 768) {
$(".pop-up-img").unbind();
running = false;
}
else if ($(window).width() > 768 && running == false) {
imagePopUp();
}
});
As suggested I added the variable "running = false".
To make the function stop from working I used "unbind".
So when the screen becomes < 768px width when resizing, the event doesn't work anymore and the variable "running" goes from "true" to "false" again.
That was needed so when the screen goes back to > 768px, the function would only be added once, because after it is added the "running" variable becomes "true", so it doesn't fit the "else if" statement requirements anymore.
A: You can make use of the .on() function in order to fire an event once the window is resized or loaded.
Example of non working code:
var running = false;
function imagePopup() {
running = true;
do the rest here
}
$(window).on("load resize",function(e){
if ($(window).width() > 768 && running == false) {
imagePopup();
}
});
Read more here about on() - that's one way of doing it, if you're showing an image, you can always use a css selector to see if its showing or not rather than a flag (true, false).
At the end of the day; I believe; what you want is called a modal image; you can see an example of how to do it here.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/52661669",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Static landing page on Angular I'm learning Angular and I'm having trouble to set a static landing page. What I would like is to have a static html landing page that has 2 buttons that call /login and /signup
and from there I would like to bootstrap angular app (calling app-root). I serve my app with nginx.
1- Where do I set my landing page? I tried adding a landing.html at root level with index.html, and changed at angular.json :
my landing.html on project root
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:browser",
"options": {
"outputPath": "dist/",
"index": "src/index.html", <--- //changed for src/landing.html
"main": "src/main.ts",
I read other questions where they used index.html as a static page, but I could not understand how to call later for my app-root (that bootstrap my SPA), anyway when I delete app-root from my index.html I have a blank page with this error:
Error: The selector "app-root" did not match any elements
at DefaultDomRenderer2.selectRootElement (vendor.js:201546)
at BaseAnimationRenderer.selectRootElement (vendor.js:141558)
at locateHostElement (vendor.js:170017)
at ComponentFactory$1.create (vendor.js:188576)
at ApplicationRef.bootstrap (vendor.js:194164)
at vendor.js:193812
at Array.forEach (<anonymous>)
at PlatformRef._moduleDoBootstrap (vendor.js:193811)
at vendor.js:193770
at ZoneDelegate.invoke (polyfills.js:572)
If someone can give me some light, I really would like to understand where the magic happens to use a static landing page and as a second step (login or signup) calls my SPA.
PS1.: I did not set any LandingModule or this.router.url == '/landing' or this.router.url == '/index'
PS2.: if someone knows also what to do at the nginx after...
Thanks!!!
A: Here is option to build everything in Angular without Nginx
*
*Create a App/Home component, which renders your landing page including Login & Register buttons.
*Build a normal app/routing for Login & Register.
*During compile time (ng build), pre-render the App component using AppShell technique.
Here is blog for your reference https://medium.com/technext/boost-your-angular-app-using-appshell-217651af6698
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/66678299",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: 2 pagination for 2 tabs on a page From HTML to Wordpress, I made a page with 2 tab as below.
NEWS and EVENT tab
Each NEWS and EVENT will show the posts for its own category, then I inserted pagination.
I click on "Page 2" on NEWS tab, then click EVENT tab, it also takes EVENT to Page 2 (EVENT should be Page 1 by default)...I Hope each one has its own pagination.
I searched for Multiple Custom Loop in One Page with Pagination in many places but the advices quite different to my case.
Is there any way to fix it? Thank all in advanced!
page-news.php
<section id="news"\>
<div class="container"\>
<div class="warpper"\>
<input class="radio" id="one" name="group" type="radio" checked\>
<input class="radio" id="two" name="group" type="radio"\>
<div class="tabs">
<label class="tab" id="one-tab" for="one">NEWS</label>
<label class="tab" id="two-tab" for="two">EVENT</label>
</div>
<div class="panels">
<!-- NEWS -->
<div class="panel" id="one-panel">
<?php
$my_query1 = new WP_Query(
array(
'post_type' => 'post',
'paged' => $paged,
'posts_per_page' => 3,
'category_name' => 'news',
)
);
if ($my_query1->have_posts()):
echo '<ul>';
while ($my_query1->have_posts()):
$my_query1->the_post();
?>
<li>
<a href="<?php the_permalink(); ?>">
<?php the_title(); ?><br>
<?php the_time('Y.m.d') ?><br>
<?php the_post_thumbnail(); ?>
</a>
</li><br>
<?php
endwhile;
echo '</ul>';
my_paginate($my_query1);
wp_reset_postdata();
endif;
?>
</div>
<!-- EVENT -->
<div class="panel" id="two-panel">
<?php
$my_query2 = new WP_Query(
array(
'post_type' => 'post',
'paged' => $paged,
'posts_per_page' => 3,
'category_name' => 'event',
)
);
if ($my_query2->have_posts()):
echo '<ul>';
while ($my_query2->have_posts()):
$my_query2->the_post();
?>
<li>
<a href="<?php the_permalink(); ?>">
<?php the_title(); ?><br>
<?php the_time('Y.m.d') ?><br>
<?php the_post_thumbnail(); ?>
</a>
</li><br>
<?php
endwhile;
echo '</ul>';
my_paginate($my_query2);
wp_reset_postdata();
endif;
?>
</div>
</div>
</div>
</div\>
</section\>
Functions.php
function my_paginate($query_name = '')
{
$settings = array(
'side_range' => 3,
// 現在ページの左右の表示数.
'txt_prev' => '<',
// 一つ戻るテキスト.
'txt_next' => '>',
// 一つ進むテキスト.
'txt_first' => '|<',
// 最初へ移動テキスト.
'txt_last' => '>|', // 最後へ移動テキスト.
);
if ('' !== $query_name) {
$query = $query_name;
} else {
global $paged, $wp_query;
$query = $wp_query;
}
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$showitems = ($settings['side_range'] * 2) + 1;
$pages = $query->max_num_pages;
if (1 !== $pages) {
echo "<div class=\"pagination\">\n";
echo " <ul class=\"pagination__list\">\n";
for ($i = 1; $i <= $pages; $i++) {
if (1 !== $pages && (!($i >= $paged + $settings['side_range'] + 1 || $i <= $paged - $settings['side_range'] - 1) || $pages <= $showitems)) {
echo ($paged === $i) ?
' <li class="pagination__item--current">' . esc_html($i) . "</li>\n" :
' <li class="pagination__item"><a href="' . esc_url(get_pagenum_link($i)) . '">' . esc_html($i) . "</a></li>\n";
}
}
echo " </ul>\n";
echo ' <p class="pagination__pos">Page ' . esc_html($paged) . '/' . esc_html($pages) . "</p>\n";
if ($paged > 2 && $paged > $settings['side_range'] + 1 && $showitems < $pages) {
echo ' <a class="pagination__btn--first" href="' . esc_url(get_pagenum_link(1)) . '">' . esc_html($settings['txt_first']) . "</a>\n";
}
if ($paged > 1) {
echo ' <a class="pagination__btn--prev" href="' . esc_url(get_pagenum_link($paged - 1)) . '">' . esc_html($settings['txt_prev']) . "</a>\n";
}
if ($paged < $pages) {
echo ' <a class="pagination__btn--next" href="' . esc_url(get_pagenum_link($paged + 1)) . '">' . esc_html($settings['txt_next']) . "</a>\n";
}
if ($paged < $pages - 1 && $paged + $settings['side_range'] - 1 < $pages && $showitems < $pages) {
echo ' <a class="pagination__btn--last" href="' . esc_url(get_pagenum_link($pages)) . '">' . esc_html($settings['txt_last']) . "</a>\n";
}
echo "</div>\n";
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/74806093",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: BigQuery batch load execution time and frequency I'm considering switching from Streaming insert to Batch loading for my BigQuery insertion. However, I can't find some information I'd need.
*
*Time: Let's say I have a csv file with 1 million record. Roughly, how much time does a load take? Are we talking hours or minutes?
*Frequency: Can I have a load job every 10 minutes or so?
*Concurrency: Can two jobs happen at the same time, or do I need to wait for the previous one to finish?
A: For uncompressed CSV files with 1 million records expect around 10-15 seconds of processing time. But the question to put here is where the file is stored, and how long it will be taken to be uploaded, as that can be more than the above time section.
We have successfully imported in 2 minutes CSV files up to 5TB of data in it.
Your project can run up to 100,000 load jobs per day. Failed load jobs count toward this limit.
But be aware:
Your project can make up to 5,000 partition modifications per day to an ingestion-time partitioned table.
Your project can make up to 30,000 partition modifications per day for a column-partitioned table.
Your project can run up to 50 modifications per partitioned table every 10 seconds.
You can have multiple load jobs in parallel.
BigQuery is really petabyte scaling, so large jobs fit nice.
Although it has some Quotas, but they are quite decent, see them here.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73167645",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to create a variable in a bash script that contains the data from a postgres database I'm looking to create a script than can find a specific date/time based on a field in a database
Currently i do it manually...
# psql gttvdb -U postgres
gttvdb=# select patch_date from version_history where version ='1.1.1';
What i need is to be able to reference that date as a variable in a bash script
#! /bin/sh
patchdate=$("select patch_date from version_history where version ='1.1.1';")
echo "last update was " $patchdate
A: Try this:
patchdate=` psql -t -q -c "select patch_date from version_history where version ='1.1.1'"`
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/11907204",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Prevent record duplication in Rails I don't really have any examples, but I have forms that create new records in my ActiveRecord database that do not really have any unique attributes other than their given ID. It has come to my attention that Users are submitting their form, but realized they mistyped something, so they have been pressing the browser's back button and resubmitting the same content, which causes duplication of that record.
I want to prevent this from happening, there is no need to post code, I would just like some suggestions.
Thanks!
A: In the record's Model, add a uniqueness validation as detailed in this Rails Guide. You can apply a scope on that validation, so that the uniqueness is determined using multiple record attributes.
Alternatively, if you really don't want to mark these records as unique, add an easy way for the user to update their submission to the post record creation page. i.e. they add a new record, the ability to edit that record immediately pops up in their view so that, rather than hitting back and creating a new record, they update the one they just made.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/36607243",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Purpose of MySQL data type Often when creating a new web app and configuring MySQL, certain fields will need to change in format as the app develops. For instance, I may change the format of a date field or a field which once was just int now needs a letter or what not. So usually I just make every field Varchar 255 until Im finished at which time Ill change data types to correct ones.
So my question is, how important are data types? Whats the purpose? Speed?
A: Data types are extremely important - without them, there's no way to be sure what data is actually stored in the column. For example, a VARCHAR(255) could be anything - string, numeric, date/time... It makes things extremely difficult to find particular data if you can't guarantee what the data is or any form on consistency.
Which means data typing also provides basic validation - can't stick letters into a column with a numeric or date/time data type...
The speed of data retrieval is also improved by using indexes on a column, but an index can not be used if you have to change the data type of the data to something else before the data can be compared.
It's a good thing to realize what the difference is between data, and presentation. Like the case with date field formatting - that's presentation, which can be easily taken care of if the data type is DATETIME (or converted to DATETIME).
A: Short answer: Speed, optimal data storage, Index, Search ability.
Your database can better make use of the internal works when everything has the correct datatype. You can also make better use of the special database function.
If you want to retrieve all data from a certain month. You can use special database functions to just group by a month when using a date time datatype for instance. When using a varchar to store a date, you lose all of that functionality.
Most databases are able to search or retrieve data faster from a table when the index has been created on a INT datatype. So if you had created that storage field as a varchar you would have lost performance
A: Performance is one reason but so far no ones talked about running these types of queries (which wouldn't be possible if all types are VARCHAR)
SELECT SUM(total) total FROM purchases WHERE status = 'PAID';
SELECT * FROM users WHERE DATE_ADD(last_login, INTERVAL 3 MONTH) < NOW();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/3579261",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: MySQL UPDATE with INNER JOIN has warnings but will not show them I'm getting warnings when updating a table but the warnings are not showing. Through tedious and lengthy trial-and-error, the cause of the warnings has been tracked down to the INNER JOIN. I need a better way to debug a warning.
Setup is OK. I know warnings are on because MySQL command prompt was started with option '--show-warnings' and warnings are turned on warnings with '\W':
mysql> \W
Show warnings enabled.
mysql> show variables like '%warn%';
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| log_warnings | 0 |
| sql_warnings | ON |
| warning_count | 0 |
+---------------+-------+
3 rows in set (0.01 sec)
To make sure warnings were on, I forced a truncating warning on a VARCHAR(255) field:
mysql> UPDATE course
-> SET course.transcript_title = 'Field transcript_title is VARCHAR(255). This is over 255 characters to force truncating warning. Field transcript_title is VARCHAR(255). This is over 255 characters to force truncating warning. Field transcript_title is VARCHAR(255). This is over 255 characters to force truncating warning.'
-> WHERE course.title LIKE '%SLP%'
-> AND course.year = 2008
-> AND course.gid = 35;
Query OK, 104 rows affected, 104 warnings (0.19 sec)
Rows matched: 104 Changed: 104 Warnings: 104
Warning (Code 1265): Data truncated for column 'transcript_title' at row 1
Warning (Code 1265): Data truncated for column 'transcript_title' at row 2
.... etc.
I want to get the warning from this type of query:
mysql> UPDATE course
-> INNER JOIN group_info ON course.gid = group_info.id
-> SET course.description = 'Foo.'
-> WHERE course.title LIKE '%SLP%'
-> AND course.year = 2008 AND group_info.id = 35;
Query OK, 0 rows affected (0.02 sec)
Rows matched: 104 Changed: 0 Warnings: 104
mysql> SHOW WARNINGS;
Empty set (0.00 sec)
From trial and error, I know the error is from having the INNER JOIN clause. If I remove the INNER JOIN and directly use the gid (group id) field in the course table, then no warnings:
mysql> UPDATE course
-> SET course.description = 'Bar.'
-> WHERE course.title LIKE '%SLP%'
-> AND course.year = 2008
-> AND course.gid = 35;
Query OK, 104 rows affected (0.01 sec)
Rows matched: 104 Changed: 104 Warnings: 0
But I need the INNER JOIN clause because what I really want to do is use the more friendly 'name' field in the joined 'group_info' table:
UPDATE course
INNER JOIN group_info ON course.gid = group_info.id
SET course.description = 'Foo.'
WHERE course.title LIKE '%SLP%'
AND course.year = 2008
AND group_info.name = 'One-to-One Meeting Time';
I've been googling, reading, and debugging the warning for over 1 hour. I've searched for answers or explanations for why this would not show warnings but no luck.
How do I get warnings to show for the INNER JOIN type of UPDATE?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/26447367",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Fiware IoT Broker and IoT Configuration Manager XML Validation I figured out I had to have another GE, the IoT Configuration Manager working parallel to the IoT Broker in order to manage the entities from which we will get data. Now, it seems that the XMLValidator code is giving me some trouble. I registered an entity via HTTP POST osgi9 directly with the configuration manager. Then I try to access it by communicating via osgi10 with the IoT broker. The IoT Broker communicates with the IoT DIscovery service and gets a response, but then the XMLValidator says the XML is wrong even tough it clearly is not.
This is the IoT Broker asking for the availability of a resource to the IoT ConfMan:
2014-11-27 10:31:13,682 | INFO | (HttpConnectionClient.java:initializeConnection:170) | Output
Stream: <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<discoverContextAvailabilityRequest>
<entityIdList>
<entityId isPattern="false">
<id>Dorm</id>
</entityId>
</entityIdList>
<attributeList/>
<restriction>
<scope>
<operationScope>
<scopeType>IncludeAssociations</scopeType>
<scopeValue xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xs="http://www.w3.org/2001/XMLSchema" xsi:type="xs:string">SOURCES</scopeValue></operationScope>
</scope>
</restriction>
</discoverContextAvailabilityRequest>
Then IoT Broker gets:
2014-11-27 10:31:13,947 | INFO | (HttpConnectionClient.java:initializeConnection:188) |
<?xml version="1.0" encoding="UTF-8"?><discoverContextAvailabilityResponse>
<contextRegistrationResponseList>
<contextRegistrationResponse>
<contextRegistration>
<entityIdList>
<entityId type="Room" isPattern="false">
<id>Dorm</id>
</entityId>
</entityIdList>
<contextRegistrationAttributeList>
<contextRegistrationAttribute>
<name>temperature</name>
<type>degree</type>
<isDomain>false</isDomain>
<metadata>
<contextMetadata>
<name>ID</name>
<type>string</type>
<value/>
</contextMetadata>
<contextMetadata>
<name/>
<type/>
<value/>
</contextMetadata>
</metadata>
</contextRegistrationAttribute>
</contextRegistrationAttributeList>
<providingApplication>http://192.168.100.1:70
</providingApplication>
</contextRegistration>
</contextRegistrationResponse>
</contextRegistrationResponseList>
<errorCode>
<code>200</code>
<reasonPhrase>OK</reasonPhrase>
<details xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">Result</details>
</errorCode>
</discoverContextAvailabilityResponse>
2014-11-27 10:31:13,949 | INFO | (HttpConnectionClient.java:initializeConnection:218) | Connection Closed!
2014-11-27 10:31:13,987 | INFO | (XmlValidator.java:error:128) |
ERROR
org.xml.sax.SAXParseException; lineNumber: 0; columnNumber: 0; cvc-complex-type.2.4.b: The content of element 'contextRegistration' is not complete. One of '
{registrationMetaData, providingApplication}
' is expected.
It is clearly seen by the received xml that at least the providingApplication is received but XMLValidator is not seeing this.
A: In the meantime new releases with a lot of bug fixes have been issued, so your problem should be no longer existent.
In addition we added a configuration manager 'light' into the IoT broker, which enables you to use it standalone.
P.S. I became aware of this help request only recently. I am very sorry that we therefore could not provide you an answer in due time.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/27188524",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to use a variable as the input for a form field in Google Colaboratory? The official example shows how to use Form Fields in Google Colaboratory: https://colab.research.google.com/notebooks/forms.ipynb.
Let's say we have a list:
fruit_list = ['apples', 'bananas', 'mangoes']
Now I would like to add the elements of this list as a dropdown in the Form:
#@title # Select Your Choice of Fruit
fruit_selected = 'apples' #@params fruit_list {input: string}
As of now I can think of some hacks like this one:
#@title Boolean fields { run: "auto", vertical-output: true }
this_list = ["False", "True"]
boolean_checkbox = False #@param {type:"boolean"}
boolean_dropdown_asis = False #@param ["False", "True"] {type:"raw"}
boolean_dropdown_var = this_list[1] #@param {type:"raw"}
print(boolean_checkbox)
print(boolean_dropdown_asis)
print(boolean_dropdown_var)
But I would prefer to have another type of input: variable instead of just raw/string. The final implementation could be like this:
#@title # Select Your Choice of Fruit
fruit_list = ['apples', 'bananas', 'mangoes']
fruit_selected = 'apples' #@params fruit_list {input: variable}
I worked on some OVERKILL. You are free to look at it. Comments are welcome! :)
Anyone, any better idea?
Notes: There is another stackoverflow discussion where Sergio Lucero raised a similar question. But the main thread has a different question.
A: If you use the widget like in the notebook of blois, you can use the following code to call the value:
fruit_picker.value
This will return the value of your chosen fruit.
The code in total will look like this:
import ipywidgets as widgets
fruit_list = ['pomegranate', 'watermelon', 'lychee']
fruit_picker = widgets.Dropdown(options=fruit_list, value='watermelon')
fruit_picker
fruit_picker.value
A: Your original code almost has the solution.
If you look carefully you will find it in the documentation.
Instead of
fruit_list = ['apples', 'bananas', 'mangoes']
fruit_selected = 'apples' #@params fruit_list {input: string}
Use
fruit_selected = 'new' #@param ['apples', 'bananas', 'mangoes'] {allow-input: true}
And you will be able to choose from the list OR enter new elements.
If you want to input the name of an existing variable, you could do this
fruits=['apples', 'bananas', 'mangoes']
other={"a": 1, "b": 2}
fruit_selected = 'b' #@param ['apples', 'bananas', 'mangoes'] {allow-input: true}
#---- Find it in a dictionary
if fruit_selected not in fruits:
if fruit_selected in other:
print(f'{other[fruit_selected]}')
else:
print("Fruit selected NOT in other")
#---- Find it by name
a="x2"
if fruit_selected in globals():
print(f'Got {fruit_selected}')
But for this kind of interactions maybe ipywidgets is a better tool.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/54664021",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: how to submit the form in jquery to server side by escaping or bypassing the Validations that were set how to submit the form in jquery to server side by escaping or bypassing the Validations that were set
A: You can just call the DOM (not jQuery) form.submit() method, like this:
$("form")[0].submit();
Or if it's by ID:
document.getElementById('myForm').submit();
//or
$("#myForm").get(0).submit();
This bypasses the jQuery event handlers and prevents them from running, instead it directly submits the <form>.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/3337361",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Singleton events I am refactoring some old code, where I have a lot of static events like this
public static event Action Updated;
public static void OnUpdated()
{
if (Updated != null)
Updated();
}
I found out what using lazy singletons is often better than using static classes:
*
*no memory is consumed until first Instance call;
*private serialization/deserialization.
So that I refactor those to singletons and now I have Code Analysis complains.
Such events clearly offend CS1009 but I have some doubts:
*
*for static events sender doesn't makes sense, why and in what scenario would singleton sender be of any use? I can only think about deserialization, but it's an internal class implementation (moreover class is sealed), so I can take care to not use events and if I need one, I can create private event.
*creating e (deriving from EventArgs) is unnecessary complication to simply pass parameters, the biggest part I hate is to move it into namespace level, the only thing which EventArgs adds (could be useful sometimes) is Empty and then you have dozens of classes ...EventArgs. I could think what sometimes you need Cancel or Handled mechanics, but it was neverd needed for me.
When using event does everybody expect (object sender, SomeEventArgs args) and this is the only reason?
To summarize, here is my main question (but I would appreciate clarifying other questions as well): CS1009 and singletons, should I fix events or simply suppress the message?
P.S.: related subjects: this, this and this.
I found this question. According to event design guidelines I have to use Event<T> (disregards to this question), where T is based on EventArgs class.
Regarding sender in static events:
On static events, the sender parameter should be null.
This is a design guideline, which may not looks pretty to me, but will be very welcomed by anybody else (who is reading/maintaining my code).
It breaks both KISS and YAGNI principles as for me. And the more I think about it, the less and less I am sure of what to do.
A: I would fix your error. The general design guideline is indeed the (object sender, EventArgs e) signature.
It's a convention and is all about code consistency, code readability...etc. Following this pattern will help other people attaching handlers to your events.
Some general tips/answers:
*
*For a static event, you should indeed use null as sender (because there is no sender instance per definition).
*If you have nothing to pass for the e parameter, use EventArgs.Empty instead of new EventArgs() or null.
*You could use EventHandler and EventHandler<T> to simplify the definition of your events.
*For the sake of simplicity, you could use a custom EventArgs<T> class inheriting from EventArgs if you want to pass a single value to your event handler.
If you want to use the singleton pattern with a Lazy<T> definition, here's a complete example. Do note no event is static, so the sender parameter contains a reference to the singleton instance:
public class EventArgs<T> : EventArgs
{
public EventArgs(T value)
{
this.Value = value;
}
public T Value { get; set; }
}
public class EventArgs2 : EventArgs
{
public int Value { get; set; }
}
internal static class Program
{
private static void Main(string[] args)
{
Singleton.Instance.MyEvent += (sender, e) => Console.WriteLine("MyEvent with empty parameter");
Singleton.Instance.MyEvent2 += (sender, e) => Console.WriteLine("MyEvent2 with parameter {0}", e.Value);
Singleton.Instance.MyEvent3 += (sender, e) => Console.WriteLine("MyEvent3 with parameter {0}", e.Value);
Singleton.Instance.Call();
Console.Read();
}
}
public sealed class Singleton
{
private static readonly Lazy<Singleton> lazy = new Lazy<Singleton>(() => new Singleton());
public static Singleton Instance { get { return lazy.Value; } }
/// <summary>
/// Prevents a default instance of the <see cref="Singleton"/> class from being created.
/// </summary>
private Singleton()
{
}
/// <summary>
/// Event without any associated data
/// </summary>
public event EventHandler MyEvent;
/// <summary>
/// Event with a specific class as associated data
/// </summary>
public event EventHandler<EventArgs2> MyEvent2;
/// <summary>
/// Event with a generic class as associated data
/// </summary>
public event EventHandler<EventArgs<int>> MyEvent3;
public void Call()
{
if (this.MyEvent != null)
{
this.MyEvent(this, EventArgs.Empty);
}
if (this.MyEvent2 != null)
{
this.MyEvent2(this, new EventArgs2 { Value = 12 });
}
if (this.MyEvent3 != null)
{
this.MyEvent3(this, new EventArgs<int>(12));
}
Console.Read();
}
}
EDIT:
You could also build some EventArgs<T1, T2> if you need to pass two values. Ultimately, EventArgs<Tuple<>> would also be possible, but for more than 2 values I would build a specific XXXEventArgs class instead as it's easier to read XXXEventArgs.MyNamedBusinessProperty than EventArgs<T1, T2, T3>.Value2 or EventArgs<Tuple<int, string, bool>>.Value.Item1.
Regarding KISS/YAGNI: remember the (object sender, EventArgs e) convention is all about code consistency. If some developer uses your code to attach an handler to one of your events, I can assure you he will just love the fact that your event definition is just like any other event definition in the BCL itself, so he instantly knows how to properly use your code.
There even are others advantages than just code consistency/readability:
I inherited my custom XXXEventArgs classes from EventArgs, but you could build some base EventArgs class and inherit from it. For instance, see MouseEventArgs and all classes inheriting from it. Much better to reuse existing classes than to provide multiple delegate signatures with 5/6 identical properties. For instance:
public class MouseEventArgs : EventArgs
{
public int X { get; set; }
public int Y { get; set; }
}
public class MouseClickEventArgs : MouseEventArgs
{
public int ButtonType { get; set; }
}
public class MouseDoubleClickEventArgs : MouseClickEventArgs
{
public int TimeBetweenClicks { get; set; }
}
public class Test
{
public event EventHandler<MouseClickEventArgs> ClickEvent;
public event EventHandler<MouseDoubleClickEventArgs> DoubleClickEvent;
}
public class Test2
{
public delegate void ClickEventHandler(int X, int Y, int ButtonType);
public event ClickEventHandler ClickEvent;
// See duplicated properties below =>
public delegate void DoubleClickEventHandler(int X, int Y, int ButtonType, int TimeBetweenClicks);
public event DoubleClickEventHandler DoubleClickEvent;
}
Another point is, using EventArgs could simplify code maintainability. Imagine the following scenario:
public MyEventArgs : EventArgs
{
public string MyProperty { get; set; }
}
public event EventHandler<MyEventArgs> MyEvent;
...
if (this.MyEvent != null)
{
this.MyEvent(this, new MyEventArgs { MyProperty = "foo" });
}
...
someInstance.MyEvent += (sender, e) => SomeMethod(e.MyProperty);
In case you want to add some MyProperty2 property to MyEventArgs, you could do it without modifying all your existing event listeners:
public MyEventArgs : EventArgs
{
public string MyProperty { get; set; }
public string MyProperty2 { get; set; }
}
public event EventHandler<MyEventArgs> MyEvent;
...
if (this.MyEvent != null)
{
this.MyEvent(this, new MyEventArgs { MyProperty = "foo", MyProperty2 = "bar" });
}
...
// I didn't change the event handler. If SomeMethod() doesn't need MyProperty2, everything is just fine already
someInstance.MyEvent += (sender, e) => SomeMethod(e.MyProperty);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/30842956",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Does it need to DeleteObject after CBrush () Does DeleteObject need to be called after CBrush ()
Does it is need to call deleteObject() if CBrush bNewBrush(RGB(255, 255, 255));
Thank you in advance.
A: No, you do not have to manually call it. The destructor of CBrush calls DeleteObject() for you...actually the destructor for CGdiObject from which CBrush is derived.
To make sure bad things don't happen, you should also make sure that the brush is not selected into a device context when the destruction occurs.
A: no, you can find in the msdn an exemple of code.
http://msdn.microsoft.com/fr-fr/library/btwwha51.aspx
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/22016003",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Send a number of "Toast"s spaced by 2 seconds I need to display 4 "Toast"s spaced by 2 seconds between them.
How do I do this in such a way that they wait for each other and that the program itself waits until the last of them has displayed?
A: simply use handlers.
handler has a method called sendMessageDelayed(Message msg, long delayMillis).
just schedule your messages at the interval of 2 seconds.
here is a sample code.
int i=1;
while(i<5){
Message msg=Message.obtain();
msg.what=0;
hm.sendMessageDealayed(msg, i*2);
i++;
}
now this code will call handler's method handleMessage after every 2 seconds.
here is your Handler
Handler hm = new Handler(){
public void handleMessage(Message msg)
{
//Toast code.
}
};
and you are done.
Thanks.
A: Handlers are definitely the way to go but I would just postDelayed instead of handling an empty message.
Also extending Toast and creating a method for showing it longer is nice.
Sample Code:
// make sure to declare a handler in the class
private final Handler mHandler = new Handler();
// The method to show longer
/**
* Show the Toast Longer by repeating it.
* Depending upon LENGTH_LONG (3.5 seconds) or LENGTH_SHORT (2 seconds)
* - The number of times to repeat will extend the length by a factor
*
* @param number of times to repeat
*/
public void showLonger(int repeat) {
// initial show
super.show();
// to keep the toast from fading in/out between each show we need to check for what Toast duration is set
int duration = this.getDuration();
if (duration == Toast.LENGTH_SHORT) {
duration = 1000;
} else if (duration == Toast.LENGTH_LONG) {
duration = 2000;
}
for (int i = 1; i <= repeat; i++) {
// show again
handler.postDelayed(new Runnable() {
@Override
public void run() {
show();
}
}, i * duration);
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/6242348",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to populate struts 2 ui select tag by json returned list using jquery? //struts.xml
<package name="ajax" namespace="/" extends="struts-default,json-default">
<action name="CheckUserAction" class="com.controller.ajax.AjaxAction">
<result type="json">
<param name="root">jsonData</param>
</result>
</action>
</package>
//Action Class
public class AjaxAction extends ActionSupport {
private String capacity;
private String greeting;
private List<String> countryList;
private Map<String, Object> jsonData;
public String execute() throws Exception {
jsonData = new LinkedHashMap<String, Object>();
greeting = "HI " + "AMIT";
countryList = new ArrayList<String>();
countryList.add("US");
countryList.add("UK");
countryList.add("Russia");
jsonData.put("capacity", this.getCapacity());
jsonData.put("countryList", countryList);
jsonData.put("countryMap", countryMap);
jsonData.put("greeting", greeting);
return SUCCESS;
}
//Getter and setters
}
//Script
$(document).ready(function() {
$("#capacity").change(function() {
var capacity = $("#capacity").val();
$.getJSON('CheckUserAction.action', {
capacity : capacity
}, function(data) {
$('#abc').append('<br>' + data.capacity);
$('#abc').append('<br>' + data.countryList);
$('#xyz').attr('value', data.greeting);
$('#pqr').attr('list', data.countryList);
});
return false;
});
});
//JSP code
<table border="0">
<tr>
<td><s:label for="capacity" value="Capacity" /></td>
<td><s:textfield name="capacity" placeholder="100" id="capacity"
value="abc"></s:textfield></td>
</tr>
<tr>
<td><s:label for="dynamic" value="Ajax" /></td>
<td><s:textfield name="dynamic" value="learning" id="xyz"></s:textfield></td>
</tr>
<tr>
<td><s:label for="flightId" value="Flights" /></td>
<td><s:select list="#{'1':'1' }" name="fightId" id="pqr"></s:select></td>
</tr>
</table>
<div id="abc">Initial</div>
I want to populate list(id:pqr) with json returned list countryList, i am able to change attribute value of textfield(id:xyz),i also appended it to div(id:abc) but i am not able to change attribute list of struts select tag.
Is it has something to do with how struts tag are populated in HTML.
Also i am not using struts-jquery plugin nor dojo plugin.
Thanks
A: What kind of data you are receiving in data.countryList? Can u post that data? I hope there is no attr property named list for dropdown. List property provided by Struts. You can compose the data for dropdown like
<option value="1">India</option>
<option value="2">United States</option>
<option value="3">United Kingdom</option>
and if you are sending new list you can do fill the countryList like,
$('#pqr').html(composed_country_list);
Else you are updating counrty means you can append the data to dropdown like,
$('#pqr').append(composed_country_list);
Let me know if this helps..
A: The following code worked for me
//JSP
<s:select list="{}" name="fightId" id="pqr"></s:select>
Script File
$(document).ready(function() {
$("#capacity").change(function() {
var capacity = $("#capacity").val();
$.getJSON('CheckUserAction.action', {
capacity : capacity
}, function(data) {
countryListItem = data.countryList;
});
return false;
});
});
var pqr = $('#pqr');
pqr.find('option').remove();
pqr.append('<option value=-1>--Select--</option>');
for(var i = 0; i < countryListItem .length; i++) {
var opt = document.createElement('option');
opt.innerHTML = countryListItem [i];
opt.value = countryListItem [i];
pqr.append(opt);
}
Used javascript to populate the list by creating option attribute.
The struts select tag actually generates this kind of HTML internally.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/19287651",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How Delete session from visitor browser I have problem with session, I try unset($_SESSION) and session_unset() and session_destroy() session destroyed but still show in browser (cookie extension)
I want remove it finality like session_start(['cookie_lifetime' => 10]) but I not want set a time, I want only remove it in a location on my php code, any idea?
My code here:
<?php
session_start();
$_SESSION['style'] = $style;
echo "Your style is : " . $style;
unset($_SESSION['style']);
session_destroy();
A: The session cookie stored in the browser simply contains a reference to the session ID on the server and does not contain any actual session data. All of that is stored solely on the server and it would actually be a huge security issue if it were stored client-side. If you delete the session on the server, this deletes all data stored on the server to do with that session and any attempt to re-authenticate using the old session ID will fail. If the browser sends an old session cookie back to the server after the session has been destroyed, it will simply be ignored by the server. Therefore there is no need to delete the session cookie from the user's browser since this will be done automatically by the browser when the window is closed. The recommended way to kill a session is simply to do:
$_SESSION = array();
However, with that said, if you want to manually force the cookie to be deleted for whatever reason:
<?php
session_start();
$_SESSION['style'] = $style;
echo "Your style is : " . $style;
unset($_SESSION['style']);
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(session_name(), '', -1,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
session_destroy();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/52068808",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Why is an Action not implicit convertable to Action when T : U? Consider this code:
class BaseEvent {}
class DummyEvent : BaseEvent {}
void FooBase(BaseEvent e) {}
void FooDummy(DummyEvent e) {}
void main(String[] args) {
Action<BaseEvent> actionBase = FooBase;
Action<DummyEvent> actionDummy = FooDummy;
// Works implicit
Action<DummyEvent> actionDummy2 = actionBase;
// Only explcit
Action<BaseEvent> actionBase2 = (Action<BaseEvent>)actionDummy;
}
I dont understand why it works like this, wouldn´t it make more sense the other way around considering how it works with object references?
void main(String[] args) {
BaseEvent baseEvent = new BaseEvent();
DummyEvent dummyEvent = new DummyEvent();
// Works implicit
BaseEvent baseEvent2 = dummyEvent;
// Only explicit
DummyEvent dummyEvent2 = (DummyEvent)baseEvent2;
}
I want to write code which stores a Map of Action and pass in diffrent Events like this:
class EventManager {
Dicionary<int, Action<BaseEvent>> eventHandlers = new Dicionary<int, Action<BaseEvent>>();
public void AddHandler(int eventType, Action<BaseEvent> eventHandler) {
eventHandlers.Add(eventType, eventHandler);
}
public void TriggerEvent(BaseEvent e) {
eventHandlers[e.EventType](e);
}
}
void HandleDummyEvent(DummyEvent e)
{
// Some code
}
void main(String[] args) {
EventManager eventManager = new EventManager();
eventManager.AddHandler(DummyEvent.EventType, HandleDummyEvent);
eventManager.TriggerEvent(new DummyEvent());
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/25449439",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: OSB Production Logs Mixing up - Work Manger We are using custom loggers through Java code in OSB. It was working fine till before Production environment. In production under heavy load, all application logs are getting mixed up. I need to Configure Work Manager (WM) for each application. For an OSB project, I have configured for Proxy service one WM and for multiple Business Services One WM setting max Thread Constraint to 7 [Done multiple trial and error for Max Thread]. But still under heavy loads logs are getting mixed up. What values should I actually set for Work Manager properties?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/54090959",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to make two openlayers map work synchronized I create two openlayer maps in my page, now I want them work synchronized.
For example, one map's center or zoom is changed, then another have change its accordingly.
And vice versa.
Which event should I registed to the map?
A: This is indeed possible, as I have just done it. You need to trap the 'moveend' and 'move' events from the map being panned or zoomed (moveend is triggered at the end of a zoom, but you could trap 'zoomend' as well to be on the safe side). If you trap these using the parent map as the context then you can get the new map centre. Bear in mind that the map centre can change when the map is zoomed if the navigation control is being used and the zoom is done using the mouse. Then use the moveTo method (childmap.moveTo().
I've chosen the moveTo method as (although not well documented) this is what is always finally called in any pan or zoom event on any map. As an aside, calling moveTo will also cause the 'move', 'moveend' events to be triggered on the child map.
If you make a collection of maps using json, and use jQuery, the actual code would look something like this (I'm assuming you know how to trap map events in OpenLayers);
var newCentre = zoomedMap.getCenter();
$.each(maps, function (ind, map) {
if (map !== zoomedMap) map.moveTo(newCentre, newZoom);
});
where maps is my collection of maps, zoomedMap is the map the user actually triggered the pan or zoom event on (I've called it zoomeMap but it could just as easily be called pannedMap), and (obviously) map is the map in the collection that needs moving.
I played around a bit before I settled for the above code. The advantage here is that $.each doesn't wait for the moveTo function to return, so you get a much slicker looking synch. Of course this wouldn't really be an issue if you're only synching two maps.
I'm sorry to have posted this so long after the question was asked, but maybe it will help any new searchers out there.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/16827178",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: jquery event not working on mozilla and work for other browser i have been try to make a responsive design but the click event seems locked on mozilla and work just fine on other browser i have the following codes
jQuery(document).ready(function($){
$("#serach-button").click(function() {
var display=$("#head-form").css("display");
if(display!="none"){
$("#head-form").fadeOut();
}else{
$(".menu").hide();
$("#head-form").show();
}
});
});
<div class="button-responsiv-list">
<button class="button-responsiv"><i id="serach-button"class="glyphicon glyphicon-search"></i></button>
<button class="button-responsiv"><i id="navbar-button" class="glyphicon glyphicon-align-justify"></i></button>
<button class="button-responsiv" ><i id="sidebar-button-show" class="glyphicon glyphicon-indent-right"></i>
<i id="sidebar-button-hide" style="display:none;" class="glyphicon glyphicon-indent-left"></i>
</button>
</div>
i had tried the e.preventDeafualt() but still not working.
A: You may want to try live binding the event and see if that makes a difference. The other issue may be your css as the italic tag is an inline element you may not have a decent target area for the click event (this space can vary from browser to browser). You may want to try binding to the parent button tag instead as this should contain the child element. Also since there is no default action to an italic tag or button there is no reason to include a preventDefault() or return false.
$(function(){
$(document).on("click", "#serach-button", function() {
if($("#head-form").is(":visible")){
$("#head-form").fadeOut();
}else{
$(".menu").hide();
$("#head-form").show();
}
});
});
Also take note of how you are spelling your class names and id's as pointed out by other people in this thread there are several misspellings and several answers have tried correcting that spelling for you.
A: Actually I will upvote your question because it leads to an issue I didn't know before :
elements embedded inside a buttton in FF will lose their click event.
$("#p").click(function() {
alert('hello');
});
document.getElementById('i').addEventListener('click', function(e) {
alert('hello2');
}, false);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="b">
<img id="i" src="http://lorempixel.com/25/20" />
<em id="em">elements embedded inside a buttton in FF will lose their click event.</em>
</button>
I don't know if it's a bug as specs only state that
It is illegal to associate an image map with an IMG that appears as the contents of a BUTTON element.
So for you the solution is to reattach the event to the button (either by giving the serach-button id to your real button element, or with $("#serach-btn").parent().click(function() {.
jQuery(document).ready(function($) {
$("#serach-button").parent().click(function() {
alert('hello');
});
$("#real-button").click(function() {
alert('hello');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="button-responsiv-list">
<button class="button-responsiv"><i id="serach-button" class="glyphicon glyphicon-search"></i>
</button>
<button class="button-responsiv" id="real-button"><i id="navbar-button" class="glyphicon glyphicon-align-justify"></i>
</button>
<button class="button-responsiv"><i id="sidebar-button-show" class="glyphicon glyphicon-indent-right"></i>
<i id="sidebar-button-hide" style="display:none;" class="glyphicon glyphicon-indent-left"></i>
</button>
</div>
A: Your button has this class .search-btn so, you can try this:
$(function(){
$(".search-btn").click(function() {
if($("#head-form").is(":visible")){
$("#head-form").fadeOut();
}else{
$(".menu").hide();
$("#head-form").show();
}
});
});
A: Try changing "serach" to "search".
Also you can change jQuery to $:
$(document).ready(function () {
$("#search-button").click(function () {
var display = $("#head-form").css("display");
if (display != "none") {
$("#head-form").fadeOut();
} else {
$(".menu").hide();
$("#head-form").show();
}
});
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/27968694",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: CSS image not properly sized I have this paralax image on my website (the big nature one)
This is how the page is normally seen
But its not properly sized. When i open chrome dev tools it looks like the image below and that's how i want it to be.
this is the image how it needs to be (the nature image)
so what i want: I want the nature image seen on the pics above to be shown as it is in the second picture (with devtools). I know that the image is not properly sized for the box. But i don' t know how to fix it and can' t find something on the internet.
Can someone help me?
If my question is not clear enough please reply what i should add!
My CSS code attached to the image-paralax:
.header{
background-image: url("nav-bg.png"); //The background image
border-bottom-right-radius: 20px;
border-bottom-left-radius: 20px;
background-repeat: no-repeat;
background-attachment: fixed;
background-size: 100% 100%;
}
.parallax-2 {
background-attachment: fixed;
background-position: center;
background-repeat: no-repeat;
background-size: cover;
}
HTML code:
<div class="header parallax-2">
<div class="logo fade-in-3"><img src="logo.png" alt="BeldrProductions" width="500"></div>
<!-- The nav-items go here. but i left them out to save space-->
</div>
Hope to see your answer soon!
Beldr
Note:
Suggestions from the answers below:
*
*background-size: contain no-repeat; (does not work)
*object-fit: contain and object-fit: cover (does not work)
*width&height 100% (nope)
My code on JSfiddle: https://jsfiddle.net/BeldrProductions/k5f70dy9/
A: You have to wrap your background image container in another div.
Check the HTML, CSS snippets along with screenshot.
<body>
<div class="header">
<div class="parallax-2">
<div class="logo fade-in-3">
<img src="logo.png" alt="BeldrProductions" width="500" />
</div>
</div>
<!-- The nav-items go here. but i left them out to save space-->
</div>
</body>
<style>
.header {
height: 300px;
width: inherit;
border-bottom-right-radius: 20px;
border-bottom-left-radius: 20px;
}
.parallax-2 {
height: inherit;
width: inherit;
background-image: url("nav-bg.png");
background-repeat: no-repeat;
background-size: 100% 100%;
}
</style>
A: Thanks to everyone that has helped me. But i just used it without a image
Thanks, Bye!
if there still is anyone who has a solution. Please leave it below. I would love to see it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/66078761",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to calculate the Euclidean distance in python I have a dataset in .csv format. contains 2099846 rows and 38 columns
I want to calculate the Euclidean distance of any pair of rows and set to another 2d array.
import pandas as pd
import numpy as np
data = pd.read_csv('fraudDataset.csv', encoding= 'unicode_escape')
row = len(data)
data = data.astype(int)
distanceMatrix = np.zeros((np.shape(data)))
for datai in range(len(data)):
for dataj in range( datai + 1,len(data)):
distanceMatrix[datai,dataj] = np.linalg.norm(data[3] - data[4], ord=None, axis=None, keepdims=False)
but it gives the error
return self._engine.get_loc(casted_key)
File "pandas\_libs\index.pyx", line 70, in pandas._libs.index.IndexEngine.get_loc
File "pandas\_libs\index.pyx", line 101, in pandas._libs.index.IndexEngine.get_loc
File "pandas\_libs\hashtable_class_helper.pxi", line 1675, in pandas._libs.hashtable.PyObjectHashTable.get_item
File "pandas\_libs\hashtable_class_helper.pxi", line 1683, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 3
Could you please help me how to do this task?
A: I cannot replicate the problem, as there is inadequate information about the type of data, thus suggesting a fix to the error message.
But from your problem description, I think cdist function from scipy.spatial* could solve your problem. As you have not provided an example data row, I created an integer matrix A.
from scipy.spatial.distance import cdist
A=np.random.randint(10, size=(10,10))
B=cdist(A, A, metric='euclidean')
B is a symmetric matrix, naturally.
* https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.cdist.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/69778061",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: ReSharper Unit Test Runner ignores deployment items configuration I'm using Resharper 6.1 for unit testing a new project and it seems to ignore the the Deployment section of my local.testsettings file.
I tried to configure in "ReSharper -> Options -> Unit testing -> MSTest -> Use this test run configuration" to explicitly use the local.testsettings file, how is suggested in this question: ReSharper Unit Test Runner: Support for Deployment Items, but nothing happens.
Desperately I tried to move the files out of the test project, create another Test Settings file, move the test project to another solution, but still nothing.
Any tips?
A: This is also a ReSharper-Configuration problem that I encounter myself. May this help you.
When I try to run the application, it get this ReSharper error: "The project to be run with this configuration is not present in the solution"
In Resharper help page, I found the path to the run configurations:
https://www.jetbrains.com/help/resharper/2016.2/Run_Configurations.html
ReSharper | Tools | Run Configurations...
Since the project doesn't exist anymore, I delete that connfiguration:
{Project Name} > Configure > Delete...
A: This issue (http://youtrack.jetbrains.com/issue/RSRP-295311) should be fixed in ReSharper 7 here: http://www.jetbrains.com/resharper/download/index.html.
Thank you!
A: I got the same ReSharper error in VS2019, VS2022:
ReSharper – Failed to execute run configuration
The project to be run with this configuration is not present in the
solution.
Turns out that you don’t have to necessarily run the project that is problematic. If there is some configuration saved for another project in ReSharper, and that project is not present anymore (for example, you’ve switched branches or deleted some project from the solution), this error will pop-up. It was my case.
Solution is as described above:
Go to Extensions -> ReSharper -> Tools -> Run configurations… -> nonExistingProject -> Configure -> Delete
This will delete configuration that is preventing ReSharper to work well and blocks your run at the IDE.
Apparently, still not fixed...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/11622581",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.