text
stringlengths
0
13M
Title: opengl overlay on camera view Tags: android;camera;opengl-es-2.0;android-camera Question: I still haven't found a proper way to show an opengl overlay oon top of camera preview, There's a hack, where you call ```setContentView(GLSurfaceView) addContentView(MyCameraSurfaceView) ``` but it doesn't work properly - i.e. when you switch to anouther activity and go back, the opengl layer isnt displayed over camera preview. there are a lot of tutorials and samples which use the above method, but it simply doesn't work as expected does anyone know how they do it in layar Here is the accepted answer: It looks like I've found the solution to my problem - its ```setZOrderMediaOverlay``` function, heres my code: ```private void initViews() { mFrame = new FrameLayout(this); initCameraView(); initGLView(); setContentView( mFrame ); } private void initGLView() { mRenderer = new MyGLRenderer( this ); mGLView = new GLSurfaceView(this); mGLView.setZOrderMediaOverlay(true); mGLView.setEGLConfigChooser(8, 8, 8, 8, 16, 0); mGLView.setRenderer(mRenderer); mGLView.getHolder().setFormat(PixelFormat.TRANSLUCENT); mFrame.addView( mGLView ); } private void initCameraView() { mCameraSurfaceView = new CameraSurfaceView(this); mFrame.addView(mCameraSurfaceView); } ``` Here is another answer: Did you ever consider that when switching to another activity you are loosing the opengl context from the overlaying glsurface? Comment for this answer: That is not the problem - I created both views with 150 dp margin, one right aligned, and the other left aligned, and both of thew where ok, but the camera view was over the GLSurvaceView. Luckily I think I've found the solution - see my answer.
Title: Post notes slides over the posts in Tumblr's permalink page Tags: html;css Question: On my tumblr blog, I am using a custom masonry theme, in which post notes should be below the post in the permalink pages. First it was sliding over the post, which don't let the viewers to view the post in permalink page. Then I lowered the z-index of the post notes css, now posts notes slides under the post. For example : Click here ```#content { {block:IndexPage} width:66%; {/block:IndexPage} {block:PermalinkPage} width: 55%; {/block:PermalinkPage} top:170px; {block:IndexPage} left: 1%; {/block:IndexPage} {block:PermalinkPage} left: 10%; {/block:PermalinkPage} float: left; position: absolute; border-right:1px solid #2b2b2b; } .entry { float:center; {block:indexpage} width: 43%; overflow:hidden; {/block:indexpage} margin: 2%; {block:permalinkpage} width: 500px; {/block:permalinkpage} padding: 10px; background: {color:box}; display: inline-block; position: relative; z-index:2; -webkit-border-radius:3px; -moz-border-radius:3px; border-radius:3px; } .entry img { display: block; width:auto; max-width: 100%; } .perma2, .perma2 a { margin-top: 5px; font-family: 'Coda', sans-serif; font-size:15px; color: #40c143; } .prmlnk { background:{color:box}; font-size:15px; margin-left:10px; margin-top:5px; width: 500px; padding: 10px; z-index:2; display: block; overflow:hidden; position: relative; -webkit-border-radius:3px; -moz-border-radius:3px; border-radius:3px; } .wrap {position: fixed; bottom:10px; left:0px;} .wrap:hover .cred a {width: 130px; height: 20px; text-align: right;} .cred a { height: 100%; width: 80px; height: 20px; margin-left:-65px; background-color: #000; font-size: 13px; text-align: right; overflow: hidden; z-index: 9999999; padding-top: 3px; top: -2px; color: #fff; padding-right: 5px; -moz-border-radius: 2px; border-radius: 2px; display: inline-block; text-transform: capitalize; -webkit-transition: all 0.5s ease-out; -moz-transition: all 0.5s ease-out; opacity: .7; filter: alpha(opacity = 70); font-family: 'Lato', sans-serif; line-spacing: 1px; } ol.notes { padding: 0px; margin: 25px 0px; list-style-type: none; border-bottom: solid 1px #5a5a5a; } ol.notes li.note { border-top: solid 1px #5a5a5a; padding: 10px; } ol.notes li.note img.avatar { vertical-align: -4px; margin-right: 10px; width: 16px; height: 16px; } ol.notes li.note span.action { font-weight: normal; color:#f2f2f2; } ol.notes li.note .answer_content { font-weight: normal; } ol.notes li.note blockquote { border-color: #eee; padding: 4px 10px; margin: 10px 0px 0px 25px; } ol.notes li.note blockquote a { text-decoration: none; }``` ```<div id="content"&gt; <div class="autopagerize_page_element"&gt; {block:Posts} <div class="entry"&gt; .....POSTS..... </div&gt; {block:permalinkpage}{block:NoteCount} <div class="prmlnk"&gt;<div class="perma2"&gt; Posted: <a href="{Permalink}"&gt;{TimeAgo}</a&gt; {/block:NoteCount} {block:PostNotes} {PostNotes} {/block:PostNotes} </div&gt; </div&gt; {/block:permalinkpage} {/block:Posts} </div&gt; <!------------autopagerise page element ends here----------------&gt; </div&gt;<!----------------------Content div ends here--------------------&gt;``` Here is the accepted answer: On the linked page, if I add ```top: 100%;``` to the .prmlnk CSS, the notes then show up below the post instead of being in the same position as the post.
Title: I am not geting all data Tags: c#;sql-server Question: I am trying to get some data from my DB with a stored procedure like this ```[getAllRecordsForSalaryCalculation] @year NCHAR(10), @Bruger NCHAR(20) AS BEGIN IF (@year = 2018) BEGIN SELECT SUM(Overtid1) AS overtid1Before FROM timer WHERE DateForQuery &gt;= CONVERT(DATETIME, '2018-12-01') AND DateForQuery <= CONVERT(DATETIME, '2019-04-30') AND Bruger LIKE '%@Bruger%' SELECT SUM(Overtid1) AS overtid1after FROM timer WHERE DateForQuery &gt;= CONVERT(DATETIME, '2019-05-01') AND DateForQuery <= CONVERT(DATETIME, '2019-11-30') AND Bruger LIKE '%@Bruger%' SELECT SUM(Overtid2) AS overtid2Before FROM timer WHERE DateForQuery &gt;= CONVERT(DATETIME, '2018-12-01') AND DateForQuery <= CONVERT(DATETIME, '2019-04-30') AND Bruger LIKE '%@Bruger%' SELECT SUM(Overtid2) AS overtid2after FROM timer WHERE DateForQuery &gt;= CONVERT(DATETIME, '2019-05-01') AND DateForQuery <= CONVERT(DATETIME, '2019-11-30') AND Bruger LIKE '%@Bruger%' SELECT SUM(Vagt) AS vagtBefore FROM timer WHERE DateForQuery &gt;= CONVERT(DATETIME, '2018-12-01') AND DateForQuery <= CONVERT(DATETIME, '2019-04-30') AND Bruger LIKE '%@Bruger%' SELECT SUM(Vagt) AS vagtafter FROM timer WHERE DateForQuery &gt;= CONVERT(DATETIME, '2019-05-01') AND DateForQuery <= CONVERT(DATETIME, '2019-11-30') AND Bruger LIKE '%@Bruger%' END END ``` My code looks like this ```con.Open(); SqlDataAdapter da = new SqlDataAdapter("getAllRecordsForSalaryCalculation", con); da.SelectCommand.CommandType = CommandType.StoredProcedure; da.SelectCommand.Parameters.AddWithValue("@year", year); da.SelectCommand.Parameters.AddWithValue("@Bruger", bruger); da.Fill(ds); con.Close(); ``` But I get only the first select and its empty. There is data in there, and it works when I run it as a query. I am not sure where i am doing wrong. Can somebody help? Comment: Your LIKE clause definition is wrong, see this issue: https://stackoverflow.com/questions/14237755/t-sql-and-the-where-like-parameter-clause. Use `Bruger LIKE '%' + @Bruger + '%'` instead. Comment: Possible duplicate of [T-SQL and the WHERE LIKE %Parameter% clause](https://stackoverflow.com/questions/14237755/t-sql-and-the-where-like-parameter-clause) Comment: Clearly it does not work when run as a query as `'%@Bruger%'` doesn't do what you think it does .Also there are a lot of reasons to not use `AddWithvalue`. Also `NCHAR` is a bad datatype for _Year_ Comment: My goal is to generate a report of income year to date based on the records the users has typed in. They will of cource newer see the code behind. The answer from Xabi gave me just what i wonted. Comment: And a discussion about not using [addwithvalue](https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/) Comment: Your procedure generates 6 resultsets of 1 (potentially) row each, not 1 resultset of 6 rows (with varying column names). Do you understand the difference? In addition, how does the consumer of this information know what each row "means"? You force the consumer to assume something based on position. This is not a good design - start over. Here is another answer: My proposal for the procedure: ```CREATE PROC [getAllRecordsForSalaryCalculation] (@year INT, @Bruger NVARCHAR(20)) AS BEGIN SET DATEFORMAT YMD IF (@year = 2018) BEGIN WITH tm AS ( SELECT Overtid1 AS Ov1, Overtid2 AS Ov2, Vagt AS Vag, DateForQuery AS Dt FROM timer WHERE Bruger LIKE '%' + @Bruger + '%' AND DateForQuery BETWEEN '2018-12-01' AND '2019-11-30' ) SELECT overtid1Before =(SELECT SUM(Ov1) FROM tm WHERE Dt BETWEEN '2018-12-01' AND '2019-04-30') ,overtid1After =(SELECT SUM(Ov1) FROM tm WHERE Dt BETWEEN '2019-05-01' AND '2019-11-30') ,overtid2Before =(SELECT SUM(Ov2) FROM tm WHERE Dt BETWEEN '2018-12-01' AND '2019-04-30') ,overtid2After =(SELECT SUM(Ov2) FROM tm WHERE Dt BETWEEN '2019-05-01' AND '2019-11-30') ,vagtBefore =(SELECT SUM(Vag) FROM tm WHERE Dt BETWEEN '2018-12-01' AND '2019-04-30') ,vagtAfter =(SELECT SUM(Vag) FROM tm WHERE Dt BETWEEN '2019-05-01' AND '2019-11-30') END END ``` Here is another answer: The LIKE clause is wrong. '%@Bruger%' Instead use '%'+ @Bruger+ '%' Try this. ```[getAllRecordsForSalaryCalculation] @year NCHAR(10), @Bruger NCHAR(20) AS BEGIN IF (@year = 2018) BEGIN SELECT SUM(Overtid1) AS overtid1Before FROM timer WHERE DateForQuery &gt;= CONVERT(DATETIME, '2018-12-01') AND DateForQuery <= CONVERT(DATETIME, '2019-04-30') AND Bruger LIKE '%'+ @Bruger +'%' SELECT SUM(Overtid1) AS overtid1after FROM timer WHERE DateForQuery &gt;= CONVERT(DATETIME, '2019-05-01') AND DateForQuery <= CONVERT(DATETIME, '2019-11-30') AND Bruger LIKE '%'+ @Bruger +'%' SELECT SUM(Overtid2) AS overtid2Before FROM timer WHERE DateForQuery &gt;= CONVERT(DATETIME, '2018-12-01') AND DateForQuery <= CONVERT(DATETIME, '2019-04-30') AND Bruger LIKE '%'+ @Bruger +'%' SELECT SUM(Overtid2) AS overtid2after FROM timer WHERE DateForQuery &gt;= CONVERT(DATETIME, '2019-05-01') AND DateForQuery <= CONVERT(DATETIME, '2019-11-30') AND Bruger LIKE '%'+ @Bruger +'%' SELECT SUM(Vagt) AS vagtBefore FROM timer WHERE DateForQuery &gt;= CONVERT(DATETIME, '2018-12-01') AND DateForQuery <= CONVERT(DATETIME, '2019-04-30') AND Bruger LIKE '%'+ @Bruger+ '%' SELECT SUM(Vagt) AS vagtafter FROM timer WHERE DateForQuery &gt;= CONVERT(DATETIME, '2019-05-01') AND DateForQuery <= CONVERT(DATETIME, '2019-11-30') AND Bruger LIKE '%'+ @Bruger+ '%' END END ``` Here is another answer: Try this: ```SELECT (select sum(Overtid1) from timer where DateForQuery &gt;= Convert(datetime,'2018-12-01') and DateForQuery <= Convert(datetime,'2019-04-30') and Bruger like'%@Bruger%') as overtid1Before, (select sum(Overtid1) from timer where DateForQuery &gt;= Convert(datetime,'2019-05-01') and DateForQuery <= Convert(datetime,'2019-11-30') and Bruger like'%@Bruger%') as overtid1after, (select sum(Overtid2) from timer where DateForQuery &gt;= Convert(datetime,'2018-12-01') and DateForQuery <= Convert(datetime,'2019-04-30') and Bruger like'%@Bruger%') as overtid2Before, (select sum(Overtid2) from timer where DateForQuery &gt;= Convert(datetime,'2019-05-01') and DateForQuery <= Convert(datetime,'2019-11-30') and Bruger like'%@Bruger%') as overtid2after, (select sum(Vagt) from timer where DateForQuery &gt;= Convert(datetime,'2018-12-01') and DateForQuery <= Convert(datetime,'2019-04-30') and Bruger like'%@Bruger%') as vagtBefore, (select sum(Vagt) from timer where DateForQuery &gt;= Convert(datetime,'2019-05-01') and DateForQuery <= Convert(datetime,'2019-11-30') and Bruger like'%@Bruger%') as vagtafter ; ```
Title: Images within a post display fine but clicking on images return 404 not found error Tags: wordpress;http-status-code-404;permalinks Question: To start with, I am not an expert of any kind. Codes drive me insane. I run a site called: http://nascentarray.com. I moved the site from one host to another and after the migration, I found that many images were broken. So, I changed the permalink structure: From: nascentarray.com/post-name/ To: nascentarray.com/year/month/date/post-name/ Everything looked fine until I started getting 404 errors on images interested into the posts directly. To me more specific, I use two methods to insert images: I use the Jetpack module of WP to create a gallery in mosaic layout that gives a carousel of images when someone clicks on the gallery. For some posts, using Jetpack gallery module makes no sense and so, I simple insert individual images between texts using the simple media uploader. Problem: The problem is with the posts where I do not use the Jetpack gallery module. When I click on a post, the post opens fine and shows all images in it. However, the moment I start clicking on individual images, they start giving 404 error. Example: http://nascentarray.com/2013/02/08/tallest-buildings-of-2013/ Clicking on any image in the post will return a 404 error. How to solve this problem? Anyone, please help me. This is so disturbing and I don't have enough technical expertise to deal with this on my own and so I can came here with a hope to find some help from experts. Here is the accepted answer: The posts where you don't use jetpack image gallery module doesn't embed a gallery. Instead, you embed images in your posts individually. When you embed, there's option with image link whether you want to link image with post, attachment page, custom link or source file. Your images are not linked to source file - instead those are linked to POST ATTACHMENT link. Once you changed the permalinks structure of your post, the links associated with your image files were not updated and those remained as per previous permalink structure those don't exist now and thus it gives 404 error. It's solution can be to revert your permalinks structure to previous one (short and immediate solution) and other solution can be writing a short script and update all links of images in batch with their source file or anything else. Another solution is to use Yoast SEO plugin to generate redirect URL's for old backlinks. See the guide in this blog post regarding this solution. I hope this helps and you understand the issue now. Comment for this answer: Thanks for appreciation. Please ACCEPT my answer by clicking TICK sign and VOTE for my answer. In case you need any further help, let me know. But don't forget to accept my answer and i will VOTE for your question as well that will increase your reputation points. @user2513375 Comment for this answer: Thanks. You first click "Arrow UP" icon that's on left side of answer, that's above score (here score is 1 at the moment) for VOTING UP & then click the TICK icon. Thanks. Comment for this answer: That was awesome! I will give the last option a try once I move to new host. My current host godaddy has a weird restriction that they never mentioned when I bought a hosting plan with them. They do not allow more than 1024 files in a single folder and it should be preferably below 1000. They also do not allow more than 500,000 files in entire windows or linux hosting even if you have unlimited space. That is the most ridiculous thing I have ever heard of. Comment for this answer: Sorry, just went back to my website and didn't notice your reply. How do I accept and vote. I am new here. I don't know how to do so. Will you mind guiding me again? Comment for this answer: I think I just figured out and did it :) Here is another answer: Your permalink structure is incorrect. You need to change it back to nascentarray.com/year/month/date/post-name/ If it's already that way, then you need to double check your folders in uploads. Because if you look at your one page here http://nascentarray.com/2013/06/17/stock-wallet-the-only-wallet-you-will-ever-need/ That image is linked with ../year/month/date/post_name/image_name/ i.e. http://i0.wp.com/nascentarray.com/wp-content/uploads/2013/06/stock_wallet_2.jpg?resize=389%2C176 Obviously your plugin for viewing galleries adds the extra stuff in the URL's. Where as the link you gave above has just ../post_name/image_name/ Which isn't working with your plugin or linking of the image file. Comment for this answer: Thank you for the reply. I think, the other person has given be a nice solution. I may just try that once.
Title: Java Xmemcached or Spymemcached client unable to get the key value which is set by C# Enyim client Tags: java;c#;spymemcached;enyim;xmemcached Question: Java Xmemcached or Spymemcached client are unable to get the correct value from memcached by key which is set by C# Enyim client. We have already tried set C# MemcachedProtocol.Binary to Text to store basic String format data, but both Java Xmemcached client and Spymemcached client are not able to get the data. The errors are below: ```2018-01-11 11:08:06.655 [ERROR] [main] BaseSerializingTranscoder: Failed to decompress data java.util.zip.ZipException: Not in GZIP [email protected](GZIPInputStream.java:165) ~[?:1.8.0_144] at java.util.zip.GZIPInputStream.(GZIPInputStream.java:79) ~[?:1.8.0_144] at java.util.zip.GZIPInputStream.(GZIPInputStream.java:91) ~[?:1.8.0_144] at net.rubyeye.xmemcached.transcoders.BaseSerializingTranscoder.gzipDecompress(BaseSerializingTranscoder.java:274) [xmemcached-2.4.0.jar:?] at net.rubyeye.xmemcached.transcoders.BaseSerializingTranscoder.decompress(BaseSerializingTranscoder.java:219) [xmemcached-2.4.0.jar:?] at net.rubyeye.xmemcached.transcoders.SerializingTranscoder.decode(SerializingTranscoder.java:87) [xmemcached-2.4.0.jar:?] at net.rubyeye.xmemcached.XMemcachedClient.fetch0(XMemcachedClient.java:657) [xmemcached-2.4.0.jar:?] at net.rubyeye.xmemcached.XMemcachedClient.get0(XMemcachedClient.java:1085) [xmemcached-2.4.0.jar:?] at net.rubyeye.xmemcached.XMemcachedClient.get(XMemcachedClient.java:1043) [xmemcached-2.4.0.jar:?] at net.rubyeye.xmemcached.XMemcachedClient.get(XMemcachedClient.java:1065) [xmemcached-2.4.0.jar:?] ``` If we use StringTranscoder(), the error will be decoding String error: ```Exception in thread "main" java.lang.RuntimeException: Decode String [email protected](StringTranscoder.java:35) at net.rubyeye.xmemcached.transcoders.StringTranscoder.decode(StringTranscoder.java:11) at net.rubyeye.xmemcached.XMemcachedClient.fetch0(XMemcachedClient.java:657) at net.rubyeye.xmemcached.XMemcachedClient.get0(XMemcachedClient.java:1085) at net.rubyeye.xmemcached.XMemcachedClient.get(XMemcachedClient.java:1043) at net.rubyeye.xmemcached.XMemcachedClient.get(XMemcachedClient.java:1065) ``` Here is another answer: The problem has been fix by writing a custom transcoder and ignoring the GZIP/ZIP flag part.
Title: using crystalreportviewer for windows 10 Tags: c#;crystal-reports;windows-10 Question: i have a project and using "crystalreportviewer" control, to view .rpt files. my complied project, executes correctly in my PC and other pc with windows 7. But in windows 8.1 and 10 , it has this error: ```crystaldecisions.crystalreports.engine.reportdocument' threw an exception ``` I installed CRRuntime_32bit_13_0_3.msi and CRRedist2005_x86.msi . But it dosn't show the report . Please Help me, what do i do? Here is another answer: Go to the aspnet_client folder. Rename the folder ''4_0_30319" to "4_6_79" . It will work. Comment for this answer: But, my Project is a windows local App! (.exe)
Title: How can I use AMD drivers for AMD A10-8700P Radeon R6 on Ubuntu 14.04 LTS? Tags: drivers Question: I open Software &amp; Updates> Additional Drivers. It's currently : opensource, tested. I select any of the others (Proprietary) and apply. But it won't let me swap, just goes back to the open source one. Here is another answer: Load Ubuntu onto a flashdrive/CD and load the Ubuntu live [email protected]. If everything load fine and Ubuntu runs ok you should be set, if any other issues come up you should be able to fix them.
Title: link back-end password protected access database within same location Tags: ms-access;vba Question: I'm using the code below to link my bank-end database to the front-end. It works fine without having a password on the back-end DB. How do I use the same code with a password protected back-end file. NOTE: The following code is obtained from [Stackoverflow question][1] ``` [1]: https://stackoverflow.com/questions/3315306/how-can-a-relative-path-specify-a-linked-table-in-access-2007 Private Sub Form_Load() Dim strOldConnect As String Dim strNewConnect As String Dim intSlashLoc As Integer Dim intEqualLoc As Integer Dim strConnect As String Dim strFile As String Dim strCurrentPath As String strCurrentPath = CurrentProject.path Dim tblDef As TableDef Dim tblPrp As Property For Each tblDef In CurrentDb.TableDefs Debug.Print tblDef.Name If tblDef.Connect &amp; "." <&gt; "." Then strOldConnect = tblDef.Connect intEqualLoc = InStr(1, strOldConnect, "=", vbTextCompare) strConnect = Left(strOldConnect, intEqualLoc) intSlashLoc = InStrRev(strOldConnect, "\", -1, vbTextCompare) strFile = Right(strOldConnect, Len(strOldConnect) - intSlashLoc) strNewConnect = strConnect &amp; strCurrentPath &amp; "\" &amp; strFile tblDef.Connect = strNewConnect tblDef.RefreshLink End If Next tblDef End Sub ``` Here is the accepted answer: I found a workaround myself and would like to share it, thank you. ```Public Function DBconnect() Dim Password As String Dim FileName As String Dim CurrentConnection As String Dim AccessConnect As String Dim NewConnection As String Dim CurrentPath As String Dim CurrentLocationEnd As Integer AccessConnect = "MS Access;PWD=password;DATABASE=" Password = "password" CurrentPath = CurrentProject.Path Dim tblDef As TableDef Dim tblPrp As Property For Each tblDef In CurrentDb.TableDefs Debug.Print tblDef.Name If tblDef.Connect &amp; "." <&gt; "." Then CurrentConnection = tblDef.Connect CurrentLocationEnd = InStrRev(CurrentConnection, "\", -1, vbTextCompare) FileName = Right(CurrentConnection, Len(CurrentConnection) - CurrentLocationEnd) NewConnection = AccessConnect &amp; CurrentPath &amp; "\" &amp; FileName tblDef.Connect = NewConnection tblDef.RefreshLink End If Next tblDef End Function ``` Here is another answer: The whole connection string for Access ```Microsoft ACE OLEDB 12.0``` is: ```Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\myFolder\myAccessFile.accdb; Jet OLEDB:Database Password=MyDbPassword; ``` See this link for reference https://www.connectionstrings.com/access/ In your case this would to the trick: ```tblDef.Connect = "PWD=" &amp; MyPassword &amp; ";DATABASE=" &amp; YourDatabasePath ``` Comment for this answer: Run-time error '3170': Could not find installable ISAM.
Title: TypeError: state.userInfo is not iterable in Jest Testing Tags: javascript;reactjs;redux;react-redux;jestjs Question: I keep getting this TypeError when I run my jest tests on one of my reducers. It seems like it has to do with the fact that it can't find the state of the store? This is the exact error I get in the console when i run yarn test --coverage on the reducer test file: Console Error: ``` TypeError: state.userInfo is not iterable 63 | allDocumentComments: action.payload.allDocumentComments ? _.cloneDeep(action.payload.allDocumentComments) : null, 64 | userInfo: [ &gt; 65 | ...state.userInfo, | ^ 66 | ...action.payload.userInfo 67 | ] 68 | }; at _default (src/reducers/sopCommentsReducer.js:65:20) at Object.test (src/tests/reducers/sopCommentsReducer.test.js:130:40) ``` Here is the reducer test file with the test I'm trying to pass: Reducer Test File: ```import sopCommentsReducer from '../../reducers/sopCommentsReducer'; import * as mocks from '../../setupTests'; import _ from 'lodash'; // Testing tableActions.js reducer equivalents describe('testing reducers to tableActions.js actions', () =&gt; { const allDocumentComments = { 'comement-string' :{ _id: "5e792", document_id: "1", commenter_id: "2", comment: "this is a comment", resolved: false, timestamp: "2020-03-23 21:31:36+00:00", resolved_timestamp: "2020-03-24 17:36:15+00:00", total_comments: 1, replies: [ { commenter_id: "3", comment: "Reply", timestamp: "2020-03-23 21", } ], } }; const userAccountData = [{ _id: "5e792", msid: "alex", roles: ["admin"], email_address: "[email protected]", family_name: "Pelo", given_name: "Alex", }]; describe('testing addSOPComment action reducer', () =&gt; { test('Returns the correct reducer result given the action', () =&gt; { let expectedAction = { 'payload': { 'allDocumentComments': allDocumentComments, 'userInfo': userAccountData }, 'type': 'ADD_SOP_COMMENT' }; let addSOPCommentReducerResult = sopCommentsReducer(mocks.mockFullStore, expectedAction); expect(addSOPCommentReducerResult).toMatchSnapshot(); }); }); ``` And here is the reducer file where the test case is failing Reduce file: ```import { ADD_SOP_COMMENT, } from '../actions/types'; import _ from 'lodash'; const INITIAL_STATE = { allDocumentComments: {}, userInfo: [], }; export default (state = INITIAL_STATE, action) =&gt; { switch(action.type){ case ADD_SOP_COMMENT: return { ...state, allDocumentComments: action.payload.allDocumentComments ? _.cloneDeep(action.payload.allDocumentComments) : null, userInfo: [ ...state.userInfo, ...action.payload.userInfo ] }; default: return state; } }; ``` Comment: Try printing your `state`, to make sure what it contains Comment: Could you provide a codesandbox link? Here is another answer: I was also facing the same issue. I can share what mistake I was making and how I resolved it. I was making a mistake while mocking ```axios``` request during writing integration tests. For example: Let's say once a user logs in successfully, we're making network calls to fetch wishlist, cart details and initializing the state for both. But, while writing test cases, we forgot to mock the response part for wishlist/cart, in that case, it might initialize the state as ```null``` if it's not handled correctly. So, this was the mistake, I fixed this by correcting the mockup. Please check your mockups properly, maybe the same kind of mistake you're making.
Title: React gives Too many renders error when trying to sort data Tags: javascript;reactjs Question: I'm trying to sort the table with the data I get from an API.Basically, what I want is that I would sort the table ascending or descending according to which cell has clicked. To do so I've created this code but I do something wrong but not able to see it. Would be happy if anyone can guide me on where I'm having the trouble. I keep getting this error message every time I run the app : ```Too many re-renders. React limits the number of renders to prevent an infinite loop.``` What do I have : ```import React, { useState } from 'react'; import { Table } from 'semantic-ui-react'; import Moment from 'react-moment'; import _ from 'lodash' const UserTable = ({ repoData }) =&gt; { const [initialObject, setInitialObject] = useState({ column: null, data: repoData, direction: null }); const handleSort = (clickedColumn) =&gt; { if (initialObject.column !== clickedColumn) { setInitialObject({ column: clickedColumn, data: _.sortBy(initialObject.data, [clickedColumn]), direction: "ascending" }) return } setInitialObject({ data: initialObject.data.reverse(), direction: initialObject.direction === "ascending" ? "descending" : "ascending", }) } return ( <div &gt; <Table sortable celled fixed&gt; <Table.Header&gt; <Table.Row&gt; <Table.HeaderCell sorted={initialObject.column === 'name' ? initialObject.direction : null} onCLick={handleSort("name")} &gt; Repository Name </Table.HeaderCell&gt; <Table.HeaderCell sorted={initialObject.column === 'description' ? initialObject.direction : null} onCLick={handleSort("description")} &gt; Description </Table.HeaderCell&gt; <Table.HeaderCell sorted={initialObject.column === 'created_at' ? initialObject.direction : null} onCLick={handleSort("created_at")}&gt; Created At </Table.HeaderCell&gt; </Table.Row&gt; </Table.Header &gt; <Table.Body&gt; {initialObject.data.map(repos =&gt; { return <Table.Row&gt; <Table.Cell&gt;{repos.name}</Table.Cell&gt; <Table.Cell&gt;{repos.description}</Table.Cell&gt; <Table.Cell&gt; <Moment fromNow&gt;{repos.created_at}</Moment&gt;</Table.Cell&gt; </Table.Row&gt; })} </Table.Body&gt; </Table&gt; </div&gt; ); } export default UserTable; ``` Here is the accepted answer: Issue is with ```onClick``` : ```onClick={handleSort("name")} // <-- this will call the function on render it self ``` ```const handleSort = (clickedColumn) =&gt; { if (initialObject.column !== clickedColumn) { setInitialObject({ // <------------ HERE : this will also cause rerender column: clickedColumn, data: _.sortBy(initialObject.data, [clickedColumn]), direction: "ascending" }) return } setInitialObject({ // <------------ HERE : this will also cause rerender data: initialObject.data.reverse(), direction: initialObject.direction === "ascending" ? "descending" : "ascending", }) } ``` Result : infinite loop ```Too many re-renders. React limits the number of renders to prevent an infinite loop. ``` Solution is, change it to : ```onClick={() =&gt; handleSort("name")} ``` Comment for this answer: Thanks, that was the real problem but do you mind explaining the potential thing causing this error when its not arrow function? Comment for this answer: `onClick={handleSort("name")}` this invokes the function without clicking , and arrow function will only invoke when it's clicked, and its not due to arrow, it's because you are passing parram, if you try `onClick={handleSort}` this will not invoke because you are not calling it, you are just passing function ref, but with `onClick={handleSort("name")}` this you are first calling the function
Title: Configuring NodeManager memory and vcores in a heterogenous YARN cluster? Tags: memory-management;hadoop-yarn;ambari Question: I am aware to set the memory and vcores in YARN using the following properties: ``` yarn.nodemanager.resource.memory-mb yarn.nodemanager.resource.cpu-vcores ``` I have a heterogenous YARN cluster with nodes having following configuration: ``` Node1 (8cores, 16GB RAM) Node2 (8cores, 16GB RAM) Node3 (32cores, 64GB RAM) Node4 (32cores, 64GB RAM) ``` I want to set the nodemanager memory and cores to be different for Node1,Node2 and Node3,Node4. Node1 &amp; Node2 ``` yarn.nodemanager.resource.memory-mb = 10240 yarn.nodemanager.resource.cpu-vcores = 15 ``` Node3 &amp; Node4 ``` yarn.nodemanager.resource.memory-mb = 40240 yarn.nodemanager.resource.cpu-vcores = 25 ``` How to achieve this with/without using Ambari? Here is the accepted answer: Without Ambari: You can achieve the heterogeneous resource assignment directly by configuring the above properties in ```yarn-site.xml``` of individual nodes and restarting the YARN services. With Ambari: In Ambari, You can create ```Configuration Groups``` for ```individual nodes``` of cluster from the ```Manage Configuration Group``` link visible on the ```Configs``` tab next to ```Group drop down```. While creating the configuration groups you will find option of selecting the node where you wants to apply the configuration. Once configurations gets created for individual nodes, changes can be applied by restarting the YARN services. Follow Heterogeneous Configuration to know how it can be configured. Comment for this answer: I am aware of this but this can be done using Ambari as well? I believe it applies the same copy to all nodes and you cannot manually change the per node config since Ambari syncs it back. Comment for this answer: Thanks, this looks great Comment for this answer: @RakeshRakshit, I have added details for Ambari configuration as well, please follow that.
Title: How can I disable (and then enable) text messaging feature from Android SDK Tags: java;android Question: I am working with Android SDK for less than a week now. I was able to build sample apps and run them on Nexus 5. One of my requirements is to 1) disable the SMS text messaging feature based on certain criteria and 2) then enable the SMS text messaging feature after certain duration. I understand that Android SDK has API to send text messaging from the app. Is there also any API to disable (and then enable) the SMS text messaging programmatically Comment: Do you want to block outgoing and incoming messages programmatically? Comment: Yes, I want to block them programmatically Here is the accepted answer: If the app has root level access, or is using a framework such as Exposed, then yes app can access low level API's to affect SMS. Otherwise, there is no known official API for that yet. Though Android has introduced device admin API, There seems to be no SMS specific policy present. Comment for this answer: Alternatively, is it possible to lock the keyboard (that should disable the SMS, besides everything on the phone). Thanks, I am going to look at the links
Title: Objective-C: variable optimized away by compiler Tags: objective-c;cocoa;xcode;compiler-construction;gdb Question: I am trying to run the following code: ```1. NSURL *checkLicenseURL = [NSURL URLWithString:@"check_license.php?accesskey=&amp;license_key="]; // call server API 2. NSError *err = nil; 3. NSXMLDocument *xmlResult = [[NSXMLDocument alloc] initWithContentsOfURL:checkLicenseURL options:NSXMLDocumentTidyXML error:&amp;err]; ``` But when looking at variables in gdb, after line 1 was executed, doing ```p checkLicenseURL ``` returns ```$1 = <variable optimized away by compiler&gt; ``` It also causes line 3 to crash. Why is this happening and how do I fix this? Here is the accepted answer: Just compile without optimizations turned on, or select a "debug" build if you used a wizard of some sort to build your project. I'm not sure where to turn off optimizations in XCode but you probably want these GCC command line options for debugging: ```-O0 -fno-inline ``` Comment for this answer: I'm using the "debug" mode in Xcode, but it is still giving this error. Here is another answer: Turning off optimizations for everything is one option. It is also possible to instruct the compiler that particular variables should not be optimized away. The way to do it is with the ```volatile``` keyword: ```volatile NSURL *checkLicenseURL = ... ``` Wikipedia entry on volatile variables Another similar question: iPhone Variable Optimized Away by Compiler
Title: Code.org AppLabs: I am unable to get a specific whether condition on and display it on the screen Tags: javascript;code.org Question: I'm working on this weather app, but I ran into a problem where I am unable to get the specific whether condition from the data set onto the screen. It always displays the whether condition for one of the cities, but not the others. I need some help on this if possible, and could be a big help if you point out any mistakes I have made. ```//The variables var low = getColumn("Daily Weather", "Low Temperature"); var high = getColumn("Daily Weather", "High Temperature"); var city = getColumn("Daily Weather", "City"); var icon = getColumn("Daily Weather", "Icon"); var condition = getColumn("Daily Weather", "Main Condition"); var forecastNum = getColumn("Daily Weather", "Forecast Number"); var id = 0; //filtered variables var todayLow = []; var todayHigh = []; var todayCondition = []; var todayIcon = []; onEvent("locationDropdown", "change", function( ) { if (getText("locationDropdown") == "Anchorage, Alaska") { id = 1; } else if ((getText("locationDropdown") == "Fairbanks, Alaska")) { id = 6; } else if ((getText("locationDropdown") == "Denver/Boulder, Colorado")) { id = 16; } else if ((getText("locationDropdown") == "Chicago, Illinois")) { id = 31; } else if ((getText("locationDropdown") == "Des Moines, Iowa")) { id = 56; } else if ((getText("locationDropdown") == "Goodland, Kansas")) { id = 66; } else if ((getText("locationDropdown") == "Louisville, Kentucky")) { id = 86; } else { id = 96; } }); onEvent("conditionButton", "click", function( ) { updateScreen(); setScreen("screen2"); }); onEvent("conditionButton1", "click", function( ) { updateScreen(); setScreen("screen2"); }); onEvent("tempButton", "click", function( ) { updateScreen(); setScreen("screen3"); }); onEvent("homeButton1", "click", function( ) { updateScreen(); setScreen("screen1"); }); onEvent("homeButton2", "click", function( ) { updateScreen(); setScreen("screen1"); }); onEvent("temperatureButton", "click", function( ) { updateScreen(); setScreen("screen3"); }); function updateScreen() { var index = id; console.log(id); for (var i = 0; i < 8; i++) { if (forecastNum[i] == 1) { appendItem(todayLow, low[i]); appendItem(todayHigh, high[i]); appendItem(todayCondition, condition[i]); appendItem(todayIcon, icon[i]); } } setText("lowTemp", todayLow[1]); setText("highTemp", todayHigh[1]); setText("label2", todayCondition[1]); setProperty("image2", "image", todayIcon[1]); console.log(idNum); console.log(index); console.log(todayLow); }``` ```=``` Comment: Your code example doesn't work. 1. The html part only has a `=` 2. You probably forgot to load dependency scripts because the error in the console says: "ReferenceError: getColumn is not defined" Here is another answer: ```function updateScreen() { var index = id; console.log(id); for (var i = 0; i < 8; i++) { if (forecastNum[i] == 1) { appendItem(todayLow, low[i]); appendItem(todayHigh, high[i]); appendItem(todayCondition, condition[i]); appendItem(todayIcon, icon[i]); } } setText(&quot;lowTemp&quot;, todayLow[1]); setText(&quot;highTemp&quot;, todayHigh[1]); setText(&quot;label2&quot;, todayCondition[1]); setProperty(&quot;image2&quot;, &quot;image&quot;, todayIcon[1]); console.log(idNum); console.log(index); console.log(todayLow); } ``` Correct me if I'm wrong, but I believe this is where the problem is. Whenever you want to update the screen, it only updates it to whatever is index 1 inside ```todayLow``` ```todayHigh``` ```todayCondition``` and ```todayIcon``` arrays. Instead of putting &quot;1&quot; for the array of these, you should find a way to automatically change the value based on whatever dropdown the user selected. Also, not really a bad thing that you did, but instead of doing: ```onEvent(&quot;locationDropdown&quot;, &quot;change&quot;, function( ) { if (getText(&quot;locationDropdown&quot;) == &quot;Anchorage, Alaska&quot;) { id = 1; } else if ((getText(&quot;locationDropdown&quot;) == &quot;Fairbanks, Alaska&quot;)) { id = 6; } else if ((getText(&quot;locationDropdown&quot;) == &quot;Denver/Boulder, Colorado&quot;)) { id = 16; } else if ((getText(&quot;locationDropdown&quot;) == &quot;Chicago, Illinois&quot;)) { id = 31; } else if ((getText(&quot;locationDropdown&quot;) == &quot;Des Moines, Iowa&quot;)) { id = 56; } else if ((getText(&quot;locationDropdown&quot;) == &quot;Goodland, Kansas&quot;)) { id = 66; } else if ((getText(&quot;locationDropdown&quot;) == &quot;Louisville, Kentucky&quot;)) { id = 86; } else { id = 96; } }); ``` You could have also done: ```onEvent(&quot;locationDropdown&quot;, &quot;change&quot;, function( ) { switch (getText(&quot;locationDropdown&quot;)) { case &quot;Anchorage, Alaska&quot;: id = 1; break; case &quot;Fairbanks, Alaska&quot;: id = 6; break; case &quot;Denver/Boulder, Colorado&quot;: id = 16; break; case &quot;Chicago Illinois&quot;: id = 31; break; case &quot;Des Moines, Iowa&quot;: id = 56; break; case &quot;Goodland, Kansas&quot;: id = 66; break; case &quot;Louisville, Kentucky&quot;: id = 86; break; default: id = 96; break; } }); ``` The ```switch statement``` is very useful in code because it saves time because you no longer have to write ```getText(&quot;locationDropdown&quot;)``` for every else if statement you write. Anyways, I hope my answer helped at least a little. I wish you the best of luck! Comment for this answer: Instead of a switch the question owner could also use a hash map/lookup table: https://medium.com/front-end-weekly/switch-case-if-else-or-a-lookup-map-a-study-case-de1c801d944
Title: How do I edit the legend title and labels? Tags: r;ggplot2 Question: First post so hopefully I've included everything. I'm trying to do two things on the below charts: Change the legend title from z,z1,z2 to POS, ROD, INS Change the legend labels all to AOK and TUR I've been trying to find the answer all day and so far nothing has worked. My data is: ```Year Area Percentage <dbl&gt; <fct&gt; <dbl&gt; 1 2008 AOKPOS 0.571 2 2008 AOKPOS 0.6 3 2008 AOKPOS 0.5 4 2008 AOKPOS 0.846 5 2008 AOKPOS 0.2 6 2008 AOKPOS 0.625 ``` My code is: ```plot1 <- ggplot() + # blue plot scale_x_continuous(name="", limits = c(2008, 2019),breaks = 0:2100)+ #No X axis title scale_y_continuous(name = "",labels = scales181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16percent)+ theme(text = element_text(size=10))+ coord_cartesian(ylim = c(0,1))+ geom_smooth(data=Possum, aes(x=x, y=y, group=z, colour=z), size=1) plot1 plot2 <- ggplot() + # blue plot scale_x_continuous(name="", limits = c(2008, 2019), breaks = 0:2100)+ #No X axis title scale_y_continuous(name = "",labels = scales181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16percent)+ theme(text = element_text(size=10))+ coord_cartesian(ylim = c(0,1))+ geom_smooth(data=Rodent, aes(x=x1, y=y1, group=z1, colour=z1), size=1) plot2 plot3 <- ggplot() + # blue plot scale_x_continuous(name="", limits = c(2008, 2019), breaks = 0:2100)+ #No X axis title scale_y_continuous(name = "",labels = scales181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16percent)+ theme(text = element_text(size=10))+ coord_cartesian(ylim = c(0,1))+ geom_smooth(data=Insect, aes(x=x2, y=y2, group=z2, colour=z2), size=1) plot3 grid.arrange(plot1, plot2, plot3, nrow=3) ``` Here is another answer: I don't know how you want to change it but you can use labs() function to do that like so ```#Default plot print(p) #Modify legend titles p + labs(fill = "Dose (mg)") ``` after using the code the title is change like this Comment for this answer: Welcome to SO, the provided data doesn't seem to reflect the plot in the linked image. For the legend title try ```+ labs(fill="POS")``` to plot1 and so forth. For the legend labels you could change the Area factor levels. It will be good to have a minimal reprex (See [here][1]). You seem to have a 4th variable (possum, rodent and insect) not available in the data. [1]: https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610 Here is another answer: Ok, so shortly after posting I managed to figure it out: ``` plot1<-ggplot() + scale_x_continuous(name="", limits = c(2008, 2019),breaks = 0:2100)+ #No X axis title scale_y_continuous(name = "",labels = scales181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16percent)+ theme(text = element_text(size=10))+ coord_cartesian(ylim = c(0,1))+ geom_smooth(data=Possum, aes(x=x, y=y, group=z, colour=z), name = "Possum",size=1) plot1<- plot1 + scale_color_discrete(name="Pos", label=c("Aok","Tur")) plot1 plot2<-ggplot() + scale_x_continuous(name="", limits = c(2008, 2019), breaks = 0:2100)+ #No X axis title scale_y_continuous(name = "",labels = scales181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16percent)+ theme(text = element_text(size=10))+ coord_cartesian(ylim = c(0,1))+ geom_smooth(data=Rodent, aes(x=x1, y=y1, group=z1, colour=z1), size=1) plot2<- plot2 + scale_color_discrete(name="Rod", label=c("Aok","Tur")) plot2 plot3<-ggplot() + scale_x_continuous(name="", limits = c(2008, 2019), breaks = 0:2100)+ #No X axis title scale_y_continuous(name = "",labels = scales181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16percent)+ theme(text = element_text(size=10))+ coord_cartesian(ylim = c(0,1))+ geom_smooth(data=Insect, aes(x=x2, y=y2, group=z2, colour=z2), size=1) plot3<- plot3 + scale_color_discrete(name="Ins",label=c("Aok","Tur")) plot3 grid.arrange(plot1,plot2,plot3, nrow=3) ```
Title: Generate file descriptor set (.desc) with scalapb Tags: scalapb Question: I am using scalapb in a project that needs to have access to the FileDescriptorSet. Is there a way to have scalapb generate the .desc file in addition to all other class files? Or is there some programatic way of obtaining a FileDescriptorSet from what is already generated? Here is the accepted answer: Yes, to both questions. If you are using ```sbt-protoc```, you can have the following definition in your SBT file: ```PB.protocOptions in Compile := Seq( "--descriptor_set_out=" + (baseDirectory in Compile).value.getParentFile / "src" / "main" / "resources" /"out.desc" ) ``` One caveat is that you would have to create ```src/main/resources``` yourself, otherwise you would get an error. It would probably be better to generate into ```resourceManaged``` (that would also require creating a directory ahead of time, since ```protoc``` doesn't do that) You can also build a FileDescriptorSet at run time. For each proto file, ScalaPB generates a Scala object with ```scalaDescriptor``` (and also ```javaDescriptor``` if that's more convenient). The descriptors contains a list of their dependencies which are also ```FileDesciptor```s - you can traverse that tree structure and build a list of ```FileDescriptor```s which is essentially a ```FileDescriptorSet```. Comment for this answer: In the rare case someone else looks for a way to generate only the `FileDescriptorSet`, `sbt-protoc` happens to provide a generator for that purpose: `Compile / PB.targets += (PB.gens.descriptorSet -> (Compile / crossTarget).value / "my.fds")`
Title: how do i save / use user input in android kotlin Tags: android;kotlin;input Question: i'm trying to write my very first android app. the only programing i have done in the past was some html 4 many years ago (before cms was a thing) it is essentially a check list but i want to be able to have multiple lists seperated by a list name supplied by the user. i have an input text box called "island name" but i cant figure out how to capture that text from the user and save it for future use... ``` <?xml version="1.0" encoding="utf-8"?&gt; <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent"&gt; <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="189dp" android:text="temp call islander page" android:textSize="30sp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /&gt; <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginEnd="125dp" android:layout_marginBottom="271dp" android:onClick="loadHome" android:text="home" android:textSize="30sp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" /&gt; <EditText android:id="@+id/editText" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="41dp" android:ems="10" android:hint="island name" android:inputType="textPersonName" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/button" /&gt; <CheckBox android:id="@+id/checkBox" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginEnd="7dp" android:layout_marginBottom="8dp" android:text="north" app:layout_constraintBottom_toTopOf="@+id/checkBox2" app:layout_constraintEnd_toEndOf="@+id/checkBox2" /&gt; <CheckBox android:id="@+id/checkBox2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="2dp" android:layout_marginBottom="88dp" android:text="south" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintStart_toStartOf="@+id/editText" /&gt; println("your island name is $name") <TextView android:id="@+id/textView4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="5dp" android:layout_marginTop="19dp" android:text="you entered $name" app:layout_constraintStart_toEndOf="@+id/checkBox2" app:layout_constraintTop_toBottomOf="@+id/checkBox2" /&gt; </androidx.constraintlayout.widget.ConstraintLayout&gt; ``` Comment: You can't write Kotlin code in the middle of your XML. Program logic is not defined by layout files. This XML is merely a text document describing a particular layout of views. Your Kotlin or Java code is used to define an Activity and Fragments, which read the XML file at run-time to create ("inflate") a view hierarchy. You need to go through one of the introductory tutorials before we can really help you with any of your questions in a practical way. https://developer.android.com/training/basics/firstapp Here is another answer: For those who is experiencing the same issue you can use sharedPreferences. As an example: ```private lateinit var sp: SharedPreferences private lateinit var editor: SharedPreferences.Editor override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) nameEditText = findViewById(R.id.etName) ageEditText = findViewById(R.id.etAge) sp = getSharedPreferences(&quot;my_sf&quot;, MODE_PRIVATE) editor = sp.edit() } override fun onPause() { super.onPause() val name = nameEditText.text.toString() val age = ageEditText.text.toString().toInt() editor.apply { putString(&quot;my_name&quot;, name) putInt(&quot;my_age&quot;, age) commit() } } override fun onResume() { super.onResume() val name = sp.getString(&quot;my_name&quot;, null) val age = sp.getInt(&quot;my_age&quot;, 0) nameEditText.setText(name) if (age!=0) ageEditText.setText(age.toString()) } ``` Here is another answer: To put it simply, in Android dev (Android Studio) you have your view, which is your .xml file and your program logic is written in your .kt or .java file then you refer to your respective view from the .kt oe ,java file. e.g activity_main.xml ```<LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"&gt; <com.google.android.material.textfield.TextInputEditText android:id="@+id/textView" android:layout_height="wrap_content" android:layout_width="200dp"/&gt; <Button android:id="@+id/saveBtn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Save" /&gt; </LinearLayout&gt; ``` MainActivity.kt : ``` import kotlinx.android.synthetic.main.activity_main.* //this will reference all views in activity_main - //Android studio usually auto imports this when you simply type control name class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) saveBtn.setOnClickListener { saveDetails() } } fun saveDetails(){ var userText = textView.text.toString() textView4.setText(userText) //do something with text } } ``` Comment for this answer: thank you for your response. i must confess i've been playing with it for a couple days now and i keep getting an unresolved reference error for both "text" (in var userText = textView.text.toString) and "textView4" (in textView4.setText(userText) i'm sure i'm missing something very simple here...
Title: How to get limited page numbers visible in pagenation list to display a list of items? Tags: jsp;jstl Question: ```<c:if test="${paging.pageCount &gt; 1}"&gt; <c:if test="${not empty searchkey}"&gt; <c:set var="pagingpath1" value="&amp;key=${searchkey}&amp;value=${searchvalue}" /&gt; </c:if&gt; <div style=" background:#f5f5f5; border:1px solid #dedede; height:30px; width:985px; margin:20px auto"&gt; <div class="pagDiv_1"&gt;<a&gt;Results:<span&gt;<c:out value="${ paging.page }"&gt; - </c:out&gt; - <c:out value="${ paging.pageCount }"&gt;</c:out&gt; ( total: <c:out value="${ paging.count }"&gt;</c:out&gt; )</span&gt;</a&gt;</div&gt; <div class="page-nav"&gt; <a&gt;Pages:</a&gt; <c:choose&gt; <c:when test="${paging.orderStatus}"&gt; <c:set var="pagingpath" value="&amp;order=${paging.order}&amp;dir=${paging.direction}"&gt; </c:set&gt; </c:when&gt; <c:otherwise&gt;<c:set var="pagingpath" value=""&gt;</c:set&gt;</c:otherwise&gt; </c:choose&gt; <a class=lftarrow href="#"&gt;Previous &amp;#9668;</a&gt; <c:forEach var="pid" varStatus="status" begin="1" end="${paging.pageCount}" step="1"&gt; <c:choose&gt; <c:when test="${pid == paging.page}"&gt;<span class="cur-page"&gt;<b&gt;${ pid }</b&gt;</span&gt;<label&gt;|</label&gt;</c:when&gt; <c:otherwise&gt;<a class="page" href="consultant_list.htm?p=${pid}${pagingpath1}&amp;selectiontype=${selectiontype1}&amp;searchtext=${textbox1}"&gt;${ pid }</a&gt;<label&gt;|</label&gt;</c:otherwise&gt; </c:choose&gt; </c:forEach&gt; <a class=lftarrow href="#"&gt;&amp;#9658; Next</a&gt; </div&gt; </div&gt; </c:if&gt; ``` The image attached has the listing page in which I am working . The code snippet is to display the pagenation in the footer. How to make only say 4 page numbers visible at once and on click of "Next" the other pages must be visible? Comment: Just a tip: don't do that in JSP/JSTL/EL code. Prapare the work for the view in a controller, in Java. Regarding the code, it's just a matter of only generating the links for some pages around the current one, and potentially a link for the first and last one. integer arithmetics. Comment: Thanks ..me too thinking the same.any best logical idea for doing it ? Here is another answer: You can create a Tag for this which can display only relevant pages (few around the current page and start &amp; last page), which can be used at multiple places and will be cleaner approach as well. You can create a tag, which will accept these parameters: a) the url you want to hit on selection of each page. b) the number of links you want to show at a time, say 10. c) total page size. In this tag you can add this code to show only few page numbers (say 10) with first &amp; last page link. Now this thing can be used as a component which can be used in various places of your application. Comment for this answer: You can create a tag, which will accept these parameters: a) the url you want to hit on selection of each page. b) the number of links you want to show at a time, say 10. c) total page size. In this tag you can add this code to show only few page numbers (say 10) with first & last page link. Now this thing can be used as a component which can be used in various places of your application. Comment for this answer: I dint get you .. can u re-explain Here is another answer: DisplayTag is a wonderful little library that makes what you want to do easy.. http://www.displaytag.org/1.2/ Alternatively, if the size of your dataset's aren't very large in size (bytes) the following Jquery library is also cool: http://datatables.net/
Title: preventDefault not working after fadeout then load then fadein new href content into div Tags: javascript;jquery;html;preventdefault Question: I've searched and serached and nothing really seems to answer what I'm looking for. I'm pulling in html pages into a div. I finally got it to fadeout, load new href content, then fade in the new content. However, I can't get it to preventDefault on the link. Here's my code. Any help is greatly appreciated! ```$(document).ready(function() { var url = $(this).attr("href"); $('#container').css('display', 'none'); $('#container').fadeIn(1000); jQuery('a').click(function(e){ e.preventDefault(); $('a').removeClass('current'); $(this).addClass('current'); $("#container").fadeOut('1000',function(){ $('#container').load(url); }).fadeIn('1000'); }); }) ``` Comment: What is `var url = $(this).attr("href");` doing outside the event? Comment: Thanks for your quick response. That code still allows the fadeout, load, and fadein to work (nicely coded, though); however, the links are still firing for the current page. Comment: Try `$(document).ready(function () { $('#container').css('display', 'none').fadeIn(1000); jQuery(document).on('click', 'a', function (e) { e.preventDefault(); $('a.current').removeClass('current'); $(this).addClass('current'); var url = $(this).attr("href"); $("#container").fadeOut('1000', function () { $(this).load(url).fadeIn('1000'); }); }); })` Here is another answer: You need to call this ```fadeIn``` inside the load callback. ```$(document).ready(function() { var loading = false; $('#container').css('display', 'none'); $('#container').fadeIn(1000); $('a').click(function(e){ if(loading) return false; e.preventDefault(); loading = true; var url = $(this).attr("href"), cont = $("#container"); //cache selector $('a').removeClass('current'); $(this).addClass('current'); cont.fadeOut(1000, function(){ cont.load(url, function() { cont.fadeIn(1000, function() { loading = false; }); }); }); }); }); ``` Comment for this answer: That still does the same thing, but when I click the link it's still fading out and fading in the current content. Thanks for the response, though. Comment for this answer: One thing I've noticed is that if I remove the fadeout and fadein, the preventDefault does work. So, it must be something with that. Hmmm... Comment for this answer: Actually, the retun false killed the linking in general. Darn! Getting close, though.
Title: Runtime Error: Segmentation Fault (SIGSEGV) Tags: algorithm;segmentation-fault;stack;postfix-notation;infix-notation Question: I am trying to write a program to convert infix expression to postfix expression. But I am getting the error ``` Runtime Error: Segmentation Fault (SIGSEGV) ``` I know that ``` SIGSEGV is an error caused by an invalid memory reference ``` Algorithm used Scan the infix expression from left to right. If the scanned character is an operand, output it. Else, 1 If the precedence of the scanned operator is greater than the precedence of the operator in the stack(or the stack is empty or the stack contains a ‘(‘ ), push it. 2 Else, Pop all the operators from the stack which are greater than or equal to in precedence than that of the scanned operator. After doing that Push the scanned operator to the stack. (If you encounter parenthesis while popping then stop there and push the scanned operator in the stack.) If the scanned character is an ‘(‘, push it to the stack. If the scanned character is an ‘)’, pop the stack and and output it until a ‘(‘ is encountered, and discard both the parenthesis. Repeat steps 2-6 until infix expression is scanned. Print the output Pop and output from the stack until it is not empty. Code ```class Solution { int prec(char a) { if (a == '^') return 3; else if (a == '*' || a == '/') return 2; else if (a == '+' || a == '-') return 1; else return -1; } public: string infixToPostfix(string str) { stack<char&gt; stk; string ans; for (auto e : str) { if ((e &gt;= 'a' &amp;&amp; e <= 'z') || (e &gt;= 'A' &amp;&amp; e <= 'Z')) ans += e; else if (e == '(') stk.push(e); else if (stk.empty()) stk.push(e); else if (prec(stk.top()) < prec(e)) { if (e != ')') stk.push(e); else { while (!stk.empty() &amp;&amp; stk.top() != '(') { ans = ans + stk.top(); stk.pop(); } if (stk.empty()) continue; else stk.pop(); } } else if (prec(stk.top()) &gt;= prec(e)) { while (prec(stk.top()) &gt;= prec(e) &amp;&amp; !stk.empty()) { if (prec(stk.top()) &gt; prec(e)) { ans = ans + stk.top(); stk.pop(); } else { //same precedence so checking for associativity if (stk.top() == '^') //associativity from R-&gt;L stk.push(e); else //associativity from L-&gt;R { ans = ans + stk.top(); stk.pop(); } } } stk.push(e); } } if (stk.empty()) return ans; else { while (!stk.empty()) { ans = ans + stk.top(); stk.pop(); } return ans; } } }; ``` I have tried a lot to find out the fault in the code, but I was unable to figure it out. Please help me. Comment: @ScottHunter It just prints "Runtime Error: Segmentation Fault (SIGSEGV)". Comment: Thanks @abhishek_naik your suggesion worked. Comment: Can you try using `!stk.empty()` everywhere before you do `stk.top()`? I see it not being done in a few places. Also, the order is important. So instead of `prec(stk.top()) >= prec(e) && !stk.empty()`, do `!stk.empty() && prec(stk.top()) >= prec(e)` Comment: When you use a debugger, what is the *first* thing the program does incorrectly? Comment: What debugger are you using?
Title: POSTGRES - LIMIT 1 DESC for each ID in WHERE IN Tags: sql;postgresql;greatest-n-per-group Question: Problem: I have a table where there are several rows with same code but different date, I also have a query: ```SELECT * FROM movies WHERE CODE IN ('action', 'comedy') ``` Question: How can I return row with latest date FOR EACH code in the list and limit it to 1 since there can be duplicates: so it returns just ID 1 and 4. Something like ```SELECT * FROM movies WHERE CODE IN ('action', 'comedy') DESC LIMIT 1 ``` but for each code. Thank you. Here is the accepted answer: In Postgres, use ```DISTINCT ON```: ```SELECT DISTINCT ON (CODE) m.* FROM movies m WHERE m.CODE IN ('action', 'comedy') ORDER BY m.CODE, m.start_date DESC; ``` ```DISTINCT ON``` is a Postgres extension. It returns a result set with one row per unique combination of values of the expressions in parentheses (like ```GROUP BY``` keys in that respect). The particular row is determined by the ```ORDER BY``` clause. The unique keys come first and the rest of the keys define "which" row. Here is another answer: ```SELECT code, MAX(start_date) FROM movies GROUP BY code ``` Comment for this answer: This won't return the id field (or fields other than code and start_date). The OP asks for SELECT *, so this won't work :(
Title: DC motor acceleration Tags: newtonian-mechanics;acceleration;friction;torque Question: I'm doing a research project on the mathematics of robotics. For this research project I need to use calculus somewhere in the project. My plan was to calculate the acceleration of the robot and find the velocity and position by integrating. I am currently using the following equations to find acceleration Force = Torque / radius of wheel acceleration = Force / mass the problem is that the acceleration of a robot shouldn't be a constant as this equation finds, because at some point the acceleration should reach a max and gradually approach 0. So, how would I go about finding the real acceleration of the robot? I think where i'm going wrong is plugging in static numbers for Torque, but I can not figure out how I would find the change in torque over time. The specs for the motor I am using are here . Also, the mass of the robot is 135 pounds. Comment: The force and torque don't have to be constant and in real life they are not. Having said that, there is no calculus here, at all, since the wheel radius and the mass are merely constants, so the acceleration is simply proportional to the torque. You won't need calculus, unless you are trying to find the velocity and the position from the time dependent torque. Comment: The torque is whatever your motor produces, unless you want to look at the entire system as a dynamical problem, in which case you will have to solve a bunch of differential equations. That is "calculus", but in practice you would either deal with a linear system, which is a long solved problem (that may still be above your current level of math, though), or it becomes a numerical simulation (for which plenty of software exists). At this point it seems to me that you lack the necessary tools to attack this. Who gave you the assignment? Comment: The level of math that would allow you to solve the real problem would be first year undergrad physics or engineering math, something which you can't be expected to master (you can, if you really care, but it's not required in any high school system that I am aware of). In a real machine application one would not load the motors to either torque maximum, but the motor torque would be electronically controlled by a feedback system that matches the position of the machine to a programmed trajectory. That's a tough control problem that you don't want to tackle. Comment: What you can tackle is an ideal scenario where you interpolate two points with a quadratic ramp function. Differentiated twice this amounts to a control that delivers constant torque to accelerate the robot and then an opposite torque to decelerate. If you want to be a little closer to reality, still, ramp the torque from zero to a predetermined max. with a liner ramp, that gives you third order polynomial solutions. Calculate the fastest times that such a machine can achieve from A to B. That's within your current level of math, I would say. Comment: Sorry, I must have miscommunicated. That's kinda the whole point. I want to find velocity via the integral of acceleration and position via the integral of velocity. The issue is that I can't find a way to calculate change in torque. If I could calculate that, I wouldn't have a constant acceleration and via integral a linear velocity. Comment: so my confusion with torque is that there are two values that the manufacturer gives for torque, stall and load. This assignment is for an IB HL mathematics paper in high school. It's basically a self guided exploration into a field of applied mathematics. With everything i've told you, do you think it's even possible to do what I want to do? Also, if it helps, I have completed calculus 2. Here is another answer: You are right Jeff. Using a static number for torque, and no velocity dependent frictional term will give you an unreasonably increasing acceleration. As your intuition predicted, electric motors start out with high torque at rest and decrease to zero torque as speed increases to max speed (Good discussion here). According to your spec sheet, your motor has a max torque of 343.4 oz/in at zero speed, and 0 torque at 5310 RPM. Sort of by definition, max speed is the zero net torque point. An interesting question is why does the motor have a max speed? Of course there is friction acting on the motor, but the stronger effect is that as the magnetic rotor turns past the electro magnetic coils, it induces a counter flow of current. The faster the motor spins, the greater the counter flow. When the motor hits a speed at which the counter flow of current equals the current from the applied voltage, the torque falls to zero. You can calculate the torque as a function of robot speed, convert to force and divide by the robot mass to get acceleration. You can use a block diagram software like VisSim to integrate the accel to get velocity and integrate the velocity to get position. VisSim uses 1/s to mean an integrator block. This is some engineering short hand based on the the Laplacian 's' operator (derivative WRT time). The inverse of derivative is integrator. Here is the calculation in a VisSim diagram: If you go to the VisSim web site and sign in you can download VisSim for free and play with it yourself. Here is another answer: I recommend using an accelerometer to find the experimental acceleration of the robot. Probably the best quality would be to use a LabQuest and/or LoggerPro paired with the Vernier Motion Sensor, but you could also use SparkFun accelerometers alongside an arduino/RPi. Another option, which very well may be the best given constraints for your time and resources, is to use an app called "MyTech," which was developed by a team at North Carolina State University for classroom physics measurements, which uses MEMS differential capacitors to measure acceleration. It returns the accelerations in vector components, and allows the user to download a CSV file with the measurements. If you could open the CSV file in Microsoft Excel (or Google Sheets, etc.), then you could do regression analysis on your data, and find the equation for a line of best fit. Then you could integrate that equation to find velocity and position. That may not have answered your question directly, but I think it is a better route for experimental design, and if I understand the scope of your project, I think it would serve you better. Here is another answer: You should alter your formulae a tiny bit: Force = Torque / radius of wheel: $$F=\tau / R$$ Acceleration = Force / mass $$a=\sum F/m$$ I have added the sum symbol $\sum$. While accelerating, you will at some point have other forces interacting as well. For example friction and drag (air resistance). (Of course there might be engine-limitations as well.) The sum symbol shows that this force in Newton's 2nd law is not just the force $F$ on the road, rather it is all forces that are present. If friction $f$ and air drag $D$ start having significant effects, these must be included in this sum (with proper signs): $$a=(F-f-D)/m$$
Title: Merging getComputedStyle and evaluate in Greasemonkey Tags: javascript;css;greasemonkey;xpath Question: I need to get all the text nodes with a certain font-face in a page to an array. I tried.. ```textnodes = document.evaluate("//* [@style='font-family: foo;']//text()[" + "not(ancestor181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16script) and not(ancestor181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16style)]", document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null); ``` and ```textnodes = document.evaluate("//* [@face='foo']//text()[" + "not(ancestor181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16script) and not(ancestor181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16style)]", document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null); ``` But these does not work with pages that is styled by external CSS files. Seems getComputedStyle() is the way to go. I think what I need is something like.. ```var tags = document.getElementsByTagName('*'); for (var i in tags) { var style = getComputedStyle(tags[i], ''); if (style.fontFamily.match(/foo/i)) { textnodes.push(tags[i]); } } ``` But text nodes were not returned in this method. Is there anyway I can use a hybrid of xpath evaluate() and getComputedStyle() or any other way to achieve this? Comment: @Brock-Adams: This question seems a lot more about DOM and CSS and their particular implementation. An XPath expression is one that presents a specific XML document, defines what nodes are to be selected and asks for an XPath expression that selects exactly these nodes. There is no XML document provided in this question and it is impossible to verify whether the proposed expressions select (what???) nodes. Please, read the questions tagged xpath to see how they differ from this question. Comment: @Brock-Adams: As you can see, the answers have nothing to do with XPath. Maybe it isn't exactly "xpathengines", maybe it is "xpath-histing-languages-and-apis", but for now the closest to these is "xpathengines". As for "most XPath users are in a similar state", well, I'd value the opinion of other experts, such as @Alejandro and @LarsH and @Tomalak and @Abel. Comment: @Dimitre Novatchev: Why was this changed from [xpath], which seems appropriate, to [xpathengines], which seems incorrect? Comment: @Dimitre Novatchev: I've a working knowledge of XPath and have perused many [xpath] questions since I [email protected]. Still not clear on the difference. Judging by all the retagging that seems to be occurring, I'd wager most XPath users are in a similar state. Perhaps if you created the [xpathengines wiki](http://stackoverflow.com/tags/xpathengines/info), you could explain the difference between the new tags more clearly. Here is the accepted answer: Use jQuery. jQuery will be dead useful for the other things your GM script will do, plus, it's much more robust and cross-browser capable. (1) Add this line to the Greasemonkey metadata section, just after the ```// @include``` directive(s): ```// @require http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js ``` (Note you may have to uninstall and then reinstall the script to get jQuery copied over.) (2) Then you can use this code to get the nodes: ```var jPrelimNodes = $("*:not(html, head, title, meta, script, link, style, body)"); var aMyTextNodes = jPrelimNodes.map ( function () { var jThis = $(this); if (jThis.children().length <= 1) //-- Ignore containers. { if (/^\bTimes New Roman\b/i.test (jThis.css ("font-family") ) ) return jThis; // Or return "this" or "jThis.text()", as desired. } return null; } ).get (); ``` This checks the computed style, and in this case returns nodes that start with Times New Roman. You can see a version of this code, in action, at jsFiddle. Here is another answer: One easy way to do is to find all text nodes: ```textnodes = document.evaluate("//text()", document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null); ``` Looping through each TextNode found, you can then look up its parent's computedStyle. If it's that font, you can then ```push``` the TextNode to ```textnodes```.
Title: Get total registered users in Ion-Auth Library Tags: codeigniter;ion-auth Question: Is there a method in Ion Auth library that could get total number of registered users. I know one way could be ```$users = $this-&gt;ion_auth-&gt;users()-&gt;result(); sizeof($users); ``` But this method looks very resourceful process to get just a number. Any suggestion other than writing our own method for it? Here is another answer: You can use: ```$usersCount = $this-&gt;db-&gt;count_all_results('users');// assuming table name ``` Docs. Or ```$usersCount = $this-&gt;db-&gt;count_all('my_table'); ``` Docs. Here is another answer: There is no native method in ion auth to do this. However, it is very easy to do. Tpojka has the correct answer. I would just like to add that if by registered you mean 'active' then you can do this: ```$this-&gt;db-&gt;where('active', '1'); $total_users = $this-&gt;db-&gt;count_all_results('your_users_table_name'); ``` Further, as ```users()``` is an db object you can easily do this as well: ```$total_users = $this-&gt;ion_auth-&gt;users()-&gt;num_rows(); ``` and also something like this (haven't tested) but IonAuth has a where method built in: ```$total_users = $this-&gt;ion_auth-&gt;where('active', '1')-&gt;users()-&gt;num_rows(); ```
Title: How can I get the value of ng-repeat when clicking on it Tags: angularjs;angularjs-ng-repeat Question: Can anybody help me in getting the ng-repeat value while we click on it. ```<ul ng-repeat="section in sections"&gt; <li&gt; <a href='#'&gt;{{section.name}}</a&gt; </li&gt; <ul&gt; ``` Comment: A directive would give easy, clean access. Here is the accepted answer: Take a look at this example I've made: http://jsbin.com/UWodob/1/ using ng-click you can get the value of the item being clicked.
Title: How do I put in the values (of different data types) from two HashMaps with the same keys into a new third HashMap? Tags: java Question: I need to make a third HashMap based off the values from the PeopleAndNumbers and PeopleAndGroups hashmaps. But the third HashMap would only have the 3 groups as keys and the total amounts from the people in that group as values. (Also worth noting that the keys in the first both maps are the same.) Here are the contents of the first two maps: PeopleAndNumbers: ```{p1=1, p2=3, p3=2, p4=3, p5=1, p6=2} ``` PeopleAndGroups: ```{p1=GroupA, p2=GroupB, p3=GroupC, p4=GroupB, p5=GroupC, p6=GroupA}``` I need to make a third HashMap that'd print out like this: CombineMap: ```{GroupA=3, GroupB=6, GroupC=3}``` Here is what the code looks like so far: ```import java.util.HashMap; public class HashmapTest { public static void main(String[] args) { HashMap<String, Integer&gt; PeopleAndNumbers = new HashMap<String, Integer&gt;(); HashMap<String, String&gt; PeopleAndGroups = new HashMap<String, String&gt;(); PeopleAndNumbers.put(&quot;p1&quot;, 1); PeopleAndNumbers.put(&quot;p2&quot;, 3); PeopleAndNumbers.put(&quot;p3&quot;, 2); PeopleAndNumbers.put(&quot;p4&quot;, 3); PeopleAndNumbers.put(&quot;p5&quot;, 1); PeopleAndNumbers.put(&quot;p6&quot;, 2); PeopleAndGroups.put(&quot;p1&quot;,&quot;GroupA&quot;); PeopleAndGroups.put(&quot;p2&quot;,&quot;GroupB&quot;); PeopleAndGroups.put(&quot;p3&quot;,&quot;GroupC&quot;); PeopleAndGroups.put(&quot;p4&quot;,&quot;GroupB&quot;); PeopleAndGroups.put(&quot;p5&quot;,&quot;GroupC&quot;); PeopleAndGroups.put(&quot;p6&quot;,&quot;GroupA&quot;); System.out.println(PeopleAndNumbers); System.out.println(PeopleAndGroups); HashMap<String, Integer&gt; CombineMap = new HashMap<String, Integer&gt;(); //Insert method to do this here, How would I go about this? System.out.println(&quot;Expected Output for CombineMap should be&quot;); System.out.println(&quot;{GroupA=3, GroupB=6, GroupC=3}&quot;); System.out.println(CombineMap); } } ``` Comment: @ shmosel, it was an error, I meant for it to be GroupC=3 (I edited the post to fit this now) @ Alexey Ah alright, I'll try to see how that goes @ Louis Ah alright, noted Comment: Welcome to Stack Overflow. Please take the [tour] to learn how Stack Overflow works and read [ask] on how to improve the quality of your question. Please show your attempts you have tried and the problems/error messages you get from your attempts. Comment: Note that the Java convention is for variables like `PeopleAndNumbers` to start with a lowercase letter, e.g. `peopleAndNumbers`. Comment: Oh well, you need to iterate one of the maps, find the corresponding value in the other map, construct a new String value and insert it into the third map. A separate question is what to do when the key sets don't match in the two input maps. Comment: How do you get `GroupC=4`? Here is another answer: To achieve that you need to iterate over the entries of the PeopleAndGroups map and do the following for each entry: check if the combinedMap has a key equal to the value of the current entry If the key doesn't exist put the key with value 0: ```combinedMap.put(entry.getValue(), 0)``` Get the value of the entry's key from the PeopleAndNumbers and let's call it N: ```int N = PeopleAndNumbers.get(entry.getKey())``` add N to the old value of your result map: ```combinedMap.put(entry.getValue(), combinedMap.get(entry.getValue()) + N)``` Here is another answer: If I understand you correctly, you want to sum Numbers by Group, using the common keys to join them. If so, you can do it pretty easily with streams: ```Map<String, Integer&gt; combined = PeopleAndGroups.entrySet() .stream() .collect(Collectors.groupingBy(e -&gt; e.getValue(), Collectors.summingInt(e -&gt; PeopleAndNumbers.get(e.getKey())))); ``` Or you can iterate and merge entries into your destination map: ```Map<String, Integer&gt; combined = new HashMap<&gt;(); PeopleAndGroups.forEach((k, v) -&gt; combined.merge(v, PeopleAndNumbers.get(k), Integer181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16sum)); ```
Title: How to create a progress bar using flask? Tags: python;flask;progress-bar Question: Just want to insert a progress bar in my html page. It should load from a for in my app.py. That's what I did so far... app.py ```from flask import Flask, render_template app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') @app.route('/progress') def ajax_index(): for i in range(500): print("%d" % i) # I want to load this in a progress bar if __name__ == "__main__": app.run(debug=True) ``` I'm using a bootstrap progress-bar from w3schools in my code index.html ```<html&gt; <head&gt; <meta name="viewport" content="width=device-width, initial-scale=1"&gt; <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"&gt; <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"&gt;</script&gt; <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"&gt;</script&gt; <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;</script&gt; <script&gt; $(function () { $("#content").load("/progress"); }); </script&gt; </head&gt; <body&gt; <div class="container"&gt; <h2&gt;Progress Bar With Label</h2&gt; <div class="progress"&gt; <div class="progress-bar" role="progressbar" aria-valuenow="70" aria-valuemin="0" aria-valuemax="100" style="width:0%"&gt;</div&gt; </div&gt; </div&gt; </body&gt; </html&gt; ``` Any help, please? Comment: You need to actually do something that takes time in a separate process or background thread and have it store the progress of the task somewhere so that `/progress` can fetch it. What are you showing the progress of? Here is the accepted answer: this is pretty simple: poll your api and update the progress bar width and valuenow until finished: ```var interval = setInterval(update_progress, 1000); function update_progress() { $.get('/progress').done(function(n){ n = n / 5; // percent value if (n == 100) { clearInterval(interval); callback(); // user defined } $('.progress-bar').animate({'width': n +'%'}).attr('aria-valuenow', n); }).fail(function() { clearInterval(interval); displayerror(); // user defined }); } ``` Comment for this answer: Could you maybe provide a working example? I am facing the same problem but I am not able to implement this solution since I am fairly new to jquery and flask
Title: Redirect IO inside shell script Tags: bash;shell Question: I'm trying to recursively expand all ```.css``` files in a directory. I'm using beautifier (a node.js tool). It's supposed to to get a filename, expand its content, and write the result to stdout. So the following line do the job pretty well: ```./node_modules/.bin/beautifier ./css/foo.css &gt; ./css/bar.css ``` But when I put all the things inside a script, it just prints all the output to the ```stdout``` and leaves all files empty after exit: ```echo "Expanding CSS files..." for css in `find . -type f -name \*.css -print` do echo "Expanding $css" temp="$css.tmp" cp $css $temp ./node_modules/.bin/beautifier $temp&gt;$css rm $temp done ``` what am I doing wrong here? Comment: Try adding `set -ex` at the top of the script. It won't solve the problem, but it might help you find it. Comment: Ok. Sorry, I wrote too fast. :) Comment: Or just `#!/bin/bash -x` rather than whatever shebang your're currently using. Also note, you shouldn't do `for something in $(command)` in bash, it will incorrectly split files with spaces for example, see [this](http://mywiki.wooledge.org/ParsingLs). I would also add an `echo` in front of `./node_modules/.bin/beautifier` and put the '>' in single quotes to test specifically what it's trying to do. Comment: @rpax No. I'm using a minifier script (which joins all lines together, removes indents and extra spaces). The beautufier does the reverse. Breaks lines, adds indents and formats the source code. Comment: @Biffen seems shell removes the `>` from what to command. It runs something like: `./node_modules/.bin/beautifier ./css/bootstrap-theme.min.css.tmp ./css/bootstrap-theme.min.css` Here is the accepted answer: Putting the variables inside ```""``` solves the problem ```echo "Expanding CSS files..." for css in `find . -type f -name \*.css -print` do echo "Expanding $css" temp="$css.tmp" cp $css $temp ./node_modules/.bin/beautifier "$temp" &gt; "$css" rm $temp done ``` EDIT: The real problem was there were no spaces between ```&gt;``` . But as @Biffen pointed, this is a good practice. If the line were like this, ```"$temp"&gt;"$css" ``` An error raises: ```unexpected EOF while looking for matching `"' syntax error: unexpected end of file ``` So it's easier to debug. Although my answer works, @Briffen is discovered the real error, the credit should go to him. Comment for this answer: Which is good practice, too, since file names may contain spaces. You may want to add it to the `cp` and `rm` commands as well. Comment for this answer: It (almost) never hurts. BTW, are you sure it was the quoting, and not the spaces around `>`? Comment for this answer: I did it initially, but I I wanted to solve only the problematic line Comment for this answer: @Biffen You are right. Are the spaces around `>`. But now, if the spaces are removed, `unexpected EOF while looking for matching \`"'` Comment for this answer: @Briffen see my edited answer. The only thing I can do is +1 to your comment, sorry. Comment for this answer: Can you explain why this was the problem? You would never get files with spaces here anyway since they would get incorrectly split by `for css in $(find . -type f -name \*.css -print)` Comment for this answer: Are you sure you're running it as a `bash` script? There shouldn't be any difference between `"$a" > "$b"` and `"$a">"b"` in bash. @Biffen was pointing out that variables should be quoted in bash, which is completely true, but would not have any effect here either since the script is broken to begin with as files with spaces would get split into separate tokens by the for loop. Here is another answer: This isn't really an answer, but again your script will incorrectly split files with spaces. You should do something like below instead ```#!/bin/bash echo "Expanding CSS files..." while IFS= read -r -d '' css do echo "Expanding $css" temp="$css.tmp" echo cp "$css" "$temp" echo ./node_modules/.bin/beautifier "$temp" '&gt;' "$css" echo rm "$temp" done < <(find . -type f -name \*.css -print0) ``` I put ```echo```'s everywhere and quotes around ```&gt;``` so it doesn't actually do anything other than show you what it would do. Could also do ```#!/bin/bash -x``` which would show what it's doing while executing commands. Comment for this answer: Yes, do this rather than `for css in $(find [...])`.
Title: lambda calculus - if more parameters needed Tags: lambda;functional-programming;sicp Question: Lambda Calculus Question: ```TRUE = lambda x y . x FALSE = lambda x y . y 1 = lambda s z . s z 2 = lambda s z . s (s z) ... BoolAnd = lambda x y . x y FALSE BoolOr = lambda x y. x TRUE y BoolNot = lambda x . x FALSE TRUE If I want to know the result of BoolNot 1: BoolNot 1 (lambda x . x FALSE TRUE)(lambda s z . s (s z)) (lambda s z . s z) FALSE TRUE (lambda x y . y) (lambda x y . x) ``` Here needs x and y 2 parameters, but only have 1 here, How can I continue this calculus? Here is the accepted answer: ```λ x y. E``` is "shorthand" for ```λx. (λy. E)```. Thus, ```(λ x y. y) (λ x y. x) ==&gt; (λx. (λy. y)) (λ x y. x) ==&gt; λy. y ``` That is, the identity function. Comment for this answer: Thanks, but could you tell me what does λy. y mean? Comment for this answer: @Andy I'm not sure what you're asking, but `λ` is the lowercase greek character "lambda", if that's what you're wondering. Here is another answer: Think that you apply one argument at the time and at each step you have a function taking one less. It doesn't make sense to do ```(not 1)``` but the result is the identity function since ```true``` becomes the variable not used and thus it will take another argument ```y``` and evaluate to ```y```
Title: I have browser errors when trying to get Phaser 2 to work on Quasar Tags: javascript;vue.js;phaser-framework;webpack-4;quasar-framework Question: I am using Phaser 2 and I am trying to get it working with quasar framework, but I just keep stumbling into errors. I suspect it may be a webpack configuration issue, coupled with package incompatibility issues. The relevant section of my ```quasar.conf.js``` file is as follows ```... const webpack = require('webpack'); const path = require('path'); const phaserModule = path.join(__dirname, '/node_modules/phaser/'); const p2 = path.join(phaserModule, 'build/custom/p2.js'); const phaser = path.join(phaserModule, 'build/custom/phaser-split.js'); const pixi = path.join(phaserModule, 'build/custom/pixi.js'); module.exports = function (/* ctx */) { return { .... extendWebpack(cfg) { cfg.resolve.extensions = ['.js', '.vue', '.json']; cfg.resolve.alias.p2 = p2; cfg.resolve.alias.pixi = pixi; cfg.resolve.alias.phaser = phaser; cfg.module.rules.push({ enforce: 'pre', test: /\.(js|vue)$/, loader: 'eslint-loader', exclude: /(node_modules|quasar)/, }); cfg.module.rules.push({ test: /\.(frag|vert)$/, // loader: 'gl-fragment-loader' loader: 'raw-loader', }); cfg.module.rules.push({ test: /pixi\.js/, loader: 'expose-loader', options: { exposes: { globalName: 'PIXI', moduleLocalName: 'PIXI', override: false, }, }, }); cfg.module.rules.push({ test: /phaser-split\.js$/, loader: 'expose-loader', options: { exposes: { globalName: 'Phaser', moduleLocalName: 'Phaser', override: false, }, }, }); cfg.module.rules.push({ test: /p2\.js/, loader: 'expose-loader', options: { exposes: { globalName: 'p2', moduleLocalName: 'p2', override: false, }, }, }); cfg.plugins.push(new webpack.DefinePlugin({ // Required by Phaser: Enable the WebGL and Canvas renderers. WEBGL_RENDERER: true, CANVAS_RENDERER: true, })); }, }, }; }; ``` My ```package.json``` file is as follows (Please ignore the use of Phaser and Phaser-ce. I know one can be used in place of the other, but I have been trying different configurations) ```{ ... &quot;dependencies&quot;: { &quot;@quasar/extras&quot;: &quot;^1.0.0&quot;, &quot;amazon-cognito-identity-js&quot;: &quot;^4.5.4&quot;, &quot;axios&quot;: &quot;^0.18.1&quot;, &quot;core-js&quot;: &quot;^3.6.5&quot;, &quot;cross-fetch&quot;: &quot;^3.0.6&quot;, &quot;phaser&quot;: &quot;^2.4.6&quot;, &quot;phaser-ce&quot;: &quot;^2.18.0&quot;, &quot;quasar&quot;: &quot;^1.0.0&quot;, &quot;vue-paystack&quot;: &quot;^2.0.4&quot;, &quot;vue-social-sharing&quot;: &quot;^3.0.5&quot;, &quot;vue-worker&quot;: &quot;^1.2.1&quot; }, &quot;devDependencies&quot;: { &quot;@quasar/app&quot;: &quot;^2.0.0&quot;, &quot;@quasar/quasar-app-extension-dotenv&quot;: &quot;^1.0.5&quot;, &quot;babel-eslint&quot;: &quot;^10.0.1&quot;, &quot;eslint&quot;: &quot;^6.8.0&quot;, &quot;eslint-config-airbnb-base&quot;: &quot;^14.0.0&quot;, &quot;eslint-loader&quot;: &quot;^3.0.3&quot;, &quot;eslint-plugin-import&quot;: &quot;^2.20.1&quot;, &quot;eslint-plugin-vue&quot;: &quot;^6.1.2&quot;, &quot;expose-loader&quot;: &quot;^1.0.0&quot;, &quot;raw-loader&quot;: &quot;^4.0.2&quot;, &quot;script-loader&quot;: &quot;^0.7.2&quot; }, ... } ``` My gameplay page is as follows ```<template&gt; <div&gt; <div :id="containerId"&gt;</div&gt; </div&gt; </template&gt; <script&gt; /* eslint-disable no-unused-vars */ import 'pixi'; import 'p2'; import Phaser from 'phaser'; /* eslint-enable no-unused-vars */ export default { name: 'game', data() { return { game: null, containerId: 'gameScreen', }; }, props: { width: { type: Number, default: document.body.clientWidth, }, height: { type: Number, default: document.body.clientHeight, }, }, mounted() { const self = this; if (this.game === null) { debugger; this.game = new Phaser.Game(this.width, this.height, Phaser.CANVAS, this.containerId, { preload: function preload() { self.preload(this); }, create: function create() { self.create(this); }, update: function update() { self.update(this); }, }); } }, methods: { preload(game) { ... }, create(game) { ... }, upload(game) { ... } }, }; </script&gt;``` The most recent error (there have been many) is shown below Here is the accepted answer: I figured it out for anyone who has the same challenge as me. I only really needed the ```phaser-ce``` and ```expose-loader``` packages. I removed the ```phaser```, ```raw-loader``` and ```script-loader``` packages. My updated ```Package.json``` file looks like this ```"dependencies": { "@quasar/extras": "^1.0.0", "amazon-cognito-identity-js": "^4.5.4", "axios": "^0.18.1", "core-js": "^3.6.5", "cross-fetch": "^3.0.6", "phaser-ce": "^2.18.0", "quasar": "^1.0.0", "vue-paystack": "^2.0.4", "vue-social-sharing": "^3.0.5", "vue-worker": "^1.2.1" }, "devDependencies": { "@quasar/app": "^2.0.0", "@quasar/quasar-app-extension-dotenv": "^1.0.5", "babel-eslint": "^10.0.1", "eslint": "^6.8.0", "eslint-config-airbnb-base": "^14.0.0", "eslint-loader": "^3.0.3", "eslint-plugin-import": "^2.20.1", "eslint-plugin-vue": "^6.1.2", "expose-loader": "^1.0.0" },``` Some changes were made in the ```quasar.conf.js``` file, though. I changed the globalName property of the ```options.exposes``` object of the expose-loader. The ```moduleLocalName``` property is optional, and so, I removed it. The updated file looks like this: ```/* * This file runs in a Node context (it's NOT transpiled by Babel), so use only * the ES6 features that are supported by your Node version. https://node.green/ */ // Configuration for your app // https://quasar.dev/quasar-cli/quasar-conf-js /* eslint-env node */ /* eslint func-names: 0 */ /* eslint global-require: 0 */ const webpack = require('webpack'); const path = require('path'); const phaserModule = path.join(__dirname, '/node_modules/phaser-ce/'); const p2 = path.join(phaserModule, 'build/custom/p2.js'); const phaser = path.join(phaserModule, 'build/custom/phaser-split.js'); const pixi = path.join(phaserModule, 'build/custom/pixi.js'); module.exports = function (/* ctx */) { return { ... extendWebpack(cfg) { cfg.resolve.extensions = ['.js', '.vue', '.json']; cfg.resolve.alias.p2 = p2; cfg.resolve.alias.pixi = pixi; cfg.resolve.alias.phaser = phaser; cfg.module.rules.push({ enforce: 'pre', test: /\.(js|vue)$/, loader: 'eslint-loader', exclude: /(node_modules|quasar)/, }); cfg.module.rules.push({ test: /pixi\.js/, loader: 'expose-loader', options: { exposes: { globalName: 'window.PIXI', // changed override: false, }, }, }); cfg.module.rules.push({ test: /phaser-split\.js$/, loader: 'expose-loader', options: { exposes: { globalName: 'window.Phaser', // changed override: false, }, }, }); cfg.module.rules.push({ test: /p2\.js/, loader: 'expose-loader', options: { exposes: { globalName: 'window.p2', // changed override: false, }, }, }); cfg.plugins.push(new webpack.DefinePlugin({ // Required by Phaser: Enable the WebGL and Canvas renderers. WEBGL_RENDERER: true, CANVAS_RENDERER: true, })); }, ... }, }; };``` The biggest changes were made in the ```gameplay.vue``` file. The updated file is as follows ```<template&gt; <div&gt; <div id="gameScreen"&gt;</div&gt; </div&gt; </template&gt; <script&gt; /* eslint-disable no-unused-vars */ import 'pixi'; import 'p2'; import Phaser from 'phaser'; /* eslint-enable no-unused-vars */ export default { name: 'game', data() { return { game: null, containerId: 'gameScreen', game: null, width: null, height: null, }; }, mounted() { // putting this here ensured the accurate width and height were calculated this.width = document.body.clientWidth; this.height = document.body.clientHeight; const self = this; if (this.game === null) { // this.width and this.height were returning undefined this.game = new Phaser.Game(self.width, self.height, Phaser.CANVAS, "gameScreen", { preload: function preload() { self.preload(this); }, create: function create() { self.create(this); }, update: function update() { self.update(this); }, }); } }, methods: { // notice the game object, as opposed to the game parameter. This caused the program to silently break. The `this` parameter passed in the functions belong to the Phaser.Game instance and thus `this.game` also had the same properties in some cases as `this`, causing the silent bug. preload({ game }) { ... }, create({ game }) { ... }, upload({ game }) { ... } }, }; </script&gt;``` It works perfectly now.
Title: Measure where someone is standing? Tags: pi-2;sensor;bluetooth Question: I have a camera with an API to turn and pan it. (Hangs from a ceiling so it can turn and pan every side) I want to use the Raspberry Pi to control the panning and tilting based on where a device/sensor is (Too point the camera to it). So when I have a unique device in my pocket the camera has to point at where the device is even when it's moving. What is worth to note I don't want to use the face recognition or something from the camera it self. Just a device/sensor to point out a "target" where to focus on. I can't figure out how to do that... I was thinking as putting the raspberry at the same position as the camera (underneath it for example) and take that as the 0 point. With Bluetooth proximity I can check how far someone is and try to measure the distance and change the pan/tilt on that but it doesn't sound like that would work. Basically I wanted to know if someone knows what is the best way to do this ? Comment: There are commercial solutions. They are used by lecturers when videoing their classes so that the camera stays on them as they move around. I don't think they are alarmingly expensive. Unfortunately I can't think of the right search terms to find an example. You may have better luck. Comment: @joan I was thinking about indoor solutions like estimote or ibeacons they can pinpoint where you are in a room. But they will give a location based on the devices in the room... You need to translate those coordinates to pan and tilt movements.. Does this sound possible ? Comment: Yes, the solution I mentioned is for indoor use. I think the lecturer has an active tag which is triangulated and used to pan/tilt (or possibly just pan) the camera. If you can find the commercial product you might get enough information for your own solution. Comment: Perhaps you could use the Wiimote approach (IR camera receiver) and IR Sensor Bar. May even be able to strap a Wiimote to your Pi/camera, and communicate with it using the Pi. Then, keep the sensor bar on you (may or may not be able to see penetrate clothes). Anyway, may be a start as there are lots of Wii hacks out there, and you can probably get a used one cheap. Here is another answer: As @joan suggested, you can look up existing solutions for recording lectures in google. I used keywords "lecture camera". From the results you get you can see that other good terms to use are "lock track" or "motion tracking". There are different hardware/software solutions that you can experiment or be inspired from.
Title: Extended globbing inside script - what am I doing wrong? Tags: bash;scripting;wildcards;shopt Question: so I'm trying to select a range of files using an interactive script. The end goal is to use the ```read``` command but for demonstration here I assigned the ```glob``` variable manually ```#!/bin/bash shopt -s extglob # read -rp "Please enter a globbing string:"$'\n' glob # This will give me an error (See below) glob=*2020_04_03_{06..18}.jpg /bin/ls -la /mnt/drive1/images/*/*/${glob} # While this will return the desired files /bin/ls -la /mnt/drive1/images/*/*/*2020_04_03_{06..18}.jpg ``` The error is as follows: ```Error /bin/ls: cannot access "/mnt/drive1/images/*/*/*2020_04_03_{06..18}.jpg": No such file or directory ``` So what am I missing here in either assigning the ```glob``` variable or appending the ```glob``` variable to my path? Solution: I found a solution but I'm not quite sure why but ```bash <<EOF /bin/ls -la /mnt/drive1/images/*/*/${glob} EOF ``` will give me the desired output. Comment: Think about this for a bit. What value are you hoping that your `$glob` variable should contain? And what happens if that value is appended to a path? When should the brace expansion be done (when assigning to `glob` or in the call to `ls`)? Brace expansions are, by the way, done before variable expansions, so you can't expect a brace expansion inside a variable's value to do anything. Comment: Your script does not contain any extended globbing pattern, so `shopt -s extglob` is not needed. Comment: You could do that with `eval`, but then you will be in worse trouble if a user inputs a string such as `; rm -rf *` (removes files) or `/*/*/*/*/../../../../*/*/*/*` (may act like a denial-of-service attack). I may look for a solution to this question during the upcoming week if nobody else gives a good answer. Comment: What's the _intention_ with your code? Are you going to use the generated output from `ls` for anything? Is the purpose of getting the user to input a pattern to make it easier for the user to generate the `ls` output? Comment: If you have a solution that works for you, you may want to add it as an answer rather than as part of the question. Self-answers are allowed. Unless you want to rephrase your question to be about what you ask in your edit. Comment: Use an array instead of a variable. Comment: @Kusalananda thank you for your comment, I've never thought about that. I think I want the brace expansion to happen with the call of ´ls´ so that the ´$glob´ variable only carries the string over to the path. Is there a way to do so, since you mentioned that brace expansion happens before variable expansion? Comment: @Kusalananda So the use case for me is to pass a globbing string into the glob variable through the `ŕead` command. Then the `ls` output will be piped to `wc -l` to count the globbed files. After that I'll use the same `glob` variable to `convert` my .jpg files to a .gif. I'll be the only user of this script so security concerns as you mentioned above are not really an issue for me. Here is another answer: You can use an array assignment instead of just a variable. ```shopt -s nullglob ##: just in case there is non match for the glob. glob=(*2020_04_03_{06..18}.jpg) ##: This will expand the glob * and brace expansion. /bin/ls -la /mnt/drive1/images/*/*/"${glob[@]}" ``` That should work for your sample code. The problem will come when you decided to replace the numbers inside the brace expansion with a variable which was mentioned by @kusalananda, about the sequence of expansion. Add the ```failglob``` shell option if you want to see an error and exit with non-zero if there are none matching pattern. Comment for this answer: It would be too early to expand the `*` glob in the array assignment, so quote the bits of the string that shouldn't be expanded, e.g. `glob=( '*2020_04_03_'{06..18}.jpg`. You then get a list in `glob`. You may also want to take a look at what happens when you expand that list with the path prepended to it in the call to `ls` (it will _not_ prepend the path to each element). There, you additionally _don't_ want to quote the expansion, since you want it to act as a globbing pattern. Comment for this answer: I will not answer the question because I don't really see a safe way of using a globbing pattern provided by the user. Sure, it's relatively easy to do, but since code written here tends to be picked up by more people than the person asking the question, I wouldn't want the _convenient_ solution to find its way into production systems. Comment for this answer: @Kusalananda, ok, I will just wait for your answer so I can learn from this too. Comment for this answer: @Jetchisel thank you for your answer. Unfortunately your example will select and return every file within `/mnt/drive1/images/*/*/`. I also tried the suggestion from Kusalananda without success.
Title: pseudocode structuring advice and techniques Tags: pseudocode Question: I am having some issues with one of my courses, the teacher gives us overly simplified explanations for pseudocode and how to use it and then asks us to make our own pseudocode for his desired parameters which I find a bit too hard for me as of this moment. I am not asking for a full answer or anything, I just want some help in the "key words" and maybe some tips on how to get started and how the pseudocode should flow. I have an algorithm already and I feel like it should help me with the structure. But anyways, here is what I am asked to find (please remember I am not looking to cheat an awnser, I just want help): "write a pseudocode that inputs 10 positive numbers and gives these results:" 1. the sum of odd numbers 2. the average 3. the min 4. the max 5. total number of inputs that are even and divisible by 5 Comment: i guess it is more like "fizzbuzz" Comment: First off: What language? For example, on Wikipedia: https://en.wikipedia.org/wiki/Pseudocode there are different flavors of pseudocode. I mean, you could just do a flowchart, or write out full sentences explaining what each process is. Does he post example pseudocode? Here is another answer: Just a little example for you ```as long as count < 10 if mark < 6 then print "failed" otherwise print "success" count++ ``` Normally you follow the structure of a well known language ignoring detail and keeping a high level of abstraction. Cheers! Comment for this answer: Thanks for the example! I will give it a go Comment for this answer: @gengas -- if this answer helped you solve your problem, please click the grey checkmark on the left to accept the answer and close this question out.
Title: When can ResourceCounter.Quota Property be null? Tags: azure-cognitive-search Question: I am using search service statistics, and I am wondering in which scenarios I can get null from indexes quota property? when serviceStatistics.Counters.IndexCounter.Quota returns null? https://docs.microsoft.com/en-us/dotnet/api/microsoft.azure.search.models.resourcecounter.quota?view=azure-dotnet#Microsoft_Azure_Search_Models_ResourceCounter_Quota Here is another answer: From Search Service REST API ```Get Resource Statistics``` page, the quota will be null if if the service has unlimitied document counts. See this link for more details as well: https://docs.microsoft.com/en-us/azure/search/search-limits-quotas-capacity#document-limits. Comment for this answer: As per the limits document (https://docs.microsoft.com/en-us/azure/search/search-limits-quotas-capacity#index-limits), there are always a finite number of indexes that you can create. Comment for this answer: what about indexes quota?
Title: computation on array-search in php Tags: php;arrays;search Question: I have a multi-D array like so: ``` array ( 'JD'=&gt;2457002.50, 67.618536), array ( 'JD'=&gt;2457003.50, 67.619705), array ( 'JD'=&gt;2457004.50, 67.620938).... ``` I have a value say: ```$MyJD = 2457003.9553; ``` I would like to find the value in the array, and if not, match the closest number to the array in question and return the the next index (which i'm assuming is [1]) I was thinking to do an array_search, but it's not going to find the exact number, I want the closest number to $MyValue? Comment: You could calculate the distance for each number in the array and your value, then perhaps return the index of the smallest (first occurrence) distance. Here is the accepted answer: This won't return the index but will return the proper array: ```array_multisort(array_map(function($v) use($MyJD) { return abs($v['JD'] - $MyJD); }, $array), $array); $result = reset($array); ``` Calculate the difference between each ```JD``` value and ```$MyJD``` Sort on the difference (sorting the original) and get the lowest (first) one Alternately, you could combine using the difference as the key and then sort on the keys: ```$array = array_combine(array_map(function($v) use($MyJD) { return abs($v['JD'] - $MyJD); }, $array), $array); ksort($array); $result = reset($array); ``` Maybe someone will post a good array_reduce answer.
Title: How to activate the legacyDecorators option in babel? Tags: reactjs;babeljs;decorator Question: I want to use a Decorater for my component. However i encounter the following error message: ```Parsing error: Using the export keyword between a decorator and a class is not allowed. Please use `export @dec class` instead. ``` I found the solution in the following post recommending to use the ```legacyDecorators``` option in the ```.eslintrc``` file. ```{ "parserOptions": { "ecmaFeatures": { "legacyDecorators": true } } } ``` However, i have no idea where i have to insert that code to activate the legacy option. Update I meanwhile ejected my create-react-app and im now able to configure babel and eslint (eslintConfig) directly in package.jason as you see below. ```{ "name": "Test", "version": "0.1.0", "private": true, "dependencies": { "@babel/core": "7.8.4", "@babel/runtime": "7.0.0-beta.55", "@fortawesome/fontawesome-free": "^5.13.0", "@material-ui/core": "^1.5.1", "@material-ui/icons": "^1.1.0", "@svgr/webpack": "4.3.3", "@testing-library/jest-dom": "^4.2.4", "@testing-library/react": "^9.4.0", "@testing-library/user-event": "^7.2.1", "@types/jest": "^24.9.1", "@types/node": "^12.12.28", "@types/react": "^16.9.21", "@types/react-dom": "^16.9.5", "@types/react-router-dom": "^5.1.3", "@typescript-eslint/eslint-plugin": "^2.10.0", "@typescript-eslint/parser": "^2.10.0", "axios": "^0.19.2", "babel-eslint": "10.0.3", "babel-jest": "^24.9.0", "babel-loader": "8.0.6", "babel-plugin-named-asset-import": "^0.3.6", "babel-preset-react-app": "^9.1.1", "bootstrap": "^4.4.1", "camelcase": "^5.3.1", "case-sensitive-paths-webpack-plugin": "2.3.0", "css-loader": "3.4.2", "d3-ease": "^1.0.6", "dotenv": "8.2.0", "dotenv-expand": "5.1.0", "eslint": "^6.6.0", "eslint-config-react-app": "^5.2.0", "eslint-loader": "3.0.3", "eslint-plugin-flowtype": "4.6.0", "eslint-plugin-import": "2.20.0", "eslint-plugin-jsx-a11y": "6.2.3", "eslint-plugin-react": "7.18.0", "eslint-plugin-react-hooks": "^1.6.1", "file-loader": "4.3.0", "fs-extra": "^8.1.0", "html-react-parser": "^0.10.3", "html-to-react": "^1.4.2", "html-webpack-plugin": "4.0.0-beta.11", "identity-obj-proxy": "3.0.0", "install": "^0.13.0", "jest": "24.9.0", "jest-environment-jsdom-fourteen": "1.0.1", "jest-resolve": "24.9.0", "jest-watch-typeahead": "0.4.2", "jquery": "^3.4.1", "material-kit-react": "^1.8.0", "mdbreact": "^4.25.5", "mini-css-extract-plugin": "0.9.0", "npm": "^6.14.2", "optimize-css-assets-webpack-plugin": "5.0.3", "pnp-webpack-plugin": "1.6.0", "postcss-flexbugs-fixes": "4.1.0", "postcss-loader": "3.0.0", "postcss-normalize": "8.0.1", "postcss-preset-env": "6.7.0", "postcss-safe-parser": "4.0.1", "prop-types": "^15.7.2", "pure-react-carousel": "^1.26.1", "react": "^16.12.0", "react-alert": "^6.0.1", "react-alert-template-basic": "^1.0.0", "react-app-polyfill": "^1.0.6", "react-audio-player": "^0.11.1", "react-bootstrap": "^1.0.0-beta.17", "react-bootstrap-carousel": "^4.0.3", "react-dev-utils": "^10.2.0", "react-dom": "^16.12.0", "react-geocode": "^0.2.1", "react-google-autocomplete": "^1.1.2", "react-google-maps": "^9.4.5", "react-h5-audio-player": "^2.4.2", "react-image-appear": "^1.2.23", "react-loading-image": "^0.5.0", "react-redux": "^7.2.0", "react-reveal": "^1.2.2", "react-router": "^5.1.2", "react-router-dom": "^5.1.2", "react-scroll": "^1.7.9", "react-select": "^3.1.0", "react-slick": "^0.23.1", "react-transition-group": "^4.3.0", "redux": "^4.0.5", "redux-devtools-extension": "^2.13.8", "redux-thunk": "^2.3.0", "resolve": "1.15.0", "resolve-url-loader": "3.1.1", "sass-loader": "8.0.2", "semver": "6.3.0", "slick-carousel": "^1.8.1", "style-loader": "0.23.1", "styled-components": "^5.0.1", "terser-webpack-plugin": "2.3.4", "ts-pnp": "1.1.5", "typescript": "^3.7.5", "url-loader": "2.3.0", "webpack": "4.41.5", "webpack-dev-server": "3.10.2", "webpack-manifest-plugin": "2.2.0", "workbox-webpack-plugin": "4.3.1" }, "scripts": { "start": "node scripts/start.js", "build": "node scripts/build.js", "test": "node scripts/test.js" }, "eslintConfig": { "extends": "react-app", "parser": "babel-eslint", "parserOptions": { "ecmaFeatures": { "legacyDecorators": true } } }, "browserslist": { "production": [ "&gt;0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] }, "jest": { "roots": [ "<rootDir&gt;/src" ], "collectCoverageFrom": [ "src/**/*.{js,jsx,ts,tsx}", "!src/**/*.d.ts" ], "setupFiles": [ "react-app-polyfill/jsdom" ], "setupFilesAfterEnv": [], "testMatch": [ "<rootDir&gt;/src/**/__tests__/**/*.{js,jsx,ts,tsx}", "<rootDir&gt;/src/**/*.{spec,test}.{js,jsx,ts,tsx}" ], "testEnvironment": "jest-environment-jsdom-fourteen", "transform": { "^.+\\.(js|jsx|ts|tsx)$": "<rootDir&gt;/node_modules/babel-jest", "^.+\\.css$": "<rootDir&gt;/config/jest/cssTransform.js", "^(?!.*\\.(js|jsx|ts|tsx|css|json)$)": "<rootDir&gt;/config/jest/fileTransform.js" }, "transformIgnorePatterns": [ "[/\\\\]node_modules[/\\\\].+\\.(js|jsx|ts|tsx)$", "^.+\\.module\\.(css|sass|scss)$" ], "modulePaths": [], "moduleNameMapper": { "^react-native$": "react-native-web", "^.+\\.module\\.(css|sass|scss)$": "identity-obj-proxy" }, "moduleFileExtensions": [ "web.js", "js", "web.ts", "ts", "web.tsx", "tsx", "json", "web.jsx", "jsx", "node" ], "watchPlugins": [ "jest-watch-typeahead/filename", "jest-watch-typeahead/testname" ] }, "babel": { "presets": [ "react-app" ], "plugins": [ [ "@babel/plugin-proposal-decorators", { "legacy": true } ] ] }, "devDependencies": { "@babel/plugin-proposal-decorators": "^7.10.1" } } ``` I added the proposed lines under babel. However the same issue still appears. Comment: please post your .babelrc (or equivalent) config Here is another answer: You posted a code to configure, a static code linter called "eslint". But i dont think your error is related. I think your error is related to transpiling your code. So in case you are using babel to transpile your code. This is what you need to add in your .babelrc file for it to work, and of course install the needed dependency @babel/plugin-proposal-decorators ``` "plugins": [ [ "@babel/plugin-proposal-decorators", { "legacy": true } ], ], ``` in any case, the code you posted need to go into .eslintrc file, but its important only if are using eslint. And even if eslint throws an this error you can disable it by just adding ```/* eslint-disable */ ``` on the top of your code or just disabling it as a whole. Comment for this answer: Thanks for the answer. One question, is it necassary to eject my Create React App in order to activate the the legacy option? Comment for this answer: I'm not using RCA. (not yet anyway) But i don't think its relevant. First: you can provide babel settings inside package.json (heres how https://babeljs.io/docs/en/configuration#packagejson) and second its possible that once you have .babelrc present in your project RCA will merge its content into its own config (but im not sure ATM)
Title: Put some text in niceditor Tags: javascript;php;html;nicedit Question: I got simple script that put some text in textarea: Javascript ```<script language="javascript" type="text/javascript"&gt; $(document).ready(function(){ $("#add").click(function(){ $('#comment').html('[quote] <?php echo link_to($comment-&gt;user-&gt;username, 'profile/'.$comment-&gt;user-&gt;username); ?&gt; written: <?php echo $comment-&gt;content; ?&gt; [/quote]'); }); }); </script&gt; ``` HTML ```<textarea id="comment" name="comment"&gt;</textarea&gt;<br /&gt; ``` But it's working just then I turn off ```niceditor```. My niceditor code: ``` <script type="text/javascript"&gt; //<![CDATA[ bkLib.onDomLoaded(function() { nicEditors.allTextAreas({buttonList : ['bold','italic','underline','strikeThrough','image','upload','link','unlink']} ) }); //]]&gt; </script&gt; ``` Here is another answer: if you are using only php and nicedit you should place the php code straight inside the tags for example ```<textarea id="comment" name="comment"&gt;<?php echo link_to($comment-&gt;user-&gt;username, 'profile/'.$comment-&gt;user-&gt;username); ?&gt; written: <?php echo $comment-&gt;content; ?&gt;</textarea&gt; ```
Title: Pragmatically adding give-aways/freebies to an online store Tags: python;django;e-commerce;logic Question: Our business currently has an online store and recently we've been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the extra free items to their order after they checkout. Of course, it'd be nice to automate this entire process. I've been mulling over a few ideas, mainly creating a Discount model (I'm using Django in this case, but this is more of a logic question) and having that model have a variety of flags and product lists so I could create an instance like so: ``` Discount( description="Get one free pair of bands when you buy two pairs of shoes.", valid_products=[BigProductA, BigProductB], received_products=[FreebieProductA, FreebieProductB], special_in_intervals=2, # Whenever the user buys 2, give one for free ) ``` This logic kind of works. I can then take a look at what is in their cart and test against the existing Discounts in the model and see if they apply for anything. The biggest problem with this is it can get very messy especially if you have multiple specials going on and I just don't see it working out too well. Unfortunately, that's really my best idea for this right now. So, I come to ask you guys: What do you think is the best approach for this? I'm not looking for code, just some ideas of logic and ways to do this. :) Thanks in advance! Here is the accepted answer: Welcome to hell. Stay a while. ;) Ahem. Discounts are a mess, so it's not surprising that you feel tainted by having to work with them. From a design point of view, the testing should be part of the ```Discount``` instance, i.e. there should be an ```appliesTo(cart)``` method and an ```apply(cart)``` method. The first tells you whether a discount applies, the second one actually applies the discount. I suggest that the ```apply()``` method doesn't change the "user part" of the cart but instead modifies extra fields, so you can easily reset the cart (drop all discounts) and run the process again. This way, you can cleanly implement the two types of discounts that appear most often: "Get X for free, when buying Y" and "get a rebate of X% if you buy for Y $$$". Since you don't change the original figures, you can easily apply multiple discounts and rebates. I also suggest to back this up with a whole lot of unit tests to make sure the whole thing behaves as you expect. Otherwise the next discount might be your last. :) Comment for this answer: I would store it in special/additional fields in the cart. You must be able to identify the additional items which the discounts added, etc. That way, the total calculator can ignore them while the renderer can still display them. Don't hesitate to add transient fields to the items in the cart if you need them; just don't modify the data in other fields. Comment for this answer: Thanks for the answer. So far, I'm keeping all the logic within the `Discount` model and I plan to keep it that way. My biggest issue is the process of giving the user their free item to select from a list and then knowing not to do it again. Where would you store that data? I have a few ideas but they all start off good and then go into a messy hell of logic and too much steps. Still thinking though ... Comment for this answer: Thanks, that seems to be the best route for this. Will of course have to write many unit tests to ensure it works correctly, oh god .. :) Here is another answer: I don't quiet get the question - but if you select DISTINCT (I'm writing "pseudo logic" in SQL) all free items that match the items in the car , and then if you wish to give only one or n of them - SELECT TOP(n) DISTINCT from tblFREE where freebeid in (select freebdid from tbl itemsfreebe where items in (Select Items from CART where **** Freebe givaway LOGIC***)) freebe giveaway logic is the generic placeholder that should always evaluate for true or false: like where (select count(*) from cart >2) so if the logic works - you'll get items in the list, and if not - you'll get nothing. you can move this logic to your code and run only the first part of the "query" in the DB... logic can be used with AND or OR with other logics.... once the user accept the offer - you add the list to the cart, and should rais a flag that the discount/freebee was applied - so it won't happen twice... I wonder what does it means that it easier to SQL it than to say it :-) I hope that targets your question...
Title: How to get a tensorflow variable under certain namescope? Tags: python;tensorflow Question: Suppose we want fetch a value of a tensorflow variable ,we can just run it under a session. Suppose ```a = tf.Variable(...)``` Then its value can be fetched using ```sess.run(a)``` But if there are two variables with same name but different name scope, how do I fetch the value of individual variables? ```with tf.name_scope("x"): a = tf.Variable(...) with tf.name_scope("y"): a = tf.Variable(...) ``` Then how do I get values of ```a``` under ```x``` and ```a``` under ```y``` respectively? If I do ```sess.run(a)```, I am getting value under name_scope ```y``` (recent one) Comment: You are deliberately shadowing the previous variable `a`. What's the point of this? Comment: Not familiar with tensorflow, but this looks like a Python issue not a tensorflow one: when you assign a, the original value is lost, regardless of the context in which it's assigned. You'll probably have to use a different variable under the other name scope. I'd suggest `x_a` and `y_a`. Here is the accepted answer: You can checkout names of vars and get them by scope/names: ```with tf.variable_scope("x"): a = tf.get_variable('a', initializer=1) with tf.variable_scope("y"): a = tf.get_variable('a', initializer=2) with tf.Session() as s: s.run(tf.global_variables_initializer()) [print(var.op.name) for var in tf.global_variables()] res = s.run(['x/a:0', 'y/a:0']) print(res) ``` returns: ```x/a y/a [1, 2] ```
Title: Opening the GUI Designer in MonoDevelop Tags: user-interface;interface;monodevelop;designer Question: I have just installed MonoDevelop 2.0 on Windows and created a New GTK Project. I can't seem to find any way to open the GUI Designer (there are no 'Source Code' and 'Design' tabs under the codument either). How do I open/use the GUI Designer in MonoDevelop? Here is another answer: I recently installed MonoDevelop 3.0.6 and ran into this problem as well. I created a new solution, selected VBNet and Gtk# 2.0 Project. I then opened the MyWindow.vb file and there was no tabs at the bottom for selecting Souce Code or Design. Also the Toolbox was empty. I then tried creating a solution using C# and GtK# and when I opened MainWindow.cs the Designer tab and Source tabs show up at the bottom of the window. Here are the instructions for it's use http://monodevelop.com/Stetic_GUI_Designer. Update: As per the Bugzilla Bug 10986, GTK# Designer only works with C# Projects. Here is another answer: First of all, you need to create a GTK+ Project which allows you to use the GUI designer. After doing this, user interface references will be automatically loaded and a skeleton MainWindow code file will be automatically generated by the IDE itself. If you click on this MainWindow code file from the solution pad, 'Source' and 'Designer' tabs will appear at the bottom. Finally, just click on Designer tab and now you can see your application main window and GTK+ widgets in the toolbox.
Title: Python: nonblocking read from stdout of threaded subprocess Tags: python;multithreading;subprocess;nonblocking Question: I have a script (worker.py) that prints unbuffered output in the form... ```1 2 3 . . . n ``` where n is some constant number of iterations a loop in this script will make. In another script (service_controller.py) I start a number of threads, each of which starts a subprocess using subprocess.Popen(stdout=subprocess.PIPE, ...); Now, in my main thread (service_controller.py) I want to read the output of each thread's worker.py subprocess and use it to calculate an estimate for the time remaining till completion. I have all of the logic working that reads the stdout from worker.py and determines the last printed number. The problem is that I can not figure out how to do this in a non-blocking way. If I read a constant bufsize then each read will end up waiting for the same data from each of the workers. I have tried numerous ways including using fcntl, select + os.read, etc. What is my best option here? I can post my source if needed, but I figured the explanation describes the problem well enough. Thanks for any help here. EDIT Adding sample code I have a worker that starts a subprocess. ```class WorkerThread(threading.Thread): def __init__(self): self.completed = 0 self.process = None self.lock = threading.RLock() threading.Thread.__init__(self) def run(self): cmd = ["/path/to/script", "arg1", "arg2"] self.process = subprocess.Popen(cmd, stdout=subprocess.PIPE, bufsize=1, shell=False) #flags = fcntl.fcntl(self.process.stdout, fcntl.F_GETFL) #fcntl.fcntl(self.process.stdout.fileno(), fcntl.F_SETFL, flags | os.O_NONBLOCK) def get_completed(self): self.lock.acquire(); fd = select.select([self.process.stdout.fileno()], [], [], 5)[0] if fd: self.data += os.read(fd, 1) try: self.completed = int(self.data.split("\n")[-2]) except IndexError: pass self.lock.release() return self.completed ``` I then have a ThreadManager. ```class ThreadManager(): def __init__(self): self.pool = [] self.running = [] self.lock = threading.Lock() def clean_pool(self, pool): for worker in [x for x in pool is not x.isAlive()]: worker.join() pool.remove(worker) del worker return pool def run(self, concurrent=5): while len(self.running) + len(self.pool) &gt; 0: self.clean_pool(self.running) n = min(max(concurrent - len(self.running), 0), len(self.pool)) if n &gt; 0: for worker in self.pool[0:n]: worker.start() self.running.extend(self.pool[0:n]) del self.pool[0:n] time.sleep(.01) for worker in self.running + self.pool: worker.join() ``` and some code to run it. ```threadManager = ThreadManager() for i in xrange(0, 5): threadManager.pool.append(WorkerThread()) threadManager.run() ``` I have stripped out a log of the other code in hopes to try to pinpoint the issue. Comment: Are you on Linux or other Unix? If so, select + os.read 1 byte should work just fine -- can you show us the code you have along that line and what error or misbehavior it gives you? Comment: This is actually running on windoze for development will be on either Fedora or OS X for production. Here is the accepted answer: Instead of having your service_controller being blocked by i/o access, only the thread loop should read its own controlled process output. then, you can have method in the threaded object controlling the process to get the last polled output. of course, don't forget in that case to use some locking mechanism to protect the buffer that will be used both by the thread to fill it and the method called by the controller to get it. Comment for this answer: Am I far off from what you are suggesting? I have the threaded object controlling the process to get the last polled output... Comment for this answer: The get_completed method was actually supposed to return self.completed (I omitted it by mistake when retyping). I have added the RLock around the reading, but I still have the same issue. Comment for this answer: I just can't get my head wrapped around this. Perhaps some sleep tonight will make me have the breakthrough I am looking for. Comment for this answer: your get_completed method does only fill self.completed , i would suggest rename it update_completed. then adding a get_completed method returning the self.completed, (adding a threading.RLock to protect access to it). Then in your thread manager, you can periodically call get_completed on your workers. Here is another answer: Your method WorkerThread.run() launches the subprocess and then terminates immediately. Run() needs to perform the polling and update WorkerThread.completed until the subprocess completes.
Title: setup instance group GCE with HTTPS load balancer that allows custom port Tags: google-cloud-platform;google-compute-engine Question: I'm struggling with this setup for 3 days now, most certainly I'm doing something wrong, but from all the docs that I read I have no clue what to is the correct way. My goal is quite simple. I have a docker image in which I have a rest api that is served on 9090 port. I would like to have access to it over https, the port doesn't matter, best would be to use 443 (default https port) but this is not mandatory. What I did so far: Setup an instance-group with instance-template that uses docker image published on Google Container Registry. This instance-group is behind an HTTPS Load Balancer. I have tried a number of different configuration options of the LB to enable access to my instance. With instanced created from templates I no longer can setup custom firewall configurations associated with instances, in such way I was able to make a connection to a single VM over HTTP. Guys, can you help in any way ? --30.09.2019--------- Configuration Update: I have engine group setup with named ports: http: 9090 https: 9090 the template is set with both http &amp; https network allowed, but I don't have the possibility to add any rule that would enable 9090 over http or https, or that does not matter? No the Load Balancer: Frontend: I have two endpoints: 80 for http and 443 for https. The backend uses the named port http(which should point to 9090). --- Update 1/10/2019 Firewall rull: Health check Comment: updated comment Comment: yep, I think the health check is the reason, I found out that HC makes the instance-group and lb in `verified state`. I have now the backend lb and named port pointing to port 9090 thro http protocol. I have set the template to expose only port 9090. Still the only question is if I need to enforce some firewall rull on the vm instance to open the 9090 port or it is ok if I have it in the default netowork ? Comment: how to enforce this rule on the network? I created a rule with source: +1-551-708-3642/0 and allowing all traffic that should be enabled on all instances, but the health check is still not valid. Comment: Edit your question with the following. What are the load balancer frontend and backend configurations? How did you expose the container's port to be accessible outside the container host? There is a lot of information missing from your question. Be as detailed as possible. I would test first with an Unmanaged Instance Group with an existing VM instance. Once you have that working, go to the next steps with a Managed Instance Group. Also, start with HTTP (port 80) then worry about HTTPS (port 443). Normally the Load Balancer handles HTTPS and your backend handles only HTTP. Comment: 1) Your problem is caused by the health check. The health check is going to port 8080. Do you have a service listening on port 8080? 2) You have two named ports http->9090 and https->9090. Don't create two named ports going to the same destination port. Unless you are using both ports, this is not your problem, but I would delete the https definition. 3) Is your backend (container) supporting HTTP, HTTPS or both? Normally you just need HTTP. 4) Your configuration exposes three container ports (80, 8080, 9090). Which one is your service listening on? Delete the others. Comment: 5) Once you figure out question #4, enable the correct port in the VPC firewall to allow traffic in on that port. Comment: Yes, you need to create a firewall rule allow traffic on the port. I mentioned this in item #5. Comment: Show the details of your health check in your question. Here is the accepted answer: Ok, finally made it work! The problem was the firewall rule note being enforced on any of the managed instances. Even if you specify the network and target points this will not enforce the rule to run on the VM instance. You still need to add the network TAG to the instance. Now, with manually managed instances you can do it from the VM settings, if you have a template for the VMs you need to go to Advanced settings > Network > Network Tags when creating your template instance! This is the only way to make the rule applicable on your VM as far as I have read. For anyone that may have similar issues in the future. Bellow, you will find the screen. The Http Load balancer is working, probably because of provisioning reasons the https is not, so I will give it 60 minutes still. Here is another answer: You should use Named port to achieve this. In the instance group, set port name and port in Port Mapping option. Then in the load balancer configuration, select a backend then select a named port when prompted. Thats all you need to do. Comment for this answer: I have both setup, but still the services doesn't let me go throw. I have a firewall rull setup, but I think it does not get enabled on a given instance if I don't set it directly, and I'm not able to do it when instances are managed by the instance-group
Title: Get repeat answers when comparing facts in prolog Tags: recursion;prolog;logic Question: Working with SWI-Prolog. I have a list of ranks say: ```rank(London, 3.5). rank(New York, 3.5). rank(Seattle, 2.3). ``` And I am trying to get my head around making a rule that prints/returns any facts with the same rank. So in this case it would come back with London &amp; New York. Here's what I've come up with so far, the only problem is the duplicates I get with it (although they make perfect sense with the current rule). Would using recursion somehow help this? ```equal_rank(_):- rank(U1, R1), rank(U2, R2), U1 \== U2, R1 == R2, print(R1), print(': '), print(U1), print(', '), print(U2), nl, fail. ``` The output would be: ```3.5: London, New York 3.5: New York, London ``` I just can't figure out how to stop that second line. Comment: A small comment on the many inconvenient "print/1" calls: Consider using format/2 instead: format("~w: ~w, ~w\n", [R1,U1,U2]) gives you exactly the same result and is much easier to read and write. Here is the accepted answer: A simple approach would be to replace the not-equal test between U1 and U2 with a less-than test: ```U1 @< U2. ``` This way a given pair only appears once. Comment for this answer: Worked a treat, no more double results. Thanks. Here is another answer: I would probably go for something that uses ```bagof/3```, but I don't know whether that's the preferred or more apt approach for the problem you [email protected]. With the facts you defined, the following goal seems to issue the result you want: ```| ?- bagof(C, rank(C, X), Cs), length(Cs, L), L &gt; 1. Cs = [london,'new york'] L = 2 X = 3.5 yes ``` It needs some work on formatting, of course; the idea of collecting results in a list may or may not be useful to you. Oh, and by the way, I was unsure about city names needing to be variables, so as you can see I have asserted ```rank/2``` facts using plain atoms. For a little bit of additional information on ```bagof/3```, you may consult the online SWI-Prolog manual page about it. Comment for this answer: Although I'm sure this would have worked, it add more complexity over the other answer which I'm trying to avoid. Thanks anyway.
Title: jquery datatable return 3 same respond with different encho each fire Tags: asp.net-mvc;jquery;jquery-datatables Question: I had follow the below tutorial http://www.codeproject.com/Articles/155422/jQuery-DataTables-and-ASP-NET-MVC-Integration-Part but is weird that each time fire to server, it will return 3 same respond, same data but with different encho from server, is that normal behavior? but it will slow down table process ever just a few record, any idea? jquery ```var _bspaging = new bspaging(); _bspaging.Render(); self.$('#tblticket').dataTable({ "bDestroy": true, "bServerSide": true, "sPaginationType": "bootstrap", "sDom": '<"top"flp<"clear"&gt;&gt;rt<"bottom"ip<"clear"&gt;&gt;', "bSortable": true, "bAutoWidth": false, "sAjaxSource": '/Home/Ticket/AjaxHandler', "fnServerParams": function (aoData) { aoData.push({ "name": "sStatus", "value": status }); }, "bProcessing": true, "aoColumns": [ { "sTitle": "Status" }, { "sTitle": "Ticket Date", "sWidth": "10%" }, { "sTitle": "Ticket No.", "sWidth": "10%" }, { "sTitle": "Title", "sWidth": "30%" }, { "sTitle": "Category", "sWidth": "10%" }, { "sTitle": "Item", "sWidth": "10%" }, { "sTitle": "Created By", "sWidth": "10%" }, { "sTitle": "Current", "sWidth": "10%" }, { "sName": "ID", "sDefaultContent": "", "sWidth": "10%", "fnRender": function (obj) { if (status == "New") { return "<a class='btn btn-large'&gt;<i class=\"icon icon-pencil\"&gt;</i&gt; Edit</a&gt;"; } }, } ] }) ``` Here is the accepted answer: ok, I guess i'm wrong, I found the culprit that cause my jquery datatable return multiple response from server, instead of "bprocessing", I figure out that the RowGrouping plugin caused my datatable to return multiple respond from the server
Title: Custom ConfigSource for Quarkus Tags: java;datasource;cdi;quarkus;microprofile Question: I'm trying now to configure custom ConfigSource in my Quarkus App. Like in many other manuals i'm created my own DatabaseSourceConfig and implements org.eclipse.microprofile.config.spi.ConfigSource interface.I registered my ConfigSource in: ```/META-INF/services/org.eclipse.microprofile.config.spi.ConfigSource ``` There is my ConfigSource: ```public class DatabaseConfigSource implements ConfigSource { private DataSource dataSource; public DatabaseConfigSource() { try { dataSource = (DataSource) new InitialContext().lookup("openejb:Resource/config-source-database"); } catch (final NamingException e) { throw new IllegalStateException(e); } } @Override public Map<String, String&gt; getProperties() { // Implementing Method } @Override public String getValue(final String propertyName) { // Implementing Method } @Override public String getName() { return DatabaseConfigSource.class.getSimpleName(); } ``` } But this not working for Quarkus because of JNDI name. I need to use CDI. I was trying to use something like this: ```@Inject @io.quarkus.agroal.DataSource("my_connection") AgroalDataSource usersDataSource; ``` and declare this connection in application.properties but it didn't help me. I'm getting all the time NULL Exception. Maybe someone have ideas, how can i get DB connection there without to use JNDI namespace? Comment: welcome to stackoverflow. Take a tour and get your first badge-https://stackoverflow.com/tour Here is the accepted answer: I found some answer myself, maybe it will be useful also for other ppl. Like @Janmartiška said, CDI booted later, than ConfigSource, that's why i don't see any way to inject my connection via CDI. I was created some HibernateUtil Class: ```package org.myproject.config; import java.util.Properties; import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; import org.myproject.entities.ConfigurationsEntity; public class HibernateUtil { private static SessionFactory sessionFactory; private static SessionFactory buildSessionFactory() { try { Properties props = new Properties(); props.setProperty("hibernate.connection.url", "jdbc:mysql://[db-host]:[db-port]/db_name"); props.setProperty("hibernate.connection.driver_class", "com.mysql.cj.jdbc.Driver"); props.setProperty("hibernate.connection.username", "username"); props.setProperty("hibernate.connection.password", "password"); props.setProperty("hibernate.current_session_context_class", "thread"); props.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL8Dialect"); Configuration configuration = new Configuration(); configuration.addProperties(props); configuration.addAnnotatedClass(ConfigurationsEntity.class); System.out.println("Hibernate Configuration loaded"); ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build(); System.out.println("Hibernate serviceRegistry created"); SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry); return sessionFactory; } catch (Throwable ex) { // Make sure you log the exception, as it might be swallowed System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } } public static SessionFactory getSessionFactory() { if(sessionFactory == null) sessionFactory = buildSessionFactory(); return sessionFactory; } } ``` than i used it in my SourceConfig: ```package org.myproject.config; import io.quarkus.runtime.annotations.RegisterForReflection; import org.eclipse.microprofile.config.spi.ConfigSource; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.myproject.entities.ConfigurationsEntity; import javax.persistence.NoResultException; import javax.persistence.Query; import java.util.HashMap; import java.util.List; import java.util.Map; @RegisterForReflection public class DatabaseSourceConfig implements ConfigSource { public SessionFactory sessionFactory; public Session currentSession; public DatabaseSourceConfig() { sessionFactory = HibernateUtil.getSessionFactory(); this.checkFactoryConnection(); } public void checkFactoryConnection() { if (currentSession == null || (currentSession != null &amp;&amp; !currentSession.isOpen())) { try { currentSession = sessionFactory.getCurrentSession(); } catch (NullPointerException e) { currentSession = sessionFactory.openSession(); } } } @Override public Map<String, String&gt; getProperties() { // Implementing Method } @Override public String getValue(String propertyName) { this.checkFactoryConnection(); ConfigurationsEntity conf = new ConfigurationsEntity(); currentSession.beginTransaction(); try { Query query = currentSession.createNamedQuery("Configuration.selectOne", ConfigurationsEntity.class); query.setParameter("name", propertyName); conf = (ConfigurationsEntity) query.getSingleResult(); currentSession.getTransaction().commit(); } catch (Exception ex) { currentSession.getTransaction().rollback(); } return conf.getValue(); } @Override public String getName() { return DatabaseSourceConfig.class.getSimpleName(); } } ``` Now i can use my ConfigSource in other classes like: ```@Inject @ConfigProperty(name = "[property-name-like-in-db]") public String someProperty; ``` After my further research it was found that ConfigSource has no access to CDi and application.properties. That is why there is nothing left but to establish a connection to the database in the manner described above. However, I did a little editing of the example. I cached properties from the database and created a @ApplicationScoped Bean that looks into the database once every 5 minutes to see whether one of properties "updated_at" has a timestamp later than others from Bean loaded properties. However, I have to say that according to Quarkus and Apache developers - this violates “immutable deployment” and is not planned to change the application settings during runtime. So it depends on you whether you write it in the app or not. Here is another answer: You can obtain the data source via ```AgroalDataSource dataSource = Arc.container() .instance(AgroalDataSource.class, new DataSource.DataSourceLiteral("my_connection")) .get(); ``` You'll need to do this somewhere else than the constructor though, I think, because the ConfigSource instance is created before CDI is fully booted. You can cache the obtained data source instance then to avoid executing this multiple times. Comment for this answer: Problem is, that i can't Cache result, because configuration can be changed "on the flow". I need all the Time actual configuration value. But thanks for u comment - i also suspected, that CDI booted later than ConfigSource. I solved my Problem with SessionFactory without CDI. I will post my code a little bit later. Maybe u will have some more comments to it. Comment for this answer: I mean change Config Values in DataBase. And it’s not about Dev mode, but Produktion. Custom ConfigSource read Config values from database all the time without to cache them, to have an actual value. I can read more about it for example there: https://ralph.blog.imixs.com/2019/06/11/microprofile-customconfigsource-with-database/ Comment for this answer: What do you mean by changing the configuration? If you're referring to development mode, then if you change the config in dev mode, the application will reboot, so a new instance of your ConfigSource will be created and the cached value will be lost. Comment for this answer: Ok, but then you can cache the data source instance so that you don't have to do the expensive CDI lookup again. I meant caching just the instance, not the data from database.
Title: Using SimpleMembership with EF model-first Tags: entity-framework;simplemembership Question: Can SimpleMembership be used with EF model-first? When I try it, I get "Unable to find the requested .NET Framework Data Provider" when I call ```WebSecurity.InitializeDatabaseConnection.``` To put it another way: I can't get the call to ```WebSecurity.InitializeDatabaseConnection``` to work when the connection string employs the ```System.Data.EntityClient``` provider (as it does when using the model-first paradigm). To repro the issue, create an MVC 4 app, and replace the code-first UserProfile entity class (which you get for free with the MVC 4 template) with a model-first User class that you have created in the Entity Designer: Create an MVC 4 app in VS 2012 and add a new, blank Entity Data Model. Add a new Entity named ```User``` to the model, with fields for ```Id,``` ```UserName, and FullName```. So, at this point, the ```User``` data entity is mapped to a ```Users``` table and is accessed via a funky connection string that employs the ```System.Data.EntityClient``` provider. Verify that the EF can access the ```User``` entity. One easy way to do that is to scaffold out a Users controller based on the User table and its associated DbContext. Edit the ```AccountModels.cs``` file to remove the ```UserProfile``` class and its associated ```UsersContext``` class. Replace the references to the (now missing) ```UserProfile``` and ```UsersContext``` classes with references to your new User class and its associated ```DbContext``` class. Move the call to InitializeDatabaseConnection from the InitializeSimpleMembershipAttribute filter class to the Application_Start method in Global.asax.cs. While you're at it, modify the arguments to use your new User entity's connection string, table name, and UserId column name. Delete the (no longer used) ```InitializeSimpleMembershipAttribute``` class and the references to it. When you run the repro, it will get an Exception at the call to ```InitializeDatabaseConnection.``` Bob Comment: @PeterEdike Yes, that's what I tried to do. I tried to replace all of the code-first stuff with my model-first stuff, but I discovered that SimpleMembership doesn't work with the model-first magic in the connection string. As Mario Zderic says, the solution is to use something that looks like the code-first connection string. Comment: Do you mean replace public DbSet UserProfiles { get; set; } with (public DbSet userProfiles{get;set;}). I am kind of in a fix with this Here is the accepted answer: SimpleMembership can work with model first. Here is the solution. 1.```InitializeSimpleMembershipAttribute.cs``` from MVC 4 Internet Application templete should look like this ```namespace WebAndAPILayer.Filters { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)] public sealed class InitializeSimpleMembershipAttribute : ActionFilterAttribute { private static SimpleMembershipInitializer _initializer; private static object _initializerLock = new object(); private static bool _isInitialized; public override void OnActionExecuting(ActionExecutingContext filterContext) { // Ensure ASP.NET Simple Membership is initialized only once per app start LazyInitializer.EnsureInitialized(ref _initializer, ref _isInitialized, ref _initializerLock); } private class SimpleMembershipInitializer { public SimpleMembershipInitializer() { try { WebSecurity.InitializeDatabaseConnection("ConnStringForWebSecurity", "UserProfile", "Id", "UserName", autoCreateTables: true); } catch (Exception ex) { throw new InvalidOperationException("Something is wrong", ex); } } } } } ``` 2.Delete CodeFirst Classes from ```AcountModel.cs``` 3.Fix ```AccountCotroler.cs``` to work with your Model-first DbContext (```ExternalLoginConfirmation(RegisterExternalLoginModel model, string returnUrl)``` method) 4.Define your ```"ConnStringForWebSecurity"``` connection string which is not same as that funky conn string for model-first db access, notice that we use provider ```System.Data.SqlClient``` not ```System.Data.EntityClient``` ``` <connectionStrings&gt; <add name="ModelFirstEntityFramework" connectionString="metadata=res://*/Context.csdl|res://*/Context.ssdl|res://*/Context.msl;provider=System.Data.SqlClient;provider connection string=&amp;quot;data source=.\SQLEXPRESS;Initial Catalog=aspnet-MVC4;Integrated Security=SSPI;multipleactiveresultsets=True;App=EntityFramework&amp;quot;" providerName="System.Data.EntityClient" /&gt; <add name="ConnStringForWebSecurity" connectionString="data source=.\SQLEXPRESS;Initial Catalog=aspnet-MVC4;Integrated Security=SSPI" providerName="System.Data.SqlClient" /&gt; </connectionStrings&gt; ``` Comment for this answer: Thank you Mario! That raises a couple of questions regarding how the two DbContext connections cooperate with each other. I'll create new forum threads for those two questions. Comment for this answer: I'm new to the MVC world, and now I have the same problem...,what you mean in point 2, 3, please can you have a better explanation to newbie people like me, thanks in advance. Comment for this answer: The dual connection strings was the part I was missing in DbFirst! So essentialy the SimpleMembershipProvider helpers only work with classic connection strings and not EF connection strings. Here is another answer: That's a bug in MVC 4. There's a workaround in this blog post. ``` As an action filter, ```InitializeSimpleMembershipAttribute``` hooks into ```OnActionExecuting``` to perform the lazy initialization work, but this can be too late in the life cycle. The Authorize attribute will need the providers to be ready earlier if it needs to perform role based access checks (during ```OnAuthorization```). In other words, if the first request to a site hits a controller action like the following: ``` ```[Authorize(Roles="Sales")] ``` ``` .. then you’ll have an exception as the filter checks the user’s role but the providers aren’t initialized. My recommendation is to remove ISMA from the project, and initialize WebSecurity during the application start event. ``` Comment for this answer: Thanks Craig. When I first embarked on my quest to fuse my model-first entities with the SimpleMembership magic, I had, in fact, removed ISMA and moved the call to InitializeDatabaseConnection from the lazy initializer to the Application_Start method in Global.asax.cs. I just didn't want to complicate the scenario in my original posting with that detail. The "can't find the provider" exception happens whenever I try to lash up my model-first entity to SimpleMembership, whether I make the call in the lazy initializer or in Application_Start. Comment for this answer: Yeah, solution with 30 lines of negative code! I like that. +1 Here is another answer: this problem caused by ```WebSecurity.InitializeDatabaseConnection``` can't use connection string with ```System.Data.EntityClient``` provider name. providing dual connection string isn't sound good, so you can generate the connection string for EF model first in the constructor in the partial class. the code is look like bellow ```public partial class MyDataContext { private static string GenerateConnectionString(string connectionString) { var cs = System.Configuration.ConfigurationManager .ConnectionStrings[connectionString]; SqlConnectionStringBuilder sb = new SqlConnectionStringBuilder(cs.ConnectionString); EntityConnectionStringBuilder builder = new EntityConnectionStringBuilder(); builder.Provider = cs.ProviderName; builder.ProviderConnectionString = sb.ConnectionString; builder.Metadata = "res://*/MyDataContext.csdl|" + "res://*/MyDataContext.ssdl|res://*/MyDataContext.msl"; return builder.ToString(); } public MyDataContext(string connectionName) : base(GenerateConnectionString(connectionName)) { } } ``` with this trick you can use single connection string on your web config, but one problem you can't use default constructor on your datacontext, instead you should seed connection string name everywhere when you instantiate the datacontext. but it is not a big problem when you use dependency injection pattern. Here is another answer: I´m not able to work with EF and WebMatrix webSecurity class so to avoid this problem and go ahead: Change my Ef model first to code first. Change the connection string to use providerName="System.Data.SqlClient"(removing all the metadata information) or use the EF connection In my case the model, data and web are different proyects so for me is not an issue to remove this information from the web.config on the web.project. Nowadays websecuroty.initializedatabase dosen't run with EF connection string. I wish this helps Here is another answer: 1 - You need to enable migrations, prefereably with EntityFramework 5 2 - Move your ```WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "EmailAddress", autoCreateTables: true); ``` to your Seed method in your YourMvcApp/Migrations/Configuration.cs class ``` protected override void Seed(UsersContext context) { WebSecurity.InitializeDatabaseConnection( "DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true); if (!Roles.RoleExists("Administrator")) Roles.CreateRole("Administrator"); if (!WebSecurity.UserExists("lelong37")) WebSecurity.CreateUserAndAccount( "lelong37", "password", new {Mobile = "(318)549-6820", IsSmsVerified = false}); if (!Roles.GetRolesForUser("lelong37").Contains("Administrator")) Roles.AddUsersToRoles(new[] {"lelong37"}, new[] {"Administrator"}); } ``` Now EF5 will be in charge of creating your UserProfile table, after doing so you will call the WebSecurity.InitializeDatabaseConnection to only register SimpleMembershipProvider with the already created UserProfile table (In your case, you can replace the "UserProfile" parameter value with your custom table name), also tellling SimpleMembershipProvider which column is the UserId and UserName. I am also showing an example of how you can add Users, Roles and associating the two in your Seed method with custom UserProfile properties/fields e.g. a user's Mobile (number). 3 - Now when you run update-database from Package Manager Console, EF5 will provision your table with all your custom properties For additional references please refer to this article with sourcecode: http://blog.longle.net/2012/09/25/seeding-users-and-roles-with-mvc4-simplemembershipprovider-simpleroleprovider-ef5-codefirst-and-custom-user-properties/ Comment for this answer: Thanks Long Le. Unfortunately, my problem is that I'm using "model-first", not "code-first". As far as I know (correct me if I'm wrong) the "migrations" feature only applies to code-first, not to model-first. But the code examples for creating roles and users will be very helpful once I get the basic claptrap working! - Bob Comment for this answer: Bob.as.SBS - well I'm glad that at least something in my answer was helpful to you, do you mind bumping upvoting this answer since it was of some assistance to you? - thanks
Title: How to make background API server use hot reloading in a React project? Tags: node.js;reactjs;webpack Question: When I save changes to my client-side code, the browser hot-reloads as expected. But when I make changes to my server code, no hot-reloading occurs. This is a problem because we want to just run 1 command (i.e. ```npm start```) to launch our React webpack-dev-server AND our API server, and rerunning the entire ```npm start``` to manually relaunch the server after changes is slow (because it unnecessarily relaunches the React dev-server as well). Also sometimes we forget to relaunch the server code, so in reality it should just hot-reload anyway. I've looked across the internet and surprisingly can't find any straightforward solutions. I feel like I shouldn't have to eject the entire project and go deep into the webpack configurations to get this to work. This is what the ```npm start``` portion of my ```package.json``` looks like now: ```"scripts": { 46 "start": "concurrently --kill-others \"react-scripts start\" \"node server.js\"", ... } ``` Is there perhaps a way I can do "react-scripts start" with a different target or something? Comment: Man I feel stupid. I must've seen nodemon a million times but never really looked into it. All my research was in trying to figure out how to get this to work with webpack. Glad the answer was so simple, thank you! Comment: Use Nodemon: https://www.npmjs.com/package/nodemon. `"concurrently --kill-others \"react-scripts start\" \"nodemon server.js\"",`. Make sure to ignore watching the client folder, otherwise it'll restart on client saving.
Title: programa en NetbeasID13 con conexion a SQlite Tags: java;netbeans;netbeans-13 Question: estoy creando un pograma en netbeansID13 de agregar, insertar, editar y eliminar datos a una base de datos de SQlite, pero me esta arrojando el siguiente error Exception in thread &quot;main&quot; java.lang.ExceptionInInitializerError Caused by: java.lang.RuntimeException: Uncompilable code - illegal start of [email protected].(frmEmpleados.java) C:\Users\LENOVO\AppData\Local\NetBeans\Cache\13\executor-snippets\run.xml:111: The following error occurred while executing this line: C:\Users\LENOVO\AppData\Local\NetBeans\Cache\13\executor-snippets\run.xml:68: Java returned: 1 BUILD FAILED (total time: 0 seconds) Agradezco mucho me ayuden. Comment: Por favor, aclara tu problema específico o proporciona detalles adicionales para resaltar exactamente lo que necesitas. Tal como está escrito, es difícil saber exactamente qué estás preguntando. Comment: agrega el codigo de frmEmpleados para ver que es lo que no compila
Title: Cannot upgrade sklearn, pip pointing to python3 Tags: python;python-2.7;pip Question: I wanted to upgrade sklearn in python 2.7 with pip but I couldn't because since a day or two pip seems to be pointing to python 3.4, not python 2.7: ```&gt; pip install -U scikit-learn Requirement already up-to-date: scikit-learn in /home/kinkyboy/.local/lib/python3.4/site-packages Cleaning up... ``` This shows my current pip* commands: ```&gt; pip -V pip 1.5.4 from /usr/lib/python3/dist-packages (python 3.4) &gt; pip2 -V pip 1.5.4 from /usr/lib/python2.7/dist-packages (python 2.7) &gt; pip3 -V pip 1.5.4 from /usr/lib/python3/dist-packages (python 3.4) ``` and this shows that python is using python 2.7: ```&gt; which python python is /usr/bin/python python is /home/kinkyboy/conda/bin/python &gt; ls -l /usr/bin/python lrwxrwxrwx 1 root root 9 Jan 6 2016 /usr/bin/python -&gt; python2.7* ``` I managed to upgrade sklearn using pip2, but how to point pip back to python 2.7? Update: I tried the following and I get a permission denied error. ```&gt; python -m pip install -U --force-reinstall pip Collecting pip Using cached pip-9.0.1-py2.py3-none-any.whl Installing collected packages: pip Found existing installation: pip 9.0.1 Uninstalling pip-9.0.1: Exception: Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/usr/local/lib/python2.7/dist-packages/pip/commands/install.py", line 342, in run prefix=options.prefix_path, File "/usr/local/lib/python2.7/dist-packages/pip/req/req_set.py", line 778, in install requirement.uninstall(auto_confirm=True) File "/usr/local/lib/python2.7/dist-packages/pip/req/req_install.py", line 754, in uninstall paths_to_remove.remove(auto_confirm) File "/usr/local/lib/python2.7/dist-packages/pip/req/req_uninstall.py", line 115, in remove renames(path, new_path) File "/usr/local/lib/python2.7/dist-packages/pip/utils/__init__.py", line 267, in renames shutil.move(old, new) File "/usr/lib/python2.7/shutil.py", line 303, in move os.unlink(src) OSError: [Errno 13] Permission denied: '/usr/bin/pip' ``` Even if I know using sudo is bad (though I might have used it in the past), I tried to run the same command with sudo (it worked), i tried to give '/usr/bin/pip' 777 permission (but it still did not help to run the normal uninstall above), and I also did a sudo uninstall python-pip (did not help the normal uninstall above). After these attempts I put everything back to what it was. Comment: I think that pip will point to the version which was installed last. So if you want to use pip as pip2, just re-install pip2 Comment: linux mint, I forgot to write that Comment: Thank you, I will try it this evening Comment: Which OS are you using? Comment: I've answered your question below, see if my solution helps you. Here is the accepted answer: Not sure how you changed it, but you can change it back if you modify the first line of the pip file in /usr/bin/ (edit: and any other pip you have installed). The below assumes you are modifying /usr/bin/pip: 1.) Ensure you have write access to /usr/bin/pip, either as root user OR change the permission with ```sudo chmod -c 757 /usr/bin/pip``` for the moment. 2.) Update the first line of pip from ```#!/usr/bin/python3``` (what I'm assuming is showing) to ```#!/usr/bin/python``` 3.) Save ```pip``` and revert the permission back to 755 if you changed it (so nobody else messes with it). My output before/after change: ```$ pip -V pip 9.0.1 from /usr/lib/python3/dist-packages (python 3.5) $ pip -V pip 9.0.1 from /usr/lib/python2.7/dist-packages (python 2.7) ``` Without knowing exactly how it was changed in the first place, this would be my way of fixing it. Otherwise, my primary method would be figuring out what triggered it first and try to reverse it. Comment for this answer: I just read your answer but left more confused. You ended up changing the pip (which you have several installed) but surprisingly when you change it to python3 it starts pointing to python 2.7? I know that's what you wanted but python3 should point to python 3.x installations? Regardless I have updated my answer in case there are multiple installations. Comment for this answer: The first line of the /usr/bin/pip file was already #!/usr/bin/python and the permission of the file was 755, so unfortunately this did not help Comment for this answer: I solved the issue, see my own answer. if you edit your answer to include my solution I will gladly accept it Comment for this answer: sorry my mistake, I changed it to python (2.7)! I corrected my answer Here is another answer: In my case, when I installed sklearn, it was by default pointing to python3.5 where I wanted to use it with python 2.7. Following suggestion by Vitor, I ran the following command: ``` sudo python -m pip install -U scikit-learn ``` and it worked for me! Here is another answer: I've found this GitHub thread on Homebrew's repository with a similar problem: https://github.com/Homebrew/legacy-homebrew/issues/50607 Apparently, executing the following commands should solve your problem: ```python3 -m pip install -U --force-reinstall pip python -m pip install -U --force-reinstall pip ``` But you can always execute pip by using: ```python -m pip python3 -m pip ``` Comment for this answer: Unfortunately your suggestion did not help, I updated my question. Is it possible that I run some sudo pip install at some point and that messed things up? Comment for this answer: Yes, if you are getting a permission denied you probably installed either pip, python or (MAYBE) some extension using sudo. Check your `/usr/bin/pip` permissions to confirm that. You can remove using `sudo` and reinstall it. I'm really not sure what will be the consequences thought. But as I said, you can always use `python -m pip` and `python3 -m pip`. Comment for this answer: Also, take a look at this: https://github.com/Homebrew/legacy-homebrew/issues/25752 Here is another answer: I got inspired by @Idlehands 's initial answer to check if the executable for python began with #!/usr/bin/python3 . It didn't. However, pip's executable did: ```&gt; which pip pip is /usr/local/bin/pip pip is /usr/bin/pip pip is /home/kinkyboy/conda/bin/pip &gt; diff /usr/local/bin/pip /usr/bin/pip3 < #!/usr/bin/python3 ``` I changed #!/usr/bin/python3 to #!/usr/bin/python, and after that pip -V was pointing to python 2.7. sklearn was the latest and I could import a module that is present in latest (that was was I wanted to do in the first place). About this: that sklearn was latest might have happened because I previously reinstalled python-pip in linux and uninstalled pip with sudo, etc, so I am not entirely positive without all this poking around sklearn would have been up to date
Title: Uninstalling Intel Proset/Wireless Bluetooth while upgrading to windows 8 Tags: windows-8;bluetooth;uninstall Question: I purchased Windows Upgrade 8 and ran Windows Update Assistant on existing windows 7. However, It is asking me to uninstall Intel Wireless bluetooth, as it is not compatible with windows 8. I did just that and in spite of uninstalling it successfully, it is giving a message "Manually Uninstall". I dont know what this means? is it successfully uninstalled or not, and if not how do I uninstall it completely. I posted this on Microsoft forum also and found many users are facing this issue. Noone from Microsoft has answered there. ```http://answers.microsoft.com/en-us/windows/forum/windows_8-windows_install/problem-in-uninstalling-intel-prosetwireless/5e1c4a29-726e-4968-a787-80b45778d14c?page=1 ``` I have tried CCleaner, Microsoft fixit and other tools but still no help. Here is the accepted answer: This is how I fixed it: • Go to ```services.msc``` via RUN. • Stop these 3 services • Delete the bluetooth folder located under • Delete the services that are associated with them in cmd (run as administrator) with: ```sc delete "Bluetooth Device Monitor" sc delete "Bluetooth Media Service" sc delete "Bluetooth OBEX Service" ``` Here is another answer: Download the driver from here and run the setup: https://downloadcenter.intel.com/Detail_Desc.aspx?agr=Y&amp;DwnldID=22548&amp;lang=eng If you use the 32Bit Windows run the 32.exe file, if you use a 64Bit Windows run the 64.exe file. Comment for this answer: I am using windows 7. I want ot upgrade to windows 8. These drivers are for windows 8. Comment for this answer: Hi. Thanks for your reply. The problem is even after removing drivers from Win7, the upgraded Assistant still tells me to remove them. Comment for this answer: I have uninstalled the complete software. Comment for this answer: and I posted the link to the drivers so that you can download them. Remove them in Win7, updrade to Win8 and install the new drivers. Comment for this answer: have you only deleted the device in device manager or uninstalled the complete software?
Title: Pandas To_SQL is giving the DataError: (pyodbc.DataError) ('22018', "[22018] [Microsoft][ODBC SQL Server Driver][SQL Server] Tags: python;pandas Question: I am trying to load the excel file in SQL server using sqlalchemy, to_sql. When i run the code it gives me below error. ```quoted = urllib.parse.quote_plus(&quot;Driver={SQL Server};&quot; &quot;Server=XYZ;&quot; &quot;Database=SNOW;&quot; &quot;Trusted_Connection=yes;&quot;) engine = create_engine('mssql+pyodbc:///?odbc_connect={}'.format(quoted)) data = pd.read_excel(r'I:\ESS_ITRS_STATS_DATA.xlsx') # rename columns data = data.rename(columns={'Gateway': 'Gateway', 'Severity': 'Severity', 'Country': 'Country', 'CSIID': 'CSI_ID', 'NetProbe': 'NetProbe', 'Entity': 'Entity', 'Sampler': 'Sampler', 'Variable': 'Variable', 'Hostname': 'Hostname', 'Absolute_path': 'Absolute_path', 'Date': 'Date', 'Description': 'Description', 'InsertedDateTime': 'InsertedDateTime'}) df = pd.DataFrame(data, columns=['Gateway','Severity','Country','CSI_ID','NetProbe','Entity','Sampler','Variable','Hostname','Absolute_path','Date','Description','InsertedDateTime']) df['InsertedDateTime'] = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime()) df = df.fillna(value=0) df['CSI_ID'] = df['CSI_ID'].astype(str) table_name='ITRSALERTS_TEMP' df.to_sql(table_name,engine,index=False,if_exists=&quot;append&quot;,schema=&quot;dbo&quot;, chunksize=25,dtype={col_name: NVARCHAR for col_name in df}) ``` i am getting the below error DataError: (pyodbc.DataError) ('22018', &quot;[22018] [Microsoft][ODBC SQL Server Driver][SQL Server]Conversion failed when converting the nvarchar value '95.89' to data type int. (245) (SQLExecDirectW)&quot;) below is the content from my excel Gateway Severity Country CSIID NetProbe Entity Sampler Variable Hostname Absolute_path Date Description InsertedDateTime SST_ISSUER01_NAM_PROD CRITICAL UNITED STATES 0 XYZ-1 XYZ-H-1 CPU _Total.%processorTime XYZ-H-1 0 2020-09-20T15:12:35 95.89 2020-09-21 18:12:57 Here is another answer: Apparently data type in database and in dataframe do not match: database expects value '95.89' to be numerical and it is sent as a string. You should cast it to appropriate type, maybe round it (depending on database table definition) in the same way you've already done for CSI_ID column: ```df['Description'] = df['Description'].astype(float) ```
Title: How to manually populate the datagrid in asp.net 1.1 using vb.net 2003? Tags: asp.net;vb.net;visual-studio-2003;asp.net-1.1 Question: just would like to ask if it is possible to manually populate the datagrid in asp.net 2003 using vb.net we usually populate the datagrid using this code, in this code what it does is it populate the datagrid base on your query , it's automated you can't edit or evaluate the data inside. ```dataGrid.DataSource = ds dataGrid.DataBind() ``` What if if I want to edit or evaluate the data inside the DataSet? Here is the accepted answer: Before you link your ```DataSource```, you can loop through it and modify the values if you want. Try looping through the ```ds.Tables("TableName").Rows``` collection. Comment for this answer: Glad to hear it. I updated my answer with the proper syntax, thanks. Comment for this answer: Thanks. though it's ds.Tables("TableName").Rows since it's VB thanks sir
Title: Mobile responsive menu button is not responding to jquery click function Tags: javascript;jquery;html;css Question: I'm currently trying to create a responsive menu button for my navigation bar, and it does not seem to be responding to a mouse click. ```$("span.nav-btn").click(function() $("ul.nav-toggle").slidetoggle(); }) ``` Fiddle Comment: `slidetoggle` -> `slideToggle`. Also you're missing a curly brace `{`. Here is another answer: Your JS has a syntax error. Missing ```{``` at the first line and the method name ```slideToggle``` (with capital "T"). ```$("span.nav-btn").click(function() { // <== HERE === $("ul.nav-toggle").slideToggle(); }); ``` Here is another answer: Problems: The click function is missing an opening curly brace ```{``` jQuery is case-sensitive so ```slidetoggle```, should be ```slideToggle``` Notes in your fiddle is not loading the jQuery library ```$("span.nav-btn").click(function() { $("ul.nav-toggle").slideToggle(); })``` ```#nav { background-color: #6a5750; padding-top: .01%; position: fixed; width: 100%; text-align: center; } #nav li { display: inline-block; } #nav li a { text-decoration: none; text-align: center; font-size: 16px; color: #FFFFFF; -o-transition: .3s; -ms-transitiion: .3s; -moz-transition: .3s; -webkit-transition: .3s; transition: .3s; } #nav a:hover { color: #FF0000; } @media (max-width: 800px) { #nav { text-align: left; } #nav li { display: block; } .nav-btn { display: block; background-color: #6a5750; color: #FFFFFF; text-align: center; } .nav-btn:before { content: "Menu" } }``` ```<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"&gt;</script&gt; <div data-scroll-header id="nav"&gt; <span class="nav-btn"&gt;</span&gt; <ul class="nav-toggle"&gt; <li&gt;<a data-scroll href="#home"&gt;Home</a&gt; </li&gt; <li&gt;<a data-scroll href="#html"&gt;HTML</a&gt; </li&gt; <li&gt;<a data-scroll href="#css"&gt;CSS</a&gt; </li&gt; <li&gt;<a data-scroll href="#video"&gt;Video</a&gt; </li&gt; <li&gt;<a data-scroll href="#about"&gt;About</a&gt; </li&gt; <li&gt;<a data-scroll href="#contact"&gt;Contact</a&gt; </li&gt; </ul&gt;```
Title: Sort Div Whit d3js html5 Tags: jquery;css;html;sorting;d3.js Question: I am try to sort div animated with d3js, this is the code example the problem is, in the function reSort, I try to get the div.data and apply sort function but the element a and b has arrived undefined, I dont know why ``` <!doctype html&gt; <html&gt; <head&gt; <meta charset="utf-8"&gt; <style type="text/css"&gt; .resort { padding: 10px; border: 1px solid black; background: #ccc; cursor: pointer; width: 100px; margin-bottom: 20px; } .data { position: fixed; border: 1px solid black; width: 100px; } </style&gt; </head&gt; <body&gt; <div class="resort"&gt;Re-sort</div&gt; <script src="http://d3js.org/d3.v3.min.js"&gt;</script&gt; <script type="text/javascript"&gt; ;(function() { body = d3.select(" body "); function reSort() { body.selectAll("div.data").sort(function(a, b) { console.log(a); // data Arrived undefined console.log(b); // data Arrived undefined // I think a and b should return the component <div class="data"&gt;</div&gt; return d3.descending(a.id, b.id);; }) .transition().duration(500) .style({ top: function(d, i) { return 60 + ((i*30)) + "px"; } }) } d3.select(".resort").on("click", reSort); }()); </script&gt; <div class="data" id="1" style="top: 60px;"&gt;0</div&gt; <div class="data" id="2" style="top: 90px;"&gt;1</div&gt; <div class="data" id="3" style="top: 120px;"&gt;2</div&gt; <div class="data" id="4" style="top: 150px;"&gt;3</div&gt; <div class="data" id="5" style="top: 180px;"&gt;4</div&gt; <div class="data" id="6" style="top: 210px;"&gt;5</div&gt; <div class="data" id="7" style="top: 240px;"&gt;6</div&gt; <div class="data" id="8" style="top: 270px;"&gt;7</div&gt; <div class="data" id="9" style="top: 300px;"&gt;8</div&gt; <div class="data" id="10" style="top: 330px;"&gt;9</div&gt; </body&gt; </html&gt; ``` thanks for any help.. Here is the accepted answer: According to the documentation ``` The comparator function, which defaults to d3.ascending, is passed two elements' data a and b to compare. ``` Your comparator function tries to operate on the parameters a and b as if they were dom nodes. Instead, these parameters represent data bound to the corresponding nodes. You need to bind your data to each individual node to have it handed down to the comparator. Binding of the node's id could be easily achieved by applying ```body.selectAll("div.data") .datum(function() { return +this.id; }) ``` I've put together a working snippet: ```; (function() { body = d3.select("body"); function reSort() { body.selectAll("div.data") .datum(function() { return +this.id; }) .sort(function(a, b) { return d3.descending(a,b); }) .transition().duration(500) .style({ top: function(d, i) { return 60 + ((i * 30)) + "px"; } }); } d3.select(".resort").on("click", reSort); }());``` ```.resort { padding: 10px; border: 1px solid black; background: #ccc; cursor: pointer; width: 100px; margin-bottom: 20px; } .data { position: fixed; border: 1px solid black; width: 100px; }``` ```<!DOCTYPE html&gt; <html&gt; <head&gt; <link rel="stylesheet" href="style.css"&gt; <script src="http://d3js.org/d3.v3.min.js"&gt;</script&gt; </head&gt; <body&gt; <div class="resort"&gt;Re-sort</div&gt; <div class="data" id="1" style="top: 60px;"&gt;0</div&gt; <div class="data" id="2" style="top: 90px;"&gt;1</div&gt; <div class="data" id="3" style="top: 120px;"&gt;2</div&gt; <div class="data" id="4" style="top: 150px;"&gt;3</div&gt; <div class="data" id="5" style="top: 180px;"&gt;4</div&gt; <div class="data" id="6" style="top: 210px;"&gt;5</div&gt; <div class="data" id="7" style="top: 240px;"&gt;6</div&gt; <div class="data" id="8" style="top: 270px;"&gt;7</div&gt; <div class="data" id="9" style="top: 300px;"&gt;8</div&gt; <div class="data" id="10" style="top: 330px;"&gt;9</div&gt; <script src="script.js"&gt;</script&gt; </body&gt; </html&gt;```
Title: How do you do partial wave analysis with spin? Tags: angular-momentum;scattering Question: The derivations of the partial wave expansion I've seen have assumed spinless particles. However, when spin is involved, $l$ (orbital angular momentum) is no longer a good quantum number. What are some good resources to learn about doing partial wave analysis with spin involved? Edit: A better formulation of my question is, when people refer to the $l$-th partial wave of a quantity (say the phase shift) when $L$ is not conserved, are they referring to only the diagonal part of that quantity? Comment: One can use total angular momentum $\vec J = \vec L + \vec S$ whenever $l$ is no longer a good quantum number and any textbooks discussing scattering phenomena usually have the partial-wave topic covered too!
Title: json return data not working in IE or Chrome Tags: php;json;uploadify Question: I have problems returning JSON data after using Uploadify. This code works in Firefox, but not in IE 9 or Google Chrome. This is the script script for Uploadify: ``` jQuery("#uploadify_gallery").uploadify({ 'queueID' : 'fileQueue', 'uploader' : siteURL + '/wp-content/plugins/uploadify/uploadify.swf', 'script' : siteURL + '/wp-content/plugins/uploadify/uploadify_gallery.php', 'fileExt' : '*.jpg;*.jpeg;*.png', 'auto' : true, 'multi' : true, 'method' : 'POST', 'buttonImg' : siteURL + '/wp-content/themes/storelocator/img/buttons/img_upload_grey_bg.png', 'cancelImg' : siteURL + '/wp-content/plugins/uploadify/cancel.png', 'queueSizeLimit' : 20, 'scriptData' : {'entity':jQuery('#entity').val(),'entity_id':jQuery('#entity_id').val()}, 'onComplete' : function(event, queueID, fileObj, response, data) { alert('test'); // <-- THIS WORKS //This makes the json response readable var result = eval("(" + response + ")"); alert(result.toSource()); // <-- this never fires }, }); ``` This is the code I test with in ```uploadify_gallery.php```: ```$res = array('a' =&gt; 1, 'b' =&gt; 2, 'c' =&gt; 3, 'd' =&gt; 4, 'e' =&gt; 5); echo json_encode($res); ``` It worked yesterday, and I've got it working on Any suggestions on how I can make this work? Comment: Eval is bad. Avoid it at all costs. Also, what does the JSON that the server is returning to your script look like? Here is the accepted answer: Inspect the value returned by the server and verify that it is valid JSON (using JSONLint for example). After that you can use ```jQuery.parseJSON()``` to convert the response string into an object. Comment for this answer: Yes, I discovered this and that's what I'm using now. Thanks :) Here is another answer: eval(); isn't a good choice, it's considered pretty bad, since it won't work in Internet Explorer, at least the older ones. Check this out How can I get this eval() call to work in IE? http://24ways.org/2005/dont-be-eval You'll get the response as a json object, so instead of eval, just loop through it with an each ```$(response).each(function(index, value) { console.log(value); }); ``` For more information on each, check out http://api.jquery.com/each/
Title: GoogleMaps API: kml on top of polygon Tags: javascript;html;google-maps-api-3 Question: How can I render my polygon behind the kml layer? I have a kml layer imported into my Google Maps canvas. Also, I have implemented a polygon, which is drawn on the canvas whenever you click Draw. The issue is that when you click Draw the polygon is drawn on top of the kml markers. Thus, I cannot click any marker and visualize their respective names. In other words, I would like to be able to know which markers are included inside the drawn polygon, and for that I would need to click the marker and see its corresponding name. I believe the solution lies in using panes. I am aware of panes and the order in which they are arranged, but I don't know how to implement a solution using them. To follow, I'm including my code almost exactly as I have it, so you can see what I am talking about and test it yourself. The only difference is that I'm not including my key for GoogleMaps, so where you see API_KEY, replace for your own key. Thanks in advance. jsfiddle HTML: ```<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.1.min.js" type="text/javascript"&gt;</script&gt; <script type="text/javascript"src="https://maps.googleapis.com/maps/api/js?key=API_KEY&amp;libraries=geometry"&gt;</script&gt; <script src="GoogleMapTEST.js"&gt;</script&gt; <style&gt; html{ height:100%; margin:0; padding:0; } body{ height:60%; font-family:'Trebuchet MS', 'Arial', 'Helvetica', 'sans-serif'; font-size:10pt; background-color: LightGray; line-height:1.6em; } #map-canvas { width:80%; height:500px; margin-left: auto; margin-right: auto; margin-top: 50px; margin-bottom: 25px; } .col2{ border: #bfbfbf 1px solid; vertical-align: middle; display: inline; width: 39%; height: 90px; margin-left: 4%; } </style&gt; <div id="map-canvas"&gt;</div&gt; <div&gt; <form&gt; <fieldset class="col2"&gt; Search radius (km): <br&gt;<br&gt; <input type="text" id="DrawTxt" value="30"&gt; <input type="button" id="DrawBtn" value="Draw"&gt; </fieldset&gt; </form&gt; </div&gt; ``` Javascript: ```var map; var overlays_array = []; function initialize() { var MyLatLng = new google.maps.LatLng(51,-114); var mapOptions = { center: MyLatLng, zoom: 10 }; map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions); $("#DrawBtn").click( function(){ ClearOverlays(); var radius = $("#DrawTxt").val(); var circle = DrawCircle(map.getCenter(), radius); AddOverlay(circle); }); var CP_url = 'https://drive.google.com/uc?export=download&amp;id=0B2KR4Lz3foYEd04za21sMXZYaEE' var CP_options = { preserveViewport: true, map: map }; var CP_layer = new google.maps.KmlLayer(CP_url, CP_options); } google.maps.event.addDomListener(window, 'load', initialize); function DrawCircle(center, radius) { var nodes = 72; var latConv = google.maps.geometry.spherical.computeDistanceBetween( center, new google.maps.LatLng(center.lat()+0.1, center.lng()) )/100; var lngConv = google.maps.geometry.spherical.computeDistanceBetween( center, new google.maps.LatLng(center.lat(), center.lng()+0.1) )/100; var points = []; var step = parseInt(360/nodes)||10; for(var i=0; i<=360; i+=step) { var pint = new google.maps.LatLng(center.lat() + (radius/latConv * Math.cos(i * Math.PI/180)), center.lng() + (radius/lngConv * Math.sin(i * Math.PI/180))); points.push(pint); } points.push(points[0]); var poly = new google.maps.Polygon({ paths: points, strokeColor: "#00A2FF", strokeOpacity: 0, strokeWeight: 0, fillColor: "#80D0FF", fillOpacity: 0.3 }); return poly; } function AddOverlay(overlay) { if(overlay) { overlay.setMap(map); overlays_array.push(overlay); } } function ClearOverlays() { while(overlays_array[0]) { overlays_array.pop().setMap(null); } } ``` Here is another answer: One option (if your kml is not too complex) would be to render the KML as normal Google Maps Javascript API objects using a third party parser like geoxml3 or geoxml-v3, then you can control their ordering with respect to the circle. example ```<script type="text/javascript" src="http://geoxml3.googlecode.com/svn/branches/polys/geoxml3.js"&gt;</script&gt; <script&gt; function initialize() { var MyLatLng = new google.maps.LatLng(51,-114); var mapOptions = { center: MyLatLng, zoom: 10 }; map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions); geoXml = new geoXML3.parser({ map: map, infoWindow: infowindow, singleInfoWindow: true, markerOptions: {optimized: false} }); geoXml.parse("http://www.geocodezip.com/geoxml3_test/kml/CPs_Calgary.kml"); // ... ``` example with 494 markers example with 839 markers Comment for this answer: Last I checked, with v3 900 points will not cause performance issues. Not sure what your target environment is though. Comment for this answer: geoxml3 uses the XmlHttpRequest object for access to the KML, so is subject to that object's [same domain security restriction](http://www.xml.com/pub/a/2005/11/09/fixing-ajax-xmlhttprequest-considered-harmful.html). Did you host the KML on the same server as the web page? Comment for this answer: Yes, set the following option to the parser: `singleInfoWindow: false`. Then write code to either "click" on each marker after creation or open its infowindow. Comment for this answer: I have run into that parser, but my original KML is composed of about 900 points or markers. Thank you. Comment for this answer: Thanks for your time. I have just tried that and it didn't work. Most likely I'm doing something wrong. I added the script that references the source and then added the rest of your code below `map = new google.maps......`. The line where it is parsed, I substituted with my own url: https://drive.google.com/uc?export=download&id=0B2KR4Lz3foYEd04za21sMXZYaEE Comment for this answer: no, I have the KML in GoogleDrive and for the web page I use Webmatrix. Comment for this answer: using geoxml3, would there be a way of having the KML always show the info windows of all markers? Comment for this answer: Interesting, I will be trying to host the page and file on the same server next week probably. Anyway, would you know how to do what I am trying just using panes or something else?
Title: lacking photos from external Url php Tags: php;html;dom Question: I am using server side for getting photos from external url. I am using simple php dom library for getting this as per SO suggestion. But I am lacking performance in this. I mean for some sites I am not able to get all the photos. $url has the example external site which is not giving me all the images. ``` $url ="http://www.target.com/c/baby-baby-bath-bath-safety /-/N-5xtji#?lnk=nav_t_spc_3_inc_1_1"; $html = file_get_contents($url); $doc = new DOMDocument(); @$doc-&gt;loadHTML($html); $tags = $doc-&gt;getElementsByTagName('img'); foreach ($tags as $tag) { echo $imageUrl = $tag-&gt;getAttribute('src'); echo "<br /&gt;"; } ``` Is this possible I can have functionality/accuracy similar to the option of Firefox Firefox-> tools -> page info -> media I mean I just want to be more accurate for this as the existing library is not fetching all images. Also I tried file_get_content...which is also not fetching all the images. Comment: I am not sure about using iframes in this scene. But I just want to get images from the external url to use in my bookmarklet. which will open as pop up at any website. Comment: If you do an `echo $html;` you will notice that the HTML is non-existant. `hello, We’re experiencing some technical difficulties, sorry for the inconvenience.` - This is probably to stop screen scraping from their end. Is it possible to use iframes for this? Comment: ask them nicely and take copies if they say yes, and serve them locally. Comment: Do you get a timeout (`max_execution_time`)? Here is the accepted answer: You need to use regular expressions to get images' src. DOMDocument build all DOM structure in memory, You needn't it. When You get URLs, use ```file_get_contents()``` and write data to files. Also add ```max_execution_time``` if You'll parse many pages. Comment for this answer: As per last suggestions by SO I will need to fetch images using server side scripting. For doing that either I will use file_get_contents or dom libraray. but problem is that it is not giving me images for almost all the images.The same script is working for other websites. Comment for this answer: So Should I need to use curl here. because I am not able to get images using file_get_contents ? Comment for this answer: Thanks Egor.. :)...Actually I am trying to make something similar to http://www.myregstry.com. Please have a look at ADD TO MY registry feature in it if get a chance...Thanks again Comment for this answer: DOM library just convert string(HTML) to object model with their(objects) attributes(ex.: $html->img->src). Every object eat some memory, when You get all page in DOM library You get as many object as many tags on page. After that You search images and get only 1 attribute from them: src. Right way to find src from 1 step, from 1 string(HTML). Now some words about file_get_contents and timeouts. Maybe some host is too slow and your server think, that he can't take image. In this way You should get images via `cURL` functions Comment for this answer: Yes, I think it's the best solution. Here is another answer: ``` Download images from remote server ``` ```function save_image($sourcePath,$targetPath) { $in = fopen($sourcePath, "rb"); $out = fopen($targetPath, "wb"); while ($chunk = fread($in,8192)) { fwrite($out, $chunk, 8192); } fclose($in); fclose($out); } $src = "http://www.example.com/thumbs/thumbs-t2/1/ts_11083.jpg"; //image source $target = dirname(__FILE__)."/images/pic.jpg"; //where to save image with new name save_image($src,$target); ``` Comment for this answer: thanks for replying but I just want to fetch and show the images from teh external website then user wil choose the one and that will save on server.
Title: Failed once again to import shapefile to PostGIS DB using ogr2ogr Tags: postgis;shapefile;ogr2ogr Question: Once again I try to import a shapefile to my remote PostGIS database using og2ogr. Last time it was an Odyssey but I have managed to solve all the issues and report them one by one here. I have checked everything: Permissions of files, Path of shapefiles, Validity of shapefile, triple checked my ogr2ogr command, used ogrinfo to validate my connection to the DB and check the shapefile, granted roles on my user and on the required tables (e.g. spatial_ref_sys) if the table already exists etc. This is my ogr2ogr command: ```ogr2ogr -f "PostgreSQL" PG:"host=localhost user=my_user password=my_pass dbname=my_db_name" -nlt GEOMETRY my_shape_file.shp ``` And the error I get (also checked the PostgreSQL log files) is: ```ERROR 1: AddGeometryColumn failed for layer wld_bnd_adm2_gaul_2015, layer creation has failed. ERROR 1: Terminating translation prematurely after failed translation of layer wld_bnd_adm2_gaul_2015 (use -skipfailures to skip errors) ``` Last time I got this error cause I haven't GRANTED permissions to my user. That have solved the problem: ```GRANT ALL ON TABLE spatial_ref_sys TO my_user_name; ``` But not this time. And that's what I see on my log file: ```ERROR: function addgeometrycolumn(unknown, unknown, unknown, integer, unknown, integer) is not unique at character 8 HINT: Could not choose a best candidate function. You might need to add explicit type casts. STATEMENT: SELECT AddGeometryColumn('public','wld_bnd_adm2_gaul_2015','wkb_geometry',4326,'GEOMETRY',2) ``` Comment: If you need a quick solution, you could try to load it via the QGIS DB Manager plugin... Comment: Are you certain that your postgres database has the postgis extension loaded? Also, if you use pgAdmin, you could try using the PostGIS Shapefile and DBF loader that comes with that software Comment: Tried with shp2pgsql plugin. It didnt work either. Comment: Can you upload your shapefile somewhere so I can give it a go? Comment: `-nlt GEOMETRY` I don't think GEOMETRY is a valid parameter here. I think you need to pass in the geometry type, like POLYGON, LINESTRING, etc. Comment: -nlt should work. I think its a matter of the database rather than the shapefile. I tried also with other shapefiles and got the same issue. Comment: -nlt geometry is ok. There may be some old stuff in the database. I would try with -overwrite or with -nln name_i_have_not_used_before. Here is the accepted answer: I figured this out. It seems like there were some artifact functions with the name addGeometryColumn (overloading in postgres is possible). This error in the logfile made me suspect there is something very wrong with the addGeometryColumn function: ```ERROR: function addgeometrycolumn(unknown, unknown, unknown, integer, unknown, integer) is not unique at character 8 ``` After droping the functions (DROP FUNCTION ..) the issue was resolved! Comment for this answer: Interesting. So you dropped an overloaded function for which you had duplicate names, but different argument signatures? ..I'm curious as to how they got there in the first place! :)
Title: Obtener datos con POST en una misma pagina php Tags: php;html;html5 Question: Buenas, quisiera obtener datos en una misma pagina php, en un login, el problema es que cuando ingreso los valores en mi login, los guardo por POST, pero parece que siempre me guarda NULL. ```.boxlogin{ border-radius:4px; box-shadow: 2px 2px #d6d6d6; margin: 75px auto; width: 320px; -webki-border-radius:4px; -moz-border-radius:4px; } .btn{ margin-top: 14px; } ``` ```<html lang="en"&gt; <head&gt; <meta charser="UTF-8"&gt; <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"&gt; <meta http-equiv="x-ua-compatible" content="ie=edge"&gt; <title&gt;Document</title&gt; <link rel="stylesheet" href="css/bootstrap.min.css"&gt; <link rel="stylesheet" href="css/font-awesome.min.css"&gt; <link rel="stylesheet" href="css/estilos.css"&gt; <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"&gt; <script src="js/jquery.js"&gt;</script&gt; <script src="~/js/bootstrap.min.js"&gt;</script&gt; <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"&gt;</script&gt; <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"&gt;</script&gt; </head&gt; <body&gt; <header&gt; </header&gt; <div class="jumbotron boxlogin"&gt; <form method="post" name="flogin" id="flogin" action="" &gt; <label&gt;Usuario:</label&gt; <input type="text" name="username" class="form-control"&gt; <label&gt;Contraseña:</label&gt; <input type="password" name="password" class="form-control"&gt; <button name="btnClickI" type="button" class="btn btn-success" data-toggle="modal" data-target="#ingreso"&gt;Ingresar</button&gt; <a href="registro.php"&gt;<button value="btnClickR" type="button" class="btn btn-info"&gt;Registrar</button&gt;</a&gt; <?php if(!isset($_POST['btnClickI'])){ $username=isset($_POST['username'])?var_dump($_POST['username']):NULL; $password=isset($_POST['password'])?var_dump($_POST['password']):NULL; if( $username==NULL or $password==NULL ) { echo '<div id="ingreso" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"&gt; <div class="modal-diolag"&gt; <div class="modal-content"&gt; <div class="modal-header"&gt; <button type="button" class="close" data-dismiss="modal" aria-hidden="true"&gt;&amp;times;</button&gt; </div&gt; <div class="modal-body"&gt; <h3&gt;Por favor llenar todo los campos!</h3&gt; </div&gt; </div&gt; </div&gt; </div&gt;'; }else{ echo '<div id="ingreso" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"&gt; <div class="modal-diolag"&gt; <div class="modal-content"&gt; <div class="modal-header"&gt; <button type="button" class="close" data-dismiss="modal" aria-hidden="true"&gt;&amp;times;</button&gt; </div&gt; <div class="modal-body"&gt; <h3&gt;Enviando datos!...</h3&gt; </div&gt; </div&gt; </div&gt; </div&gt;'; } } ?&gt; </form&gt; </div&gt; <script type="http://code.jquery.com/jquery-latest.js"&gt;</script&gt; <script src="js/bootstrap.min.js"&gt;</script&gt; </body&gt; </html&gt;``` Comment: Vas a tener que modificar el código. Puedes enviar el formulario por AJAX, o puedes enviarlo directamente contra si mismo, en ambos casos tendrás que modificar el código.El form necesita un action, y el botón de enviar tiene que ser de tipo submit, ya que si no no ejecuta el evento de envío. Si modificas el action del form y el tipo de botón, verás que te enviará el formulario y post quedará relleno, pero no se ejecutará el modal con la respuesta, puesto que dicho modal se ejecuta en el click. Deberías modificarlo para que el evento del modal se ejecute si hay post, no al hacer click. Comment: Podrías indicarnos qué te imprime `print_r($_POST);`? Ponlo justo antes de `if(!isset($_POST['btnClickI'])){` y envía el formulario. Comment: Solo cámbiale en el boton 'value' por 'name' Here is another answer: Intenta cambiar tu condición de entrada ```if(!isset($_POST['btnClickI'])) ``` Ya que va a pasar cuando no tenga valor o no se halla declarado el $_POST['btnClickI'] es decir cuando no se ha enviado nada a traves del formulario, por tanto todo esfuerzo por obtener los campos del mismo después de esta condición van a ser en valde, dejala en positivo ```if(isset($_POST['btnClickI'])) ``` Y ya luego me dices como te fue. Saludos
Title: UIPickerview in iphone Tags: iphone-sdk-3.0;xcode3.2 Question: How to reduce the size of UIPickerview in a subView? I am reducing the CGRectMake(120, 20, 60,25). But it appears in the normal size. What i do now? Some One help me. Thanks in Advance. Here is another answer: Use the delegate method below ```- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component ``` This will resolve the issue.You can also refer the same from apple documentation. Cheers Aditya
Title: SignalR and application insights showing absurd server response times Tags: c#;asp.net-core;signalr;azure-application-insights Question: We are using SignalR in a production application deployed as an Azure Web App. We use application insights to track performance, but there is a problem. When a user opens a connection through WebSocket protocol, application insights is tracking the duration of the connection and is showing server response times of more than an hour when a user is connected for that duration. Is there something that we should configure to get a more accurate reading? Comment: My initial guess is that the Application Insights shows the server response time based on when the application closes the connection. For WebSockets, that isn't ideal. Side question, how are you using Websockets with your Azure Web App? By enabling Websockets in the portal or using the SignalR service? Comment: This seems relevant: https://github.com/microsoft/ApplicationInsights-dotnet/issues/1379. Maybe file an issue on the ApplicationInsights repo? Comment: Agreed it isn't ideal, but it's the best I see right now. Another feedback thread on the same matter here: https://feedback.azure.com/forums/357324-azure-monitor-application-insights/suggestions/8395065-server-response-time-needs-to-ignore-signalr. Comment: Right, so far that's what I thought as well. But there must be a way to configure this in a way that changes this behavior. Or at least, I feel there should be. And to answer your question, we aren't using the SignalR service. The load isn't high enough to justify using that, there isn't any scaling requirement. Comment: Thanks for that! But I'm not sure excluding it all together is the way to go.
Title: Search a file and open its folder vim Tags: vim;vim-plugin Question: I am using silver searcher in vim. A lot of times I want to search a file BUT open its folder (to see the other files that are there). How can I do it? Here is the accepted answer: Unless you have a very specific workflow that you didn't disclose, ```ag``` is a red herring, here. You can open the built-in file explorer in the parent directory of the current file with: ```:Ex ``` You can also do: ```:e %:h ``` because of the way Vim falls back to Netrw when you ask it to edit a directory. See ```:help :Explore``` and its variants, as well as ```:help filename-modifiers``` for the ```:h``` bit.
Title: The entire process of using xorg-edgers ppa? Tags: drivers;nvidia;xorg-edgers Question: Proprietary drivers apparently generally outperform open-source Nouveau drivers. The stable packages offered by default repositories seem to be too behind the latest stable ones available from the website (which need time to be tested/packaged specifically for Ubuntu). My question is, are these drivers reliable/safe to use? If proprietary drivers are better than Nouveau drivers, are the latest stable drivers for Linux from the website better than one the ones packaged specifically for Ubuntu which are behind by a few versions but which are tested for the OS? If I am to use xorg-edgers PPA, I read that I need to disable the PPA right after installing the driver because it will continue pulling driver updates that could mess up with your trackpad, etc. Why does it do this (since a PPA is just a third-party repository--why does it do something a default repository wouldn't do)? If I were to update the driver next time, I would just re-enable the PPA, install the driver, and disable the PPA? Lastly, can someone explain this (under "Importance Notice" to me: https://launchpad.net/~xorg-edgers/+archive/ubuntu/ppa? It warns that users shouldn't install individual packages from it but isn't that what people are doing via the process I described above? Also, what does this "Please use ppa-purge to remove this PPA. It is particularly recommended to do this before upgrading to a new ubuntu release!" warning mean/entail? Comment: I learned nothing from that comment. Comment: "since a PPA is just a third-party repository--why does it do something a default repository wouldn't do" Because it's a Third Party repository, not a default/official one. Here is the accepted answer: Now, before you go ahead, please note that one of the few vectors for getting malware onto your computer is a PPA, so never install a PPA because someone tells you so (including me). Always use your own personal judgement and do some research before installing a PPA! Having said that, a PPA with 1000s of users mentioned in numerous articles is always better then installing ```ppa:maffia.it/BotNet``` with a few 100 users! ;-) Having said that, I've been running with the xorg-edgers ppa for more then a year now and I get automatic updates from them, so I don't worry about installing and removing the PPA (don't know where you got that notion from). If for some or other reason you would like to hold packages, just do so. What the warning is all about is that you should not download individual ```.deb``` files from the xorg-edgers repository as they are not designed to be used that way as the ```.deb``` files have dependencies among them and have not been tested outside of the PPA. Installing individual ```.deb``` files is a bad idea anyway if you have other means of installing software …
Title: Tensorflow Modules in Jupiter Notebooks (using OSX) Tags: python;tensorflow Question: I am having trouble getting tensorflow to work using Jupiter notebooks. I am a complete noob so please keep responses as simple as possible and apologies if this is trivial. I run the following code in the notebook: ```import tensorflow as tf from tensorflow.python.framework import ops ``` And get this error message: ```ModuleNotFoundError Traceback (most recent call last) <ipython-input-15-509396287076&gt; in <module&gt;() 1 2 import tensorflow as tf ----&gt; 3 from tensorflow.python.framework import ops 4 from tf_utils import load_dataset, random_mini_batches, convert_to_one_hot, predict 5 ModuleNotFoundError: No module named 'tensorflow.python' ``` (I originally struggled to get the "import tensorflow as tf" line to work but have resolved that. The code runs fine without the second line...) Thanks for your help! Comment: Oh great! Thank you - I wasn't aware of how that worked. Sorry if it seemed like a daft question! Comment: why do you want ops? You already imported tensorflow as tf. Now you can access all tensorflow related functions with tf.
Title: How to skip nested navigator's initial route? Tags: react-native;react-navigation Question: I have a navigation like so: ```Loading: SwitchNavigator { Auth: Stacknavigator, Main: StackNavigator, Onboard: StackNavigator, } ``` every one of ```StackNavigator```s has an initial route set. Under certain circumstances, I want to go from ```loading``` navigator to a specific route on ```onboard``` navigator. If I use just ```navigator.navigate('DesiredRoute')```, it squeezes in also onboard's ```initialRoute```, so the navstack looks like ```[InitialRoute, DesiredRoute]``` instead of ```[DesiredRoute]```. How to get rid of the ```InitialRoute```? Code example: ```// Loading.js if (loadingComplete) { if (!user) { navigation.navigate('auth') return } if (user &amp;&amp; userData) { navigation.navigate('Main') return } if (onboardingCheckpointCleared) { // this creates `['InitialRoute', 'DesiredRoute']` instead of `['DesiredRoute']` navigation.navigate('DesiredRoute') return } navigation.navigate('Onboard') } ``` Comment: I haven't tested myself with all the latest packages, but supposing that what you wrote is correct, how is this a problem? What are you trying to do? This does look a lot like a issue that could be solved elsewhere Here is another answer: I assume you are navigating to ```DesiredRoute``` from outside the ```Onboard``` stack navigator If you're outside the ```Onboard``` navigator, doing ```navigation.navigate('DesiredRoute')``` will trigger two actions: first, it will navigate to the ```Onboard``` stack navigator (so it will also activate the default sub screen of it ```InitialRoute``` like you call it) and then it will push the ```DesiredRoute```. If you want to go to ```Onboard``` with only ```DesiredRoute``` on the stack, you can use the sub actions of the navigation actions like this: ```navigation.navigate('Onboard', undefined, StackActions.replace('DesiredRoute')); ``` The third argument is an action that can be will be executed by the first argument navigator (if the first argument is not a screen but a navigator). Here it will navigate to the ```Onboard``` navigator and thus put the ```InitialRoute``` in the stack (automatically as it's the initialRoute of ```Onboard```). However, the ```StackAction.replace('DesiredRoute')``` will be executed by the ```Onboard``` navigator and will replace ```InitialRoute``` with ```DesiredRoute```. See the official doc about the navigate: https://reactnavigation.org/docs/en/navigation-prop.html#navigate-link-to-other-screens Here is another answer: I ended up creating a custom router that strips out the initial route when navigating to my nested stack: ```const MyStackNav = createStackNavigator({ ...routes }) const defaultGetStateForAction = MyStackNav.router.getStateForAction const customGetStateForAction = (action, state) =&gt; { const defaultNavState = defaultGetStateForAction(action, state) // If we're pushing onto a stack that only has a defaulted initialRoute if ( !!defaultNavState &amp;&amp; !defaultNavState.routeName &amp;&amp; defaultNavState.isTransitioning &amp;&amp; defaultNavState.index === 1 &amp;&amp; action.type === NavigationActions.NAVIGATE ) { const newState = { ...defaultNavState, index: 0, // Decrement index routes: defaultNavState.routes.slice(1), // Remove initial route } return newState } return defaultNavState } ``` Here is another answer: This is expected behavior, if you want only ```DesiredRoute``` to appear then you have to set that route in ```Loading``` as well like below, ```Loading: SwitchNavigator { Auth: Stacknavigator, Main: StackNavigator, Onboard: StackNavigator, DesiredRoute: ScreenName } ``` Writing like this will not create any clash, you are safe to write. Comment for this answer: @Zygro do you have any concerns with this answer or any other requirements?
Title: Transferring state before removal from load balancer (AWS) Tags: amazon-web-services;amazon-ec2;autoscaling Question: I have an application that maintains state where it is not practical to store the state on every state change. When an AWS Auto Scaling group initiates a scale-in my plan was to then "transfer" the state to either disk or a memory grid. I assumed using the Lifecycle Hooks I'd be able to tell the node it was going to be removed and then initiate that transfer. However, it appears the hooks let me know AFTER the node is removed from the load balancer but before the instance is destroyed. I'd like to be able to hook before the load balancer removes the node. Is anyone aware of a way to do that? Comment: Hi, can you elaborate on why it's important to know *before* ELB de-registers the instance? Is there a lengthy delay between that and the terminating lifecycle notification? Comment: Not aware of an obvious solution here. Presumably it's not trivial for you to go fully stateless (https://gist.github.com/mlconnor/b8f2c2a8cb1a5ce25d66). Comment: Lets say a user is connected to server A (session is local to A) - when the load balancer de-registers A the next request from the user will go to server B but the session will not have been transferred or shared yet. On the other hand if we got a pre-de-registering hook, we could move the session to disk or distributed memory thus guaranteeing the session information is available to server B for the next request. Comment: I dont think it is. Our general issue is that the size of the session (and related in memory objects) is measured in multiple megabytes not kilobytes.
Title: umbracoFile property empty Tags: razor;umbraco Question: I manage to successfully upgrade Umbraco from 4.0.3 to 4.11.10. I have 100's of xslt files in the older version and in umbracoSettings.config file I have used "UseLegacyXmlSchema" to be true. Every thing is working except when I wrote a simple razor macro below and noticed @photo.umbracoFile is always null or empty. I found this article http://allan-laustsen.blogspot.co.uk/2012/04/umbraco-razor-dynamicmedia-umbracofile.html but the solution is a bit confusing. I wonder if any one can help on this? ```@using umbraco.MacroEngines @inherits umbraco.MacroEngines.DynamicNodeContext @{ //Check the currentpage has a value in the property 'photos' if (Model.HasValue("sliderImages")) { var MediaFolder = Library.MediaById(Model.sliderImages); <ul&gt; @foreach (var photo in MediaFolder.Children) { <li &gt; <img src="@photo.umbracoFile" alt="@photo.Name" /&gt; </li&gt; } </ul&gt; } ``` } Comment: This has occurred to me occasionally and usually it was a problem with Examine. Re-saving the media files was what fixed it for me. Usually I write a script that iterates through them and saves them. Here is another answer: Up to version 4.7 (I think), each rendering of a ```Media``` item made a call to the database. The model changed to indexing all media into the Lucene indexes much in the same way that content nodes are, and then each rendering of an image just made a call to the index. This of course made it substantially faster. During the upgrade the media files were probably not indexed. The content will already have been indexed so this wouldn't have been an issue. So, the solution would just be to republished the entire site. This will ensure that any images referenced by the content are indexed. Comment for this answer: Thanks for the Comment. I tried the following to republish but it does not seem to make any difference. Comment for this answer: AFAIK that only republishes the content nodes and doesn't include the media nodes. Here is another answer: I know this is old, but since I just ran into this exact issue I thought I'd add that to republish media nodes, the only thing I've found to work is to sort and save a given parent node, republishing the whole site seems to only republish content nodes. I sort the parent media directory of the files that are experiencing this issue alphabetically and then save the new order - this allows references to .umbracoFile in razor again (i.e. the property on the affected files is no longer empty, but instead contains the path as expected). In my case ```<UseLegacyXmlSchema&gt;``` was already set to false and rebuilding the indexes did not work either. Comment for this answer: Thanks SO MUCH for this solution! I just had to do this on EVERY FOLDER in our media tree. There were a lot of folders. I am now mad about this. Is this bug logged do you know?
Title: How do I retain the contents of a EditText in MainActivity when I proceed to a child activity and return back to MainActivity? Tags: android;android-intent Question: I'm trying to retain the contents of EditText in MainActivity when I return back to MainActivity after proceeding to its child activity. In MainActivity i have two EditText fields, one stores first name other stores last name and a Button which when clicked invokes the newActivity() method. Then in the SecondActivity which is a Child of MainActivity the first as well as the last name is displayed but when I go bact to MainActivity the contents of EditText fields are not retained. Below is the code I have written in MainActivity.java and SecondActivity.java ``` /************ MainActivity.java *************/ public class MainActivity extends ActionBarActivity { private EditText firstNameField ; private EditText lastNameField ; private String firstName, lastName; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); firstNameField = (EditText) findViewById(R.id.firstNameField); lastNameField = (EditText) findViewById(R.id.lastNameField); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } public void newActivity(View view) { firstName = String.valueOf(firstNameField.getText()); lastName = String.valueOf(lastNameField.getText()); Intent secondActivity = new Intent(this, SecondActivity.class); secondActivity.putExtra("First name", firstName); secondActivity.putExtra("Last Name", lastName); secondActivity.putExtra("Last name", lastName); startActivity(secondActivity); } @Override public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) { outState.putString(FIRST_NAME_KEY, firstName); outState.putString(LAST_NAME_KEY, lastName); super.onSaveInstanceState(outState, outPersistentState); } public void onRestoreInstanceState(Bundle savedInstanceState) { // Always call the superclass so it can restore the view hierarchy super.onRestoreInstanceState(savedInstanceState); // Restore state members from saved instance firstName = String.valueOf(savedInstanceState.getString(FIRST_NAME_KEY)); lastName = String.valueOf(savedInstanceState.getString(LAST_NAME_KEY)); firstNameField.setText(""+firstName); lastNameField.setText(""+lastName); } } /************** SecondActivity.java ***********/ public class SecondActivity extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.second_activity); String fname = String.valueOf(getIntent().getStringExtra("First name")); String lname = String.valueOf(getIntent().getStringExtra("Last name")); EditText firstNameEdt = (EditText) findViewById(R.id.firstNameEdt); EditText lastNameEdt = (EditText) findViewById(R.id.lastNameEdt); firstNameEdt.setText(""+ fname); lastNameEdt.setText("" + lname); } } ``` Comment: I just posted u an answer please try it. Here is another answer: You can save the values of your edittexts in ```SharedPreferences```. There you can save values persistent with a defined key. You would want to save the values in ```onDestroy``` of your MainActivity retrieve your values in ```onCreate```. Here you can read how to use ```SharedPreferences```: Saving Key-Value Sets Comment for this answer: Thanks a lot for your response.. Its late in my country right now so i'll try it tomorrow and let you know if it worked out Comment for this answer: okay I went as per the Recreating Activity documentation on Android developer site. http://developer.android.com/training/basics/activity-lifecycle/recreating.html It says by using onSaveInstanceState() method and onRecreateActivityMethod() i should be able to achieve the functionality I want. But why it isn't working in my case ? Here is another answer: For a simple method, if you can bring the contents to the second activity, why don't you just do the same as you go back to the 1st activity. Use bundle going back to the 1st activity then set it as a Text Here is another answer: Most UI widgets take care of propagating their own state between activity instances. If you comment out your ```onSaveInstanceState``` and ```onRestoreInstanceState``` methods, it'll probably just work. You only need to implement those methods if your activity has its own state separate from the UI. Comment for this answer: Can you give an example ? I am a beginner so its difficult for me to understand what case you're talking about. Comment for this answer: I went as per the Recreating Activity documentation on Android developer site. http://developer.android.com/training/basics/activity-lifecycle/recreating.html It says by using onSaveInstanceState() method and onRecreateActivityMethod() i should be able to achieve the functionality I want. But why it isn't working in my case ? Comment for this answer: your method didn't work as well. Commenting out both methods didn't make any difference
Title: Django absolute __in query Tags: django Question: I have a list of UUIDs that represent users in a DB table. I want to fetch all the users that match this criteria so I use the ```__in``` filter: ```users = User.objects.filter(user__in=uuids) ``` I would like to raise an exception if not all of the UUIDs appear in the table. In other words, I expect to get a result back for each uuid such that ```len(users) == len(uuids)```. Is there an easy Django way to do it? If not, is there an easy way for me to create this behavior? Comment: Why not perform this check (with for example `assert len(users) == len(uuids)`? Comment: @WillemVanOnsem - That's what I'm doing, but I'd prefer to have the code look a bit more elegant as this repeats itself so many times. Here is another answer: You could use exclude if you like it gives you the objects that does not match the query ```#this returns true if one or more and dont need to use len() #if it looks better for you you can try it out #if everything is fine will return None if User.objects.filter().exclude(user__in=uiids).first(): raise your_error ``` Here is another answer: Don't think too complicated. You want to know if a list of something is fully contained in another list of something, that's just plain python: ```user_ids = User.objects.values_list('user_id',flat=True) if not set(uuids).issubset(user_ids): # or use .difference() to get the uuids missing from user_ids raise stuff ```
Title: Paying credits after a failled spacemission Tags: star-wars-the-old-republic Question: When you start a spacemission you have to pay some credits to go to the destination. If I die during a spacemission and I press the button "retry mission". Do I have to pay that money again, or can I try the mission again without paying the credits? Here is the accepted answer: "Retry mission" is free, but if you back out and try the same mission again you'll need to pay again (since the game keeps you at the last planet you were at).
Title: c# how to make matching cards stay turned on grid? (memory game) Tags: c#;wpf Question: I have a problem with my matching/memory game that i'm making for a school project. I want two of the same cards to stay after they're clicked, and when two different cards are clicked they will return to the backside image of the card. I'm a total beginner so if someone could explain this in a really easy way to me, that would help me a lot. Currently i'm stuck on this. This is my code thus far for loading the images from a list and placing them on the grid: ```private void AddImage() { List<ImageSource&gt; images = GetImagesList(); Random random = new Random(); for (int row = 0; row < rows; row++) { for (int col = 0; col < cols; col++) { Image ImageOnBacksideOfCard = new Image(); ImageOnBacksideOfCard.Source = new BitmapImage(new Uri("project/achterkant.png", UriKind.Relative)); //Ruimte tussen kaartjes Thickness margin = ImageOnBacksideOfCard.Margin; margin.Top = 10; ImageOnBacksideOfCard.Margin = margin; ImageOnBacksideOfCard.MouseDown += new MouseButtonEventHandler(CardClick); //Randomize positie1 = random.Next(images.Count); ImageOnBacksideOfCard.Tag = images[positie1]; images.RemoveAt(positie1); Grid.SetColumn(ImageOnBacksideOfCard, col); Grid.SetRow(ImageOnBacksideOfCard, row); grid.Children.Add(ImageOnBacksideOfCard); } } //Load pictures private List<ImageSource&gt; GetImagesList() { List<ImageSource&gt; images = new List<ImageSource&gt;(); for (int i = 0; i < 16; i++) { int imageNr = i % 8 + 1; ImageSource source = new BitmapImage(new Uri("project/" + imageNr + ".jpg", UriKind.Relative)); images.Add(source); } return images; } //Cards turn on click private void CardClick(object sender, MouseButtonEventArgs e) { Image card = (Image)sender; ImageSource front = (ImageSource)card.Tag; card.Source = front; } //Reset public void Reset() { grid.Children.Clear(); AddImage(); } ``` Comment: https://github.com/Tosker/MemoryGame see, how other people do it and then write your own. Comment: Putting aside the fact that this is code behind and not MVVM, from the code you provided all I see is the initial grid generation and no attempt at solving the issue. Do you have some more code (mouse click events turning a card over, dictionary keeping track of which cards have been turned, comparison function determining whether the cards are a match) where you can specify what exactly your problem is, or do you need general guidelines to how to approach implementing such an application? Comment: WPF/UWP and XAML were designed with the MVVM pattern in mind. While you can use other approaches, doing so misses about 90% of it's power and runs into problems at every other turn. That does not look remotely like MVVM. If it was MVVM, you had a randomized array of elements. And each of them had a boolean "revealed" property. They would also have a Command "Reveal", wich would flip that bool. And the bool would stay on true if all the cards of that group ahve been "matched". The game ends when all card groupds are matched or all cards are revealed (depending on wich you prefer).
Title: undefined method `desc' for Sinatr181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16Application:Class Tags: ruby;sinatra;rake Question: This is the error I get when I run any ```rake``` command: ```undefined method 'desc' for Sinatr181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16Application:Class``` ```# app.rb require 'sinatra' require 'sinatra/activerecord' require 'sinatra/contrib' get '/' do puts "Hello World" end # config.ru require "./app" run Sinatr181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16Application # Rakefile require './app' require 'sinatra/activerecord/rake' # Gemfile source 'https://rubygems.org' ruby '2.0.0' gem 'activerecord', '~&gt; 4.0.2' gem 'sinatra', '~&gt; 1.4.4' gem 'sinatra-activerecord', '~&gt; 1.2.3' gem 'sinatra-contrib', '~&gt; 1.4.2' ``` Full trace: ```/Users/j/.rvm/gems/ruby-2.0.0-p247/gems/sinatra-contrib-1.4.2/lib/sinatra/namespace.rb:269:in `method_missing' /Users/j/.rvm/gems/ruby-2.0.0-p247/gems/sinatra-activerecord-1.2.3/lib/sinatra/activerecord/tasks.rake:4:in `block in <top (required)&gt;' /Users/j/.rvm/gems/ruby-2.0.0-p247/gems/sinatra-contrib-1.4.2/lib/sinatra/namespace.rb:126:in `class_eval' /Users/j/.rvm/gems/ruby-2.0.0-p247/gems/sinatra-contrib-1.4.2/lib/sinatra/namespace.rb:126:in `block in new' /Users/j/.rvm/gems/ruby-2.0.0-p247/gems/sinatra-contrib-1.4.2/lib/sinatra/namespace.rb:118:in `initialize' /Users/j/.rvm/gems/ruby-2.0.0-p247/gems/sinatra-contrib-1.4.2/lib/sinatra/namespace.rb:118:in `new' /Users/j/.rvm/gems/ruby-2.0.0-p247/gems/sinatra-contrib-1.4.2/lib/sinatra/namespace.rb:118:in `new' /Users/j/.rvm/gems/ruby-2.0.0-p247/gems/sinatra-contrib-1.4.2/lib/sinatra/namespace.rb:142:in `namespace' /Users/j/.rvm/gems/ruby-2.0.0-p247/gems/sinatra-1.4.4/lib/sinatra/base.rb:1972:in `block (2 levels) in delegate' /Users/j/.rvm/gems/ruby-2.0.0-p247/gems/sinatra-activerecord-1.2.3/lib/sinatra/activerecord/tasks.rake:3:in `<top (required)&gt;' /Users/j/.rvm/gems/ruby-2.0.0-p247/gems/activesupport-4.0.2/lib/active_support/dependencies.rb:223:in `load' /Users/j/.rvm/gems/ruby-2.0.0-p247/gems/activesupport-4.0.2/lib/active_support/dependencies.rb:223:in `block in load' /Users/j/.rvm/gems/ruby-2.0.0-p247/gems/activesupport-4.0.2/lib/active_support/dependencies.rb:214:in `load_dependency' /Users/j/.rvm/gems/ruby-2.0.0-p247/gems/activesupport-4.0.2/lib/active_support/dependencies.rb:223:in `load' /Users/j/.rvm/gems/ruby-2.0.0-p247/gems/sinatra-activerecord-1.2.3/lib/sinatra/activerecord/rake.rb:77:in `<top (required)&gt;' /Users/j/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/site_ruby/2.0.0/rubygems/core_ext/kernel_require.rb:51:in `require' /Users/j/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/site_ruby/2.0.0/rubygems/core_ext/kernel_require.rb:51:in `require' /Users/j/.rvm/gems/ruby-2.0.0-p247/gems/backports-3.3.5/lib/backports/tools.rb:328:in `require_with_backports' /Users/j/.rvm/gems/ruby-2.0.0-p247/gems/activesupport-4.0.2/lib/active_support/dependencies.rb:229:in `block in require' /Users/j/.rvm/gems/ruby-2.0.0-p247/gems/activesupport-4.0.2/lib/active_support/dependencies.rb:214:in `load_dependency' /Users/j/.rvm/gems/ruby-2.0.0-p247/gems/activesupport-4.0.2/lib/active_support/dependencies.rb:229:in `require' /Users/j/Desktop/app/Rakefile:2:in `<top (required)&gt;' /Users/j/.rvm/gems/ruby-2.0.0-p247@global/gems/rake-10.1.0/lib/rake/rake_module.rb:25:in `load' /Users/j/.rvm/gems/ruby-2.0.0-p247@global/gems/rake-10.1.0/lib/rake/rake_module.rb:25:in `load_rakefile' /Users/j/.rvm/gems/ruby-2.0.0-p247@global/gems/rake-10.1.0/lib/rake/application.rb:637:in `raw_load_rakefile' /Users/j/.rvm/gems/ruby-2.0.0-p247@global/gems/rake-10.1.0/lib/rake/application.rb:94:in `block in load_rakefile' /Users/j/.rvm/gems/ruby-2.0.0-p247@global/gems/rake-10.1.0/lib/rake/application.rb:165:in `standard_exception_handling' /Users/j/.rvm/gems/ruby-2.0.0-p247@global/gems/rake-10.1.0/lib/rake/application.rb:93:in `load_rakefile' /Users/j/.rvm/gems/ruby-2.0.0-p247@global/gems/rake-10.1.0/lib/rake/application.rb:77:in `block in run' /Users/j/.rvm/gems/ruby-2.0.0-p247@global/gems/rake-10.1.0/lib/rake/application.rb:165:in `standard_exception_handling' /Users/j/.rvm/gems/ruby-2.0.0-p247@global/gems/rake-10.1.0/lib/rake/application.rb:75:in `run' /Users/j/.rvm/gems/ruby-2.0.0-p247@global/gems/rake-10.1.0/bin/rake:33:in `<top (required)&gt;' /Users/j/.rvm/gems/ruby-2.0.0-p247@global/bin/rake:23:in `load' /Users/j/.rvm/gems/ruby-2.0.0-p247@global/bin/rake:23:in `<main&gt;' /Users/j/.rvm/gems/ruby-2.0.0-p247/bin/ruby_executable_hooks:15:in `eval' /Users/j/.rvm/gems/ruby-2.0.0-p247/bin/ruby_executable_hooks:15:in `<main&gt;' ``` Comment: Where does the backtrace point? Comment: Added the backtrace and Gemfile. Comment: and what's in ./app ? Comment: see also: https://stackoverflow.com/questions/30656858/undefined-method-namespace-for-mainobject-nomethoderror-active-record-r/66110634#66110634 Here is the accepted answer: The Sinatra namespace extension from Sinatra contrib is interfering with Rake’s own namespace support. They both define a ```namespace``` method, and the Sinatra contrib version is being called (incorrectly) from the Sinatra-ActiveRecord Rake tasks. If you’re not using the namespaces from Sinatra-contrib, then the easiest solution would be to only require those extensions that you need; e.g. change ```require 'sinatra/contrib' ``` to ```require 'sinatra/whatever' require 'sinatra/anotherextension' ``` If you are using Sinatra namespaces then I think you may be able to get round this by moving to a modular style app. Change your ```app.rb``` to something like ```require 'sinatra/base' # note this has changed from just 'sinatra' require 'sinatra/activerecord' require 'sinatra/contrib' class MyApp < Sinatr181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16Base register Sinatr181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16Contrib get '/' do "Hello World" end # other routes etc. as needed end ``` Then in your ```config.ru``` you need ```run MyApp``` rather then ```run Sinatr181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16Application``` (of course you can – and should – give your class a better name). This avoids the collision of the two ```namespace``` methods, since the Sinatra version is only available in your application class, not the top level. Comment for this answer: I was running a modular app, but forgot the `sinatra/base` specific require. Thanks, saved me! Here is another answer: Found an easiest solution: Juste add the require:false attribute to sinatra contrib in your gemfile: ```gem "sinatra-contrib",require: false ``` Found this here: http://aaronlerch.github.io/blog/sinatra-bundler-and-the-global-namespace/ Comment for this answer: I am using Sinatra to mock an external API for tests in a Rails app, and had the same problem with `sinatra` and `sinatra-contrib` being required globally, by default, from my Gemfile. This does fix it! Thanks :)
Title: I'm able to edit my deleted question, but I cannot look at it Tags: bug;status-bydesign;deleted-questions Question: I'm able to edit my deleted question but I cannot look at it nor undelete it. After pressing the Save my Edits button I'm redirected to a 404 page, but by reloading the edit page I'm able to see my the new revision. Here's the edit link, that I can use to edit it. How did I get that edit link? Simple: I deleted the question and pressed the edit link thinking that I could undelete it later. (Which I can't… well, maybe I could using the correct link.) Comment: A better link is: http://meta.stackexchange.com/questions/34151/ Comment: Delicious waffles ... Comment: I actually had it like this some time… Here is another answer: Yeah, the delete-edit-undelete technique only works for answers (unless you have a reputation >= 10K or are a moderator). At one time, you could close your question while you edited it and then re-open it when you were done... but that's no longer possible either. There are other restrictions on deleting questions that make this an inflexible practice, even if you do have the rep to pull it off in some instances. It's probably best to just consider a deleted question gone and post your edits as a new question (which I see you've done). Here is another answer: Here you go. Paste following on URL bar on current post (apparently any different post) to undelete that post. ```javascript:$.post("/posts/34151/vote/11",{fkey:fkey}) ``` I've tested on this question, only 10k+ users can see
Title: Adding Records from a pop-up query to a subform within the main form using VBA, Access 2010 Tags: ms-access;vba;ms-access-2010 Question: I have a main ```Purchase_Orders``` Form with an ```Items``` subform. I have also created a button that opens a popup form and queries previous Purchase orders for ```items``` that have been purchased from the same ```supplier``` which has been selected on the main form. I have added an unbound checkbox to this popup query. Now what I want to be able to do, is have an "assign" button that will select each record in the query where the checkbox = true (or 1 I'm not sure). And then input those records in to the main subform, ```Items```. Is this possible? and any ideas how I may go about coding this in VBA? I am pretty new to VBA but if I get anywhere with the code, I will edit this post with further info. Thanks! Here is another answer: If you want to add multiple items at once then you will need to use some form of unbound control, and a VBA loop to insert. The simplest way would be to load a multi-select enabled ListBox and use that to allow the user to choose items. Then upon clicking the ```Assign``` button, you can loop through the listbox and insert the items into the table. If you want more specific help you're going to need to provide much more specific data. Table structures, form fields/data sources, form names, perhaps some VBA behind the forms.
Title: Tesseract OCR.init() makes the code to exit in Sharepoint website Tags: sharepoint;ocr;tesseract;tessnet2 Question: We are using Tesseract OCR (tessnet2 dll) for converting image to text which is working fine in Console Application. But, when we host the same in sharepoint, the application [email protected](). In few posts, it is mentioned that the tessdata folder should be under bin/debug. But, for sharepoint site, where I need to keep tessdata folder? Thanks in Advance Here is another answer: I am not familiar with tessnet2 wrapper, but tesseract API allows you to specify datapath (there are relevant call also in C-API). Tesseract wrote error message to console, so it would be useful to catch error reason. You can try to set variable ```debug_file``` to redirect it to file, but I am not sure if it will be working before init...
Title: GCP App Engine unable to serve resource files like JavaScript Tags: google-app-engine;.net-core Question: I have hosted my dotnetcore 2.0 app on GCP App Engine with my ```app.yaml``` as follows. ```runtime: aspnetcore env: flex manual_scaling: instances: 1 resources: cpu: 1 memory_gb: 0.5 disk_size_gb: 10 endpoints_api_service: name: *********** rollout_strategy: managed ``` My API's work fine, but when I try to load a ```cshtml``` view with resources pointing to ```wwwroot```, I get an error loading resources (ex: .js , .css) ```{ "code": 5, "message": "Method does not exist.", "details": [ { "@type": "type.googleapis.com/google.rpc.DebugInfo", "stackEntries": [], "detail": "service_control" } ] } ``` My purpose here is to have an dotnetcore app serving web API's as well as an Angular6 UI SPA. Comment: did you configured "app.UseDefaultFiles();" and "app.UseStaticFiles();" in Startup.cs? Any chance you can try running tutorial at [1]? Just to confirm nothing wrong with the app engine environment? [1] https://codelabs.developers.google.com/codelabs/cloud-app-engine-aspnetcore/#0
Title: XSL1.0 excluding previous nodes Tags: xslt-1.0 Question: I'm constrained to vanilla XSLT1.0 (no extensions) and MSXML transforms Completely stumped on a problem. I have an XML that I need to create HTML output from. Nodes need to be sorted by version_code then by despatch_tape_colour, BUT then grouped by address_line_1 (easier to look at image below to see: cream colored headings are group headers) ```<order&gt; <order_no&gt;16292</order_no&gt; <job_no&gt;16292</job_no&gt; <loads&gt; <LoadID&gt;10</LoadID&gt; <load_seq&gt;10</load_seq&gt; <load_address_1&gt;731 Fraser Street</load_address_1&gt; <load_haulier&gt;Purolator</load_haulier&gt; <load_splits&gt; <load_split_id&gt;10</load_split_id&gt; <load_split_description&gt;Prince Rupert Northern View</load_split_description&gt; <version_code&gt;Z1</version_code&gt; <despatch_tape_colour&gt;FLAT</despatch_tape_colour&gt; </load_splits&gt; </loads&gt; <loads&gt; <LoadID&gt;11</LoadID&gt; <load_seq&gt;11</load_seq&gt; <load_address_1&gt;8506 Main Street</load_address_1&gt; <load_haulier&gt;Purolator</load_haulier&gt; <load_splits&gt; <load_split_id&gt;11</load_split_id&gt; <load_split_description&gt;*</load_split_description&gt; <version_code&gt;Z1</version_code&gt; <despatch_tape_colour&gt;FLAT</despatch_tape_colour&gt; </load_splits&gt; </loads&gt; <loads&gt; <LoadID&gt;19</LoadID&gt; <load_seq&gt;19</load_seq&gt; <load_address_1&gt;130 - 766 Cliveden Place</load_address_1&gt; <load_haulier&gt;Purolator</load_haulier&gt; <load_splits&gt; <load_split_id&gt;19</load_split_id&gt; <load_split_description&gt;*</load_split_description&gt; <version_code&gt;Z1</version_code&gt; <despatch_tape_colour&gt;FLAT</despatch_tape_colour&gt; </load_splits&gt; </loads&gt; <loads&gt; <LoadID&gt;123</LoadID&gt; <load_seq&gt;123</load_seq&gt; <load_address_1&gt;100 Railway Avenue West</load_address_1&gt; <load_haulier&gt;Purolator</load_haulier&gt; <load_splits&gt; <load_split_id&gt;123</load_split_id&gt; <load_split_description&gt;*</load_split_description&gt; <version_code&gt;Z2</version_code&gt; <despatch_tape_colour&gt;FLAT</despatch_tape_colour&gt; </load_splits&gt; </loads&gt; <loads&gt; <LoadID&gt;124</LoadID&gt; <load_seq&gt;124</load_seq&gt; <load_address_1&gt;130 - 766 Cliveden Place</load_address_1&gt; <load_haulier&gt;Purolator</load_haulier&gt; <load_splits&gt; <load_split_id&gt;124</load_split_id&gt; <load_split_description&gt;*</load_split_description&gt; <version_code&gt;Z2</version_code&gt; <despatch_tape_colour&gt;FLAT</despatch_tape_colour&gt; </load_splits&gt; </loads&gt; </order&gt; ``` In the image below you can see that 19 and 124 are grouped together as they both have same address_line_1 (it's required that 19 appears in the order it does). The problem is that node 124 then appears later and is again grouped with 19. What I need to do is ignore load_split_ids that have already been iterated over or included in a previous group. The only other way I can think of (maybe :-)) solving it is to create and msxml nodeset and then iterate over that, but I'd like to see if there's an alternative method ```<?xml version="1.0" encoding="UTF-8"?&gt; <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format" xmlns:msxsl="urn:schemas-microsoft-com:xslt"&gt; <xsl:output method="html"/&gt; <xsl:variable name="template_version"&gt;586-325-3186</xsl:variable&gt; <xsl:variable name="template_date"&gt;7th August 2016</xsl:variable&gt; <!-- Based on Shipments v51.243.225.55 --&gt; <xsl:variable name="currency_symbol"/&gt; <xsl:key name="unique_load_addresses_version_format" match="/order/loads[starts-with(load_haulier, 'Purolator')]/load_splits" use="concat(../load_address_1,'_',version_code,'_',despatch_tape_colour)"/&gt; <xsl:include href="Globals_pdf.xsl"/&gt; <xsl:template match="order"&gt; <html&gt; <head&gt; <!-- PrinceXML: Adding UTF-8 stops browser interpreting &amp;#160; as A-circumflex followed by a <space&gt; --&gt; <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/&gt; <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-2"/&gt; <style type="text/css"&gt; body {font-family: Verdana, Arial, Helvetica, sans-serif; font-size:8pt;} h1 {font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 22pt; font-weight: bold; margin: 0 0 10px 0;} .outer { width: 100%; } .tax { width: 100%;} table {font-family: Verdana, Arial, Helvetica, sans-serif;cellspacing: 0px; cellpadding: 0px; border-width: 0; border-collapse: collapse; border-spacing: 0px; width: 100%; } td {vertical-align: top; font-family: Verdana, Arial, Helvetica, sans-serif; padding: 5px 1px 5px 1px; font-size: 8pt; border-width: 1pt; border-style: solid; border-color: <xsl:value-of select="$color2"/&gt;; } th {text-align: left; vertical-align: bottom; background-color: LightSteelBlue; font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 8pt; font-weight: normal; padding: 5px 1px 5px 1px; border-width: 1pt; border-style: solid; border-color: <xsl:value-of select="$color2"/&gt;; border-collapse: collapse; border-spacing: 0px; color: black;} .bold { font-weight: bold; } .grey {background-color: #dddddd; } .proforma { color: black; } .heading { vertical-align: bottom; text-align: center;} .bottom_center { vertical-align: bottom; text-align: center; } .top_center { vertical-align: top; text-align: center; } .top_left { vertical-align: top; text-align: left; } .middle_left { vertical-align: middle; text-align: left; } .middle_center { vertical-align: middle; text-align: center; } .top_right { vertical-align: top; text-align: right; } .bottom_left { vertical-align: bottom; text-align: left; } .bottom_right { vertical-align: bottom; text-align: right; } .left_indent {padding-left: 70px;} .top_indent {padding-top: 35px;} .label {font-weight: bold; width: 15%; padding-top: 2px; padding-bottom: 2px; padding-right: 5px; text-align: right; width: 30%; font-size: 12pt;} .contents {padding-left: 5mm; width: 30%; padding-top: 2px; padding-bottom: 2px; width: 70%; font-size: 12pt;} hr {border: none; background-color: black; height: 0.5pt;} .first_row { border-top: 2pt solid red; } .red {color: #aa0000; } </style&gt; </head&gt; <body&gt; <table class="loads" style=""&gt; <tr&gt; <th&gt;S/P/I</th&gt; <th&gt;Zone</th&gt; <th&gt;Format</th&gt; <th&gt;Address</th&gt; <th&gt;Carrier</th&gt; </tr&gt; <xsl:for-each select="/order/loads[starts-with(load_haulier, 'Purolator')]/load_splits[generate-id() = generate-id(key('unique_load_addresses_version_format', concat(../load_address_1,'_',version_code,'_',despatch_tape_colour))[1])]"&gt; <xsl:sort select="concat(version_code,'_',despatch_tape_colour)" data-type="text" /&gt; <xsl:variable name="curr_address" select="../load_address_1"/&gt; <tr&gt; <td style="background-color: #fdf5e6; color: blue; border-top: 2px solid grey"&gt;Load/LoadSplitID: <xsl:value-of select="../LoadID"/&gt;/<xsl:value-of select="load_split_id"/&gt;</td&gt; <td style="background-color: #fdf5e6; color: blue; border-top: 2px solid grey"&gt;<xsl:value-of select="version_code"/&gt;</td&gt; <td style="background-color: #fdf5e6; color: blue; border-top: 2px solid grey"&gt;<xsl:value-of select="despatch_tape_colour"/&gt;</td&gt; <td style="background-color: #fdf5e6; color: blue; border-top: 2px solid grey"&gt;<xsl:value-of select="../load_address_1"/&gt;</td&gt; <td style="background-color: #fdf5e6; color: blue; border-top: 2px solid grey"&gt;</td&gt; </tr&gt; <xsl:for-each select="/order/loads[starts-with(load_haulier, 'Purolator') and load_address_1 = $curr_address]/load_splits"&gt; <xsl:sort select="concat(version_code,'_',despatch_tape_colour)" data-type="text" order="ascending" /&gt; <xsl:variable name="part_ref" select="load_despatch_code"/&gt; <xsl:variable name="line_type"&gt; <xsl:choose&gt; <xsl:when test="position() = 1"&gt;S</xsl:when&gt; <xsl:otherwise&gt;P</xsl:otherwise&gt; </xsl:choose&gt; </xsl:variable&gt; <tr&gt; <td&gt; <xsl:attribute name="style"&gt; <xsl:choose&gt; <xsl:when test="position()=1"&gt;color: red; border-top: 2px solid black</xsl:when&gt; <xsl:when test="position()=last()"&gt;color: black;</xsl:when&gt; </xsl:choose&gt; </xsl:attribute&gt; <xsl:value-of select="load_split_id"/&gt; </td&gt; <td&gt; <xsl:attribute name="style"&gt; <xsl:choose&gt; <xsl:when test="position()=1"&gt;color: red; border-top: 2px solid black</xsl:when&gt; <xsl:when test="position()=last()"&gt;color: black;</xsl:when&gt; </xsl:choose&gt; </xsl:attribute&gt; <xsl:value-of select="version_code"/&gt; </td&gt; <td&gt; <xsl:attribute name="style"&gt; <xsl:choose&gt; <xsl:when test="position()=1"&gt;color: red; border-top: 2px solid black</xsl:when&gt; <xsl:when test="position()=last()"&gt;color: black;</xsl:when&gt; </xsl:choose&gt; </xsl:attribute&gt; <xsl:value-of select="despatch_tape_colour"/&gt; </td&gt; <td&gt; <xsl:attribute name="style"&gt; <xsl:choose&gt; <xsl:when test="position()=1"&gt;color: red; border-top: 2px solid black</xsl:when&gt; <xsl:when test="position()=last()"&gt;color: black;</xsl:when&gt; </xsl:choose&gt; </xsl:attribute&gt; <xsl:value-of select="../load_address_1"/&gt; </td&gt; <td&gt; <xsl:attribute name="style"&gt; <xsl:choose&gt; <xsl:when test="position()=1"&gt;color: red; border-top: 2px solid black</xsl:when&gt; <xsl:when test="position()=last()"&gt;color: black;</xsl:when&gt; </xsl:choose&gt; </xsl:attribute&gt; <xsl:value-of select="../load_haulier"/&gt; </td&gt; </tr&gt; </xsl:for-each&gt; </xsl:for-each&gt; </table&gt; </body&gt; </html&gt; </xsl:template&gt; ``` Any XSL wizards, got any suggestions? TIA Mark Comment: Could you (a) minimize the example to only what's necessary to demonstrate the problem and (b) explain the required logic in words? How would one accomplish this task manually? -- I am especially puzzled by your requirement to sort first, then group. Does that mean you want to group only within sorted groups? I don't see that in your output (as far as I can understand it).
Title: Problem with published Adobe Air Application Tags: xml;flash;actionscript-3;encoding;air Question: I have an Air Application (Adobe Flash CS4, Adobe AIR 1.1, ActionScript 3.0). I've published it as *.air file and installed it on my computer. It worked fine. But when I tried to use it on the other computer, I found the following problem: I installed AIR from http://get.adobe.com/ru/air/ I installed my Main.air and launched it. It can't parse XML file (pattern.xml) correctly. The code of my app is following: ```public class Main extends MovieClip { public function Main():void { this.stop(); var file:File = File.applicationDirectory.resolvePath("pattern.xml"); var fileStream = new FileStream(); fileStream.open(file, FileMode.READ); var str:String = fileStream.readUTFBytes(fileStream.bytesAvailable); str=str.substr(1); var panoramaPattern=new XML(str); fileStream.close(); } } ``` I tried to comment a several commands in Main(). So, code works without ```var panoramaPattern=new XML(str); ``` What is wrong with this command? pattern.xml was included into "Included files". Here is the accepted answer: I've found the solution. I've change the encoding of pattern.xml to ANSI I've change XML loading algorithm to this one It works! Here is another answer: I imagine what is happening is that as soon as your swf's main class here (above) is created (right at initialization), the ENTER_FRAME event is binding the event listener to the button, but the button does not technically exist. Your methodology for initializing here is very bad practice but allow me explain how this all works. Any time that you have a class that extends a type of DisplayObject, you should ALWAYS create a modified constructor designed to detect the "stage" element, and if it doesn't exist, listen for the ADDED_TO_STAGE event, and then perform your display-object based initializations within the callback. This is because display object based classes are kind of created in a half-assed way. The constructor is called immediately when the class is created/instantiated, but the properties and methods of that class, including children that are display objects (as in this case, buttons etc) are not available until the class has been added to the global "stage" object. In the case of AIR, your NativeWindow object contains a single instance of "stage" that all children of that NativeWindow inherit. So when you add a MovieClip or a Sprite etc to the stage, the "stage" property of that display object is populated with a reference to the global stage object contained within NativeWindow. So always remember, when it comes to flash the practice with dealing with constructors/initialization of display objects is to delay all functionality to a callback that is processed only when the global "stage" has become available to reference. Below is an example using your code: ```public class Main extends MovieClip { public function Main():void { if(stage){ init(); }else{ this.addEventListener(Event.ADDED_TO_STAGE, init); } } //Can be private or public, doesn't matter private is better practice private function init(e:Event = null) { //Notice the function paramter has a default value assigned of null. This is required so we can call this function without args as in the constructor //Also the flag variable is not necessary because this function is called once btnDialogCreate.addEventListener(MouseEvent.CLICK,CreateProject); } //Also it is generally considered bad practice to put capitals on the start of your function/variable names. Generally only classes are named this way ie: Main. public function createProject(e:MouseEvent){ //You do not need a try/catch statement for simply opening a file browser dialogue. This is a native method you're invoking with a native, predefined default directories inside the VM. Flash is already doing this for you var directory:File=File.documentsDirectory; directory.browseForDirectory("Directory of project"); } } ``` Lastly I would highly recommend watching some of the free video tutorials on this site, as there are a wide range of subjects covered that will teach you much about flash. http://gotoandlearn.com/
Title: Database Hierarchy Structure - Different Node Representation Tags: mysql;database;database-design;hierarchical-data Question: I am looking for some feedback/guidance on modeling a hierarchy structure within a relational database. My requirement states that I need to have a tree structure, where every node within the tree can represent a different type of data. For example: Organization Department 1 Employee 1 Employee 2 Office Equipment 1 Office Equipment 2 Department 1 Team 1 Office Equipment 3 In the example above, Organization, Department, Employee, Office Equipment, and Team could all be different tables within the database and have different properties associated with them. Additionally, things like Office Equipment may not necessarily be required to be associated to a department - it could be associated to a Team or the Organization. I have two ideas surrounding modeling this: The first idea is to have a hierarchy table like below: ``` hierarchys hierarchy_id (INT, NOT NULL) parent_hierarchy_id (INT, NOT NULL) organization_id (INT, NULL) department_id (INT, NULL) team_id (INT, NULL) office_equipment (INT, NULL) ``` In the table above, each of the columns would be a nullable field with a foreign key reference to their respectable table. The idea would be that only one column from every row would be populated. My second idea is to have a single table like below: ``` hierarchys hierarchy_id (INT, NOT NULL) parent_hierarchy_id (INT, NOT NULL) type (INT, NOT NULL) ``` In this case, the table above would manage the hierarchy structure, and each &quot;node table&quot; would have a hierarchy_id which would have a foreign key reference back to the hierarchy table (i.e. organizations would have a hierachy_id column). The type column would be a lookup to represent which type node is being represented (i.e. Organization, Employee, etc). I see pros and cons in both approaches. Some additional information: I would like to keep in mind maintainability of this table - there will be additions, deletions, changes, etc. I will have to display this data on an user interface, which will likely just display an icon to represent the node type, and the name. I will have to preform some aggregations across the tree for different data requests. This structure will be backed by a MySQL database. Does anyone have an experience with a similar scenario? I have searched quite a bit for information and guidance on this approach, but have not been able to find any information. I have a feeling there is a specific term for what I am looking for that I am failing to use. Thank you in advance for the community's help. Here is the accepted answer: You may want to look into "nested sets". This is a model for representing subsets of an ordered set by two limits, which we can call "left" and "right". In this model, (6,7) is a subset of (5,10) because it is "nested" inside of it. If you use nested sets together with your design of having a separate table for the hierarchy, you'll end up with four columns in your hierarchy table: leftID, rightID, ObjectID (an FK), and level. There is a good description of the nested set model in Wikipedia, which you can view by clicking here. Here is another answer: I have encountered similar situations throughout different projects, and the approach I've taken in those cases was very similar to your second solution. I am also a bit biased towards how some Ruby on Rails gems do things, but you can easily figure out how you would implement these techniques with plain SQL and some application logic. So I'm giving you one alternative to your solution: Using "Multi Table Inheritance" (Implemented in Heritage: https://github.com/dipth/Heritage). In this scenario you would have a ```Node``` table which forms the basis of your hierarchy with: ```Node (id, parent_node_id, heir_type, heir_id) ``` Where the heir_type is the name of the table holding the details for the node (e.g., Organization, Employee, team, etc.), and the heir_id is the id of the object in that table. Then each type of node would have it's own table and it's own unique id. e.g.: ```Organization(id, name, address) ``` Having the rest of the tables independently from the hierarchy (i.e., strong entities) makes your model more flexible to new additions. Also having a separate table with its own unique id to handle the hierarchy makes it easier to render the hierarchy without having to deal with parent types etc. This model is also more flexible in the sense that one entity can be part of many different branches of the hierarchy (e.g., Employee 1 could be a member of Team 1 and Team 2 at the same time.) Your solution has one mistake: The ```hierarchys``` is miss-spelled :P JK. The hierarchys table has no unique id. It looks like the unique id is a composite key ```(hierarchy_id, type)```. The ```parent_hierarchy_id``` does not capture the type of the parent and thus it may point to multiple nodes and many inconsistencies. If you'd like me to elaborate more, let me know.
Title: Adding the onepage checkout on product page Tags: php;magento;checkout;onepage-checkout Question: I have encounter a slight problem regarding magento checkout process. Currently I am using the list.phtml file to add orders into the cart, and upon changing the product, the cart is emptied and the newly selected product is added. I do this via this functionality: this is the form for deleting (i have the form key into it) ```<form action="<?php echo $this-&gt;getUrl('checkout/cart/updatePost') ?&gt;" method="POST" name="emptyTheCart"&gt; <?php echo $this-&gt;getBlockHtml('formkey'); ?&gt; <button type="submit" name="update_cart_action" value="empty_cart" style="display:none" title="<?php echo $this-&gt;__('Empty Cart'); ?&gt;" id="empty_cart_button"&gt;</button&gt; </form&gt; $('.item').click(function() { $(this).find('input:radio')[0].checked = true; var formurl = $(this).find('input:radio').val(); var datafile=$("#product_addtocart_form").serialize(); var dataExecURL = "<?php echo $this-&gt;getUrl('checkout/cart/updatePost') ?&gt;"; var datafiles=$("#emptyTheCart").serialize(); datafiles = datafiles + "&amp;update_cart_action=empty_cart"; $.ajax({ type : 'POST', data : datafiles, url : dataExecURL, success: function() { $.ajax({ type : 'POST', data : datafile, url : formurl }); } }); }); ``` This part works very good. The thing is that on the Category page i have the following custom design in the Custom Layout Update: ```<block type="cms/block" name="opdracht_text" before="-"&gt; <action method="setBlockId"&gt;<block_id&gt;opdracht_text</block_id&gt;</action&gt; </block&gt; <block type="catalog/product_list" name="home.catalog.product.list" alias="products_homepage" template="catalog/product/list.phtml" &gt; <block type="cms/block" name=" shipping_method" &gt; <action method="setBlockId"&gt;<block_id&gt; shipping_method </block_id&gt;</action&gt; </block&gt; <block type="checkout/onepage_shipping_method_available" template="checkout/onepage/shipping_method/available.phtml"/&gt; <block type="cms/block" name="billing" &gt; <action method="setBlockId"&gt;<block_id&gt;billing</block_id&gt;</action&gt; </block&gt; <block type="checkout/onepage_billing" name="checkout.onepage.billing" as="billing" template="checkout/onepage/billing.phtml"/&gt; <block type="cms/block" name="opdracht-delivery" &gt; <action method="setBlockId"&gt;<block_id&gt;opdracht-delivery</block_id&gt;</action&gt; </block&gt; <block type="cms/block" name="payment_method" &gt; <action method="setBlockId"&gt;<block_id&gt; payment_method </block_id&gt;</action&gt; </block&gt; <block type="checkout/onepage_payment" name="checkout.onepage.payment" as="payment" template="checkout/onepage/payment.phtml"&gt; <block type="checkout/onepage_payment_methods" name="checkout.payment.methods" as="methods" template="checkout/onepage/payment/info.phtml"&gt; <action method="setMethodFormTemplate"&gt;<method&gt;purchaseorder</method&gt;<template&gt;payment/form/purchaseorder.phtml</template&gt;</action&gt; </block&gt; <block type="core/template" name="checkout.onepage.payment.additional" as="additional" /&gt; <block type="core/template" name="checkout.onepage.payment.methods_additional" as="methods_additional" /&gt; </block&gt; </reference&gt; ``` As a onepage checkout functionality I have added to magento the extension from http://www.magentocommerce.com/magento-connect/one-page-checkout.html when I navigate to my store_url/chekout/cart I can clearely see the cart and the shipping methods and update the price there and after that proceed to the checkout page at store_url/ onepage/ where I have my billing + shipping + payment methods I have taken the blocks from the checkout.xml file from the layout folder from my template (default rwd template) and added them to the category page The main issue that I am having is the fact that upon opening the page I cannot view the shipping method until after I have selected a product and refreshed the page. The State/Province Field is not shown at all and also the Payment methods do not show up. The thing that I am currently trying to accomplish is that the checkout forms to be on the product page like in the following flow: Product Selection -> Shipping Method -> Billing Method -> Payment Method These are the steps that I am currently trying to put in one single page ( the product display page / category page ) Here is the accepted answer: I have managed to find the best solutin in this case by using the default xml for the magento iwd one page chekout. in case you want to have the checkout page on the same page as the product page, in Catalog->Manage Categories, select your category, then on the Display Settings choose the Static Blocks and products option. In the custom Design tab, set the page layout to no layout and then use the wrapper block and the desired blocks that you want on the page. Also, do not forget to include the javascript files on the page. Example for One page checkout with product list on the same page: ``` <reference name="head"&gt; <action method="addItem"&gt;<type&gt;skin_js</type&gt;<name&gt;js/iwd/opc/checkout.js</name&gt;</action&gt; <action method="addItem"&gt;<type&gt;skin_js</type&gt;<name&gt;js/iwd/opc/extend.js</name&gt;</action&gt; <action method="addJs"&gt;<file&gt;mage/directpost.js</file&gt;</action&gt; <action method="addItem"&gt;<type&gt;skin_js</type&gt;<name&gt;js/opcheckout.js</name&gt;</action&gt; <action method="addItem" ifconfig="opc/paypal/status"&gt;<type&gt;skin_js</type&gt;<name&gt;js/iwd/opc/lipp.js</name&gt;</action&gt; <action method="addJs" ifconfig="payment/braintree/active"&gt;<file&gt;braintree/braintree-1.3.4.js</file&gt;</action&gt; <action method="addCss" ifconfig="payment/braintree/active"&gt;<stylesheet&gt;braintree/css/braintree.css</stylesheet&gt;</action&gt; </reference&gt; <reference name="content"&gt; <!-- Auguria Insurance --&gt; <block type="opc/wrapper" name="es.checkout.container" template="opc/wrapper.phtml"&gt; <!-- SHIPPING METHODS FORM --&gt; <block type="checkout/onepage_shipping_method" name="checkout.onepage.shipping_method" as="shipping_method" template="opc/onepage/shipping_method.phtml"&gt; <block type="checkout/onepage_shipping_method_available" name="checkout.onepage.shipping_method.available" as="available" template="checkout/onepage/shipping_method/available.phtml"/&gt; <block type="checkout/onepage_shipping_method_additional" name="checkout.onepage.shipping_method.additional" as="additional" template="checkout/onepage/shipping_method/additional.phtml"/&gt; </block&gt; <!-- Guest --&gt; <!-- BILLING FORM --&gt; <block type="opc/onepage_billing" name="checkout.onepage.billing" as="billing" template="opc/onepage/billing.phtml"/&gt; <!-- SHIPPING FORM --&gt; <block type="opc/onepage_shipping" name="checkout.onepage.shipping" as="shipping" template="opc/onepage/shipping.phtml"/&gt; <!-- COMMENT FORM --&gt; <block type="opc/onepage_comment" name="checkout.order.comment" as="customer.comment" /&gt; <!-- PAYMENTS METHOD FORM --&gt; <block type="checkout/onepage_payment" name="checkout.onepage.payment" as="payment" template="opc/onepage/payment.phtml"&gt; <block type="checkout/onepage_payment_methods" name="checkout.payment.methods" as="methods" template="checkout/onepage/payment/methods.phtml"&gt; <action method="setMethodFormTemplate"&gt;<method&gt;purchaseorder</method&gt;<template&gt;payment/form/purchaseorder.phtml</template&gt;</action&gt; </block&gt; </block&gt; <block type="checkout/agreements" name="checkout.onepage.agreements" as="agreements" template="opc/onepage/agreements.phtml"/&gt; <block type="opc/onepage_subscribed" template="opc/onepage/review/subscribed.phtml" name="opc.newsletters" /&gt; </block&gt; </reference&gt; ``` Comment for this answer: also, the page now works because of the adding of the additional javascript files. Now there is no need to wory about a refresh being needed because in the wrapper.phtml file I have added the following block: getLayout()->createBlock("checkout/cart_shipping")->setTemplate("checkout/cart/shipping.phtml")->toHtml();?> this block creates the shipping estimation block, that can help a user check if there is any shipping available in his Area.
Title: First element from array in Step functions Pass state Tags: amazon-web-services;aws-step-functions Question: I have this strange problem with AWS step functions Pass state. I currently send the following JSON to a Pass state ```[ [ { &quot;key&quot;: &quot;value&quot; } ] ] ``` I need to remove the top array and send only the array and object to the next step. ``` [ { &quot;key&quot;: &quot;value&quot; } ] ``` When I try with ```ResultPath: &quot;$[0]``` it is added an extra array on top instead. When I try with ```Params: { &quot;$&quot;: &quot;$[0]&quot; }``` it considers the following as static input and prints as is. Is there a way I can achieve the desired output? Any help is appreciated. Thanks. Here is another answer: Thanks for your question. The OutputPath field can be used here to filter your JSON. It allows you to select a specific part of your output, and pass only that data on to the next state. The ResultPath field is used to specify the path in the input to write your output. Since you specified &quot;$[0]&quot;, your output was written to index 0 of an array. We understand these fields can be quite tricky to become familiar with, and we are working on some new ways to help smooth out this process for our customers!
Title: sending data from one node js to another and displaying the sent data on the other node js Tags: node.js;http;ejs Question: i am trying to send data from one node js server to another and display the information sent. Example server A and server B. Server A sent data to server B and server B will display the information sent by server A and response with a answer back to server A. Basically my program is like a payment page and a bank-server page. Sending payment details to the bank-server and if the bank-server clicked accept, it will send back to the payment page and continue the transaction. This is my code for the payment page: ```var postData = JSON.stringify({ user: cardDetails }); const options = { hostname: 'localhost', port: 3001, path: '/bank', method: 'POST', headers: { 'content-type': 'application/json', 'accept': 'application/json' } }; const httpreq = http.request(options, (res) =&gt; { res.setEncoding('utf8'); res.on('data', (chuck) =&gt; { console.log(`BODY: ${chuck}`); }); res.on('end', () =&gt; { console.log('No more data in response.'); }); }); httpreq.on('error', (e) =&gt; { console.error(`problem with request: ${e.message}`); }) //write data to request body httpreq.write(postData); httpreq.end(); ``` This is my code for the bank-server side: App.js ```var express = require("express"); var path = require("path"); var bodyParser = require("body-parser"); var express = require('express'); var app = express(); var serverPort = 3000; var httpServer = require('http').Server(app); // ejs template path app.set("views", path.join(__dirname, "server/views/pages")); // view engine setup app.set("view engine", "ejs"); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); //import order tracking var bank = require('./server/controllers/bank'); app.get("/bank-server", bank.bankSystem); app.post("/bank", bank.add); console.log("Connected!") app.listen(3001); ``` This is my bank.js code: ```exports.add = function (req, res){ console.log(req.body.user.cardName); res.sendStatus(200); }; exports.bankSystem = function (req, res){ console.log("Bank Page Working!") res.render('bankServer', { name: "empty" }) } ``` Lastly my bankServer.ejs code: ```<h1&gt;Connection Worked!</h1&gt; <p&gt;Card Name is <%= name %&gt;</p&gt; ``` This is the output from payment node js. CardName entered = raysonkira1 This is the output from bankserver node js. received cardName Here is another answer: you can use the rabitmq for data transfer or sencond solution is both side initialize the API your side you can post the data and bank side Get the data Here is another answer: In Bank.js, you are just sending the status and not response. ```exports.add = function (req, res){ console.log(req.body.user.cardName); res.sendStatus(200); // send the response data here, for example res.send("Hello from the bank!"); }; ``` reference Comment for this answer: `console.log(BODY: ${chuck});` is doing this right? Comment for this answer: `res.on(` **`'data'`** `, (chuck) => {console.log(BODY: ${chuck});});` will show response _data_ , status code is retrived via `res.statusCode` See first example in the http [documentation](https://nodejs.org/api/http.html#http_http_request_options_callback) Comment for this answer: but how do i make the sent details appear in my ejs file? Comment for this answer: Yup! It shows OK. Meaning the server responded using the res.sendstatus Comment for this answer: Ah yea ik about that. But what can i do to make the details appear on my bankserver.ejs. since i got the info req.body.user in bank node js side.
Title: Rigid body tower falling over by itself? Tags: rigid-body-simulation Question: I have a large tower (12 blocks high) that I plan to have a ball [email protected]. But what happens is that it falls over by itself and starts to spread out on the ground. What is happening and why? Blend File Comment: You need to keyframe the dynamic check box for each piece that you want to move. Here is another answer: The issue is that rigid body physics are taking over your tower, and making it collapse before the ball hits it, which is what would happen in real life, if the tower was already broken. The way to fix this is to go under Properties > Physics > Rigid Body Dynamics and check Enable Deactivation and Start Deactivated.
Title: Group Specific Rows within Group By Tags: sql-server Question: I'm looking to combine some specific values in an aggregation query after the group by clause. If I have to hard code in that these specific examples need to be grouped, that should be ok. So after the group by, we have sales by person which I would like to get to the lower image Here is the accepted answer: You can use ```case```: ```select (case when salesperson in ('Luke', 'Bob', 'Luke/Bob') then 'Luke/Bob' else salesperson end) as salesperson, sum(sales) from t group by (case when salesperson in ('Luke', 'Bob', 'Luke/Bob') then 'Luke/Bob' else salesperson end); ```
Title: when plotting with vbar on an xaxis that's a datetime axis, how can I set the width of the bars to be "one day"? Tags: python;bokeh Question: This certainly makes the width of the bars wider, but would be better to set them to "1 day" wide: ```source = ColumnDataSource(df) p = figure(x_axis_type="datetime", height=200, ...) ... c.vbar('dt', top='pct_change', width=100000000, source=source) ``` Here is the accepted answer: You can give a ```timedelta``` object as the width keyword argument, it will be converted to milliseconds. ```import datetime ... c.vbar('dt', top='pct_change', width=datetime.timedelta(days=1), source=source) ``` ```NumberSpec``` can accept ```datetime``` values, unless ```accept_datetime``` is set to ```false```. Comment for this answer: Any reason for downvoting? I would be interseted to know. Comment for this answer: Me too, this had not occurred to me, but seems perfectly reasonable. Here is another answer: The underlying units of a datetime axis are milliseconds-since-epoch, so to make a bar be "1 day" wide, set the width to be the number of milliseconds a day, i.e. 24*60*60*1000 = 86400000
Title: Wordpress Custom Post Type "Read More" problem Tags: wordpress Question: I've created a custom post type made with this tutorial. The problem is when I try to display a part of the post it works exact the opposite way! Post text: ```You should see me! <!--more--&gt; Not me. At least not yet. ``` PHP code: ```<?php the_content("Read more...",TRUE,''); ?&gt; ``` Should display something like: "You should see me! Read more..." But it displays: "Not me. AT least not yet." And no "Read more..." link. What's going on? Comment: I [email protected] forums. However, we may be able to help here. Can you post your entire loop? Try resettings `$more` similar to `` Also, try `the_content()` without the other stuff in there, like `the_content('Read more...');`. Comment: You might be better off asking this at http://wordpress.stackexchange.com, btw. Here is another answer: I was also having same problem. After a detailed observation I found that read more tag doesn't work on template tags. See here https://developer.wordpress.org/reference/functions/the_content/ The quicktag will not operate and is ignored in Templates where just one post is displayed, such as single.php.
Title: iOS Set datepicker TimeMode minimum and maximum date between PM and AM Tags: ios;swift;xamarin;datepicker Question: I have a UIDatePicker in Time mode, and I need to set a minimum and maximum time but it needs to be between PM and AM (11:00 PM and 02:00 AM). I tried adding a day component ```components.Day = 1;``` but it doesn't see to work it get maximum [email protected]. Any thought to set multiple ranges or something to make it work ? Thanks. Comment: Do you need to select the date as well, or just a Time? Comment: @SeifSelmi I would suggest using UIPickerView with one component for your hour range and one for minutes. Comment: If you chose time mode , `MaximumDate` must be great than `MinimumDate`, so you can set 2AM~11PM but can't reverse them. Comment: try https://stackoverflow.com/a/16322625/3231194 Comment: @rbaldwin i need only Time picker Comment: @Glenn yes i tried that but same problem unfortunately. Comment: @Cole yes you are right, I had to do that programatically and setting two ranges, and that fixed my problem.
Title: SceneKit custom geometry produces “double not supported” / “invalid vertex format” runtime error Tags: swift;scenekit Question: I don't understand what's wrong with the following code: ```class Terrain { private class func createGeometry () -&gt; SCNGeometry { let sources = [ SCNGeometrySource(vertices:[ SCNVector3(x: -1.0, y: -1.0, z: 0.0), SCNVector3(x: -1.0, y: 1.0, z: 0.0), SCNVector3(x: 1.0, y: 1.0, z: 0.0), SCNVector3(x: 1.0, y: -1.0, z: 0.0)], count:4), SCNGeometrySource(normals:[ SCNVector3(x: 0.0, y: 0.0, z: -1.0), SCNVector3(x: 0.0, y: 0.0, z: -1.0), SCNVector3(x: 0.0, y: 0.0, z: -1.0), SCNVector3(x: 0.0, y: 0.0, z: -1.0)], count:4), SCNGeometrySource(textureCoordinates:[ CGPoint(x: 0.0, y: 0.0), CGPoint(x: 0.0, y: 1.0), CGPoint(x: 1.0, y: 1.0), CGPoint(x: 1.0, y: 0.0)], count:4) ] let elements = [ SCNGeometryElement(indices: [0, 2, 3, 0, 1, 2], primitiveType: .Triangles) ] let geo = SCNGeometry(sources:sources, elements:elements) let mat = SCNMaterial() mat.diffuse.contents = UIColor.redColor() mat.doubleSided = true geo.materials = [mat, mat] return geo } class func createNode () -&gt; SCNNode { let node = SCNNode(geometry: createGeometry()) node.name = "Terrain" node.position = SCNVector3() return node } } ``` I use it as follows: ``` let terrain = Terrain.createNode() sceneView.scene?.rootNode.addChildNode(terrain) ``` But get: ```2016-01-19 22:21:17.600 SceneKit: error, C3DRendererContextSetupResidentMeshSourceAtLocation - double not supported 2016-01-19 22:21:17.601 SceneKit: error, C3DSourceAccessorToVertexFormat - invalid vertex format /BuildRoot/Library/Caches/com.apple.xbs/Sources/Metal/Metal-588-992-3154/Framework/MTLVertexDescriptor.mm:761: failed assertion `Unused buffer at index 18.' ``` Here is the accepted answer: The issue is that the geometry is expecting ```float``` components but you’re giving it ```double```s—CGPoint’s components are CGFloat values, which are typedef’d to ```double``` on 64-bit systems. Unfortunately, the SCNGeometrySource ```…textureCoordinates:``` initializer insists on CGPoints, so you can’t use that; the workaround I found was to create an NSData wrapping an array of SIMD float vectors, then use the much longer ```data:semantic:etc:``` initializer to consume the data. Something like this should do the trick: ```let coordinates = [float2(0, 0), float2(0, 1), float2(1, 1), float2(1, 0)] let coordinateData = NSData(bytes:coordinates, length:4 * sizeof(float2)) let coordinateSource = SCNGeometrySource(data: coordinateData, semantic: SCNGeometrySourceSemanticTexcoord, vectorCount: 4, floatComponents: true, componentsPerVector: 2, bytesPerComponent: sizeof(Float), dataOffset: 0, dataStride: sizeof(float2)) ``` Comment for this answer: By using the way you set the texture coord (or by removing texturecoord in the elements) my code does not break anymore. Good. But it draws nothing on screen. I asked this specific question here: http://stackoverflow.com/questions/34897040/scenekit-custom-geometry-does-not-show-up
Title: Django: "readable" 500 page for http clients? Tags: python;django Question: On server error (500), the default debugging behavior of django is to return an HTML page containing the stack trace. However, I'm using django (with rest framework) to create REST api, so I'm accessing it through command line tools, and the returned html is unreadable. Is there any way to customize django to return a more readable, text only response? Comment: This is what you are looking for https://www.django-rest-framework.org/api-guide/exceptions/ and https://docs.djangoproject.com/en/dev/topics/http/views/#customizing-error-views Comment: @pako: thanks. I saw that, but it says that it is by-passed in debug mode
Title: Tell Swashbuckle to only look for controllers that have the ApiControllerAttribute Tags: c#;asp.net-core;.net-core;asp.net-core-mvc;swashbuckle Question: I'm working on a Web MVC project and inside it I want to have some api controllers for external apps to use. My API controllers have the ```ApiController``` attribute on them. Unfortunately, Swashbuckle picks up ALL the controllers/actions. Is there a way to tell it to only look for Api controllers? Thank you. Comment: Do you deveop with asp.net core mvc or asp.net mvc? If it is asp.net core, what is .net core version and `Swashbuckle.AspNetCore` version? I made a test with asp.net core 2.2 and `Swashbuckle.AspNetCore` 4.0.1, it will only generate the method for `ApiController`. In addition, you may try to refer https://github.com/domaindrivendev/Swashbuckle/issues/153#issuecomment-213342771 Here is another answer: You can put this in the controller you want to hide from Swashbuckle ```[ApiExplorerSettings(IgnoreApi = true)] public class UserController : Controller ``` Comment for this answer: Maybe you can create your own `BaseController` which inherits from `Controller` and in it put the `[ApiExplorerSettings(IgnoreApi = true)]`, and then replace the `Controller` in your controllers that you want to be ignored with the new `BaseController`. Comment for this answer: It's a valid solution but I'll have to put that in all my controllers, which is a bit too tiring...
Title: ViewPager not updating fragments Tags: java;android;android-fragments;android-viewpager;android-tablayout Question: I'm trying to replace fragments in ViewPager, but I'm facing a problem I've been unable to fix for several days. The relevant code and specific problem, as I understand it, are described below: ```public class ViewPageAdapter extends FragmentStatePagerAdapter { int mNumOfTabs; FragmentManager mFragmentManager; Fragment0 currentFragment0; Fragment1 currentFragment1; Fragment2 currentFragment2; boolean getItemNeverCalled = true; public ViewPageAdapter(FragmentManager fm, int numOfTabs){ super(fm); mFragmentManager = fm; this.mNumOfTabs = numOfTabs; } @Override public Fragment getItem(int position){ switch (position){ case 0: if(currentFragment0 == null){ Fragment0 tab0 = new Fragment0(); currentFragment0 = tab0; return currentFragment0; } else { mFragmentManager.beginTransaction().remove(currentFragment0).commit(); int value = selectedPlant.getMoistureFrag().getStat().getOptimalLevel(); currentFragment0 = Fragment0.newInstance(key0, value); notifyDataSetChanged(); // calls getItem(0). return currentFragment0; } case 1: if(currentFragment1 == null){ LightFragment tab1 = new Fragment1(); currentFragment1 = tab1; return currentFragment1; } else { mFragmentManager.beginTransaction().remove(currentFragment1).commit(); int value = selectedPlant.getLightFrag().getStat().getOptimalLevel(); currentFragment1 = currentFragment1.newInstance(key1, value); notifyDataSetChanged(); return currentFragment1; } case 2: if(currentFragment2 == null){ Fragment2 tab2 = new Fragment2(); currentFragment2 = tab2; return currentFragment2; } else { mFragmentManager.beginTransaction().remove(currentFragment2).commit(); int value = selectedPlant.getTempFrag().getStat().getOptimalLevel(); currentFragment2 = Fragment2.newInstance(key2, value); notifyDataSetChanged(); return currentFragment2; } default: return null; } } @Override public int getCount(){ return mNumOfTabs; } @Override public int getItemPosition(Object object){ return POSITION_NONE; } ``` I've overriden the ```getItemPosition(Object object)``` method to always return POSITION_NONE, and called notifyDataSetChanged() when appropriate (I think). What ends up happening is that ```notifyDataSetChanged()``` calls ```getItem(0)```, which calls `notifyDataSethanged()... and so on. This causes a TransactionTooLargeException and crashes the app. Just to give some background to the ```if/else``` statements in each case: the ```if``` is meant to load a blank Moisture/Light/etc Fragment onto the screen. This is intended to happen on start-up. The ```else``` statement is executed when a user presses on a item in the navigation drawer, which has some data. This data is then extracted and set as arguments for the fragments that are meant to replace the initial blank fragment. I genuinely appreciate any help. This problem is driving me crazy. Here is the accepted answer: Why in the world are you recreating fragments, when you can just update the old ones? Also, when you are calling notifyDataSetChanged during getItem then you are forcing a new call to getItem which will force a new call...so you are actually creating a circular call! Since you are always keeping the same fragment class in each position, and you are holding on to the fragment, then you should not replace fragment. Just change the fragment you are holding to show the new values. The code you are using is only needed if you want to change different fragment classes for position. Comment for this answer: BTW, since you are always keeping the same fragment class in each position, and you are holding on to the fragment, then you should be redesigning your code. You should not replace fragment, just change the fragment you are holding to show the new values. The code you are using is only needed if you want to change different fragment classes for position. Comment for this answer: Correct. Why should they be replaced if they can just be updated. I will be editing my answer above (if I can). Comment for this answer: You're welcome. I wish all OPs would be so appreciative. Comment for this answer: Also, don't forget to remove the `getItemPosition` function. No need, and will cause problems. Comment for this answer: Was having some troubles initially (before I knew that method existed), so I followed http://stackoverflow.com/questions/7723964/replace-fragment-inside-a-viewpager and several other posts that suggested the same thing. I will let you know how it goes. Comment for this answer: Ok, I see. Does that mean I shouldn't use the getItem method past the initialization of the tabs on start-up? Comment for this answer: Ok I see. If you are asking me for permission, you have it lol. Comment for this answer: Good lord... It works. I was under the impression that I have to call getItem() to get the tabs to change in any way. Thank you!! Comment for this answer: Ok, I did. Thank you again, you were a big help:)
Title: How can I prepare my code so that I can paste it formatted? Tags: support;faq;formatting;editor Question: If I paste C++ code with many functions/classes (braces), I have to indent all of them, including their content. I've replaced tabs with spaces in my editor, but still no improvements. What's the best solution? Comment: Highlight your code and press ctrl+k. Comment: @jliv902 I have to do it for every piece of code between braces Comment: Is there some disadvantage to wrapping unaltered copy-pasta in `` and ````` tags that I'm unaware of? Comment: Yes, it seems that your awareness is missing the tabs. It's easy to realize it if your read the following answer. Comment: By "tabs" do you mean literally the ascii character 9 "\t" is ignored for purposes of formatting, or are four ascii 0x20 " " spaces ignored for purposes of formatting as well? I've been doing ````` for a while and never noticed anything wrong, but I always replace tabs with spaces anyway. Comment: By tab I mean '\t'. Another (firstly unexpected) use is to format the code of others (and win precious points). Comment: Aaah I see. It seems I am not very altruistic. Comment: Neither I am and, to be honest, I don't understand why " '\t' is ignored for purposes of formatting". I just had a problem and I wanted a solution. Comment: Accepted answer still looks like a mild to moderate hassle - I'm going to try to cook up a bookmarklet. If anybody wants to come up with a list of tokens that demand an indent/dedent in languages other than curly-bracket languages, HTML/XML, and Ruby, they should get it to me somehow. Comment: Both the question and the answer mention the language, from what you are saying I understand that one can't indent HTML code with tabs. But you're welcome to add another answer, maybe it il gain more points so it will come first (in the page order). Here is the accepted answer: Java is my standard language, but, for formatting code to put here, this is typically what I do, depending on where I am... For example, someone posts a question to Stack Overflow, and the indenting/formatting is horrible.... First, I edit the post, then select the code that needs indenting/fixing. Type CtrlX to cut it, then: Using Eclipse: AltTab to get to Eclipse AltShiftN Up,Up,Up,Up to start a new untitled text document CtrlV into new document CtrlA, CtrlI, Tab (select everything, make indenting consistent, increase all indent by 4 spaces). CtrlC CtrlF4 to close the untitled text document (don't save) AltTab (copy it all, back to Stack Exchange) CtrlV to paste fixed code back again. Using Notepad++ Do the same as for Eclipse, to paste to a new document CtrlA, Tab (can't do easily fix indenting, but can indent everything) Edit->Blank Operations->Tab to Spaces CtrlC CtrlW to close file AltTab back to Stack Overflow CtrlV to paste fixed code back again This works for most C-like languages (Java, C++, C#, whatever). Comment for this answer: Step 3 from Notepad++ worked with Sublime Text: `View / Indentation / Convert Indentation to Spaces` Comment for this answer: wish I could upvote this again. this really saves a lot of time!!! I am using Notepad++ Comment for this answer: I use VIM: `:%>` will increase indentation, `:%retab` will repear tabs (`et`=`expandtab` needed or you can use `%s/\t/ /g` - will change all tabs to spaces) Here is another answer: Some programs to do this have been submitted for review, so you might be able to use one of them: java: Tool for creating CodeReview questions shell: Shell script for creating CR questions javascript: Tool for automatically correcting indentation and formatting of CR &amp; SO code This last one is also on JSFiddle
Title: How do I upgrade postgresl database? Incompatibility error Tags: linux;postgresql;upgrade Question: I installed postgresql via Homebrew. I have the following issue after upgrading: ```FATAL: database files are incompatible with server DETAIL: The data directory was initialized by PostgreSQL version 9.0, which is not compatible with this version 9.1.2.``` Any tips on how to upgrade? I tried the following: ```$ pg_upgrade -d /usr/local/var/postgres/ -D /usr/local/var/postgres -b /usr/local/Cellar/postgresql/9.0.4/bin -B /usr/local/Cellar/postgresql/9.1.2/bin ``` It didn't work. Here's the output. ```Performing Consistency Checks Checking current, bin, and data directories ok Checking cluster versions This utility can only upgrade to PostgreSQL version 9.1. Failure, exiting ``` error.
Title: How to tell if hex value is negative? Tags: hex Question: I have just learned how to read hexadecimal values. Until now, I was only reading them as positive numbers. I heard you could also write negative hex values. My issue is that I can't tell if a value is negative or positive. I found a few explanations here and there but if I try to verify them by using online hex to decimal converters, they always give me different results. Sources I found: https://stackoverflow.com/a/5827491/5016201 https://coderanch.com/t/246080/java-programmer-OCPJP/certification/Negative-Hexadecimal-number If I understand correctly it means that: If a hex value written with all its bits having something > 7 as its first hex digit, it is negative. All 'F' at the beginning or the first digit means is that the value is negative, it is not calculated. For exemple if the hex value is written in 32 bits: FFFFF63C => negative ( -2500 ?) 844fc0bb => negative ( -196099909 ?) F44fc0bb => negative ( -196099909 ?) FFFFFFFF => negative ( -1 ?) 7FFFFFFF => positive Am I correct? If not, could you tell me what I am not getting right? Comment: Strictly speaking you can't tell just by looking at the number whether it's negative or positive; you also need to know how wide the number is supposed to be, and whether it's supposed to be signed or unsigned. Comment: It's simplified *just* enough to be inaccurate. You need to look at bit n-1 where n is the bitsize and the rightmost bit is bit 0. Comment: @IgnacioVazquez-Abrams Okay, let's say i know the number is signed 32bits, is what i assert (in bold) in my question true? Comment: @IgnacioVazquez-Abrams Thanks, i see more clearly now. Here is the accepted answer: Read up on Two's complement representation: https://en.wikipedia.org/wiki/Two%27s_complement I think that the easiest way to understand how negative numbers (usually) are treated is to write down a small binary number and then figure out how to do subtraction by one. When you reach 0 and apply that method once again - you'll see that you suddenly get all 1's. And that is how "-1" is (usually) represented: all ones in binary or all f's in hexadecimal. Commonly, if you work with signed numbers, they are represented by the first (most significant) bit being one. That is to say that if you work with a number of bits that is a multiple of four, then a number is negative if the first hexadecimal digit is 8,9,A,B,C,D,E or F. The method to do negation is: invert all the bits add 1 Another benefit from this representation (two's complement) is that you only get one representation for zero, which would not be the case if you marked signed numbers by setting the MSB or just inverting them. Comment for this answer: “While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes.” Here is another answer: You can tell whether a hexadecimal integer is positive or negative by inspecting its most significant (highest) digit. If the digit is ≥ 8, the number is negative; if the digit is ≤ 7, the number is positive. For example, hexadecimal 8A20 is negative and 7FD9 is positive Here is another answer: The answer here in the forum looks good: ``` Each hexadecimal "digit" is 4 bits. The d in the high order position is 1101. So you see it's got a high bit of one, therefore the whole number is negative. ``` and ``` A hex number is always positive (unless you specifically put a minus sign in front of it). It might be interpreted as a negative number once you store it in a particular data type. Only then does the most significant bit (MSB) matter, but it's the MSB of the number "as stored in that data type". In that respect the answers above are only partially correct: only in the context of an actual data type (like an int or a long) does the MSB matter. If you store "0xdcafe" in an int, the representation of it would be "0000 0000 0000 1101 1100 1010 1111 1110" - the MSB is 0. Whereas the representation of "0xdeadcafe" is "1101 1110 1010 1101 1100 1010 1111 1110" - the MSB is 1. ``` Here is another answer: From what I understand, you always need to look at the left-most digit to tell the sign. If in hex, then anything from 0-7 is positive and 8-f is negative. Alternatively, you can convert from hex to binary, and if there's a 1 in the left-most digit, then the number is negative. HEX <-> BINARY <-> SIGN 0-7 <-> 0000-0111 <-> pos 8-F <-> 1000-1111 <-> neg Comment for this answer: @Herdsman: Because `%d` only prints an `int` (32-bit in your case), so it only looked at the low 32 bits of that 64-bit arg you passed. `0x9f7662f0` is a negative int32_t. The compiler should have warned you about the format mismatch. `%p` is intended for pointers; use `%#llx` to print unsigned long long hex or `%lld` to print `long long`. https://en.cppreference.com/w/cpp/io/c/fprintf Comment for this answer: This answer works as long as there aren't any leading zeros omitted. e.g. a 16-bit number holding `0xFF` needs to be written as `0x00FF` to apply this rule. Comment for this answer: but then why hex `%p` = `0x7ffc9f7662f0`, and the same printed as `%d` = `-1619631376`, hex started with `7`, yet is negative
Title: Most equivalent factors of a number Tags: c++;math Question: Given a number 'n', which is a power-of-2, how can I efficiently find the 2 factors which are most equivalent to eachother? In other words, if I have a linear array and want to map it to 2D, how can I find the 2D dimensions that are the most equal (image dimensions most close to a square)? Gotta be some kind of bitwise operation to make this fast, rather than looping over factors. Comment: `n` is representable as `2^k` (since you say it's a power of 2). If `k` is even, then `n == 2^(k/2) * 2^(k/2)` (e.g. `16==4*4`). If `k` is odd, then the closest you can get is `n == 2^((k-1)/2) * 2^((k+1)/2)` (e.g. `8==2*4`) Comment: Fantastic! Please post as answer and I will accept. Comment: You are absolutely right in your suspicions. Now, you just need to think what "2 to the nth" power means, mathematically, and given the `n`, how to find a number that when multiplied by itself results in this "2^n". Free clue: this is easy when `n` is even. Here is the accepted answer: ```n``` is representable as ```2^k``` (since you say it's a power of 2). If ```k``` is even, then ```n == 2^(k/2) * 2^(k/2)``` (e.g. ```16==4*4```). If ```k``` is odd, then the closest you can get is ```n == 2^((k-1)/2) * 2^((k+1)/2)``` (e.g. ```8==2*4```)
Title: Problema con DataTable Tags: laravel;laravel-5;datatables Question: Lo que sucede es que al refrescar la página crea un producto automáticamente (es el último producto que ingrese), es decir, está insertando al refrescar la página repetidamente, y el otro problema es que cuando ingreso recién el segundo producto, se muestra el primero en la tabla, es como si estuviera desfasado. Envió el código Gracias! addInsumos.blade.php TABLA ```<div class="panel-body" style="margin-top: 200px;"&gt; <table class="table table-bordered" id="myTable"&gt; <head&gt; <th&gt;Id</th&gt; <th&gt;Nombre</th&gt; <th&gt;Categoria</th&gt; <th&gt;fecha</th&gt; <tbody&gt; @foreach ($insumos as $insumos ) <tr&gt; <td&gt;{{$insumos-&gt;id}}</td&gt; <td&gt;{{$insumos-&gt;nombre}}</td&gt; <td&gt;{{$insumos-&gt;categoria}}</td&gt; <td&gt;{{$insumos-&gt;created_at}}</td&gt; </tr&gt; @endforeach </tbody&gt; </head&gt; </table&gt; </div&gt; ``` insumosController.php CONTROLADOR ``` function viewaddinsumo() { //Ver la tabla $insumos = \App\insumos181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16latest('id') -&gt;take(5) -&gt;get(); return view('Insumos/addInsumo',compact('insumos')); }// _____ //WW|| function sendforminsumo(Request $request) //·.·|| { //insertar el producto o insumo $insumos = \App\insumos181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16latest('id')-&gt;take(5)-&gt;get(); $name = $request-&gt;input('nameP'); $categoriaP = $request-&gt;get('categoriaP'); 181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16table('insumos')-&gt;insert(['nombre'=&gt;$name, 'categoria'=&gt;$categoriaP]); return view('Insumos/addInsumo',compact('insumos')); } ``` Here is the accepted answer: Estimado, creo que la solución a su consulta es la forma en como estabas guardando los elementos en tu controlador. Recomiendo que utilices Eloquent, para simplificar tu código. ```function sendforminsumo(Request $request) { //insertar el producto o insumo $insumos = new insumos; $insumos-&gt;name = $request-&gt;input('nameP'); $insumos-&gt;categoriaP = $request-&gt;get('categoriaP'); $insumos-&gt;save();//guardas el insumo en tu base de datos return view('Insumos/addInsumo',compact('insumos'))-&gt;with('succes'); } ``` Espero te sea de utilidad mi respuesta. Saludos Edit: Añado ademas una documentación de Laravel y en especifico la de Eloquent, que te serán de mucha ayuda. Espero te sea de utilidad. Comment for this answer: Lo intentare, gracias hector! Comment for this answer: Si te funciona, dala como respuesta correcta para que le sirva a otras personas, saludos. Comment for this answer: Funciona 10/10 jaja gracias! Comment for this answer: Te recomiendo, como extra que le añadas buenas practicas a tus modelos y controladores, como por ejemplo cuando crees tu modelo, utiliza php artisan make:model InsumosController -cr, con esto crearas tus resources en el controlador, index, store, update, etc y además creara tu controlador. Por otro lado al momento de utilizarlos en las rutas, solo deberas colocar Rout181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16resources('insumos','InsumosController'); y podras tener todos los metodos del controlador generados previamente, te lo recomiendo. Saludos y recuerda darle un voto si la respuesta fue correcta.
Title: how to pass data from table diagonal React JS Tags: javascript;html;reactjs;ecmascript-6;react-hooks Question: I'm currently trying to pass an array to the data table from diagonal. but here i pass the data using hardcoded values. ```import { useState } from &quot;react&quot;; //const rawData= [[7,0,0,1,6,1],[8,2,5,1,7],[5,4,1,4],[2,2,0]] export default function DataTable1(){ //const [tableData, setTableData] = useState(rawData) return( <table&gt; <thead&gt; <tr&gt; <th&gt;</th&gt; <th&gt;Week 1</th&gt; <th&gt;Week 2</th&gt; <th&gt;Week 3</th&gt; <th&gt;Week 4</th&gt; <th&gt;Net Lost</th&gt; <th&gt;Net Recovered</th&gt; </tr&gt; </thead&gt; <tbody&gt; <tr&gt; <th&gt;Week 1</th&gt; <td&gt;7</td&gt; <td&gt;0</td&gt; <td&gt;0</td&gt; <td&gt;1</td&gt; <td&gt;6</td&gt; <td&gt;1</td&gt; </tr&gt; <tr&gt; <th&gt;Week 2</th&gt; <td&gt;</td&gt; <td&gt;8</td&gt; <td&gt;2</td&gt; <td&gt;5</td&gt; <td&gt;1</td&gt; <td&gt;7</td&gt; </tr&gt; <tr&gt; <th&gt;Week 3</th&gt; <td&gt;</td&gt; <td&gt;</td&gt; <td&gt;5</td&gt; <td&gt;4</td&gt; <td&gt;1</td&gt; <td&gt;4</td&gt; </tr&gt; <tr&gt; <th&gt;Week 4</th&gt; <td&gt;</td&gt; <td&gt;</td&gt; <td&gt;</td&gt; <td&gt;2</td&gt; <td&gt;2</td&gt; <td&gt;0</td&gt; </tr&gt; </tbody&gt; </table&gt; ) } ``` But instead of hard coded values, i need to use the ```rawData``` array to fill the table. is there any way to fill the rawData array's values from the diagonal? Can someone give me the paths and suggestions to get the desired output using the array? what i tried: ```<td&gt;rawData[0][0]</td&gt; ``` I tried to fill using the above way. but it didn't work and felt that its not the right way to do it Here is the accepted answer: Try this ``` import { useState } from &quot;react&quot;; export default function DataTable1(){ const rawData= [[7,0,0,1,6,1],[8,2,5,1,7],[5,4,1,4],[2,2,0]] return ( <table&gt; <thead&gt; <tr&gt; <th&gt;</th&gt; <th&gt;Week 1</th&gt; <th&gt;Week 2</th&gt; <th&gt;Week 3</th&gt; <th&gt;Week 4</th&gt; <th&gt;Net Lost</th&gt; <th&gt;Net Recovered</th&gt; </tr&gt; </thead&gt; <tbody&gt; {rawData.map((item, index) =&gt; { return ( <tr&gt; <th&gt;Week {index + 1}</th&gt; {[...Array(6 - item.length)].map((item) =&gt; { return <td&gt;</td&gt;; //for empty values })} {item.map((itm) =&gt; { return <td&gt;{itm}</td&gt;; })} </tr&gt; ); })} </tbody&gt; </table&gt; ); } ``` Comment for this answer: man Is it that simple....You saved me...Thanks a lot mate... Comment for this answer: can you please explain code under the Comment for this answer: check react doc: https://reactjs.org/docs/lists-and-keys.html. You will get to know
Title: How to discard null coordinate points automatically when we make Multipoint Geometry in Spatialite? Tags: spatialite Question: I have a Spatialite table that contains a series of 80 coordinates where each coordinate placed into one column in a table. Then, I want to add all those coordinates into one Multipoint Geometry Column. Unfortunately, some of those coordinates have NULL value randomly. This will make the Multipoint Geometry Column having NULL value as well. I tried to catch the NULL value using CASE WHEN, but since the table has 80 columns, my CASE WHEN code becomes very long because I must check it column by column. Is there any automatic way to discard/unconsidered NULL coordinate points when we make a Multipoint Geomatry Column? Comment: I'd try to fix the data first. What does "NULL" represent in those columns? Comment: Null represent no coordinates in that column, may be it similar to N/A. Comment: OK.... Perhaps you can say what the columns represent?
Title: ActionScript 3.0: load an image programmatically Tags: actionscript-3;adobe Question: I'm developing an Blackberry Playbock app with ActionScript 3.0. I'm very very new with this. I have the following project structure (I'm using Adobe Flash Builder "Burrito"): project | src | assets | images On image folder I have several PNGs images that I want to load programmatically. How can I do that? And What GUI component I must use to show an image? Comment: An answer could be found here: http://manewc.com/2008/01/08/as-30-flashdisplayloader-class/ Here is the accepted answer: This example loads one image and uses buttons to change it: ```// create a Loader object to hold things that you will load var myLoader:Loader = new Loader(); // position the Loader myLoader.x = 250; myLoader.y = 0; // put something into the Loader myLoader.load(new URLRequest("tree.jpg")); // make the Loader visible addChild(myLoader); // button listeners top_btn.addEventListener(MouseEvent.CLICK, loadPhoto); last_btn.addEventListener(MouseEvent.CLICK, unloadAny); // button functions function loadPhoto(e:MouseEvent):void { myLoader.load(new URLRequest("sailboat.jpg")); addChild(myLoader); } // this function empties the Loader object function unloadAny(e:MouseEvent):void { removeChild(myLoader); } ``` Here is another answer: if u want to show multiple image using for loop then follow this code: ``` var IMAGE_URL:String = new String("image/"); ``` ```for(var i=1;i<=13;i++){ addChild(imageLoder(i,i*25)); } private function imageLoder(ranvalue:int,cor:int):Loader{ var ldr:Loader = new Loader(); ldr.load(new URLRequest(IMAGE_URL+ranvalue+".jpg")); var xcord=5; var ycord=5; ldr.x = cor; ldr.y = ycord+20; return ldr; } ``` Here is another answer: Use the Loader class.