text
stringlengths
70
452k
dataset
stringclasses
2 values
Correct way to architect an single insert event from Fragment Imagine that I have a simple modal with static data rendered. This data is passed as an Parcelable argument to the modal fragment. When the modal is opened, I want to add it to the userHistory database, a simple insert which I don't expect any kind of return. To do this implementation, I did -> A Fragment that renders the data A DAO (with Room) that inserts the data to the database A repository which calls the DAO query But I'm in an internal question about how to call the repository.insertPage from Fragment. Is it bad add the repository reference into fragment? Should I create a viewmodel just with a function to make the proxy on OnCreateView that calls the repository? Should I create a useCase that calls the repository and reference the usecase on Fragment? Honestly I think that the best approach is reference the repository in the fragment, bud I don't know if it's a bad design. Is it bad add the repository reference into fragment? What you describe is called a relaxed layered architecture where dependencies may bypass lower layers. Simon Brown describes it in chapter 34, The Missing Chapter, of the Clean Architecture book. Robert C. Martin (2017), Clean Architecture The opposite of the relaxed layered architecture is a strict layered architecture where arrows should always point downward on the next adjacent lower layer. There might be some situations when it is ok to bypass the domain layers. But only if there is no business logic in between. This is usually not the case. Usually you have at least validation logic. Should I create a useCase that calls the repository and reference the usecase on Fragment? In the clean architecture you usually pass entity objects to the repository, not request objects like a Parcelable. Entity objects ensure application agnostic domain rules. Thus you should first convert the data (the Parcelable) into entity objects and then pass these to the repostitory. You usually do this in a use case or interactor which implements application specific domain rules. Maybe the result of that use case is that it just forwards the data to the entity and then to the repository. If so it means that there is no domain logic in the use case nor the entity, even no validation. This is often a hint that you implement an anemic domain model. In such cases it might be ok to directly call the repository. But first you should try as hard as you can to maintain the architecture. Every bypass is an exception from the default architecture rules and thus weakens the architecture by making it more arbitrary. Maintaining an architecture is hard, because you must resist to create bypasses for exceptional cases. But if exceptions are the norm you might use the wrong architecture or you apply it in a wrong way.
common-pile/stackexchange_filtered
How do I report a typo on the Unity website? at http://unity.ubuntu.com/about/ A powerful desktop and netbook environment things brings consistency and elegance to the Ubuntu experience. I suggest "things" has to go in "things brings" Bugs on the Ubuntu Website can be reported directly in Launchpad: https://launchpad.net/ubuntu https://launchpad.net/ubuntu-website-content No need to file it this time, I've corrected the typo, thanks!
common-pile/stackexchange_filtered
I want to display rows in a Document Library in two columns side by side in SharePoint Designer, XSL I am working in a rowview template, which basically iterates through all of the row items and displays them according to what i have set them at. <table> <tr> <td> <choose> //different images for different when clauses </choose> </td> </tr> <tr> <td> <xsl:value-of select="@Title"/> <td> </tr> </table> The above layout is, in general, what I have. Say you have a document library with documents: Doc1 Doc2 Doc3 Doc4 I want these displayed as the following but do now know how to achieve this <tr> <td>doc1<td><td>doc2<td> </tr> <tr> <td>doc3<td><td>doc4<td> </tr> Nobody can know unless you provide the source XML document and the wanted output from the transformation. Without an input and output specified, what is it you are asking for??? There is no question here. I'm sorry, I've added more information & code for you to view. Thank you so much for helping out! I answered a similar issue here but for XSL, you need different syntax, though the concept is the same - try the following: <tr> <xsl:if test="position() mod 2 = 1"> <td> <xsl:value-of select="position()" /> <xsl:value-of select="."/> </td> </xsl:if> <xsl:if test="position() mod 2 = 0"> <td> <xsl:value-of select="position()" /> <xsl:value-of select="."/> </td> </xsl:if> </tr> The following link provides the ideal solution for what I was looking for. I just had to alter some of the syntax... Thank you guys for helping me. http://www.tonymarston.net/xml-xsl/two-column-view.html
common-pile/stackexchange_filtered
C++ "Error: a nonstatic member reference must be relative to a specific object" I'm trying to include experiencecalculator from a class but I get this Error: a nonstatic member reference must be relative to a specific object. #include "stdafx.h" #include <iostream> #include <string> #include <stdio.h> #include <iomanip> #include <windows.h> #include "ExpCalc.h" #include <algorithm> #include <string> #include <cctype> using namespace std; int main() { cout << "Pick which calculator you would like to use by typing the correct " "number.\n"; cout << "1. Experience Calculator" << endl; // cout << "" Insert other calculators and there number here. // cout << "" int choice; cin >> choice; if (choice == 1) { ExpCalc::ExperienceCalculator; } } The class I am taking it from is: ExpCalc.h class ExpCalc { public: ExpCalc(); int ExperienceCalculator; }; ExpCalc.cpp #include "stdafx.h" #include "ExpCalc.h" #include <iostream> #include <string> #include <stdio.h> #include <iomanip> #include <windows.h> #include <algorithm> #include <string> #include <cctype> using namespace std; ExpCalc::ExpCalc() {} int ExperienceCalculator() { double timetotal; double timeperinv; double xptotal; double xpitem; double amount; double perinv; double totalinv; double costper; double costtotal; SetConsoleTitle(TEXT("Runescape Skill Calculator")); cout << "=+=+=+=+=+=+=+=+=+=+=+=+=+=Runescape Skill " "Calculator=+=+=+=+=+=+=+=+=+=+=+=+=+=" << endl; cout << endl; cout << "How much experience do you want to get?" << endl; cin >> xptotal; cout << endl; cout << "How much does it cost per item?" << endl; cin >> costper; cout << endl; cout << "How much experience do you get per item?" << endl; cin >> xpitem; cout << endl; cout << "How many items can you process in one inventory?" << endl; cin >> perinv; cout << endl; cout << "How long does it take to process one inventory of items?" << endl; cin >> timeperinv; system("CLS"); amount = xptotal / xpitem; totalinv = amount / perinv; timetotal = totalinv * timeperinv; costtotal = amount * costper; cout << "=+=+=+=+=+=+=+=+=+=+=+=+=+=Runescape Skill " "Calculator=+=+=+=+=+=+=+=+=+=+=+=+=+=" << endl; cout << endl; std::cout << std::setprecision(1) << fixed; cout << "The amount of items that you will need to process is: \n" << amount << endl; cout << endl; cout << "The total amount of inventories to process all items is: \n" << totalinv << endl; cout << endl; cout << "The total time it will take to complete processing all items is:\n" << timetotal << endl; cout << endl; cout << "The total cost of the items will be: \n" << totalinv << endl; cout << endl; cout << "The total amount of inventories to process is: \n" << totalinv << endl; cout << endl; cout << "=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+==+=+==+=+==+=+==+=+==+=+=+=+=+=+=+=" "+=+=+=+=+=+=+=" << endl; system("PAUSE"); return 0; }; Any help will be much appreciated! Does nobody actually try to learn programming languages anymore? Your problem is exactly what the error message says. There is not much more that we can say. check a tutorial on structures/classes. you're mixing up static members with instance members In addition to the static/non-static issue, you've declared int ExperienceCalculator as a variable and not as a function. Your H file describes ExperienceCalculator as int field. Your CPP file describes ExperienceCalculator as a free function (even not a method of ExpCalc). So I suspect that you have to do the following amends: H file: int ExperienceCalculator(); // parenthesis to be added CPP file: int ExpCalc::ExperienceCalculator() { // class name ExpCalc to be added main file: if (choice == 1) { ExpCalc exp_calc; // instantiate the class exp_calc.ExperienceCalculator(); // make a call to non-static method } Alternatively, you can make the method as static but let make one step at a time. Happy coding!
common-pile/stackexchange_filtered
Speed up data transfer from db to application I have build an application that handles data stored in a MS SQL server database. This server is hosted externally of our company and has to be connected to via SSH because of company rules. On a regular working day it takes about 7 minutes to retrieve a list of data, while it takes less than one minute to do the same outside office hours. The database is relatively simple. There are 3 main tables which have a relation to each other on one field which is also set as primary key. These tables have relations with several other small tables where lists are stored. So the fields in the main tables are integer fields related to a small table where that integer points to a text field. I'm trying to figure out why it takes 7 minutes during office hours and less than one 1 outside office hours. There are about 12 users. Anyone have some tips for me? rg, Eric Edit: SQL code: SELECT t1.TicketNummer ,t1.SiteNummer ,t9.name AS Categorie ,t7.name AS Klant , (CASE WHEN t11.RapportNaam IS NULL THEN t5.FullName ELSE t5.FullName END) AS AangenomenDoor , (CASE WHEN t11.RapportNaam IS NULL THEN t1.AangenomenOp ELSE t1.AangenomenOp END) AS AangenomenOp , (CASE WHEN t11.RapportNaam IS NULL THEN t1.aangenomenop ELSE t8.UitgevoerdOp END) AS UitgevoerdOp , (CASE WHEN t11.RapportNaam IS NULL THEN t5.FullName ELSE t8.UitgevoerdDoor END) AS UitgevoerdDoor , (CASE WHEN t11.RapportNaam IS NULL THEN 'Via ESIT' ELSE t11.RapportNaam END) AS Rapport ,t8.VraagNummer ,t8.Uploaded ,t2.Name AS PrioCode , t4.offertenummer , t4.ponummer , CASE WHEN t4.hersteldoor=0 THEN '' WHEN t4.hersteldoor=1 THEN 'Aannemer' WHEN t4.hersteldoor=2 THEN 'Eigen personeel' WHEN t4.hersteldoor=3 THEN 'Operator' ELSE 'Aannemer' END AS TeHerstellenDoor , t12.refnraannemer , t12.offertebedrag , t13.name as Operator , t4.operatorRefNr ,(CASE WHEN t1.IsManco ='true' AND t1.IsOpgelost = 'false' THEN 'Manco' WHEN t1.IsConstatering ='true' THEN 'Constatering' ELSE '' END) AS IsManco ,(CASE WHEN t1.IsOpgelost ='true' THEN 'Direct opgelost' WHEN t6.verwijderd = 'true' THEN 'Verwijderd' ELSE t3.name END) AS VerwerkingsGroep ,(CASE WHEN (year(t4.DatumTechnischGereed)<2000 or t4.technischgereed='false') THEN NULL ELSE CONVERT(VARCHAR,t4.DatumTechnischGereed,20) END) AS DatumTechnischGereed ,(CASE WHEN (year(t4.DatumAdministratiefGereed)<2000 OR t4.administratiefgereed='false') THEN NULL ELSE CONVERT(VARCHAR,t4.DatumAdministratiefGereed,20) END) AS DatumAdministratiefGereed ,(CASE WHEN (year(t4.DatumFinancieelVerwerkt)<2000 OR t4.financieelverwerkt='false') THEN NULL ELSE CONVERT(VARCHAR,t4.DatumFinancieelVerwerkt,20) END) AS DatumFinancieelVerwerkt , (CASE WHEN t4.financieelverwerkt = 'true' THEN 'Ja' ELSE '' END) AS financieelVerwerkt , (CASE WHEN t4.AdministratiefGereed = 'true' THEN 'Ja' ELSE '' END) AS AdministratiefGereed , (CASE WHEN t4.TechnischGereed = 'true' THEN 'Ja' ELSE '' END) AS TechnischGereed , t10.Name AS Aannemer , t6.verwijderd , t14.fullname AS MutatieDoor ,(CASE WHEN (year(t4.MutatieOp)<2000) THEN NULL ELSE t4.MutatieOp END) AS MutatieOp FROM MainTickets AS t1 LEFT JOIN PrioCode AS t2 ON t1.PrioCode =t2.iD LEFT JOIN TicketVerwerking AS t4 ON t1.TicketNummer =t4.TicketNummer LEFT JOIN Verwerking AS t3 ON t4.VerwerkingsGroep =t3.ID LEFT JOIN Gebruikers AS t5 ON t1.AangenomenDoor =t5.ID LEFT JOIN TicketNummers AS t6 ON t1.TicketNummer=t6.TicketNummer LEFT JOIN Klanten AS t7 ON t1.Klant=t7.ID LEFT JOIN SubTickets AS t8 ON t8.TicketNummer =t1.TicketNummer LEFT JOIN Categorie AS t9 ON t9.ID =t1.Categorie LEFT JOIN Aannemers AS t10 ON t10.ID =t4.aannemeropdracht LEFT JOIN FormIDs AS t11 ON t8.formidcode=t11.FormIDcode LEFT JOIN OfferteAannemers AS t12 ON (t4.offertenummer=t12.offertenummer AND t12.aannemer=t4.aannemeropdracht) LEFT JOIN Operators AS t13 ON t4.operator=t13.id LEFT JOIN Gebruikers AS t14 ON t4.mutatiedoor =t14.ID ORDER BY t1.TicketNummer I ran an fragmentation count query but I don't know if this is bad or not: @dezso Yes, there is no where condition here. This table should show all tickets. I'm trying to get my customer to understand this is or will be a problem but I'm not there yet... @Eric How many are there? You realize this does nothing at all: CASE WHEN t11.RapportNaam IS NULL THEN t5.FullName ELSE t5.FullName END? It's just t5.FullName. There are other problems with the query. 349295 records. And all these YEAR(DateColumn) < 2000 should be converted to DateColumn < '2000-01-01' During work hours, take a look at sys.dm_exec_requests and see what the wait_type column says. This will tell you what the requests are waiting for. Right before working hours, you could run DBCC SQLPERF ('sys.dm_os_wait_stats', CLEAR); and then look at sys.dm_os_wait_stats to see the accumulated stats during the day. Do you have indexes defined on any of these tables? If not, then table scans might be clogging your I/O system, and locks might be causing some blocking. If people are running SQL Profiler traces during work hours, those could be slowing down the entire system. You could detect those by quering sys.traces. Running a careful profiler trace yourself might reveal some interesting facts about this query. Try capturing a Showplan XML Statistics Profile event when it runs. Maybe the query processor is choosing a very bad query plan. Maybe the plan is generating intermediate tables that have a ridiculous number of records, or maybe there is a bad nested loop that would work better with an index or with a merge join. Since this is an external server, another possibility is that you are simply overwhelming network bandwidth during working hours. You mentioned in a comment that there was a lot of data coming back. Adding some filters in the query might help-- if that is an acceptable solution for your application. Not the really the answer, but it helped. Also Gulli Meels answer helped. Next step is to redesign data retrieval with filter before sending to sql instead of filtering after. Thanks all. @Eric: Good idea! I was assuming you needed all that data, but if you can filter it at the server, that should help enormously. (I updated my answer to mention this.) @PaulWilliams: and some indexes that will go along those WHERE clauses might not hurt at all. A careful Profiler trace would be actually a server trace (with stored procedures, not Profiler) :-). Check and compare execution plan when the query run during office hours and after office hours. If plans are not same then a different plan might be causing issue .If the plans are same then it could be network issue or it might be possible that server has too much load during office hours due to high workload and thus waits are more.. Same query can generate different plan and those are quite different from each other and thus could take totally different time to execute. With such a high diff in time(e.g. OP's query) could be caused by diff plan. With same plan, at different time the execution time could be different at different time of the day depending on the workload e.g. query is CPU intensive and there are lots of queries which are using CPU during office hours and thus query execution takes time. There are so many other causes but first you have to rule out that both plans are same or not and then start next step.
common-pile/stackexchange_filtered
Is it possible to add a nuget package as runtime only dependency? I'm working with the following projects: MyFramework.csproj (class library) MyCustomerApp.csproj (class library) References MyFramework MyLauncher.csproj (Executable program) references MyLauncherDependency.nupkg MyCustomerApp.csproj is the 'runnable' project which works like so: MyLauncher.exe is copied from the MyLauncher project to the output of MyCustomerApp When running MyLauncher.exe, this uses Assembly.Load(..) to load the MyCystomerApp.dll There's a specific reason as to why we have this mechanism which I won't get into - consider it out of scope for now. Now here's the problem; MyLauncherDependency is a dependency of MyLauncher, but its not a dependency of MyCustomerApp. Therefore MyLauncherDependency is not a compile time dependency of MyCustomerApp - but it is a runtime dependency - because it needs MyLauncherDependency.dll at runtime. I don't want to add MyLauncherDependency.nupkg to MyCustomerApp because I don't want to give engineers access to classes from MyLauncherDependency in MyCustomerApp. So my question is: How can I add MyLauncherDependency.nupkg (or MyLauncherDependency.nupkg) to MyCustomerApp as a runtime only dependency? MyCustomerApp depends on MyLauncher ? no? then there is no dependency at all ... it's more likely publishing problem MyCustomApp does not depend on MyLauncherDependency at all. It is MyLauncher that has the dependency, so when copying MyLauncher.exe you would need to copy all dependencies. Or make MyLauncher fetch all dependencies it needs, or package MyLauncher as a single exe. @Selvin I'm using <content> tags to copy the MyLauncher.exe straight into the bin/debug so there's not reference @JonasH you're right i think. There a quite a few dependencies however - and i'd like to be able to say 'hey, just copy all dlls from this nuget package to the output and generate the right binding redirects if you can (in case of version conflicts)' instead of having to manually copy and match dlls. I feel like this is not really easy to do, impossible even, but i'm really just fishing for solutions. @sommen will the user copy MyLauncher manually? if so, perhaps package it as a zip-file? Or will it be a nuget reference? In that case there should not be a problem? Do you have to use Nuget? MEF (Managed Extensibility Framework) is great for loading plug-ins at runtime. https://learn.microsoft.com/en-us/dotnet/framework/mef/
common-pile/stackexchange_filtered
Storing keys in KeyChain with KeyChainItemWrapper I'm using KeyChainItemWrapper class, provided by Apple's Sample Code to save the authentication token to the keychain. KeychainItemWrapper *keychain = [[KeychainItemWrapper alloc] initWithIdentifier"JetTaxiApp_AuthToken" accessGroup:nil]; But when I'm trying to set the value to keychain, an odd exception is raised [_authenticationTokenKeychain setObject:authenticationToken forKey: @"auth_token"]; Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Couldn't add the Keychain Item.' The keychain doesn't exist yet (at the moment of this call) What can cause this exception? Make sure you added the keychain access plist file. Take a look at http://stackoverflow.com/questions/5859615/iphone-debugging-the-generickeychain-example You need to use standard keys, so here your @"auth_token" is incorrect. The keys that can be used for this purpose and the possible values for each key are listed in the “Keychain Services Constants” section. source, with list of valid constants: Keychain Services Reference For instance, you can use: [_authenticationTokenKeychain setObject:authenticationToken forKey: (__bridge NSString *)kSecValueData]; When using the ARC version of keychainItemWrapper, you need to do it the following way : [_authenticationTokenKeychain setValue:authenticationToken forKey:(__bridge NSString*)kSecValueData]; @DamienMATHIEU I'm using the ARC version but I'm still having issues. I get this error: '[<KeychainItemWrapper 0x89c5900> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key v_Data.' Any ideas what could be wrong? @Interfector instead of using setValue, use setObject [_authenticationTokenKeychain setObject:authenticationToken forKey: @"auth_token"]; For code snippet above, key param is only can use the keys provided from sdk. You can find all in SecItem.h
common-pile/stackexchange_filtered
Behavior of matrix rank under thresholding of its elements Let $A$ be a $n \times n$ real matrix of, say, rank $r$. Consider the matrix $$\max \{0,A\}$$ whereby each negative element of $A$ is set to $0$ and the non-negative elements are left unchanged. Is there anything known about by how much the rank of $A$ can increase by such a deformation? I am typically thinking of the situation when $r \ll n$ and I am wondering if there are conditions known which if true then the new matrix also continues to have a rank far below $n$. An analogy can be drawn to how under the Hadamard product rank is sub-multiplicative. Hadamard product of two low rank matrices can't be of rank arbitrarily high. Well, here's an easy example: if $A$ has rank one, then the deformed matrix has rank at most two. The deformation of a matrix of rank two can have full rank, e.g., $$\pmatrix{1&1&-1&-2&-3\cr1&2&0&-1&-2\cr1&3&1&0&-1\cr1&4&2&1&0\cr1&5&3&2&1\cr}$$ Maybe this is an effect of the fact that here the rank i.e $2$ is already pretty close to the dimension i.e 5? I leave it to you, gradstudent, to show that 5 is a variable here, that is, the construction works for every $n$. Okay. So for every n you can have a rank 2 matrix whose rank after max-0 will be n. Or maybe a bit easier to see: $$ \pmatrix{1 & 0 & -1 & -2 & -3\cr 2 & 1 & 0 & -1 & -2\cr 3 & 2 & 1 & 0 & -1\cr 4 & 3 & 2 & 1 & 0\cr 5 & 4 & 3 & 2 & 1\cr} = \pmatrix{1\cr 2\cr 3\cr 4\cr 5} \pmatrix{1 & 1 & 1 & 1 & 1} - \pmatrix{1\cr 1\cr 1\cr 1\cr 1\cr} \pmatrix{0 & 1 & 2 & 3 & 4}$$ How does it make it obvious that the rank is 5 after the max-0 operation? Lower triangular matrix with $1$'s on the diagonal. Yes. I meant if that rank 2 decomposition you wrote somehow helps understand why a max of that is rank 5 instead of looking at the full matrix. In some cases, the rank is preserved under thresholding. For example, let $$\rm A := \begin{bmatrix} 1\\ 0\\-1\end{bmatrix} \begin{bmatrix} 1\\ 1\\ 1\end{bmatrix}^\top = \begin{bmatrix} 1 & 1 & 1\\ 0 & 0 & 0\\-1 & -1 & -1\end{bmatrix}$$ Note that $\rm A$ is a rank-$1$ matrix. Thresholding $\rm A$, we obtain another rank-$1$ matrix $$\max \{ \mathrm O_3, \mathrm A \} = \begin{bmatrix} 1 & 1 & 1\\ 0 & 0 & 0\\ 0 & 0 & 0\end{bmatrix} = \begin{bmatrix} 1\\ 0\\ 0\end{bmatrix} \begin{bmatrix} 1\\ 1\\ 1\end{bmatrix}^\top$$ Thinking of the thresholding operation in terms of the Hadamard product $$\max \{ \mathrm O_3, \mathrm A \} = \underbrace{\begin{bmatrix} 1 & 1 & 1\\ 0 & 0 & 0\\-1 & -1 & -1\end{bmatrix}}_{= \mathrm A} \circ \underbrace{\begin{bmatrix} 1 & 1 & 1\\ 1 & 1 & 1\\ 0 & 0 & 0\end{bmatrix}}_{=: \mathrm B}$$ where $\rm B$ is a binary matrix that contains information pertaining to the signs of the entries of $\rm A$. In this case, $\rm B$ is also a rank-$1$ matrix. Since $$\mbox{rank} (\mathrm A \circ \mathrm B) \leq \mbox{rank} (\mathrm A) \cdot \mbox{rank} (\mathrm B)$$ and $\mbox{rank} (\mathrm A) = \mbox{rank} (\mathrm B) = 1$, the rank does not increase under thresholding. Since $\mathrm A \circ \mathrm B \neq \mathrm O_3$, we conclude that the rank is actually preserved.
common-pile/stackexchange_filtered
Why is my istream going bad after I call getline with it I am writing code for a coding class, and I am writing a class called MyString which is supposed to be able to store a dynamic char array that acts like a String. However, when writing a read() function that is meant to act like the getline() function, I ran into an error after calling getline() with an istream object. After the call, the istream object was no longer good, and I could not figure out why. Any help/ideas would be appreciated. Here is the erroring method of the MyString.cpp file: //Copys contents of in into calling object up to when the deliminator is found in in void MyString::read(istream& in, char deliminator) { char copyString[MyString::MAX_INPUT_SIZE]; if (in.good()) { cout << "pre:all good" << endl; } else { cout << "pre:all bad" << endl; } in.getline(copyString, deliminator); if (in.good()) { cout << "post:all good" << endl; } else { cout << "post:all bad" << endl; } delete[]theString; theString = new char[strlen(copyString) + 1]; strcpy(theString, copyString); } Here is the part of my main function that is calling that my read() method: cout << endl << "----- now, line by line" << endl; ifstream in2("mystring.txt"); assert(in2); while (in2.peek() == '#') { in2.ignore(128, '\n'); } if (in2) { cout << "in2 is good!" << endl; } s.read(in2, '\n'); while (in2) { cout << "in2 is still good: " << in2.good() << endl; cout << "Read string = " << s << endl; s.read(in2, '\n'); } in2.close(); Here is the text file: # This file has some strings that are used in the string test to check # reading strings from files. The default overloaded >> of your string # class should skip over any leading spaces and read characters into # the string object, stopping at the first whitespace character (this is # similar to the behavior of >> on char *). The read method of the # string class is a little fancier. It allows client to restrict # how many characters at max to read and what character to use as # delimiter, so you can stop at newline instead of space, for example. # Reading consumes the delimiting character, so the next read starts # after that. # The first time we will read individual words, next we read whole lines I tried fidgeting around with my parameter, and changing istream to ifstream, but it did nothing. I added the cout statements to test where the fault code was, and once I found that it was the in.getline() statement that was making the istream go bad, I tried looking up my problem from there. I couldn't find anything on this problem despite someone definitely also running into this before. ny help or ideas would be greatly appreciated.
common-pile/stackexchange_filtered
Git: how to mark a file as conflicted after "git merge-file"? I've been using "git merge-file" to help me port code from a different repository. This works great. However, when a merge conflict happens, though "git merge-file" will properly report it, the file isn't marked as needing resolution in "git status". In the status, the file is just seen as modified (understandably, since the merge happened outside of git's usual flow). This is a problem because sometimes when importing a large number of files, I'll miss the message highlighting the conflict. Is there a way to manually tell git that the file needs resolution? I tried "git update-index --unmerged somefile", but that didn't appear to work: the file isn't listed as conflicted. @phd: I think (it's not entirely clear from the question) that he's not run git merge itself at all, so there are no undo index entries to recover (no REUCs for git update-index --unresolve to find). Indeed, I haven't used "git merge", only "git merge-file". The former interacts with git's index state properly, the latter doesn't at all. Possible duplicate of Is there a way to make Git mark a file as conflicted? You must use git update-index --index-info or git update-index --stdin. In particular, you must create nonzero stage index entries: up to three of them for each file. As the documentation notes, you should also remove the corresponding stage-zero entry (though you may want to make sure that it matches either the HEAD commit version or the work-tree version first, so as to avoid clobbering carefully-staged variants such as those made by git add -p). Git represents a "failure to merge" case by writing nonzero-stage entries to the index. The work-tree version of the file can contain literally anything as it is entirely irrelevant (to the updating of the index, that is; see comments below). The stage-1 entry is the base version of the file; the stage-2 entry is the --ours version; the stage-3 entry is the --theirs version. Note that one or more of these may be missing, i.e., some stage slots may be empty. For instance, if the base version is missing, the original conflict was an "add/add" conflict. Running git mergetool, for instance, extracts the three versions from the higher numbered stage entries and then invokes your chosen merge tool on the three input files. The git status command reports an unmerged state for the files. Note that the content of the three versions must exist in the repository. To write content to the repository database, use git hash-object -w. See the git hash-object documentation for details. The update-index command takes the hash ID of the in-repository blob object (plus the mode, stage number, and name, of course). "The work-tree version of the file can contain literally anything as it is entirely irrelevant." ... that's only true with merge tools set up to discard existing merge results. the kdiff3 setup does, the vimdiff one doesn't. What on earth is vimdiff doing that it’s looking at the workdir and not using the high stage index entries? @jthill: interesting - I have not actually used vimdiff (I just ran it once to see how it looked). Perhaps I should experiment more... @EdwardThomson it is looking at the index entries, it's just also taking the existing worktree content for exactly what it is, the results of any automerging you wanted done. I see. I’ll have to play around with it a bit.
common-pile/stackexchange_filtered
Looping to find related records Looking for assistance/direction in setting up a loop? function to find related records in a table. The table (tblTransactions) holds information about various transactions we are tracking. I am also using this table to reference a predecessor transaction. Now I am seeking a way to loop through the table to find related records. The table has the following fields: TransID - primary key Grantor - name field Grantee - name field PTrans - number field that references TransID Some sample data: +---------+---------+---------+--------+ | TransID | Grantor | Grantee | PTrans | +---------+---------+---------+--------+ | 1 | Bob | Sally | 0 | | 2 | Jane | Emily | 0 | | 3 | Sally | Beth | 1 | | 4 | Beth | Sam | 3 | +---------+---------+---------+--------+ Ideally I'd like to be able to start with TransID 4 and show all the transaction data, on separate rows, for the selected transaction (4) and it's predecessors. Results would be: +---+-------+-------+ | 4 | Beth | Sam | | 3 | Sally | Beth | | 1 | Bob | Sally | +---+-------+-------+ Your question concerning querying self-referential data is very similar to this question in which the user has a table of employees, each of which may have a supervisor whose employeee record is also present in the same table, thus forming a hierarchy. A relatively easy way to solve this would be using a DLookup expression within a loop or within a recursive call until the expression returned Null. For example, here is a recursive variant: Function TransLookup(lngtrn As Long) Dim lngptr lngptr = DLookup("ptrans", "tbltransactions", "transid = " & lngtrn) If Not IsNull(lngptr) Then Debug.Print lngtrn ' Do something with the data TransLookup (lngptr) End If End Function Evaluated with your data this would yield: ?TransLookup(4) 4 3 1 This is of course only printing the transaction ID, but the function could alternatively populate a separate table with the data for each transaction if required. However, returning the results record-by-record or populating a temporary table seems inelegant if we can construct a single SQL query to return all of the results in one go. However,since MS Access does not support recursive SQL queries, the difficulty when querying such hierarchical data is not knowing how many levels to code ahead of time. As such, you could use a VBA function to construct the SQL query itself, and thus always incorporating as many levels as is necessary to return the full dataset. Indeed, this is the approach I put forward in my answer to the related question linked above - the function provided in that answer could equally be adapted to suit this situation, for example: Function BuildQuerySQL(lngtrn As Long) As String Dim intlvl As Integer Dim strsel As String: strsel = selsql(intlvl) Dim strfrm As String: strfrm = "tbltransactions as t0 " Dim strwhr As String: strwhr = "where t0.transid = " & lngtrn While HasRecordsP(strsel & strfrm & strwhr) intlvl = intlvl + 1 BuildQuerySQL = BuildQuerySQL & " union " & strsel & strfrm & strwhr strsel = selsql(intlvl) If intlvl > 1 Then strfrm = "(" & strfrm & ")" & frmsql(intlvl) Else strfrm = strfrm & frmsql(intlvl) End If Wend BuildQuerySQL = Mid(BuildQuerySQL, 8) End Function Function HasRecordsP(strSQL As String) As Boolean Dim dbs As DAO.Database Set dbs = CurrentDb With dbs.OpenRecordset(strSQL) HasRecordsP = Not .EOF .Close End With Set dbs = Nothing End Function Function selsql(intlvl As Integer) As String selsql = "select t" & intlvl & ".* from " End Function Function frmsql(intlvl As Integer) As String frmsql = " inner join tbltransactions as t" & intlvl & " on t" & intlvl - 1 & ".ptrans = t" & intlvl & ".transid " End Function Now, evaluating the BuildQuerySQL function with Transaction ID 4 yields the following SQL UNION query, with each level of nesting unioned with the previous query: select t0.* from tbltransactions as t0 where t0.transid = 4 union select t1.* from tbltransactions as t0 inner join tbltransactions as t1 on t0.ptrans = t1.transid where t0.transid = 4 union select t2.* from ( tbltransactions as t0 inner join tbltransactions as t1 on t0.ptrans = t1.transid ) inner join tbltransactions as t2 on t1.ptrans = t2.transid where t0.transid = 4 Such function may therefore be evaluated to construct a saved query, e.g. for Transaction ID = 4, the following would create a query called TransactionList: Sub test() CurrentDb.CreateQueryDef "TransactionList", BuildQuerySQL(4) End Sub Or alternatively, the SQL may be evaluated to open a RecordSet of the results, depending on the requirements of your application. When evaluated with your sample data, the above SQL query will yield the following results: +---------+---------+---------+--------+ | TransID | Grantor | Grantee | PTrans | +---------+---------+---------+--------+ | 1 | Bob | Sally | 0 | | 3 | Sally | Beth | 1 | | 4 | Beth | Sam | 3 | +---------+---------+---------+--------+ Thank you @lee-mac, I did see that post and didn't think it would apply to my specific situation. This suggestion returns 3 levels, but what if I don't know how many levels it would take to reach the top (first transaction in the sequence)? @Ember Did you read my post in full? The VBA functions provided will handle any number of levels. yes I did read the whole thing, multiple times in fact, but apparently I didn't understand it fully. I added your suggested BuildQuerySQL to a new module and added the SQLquery to a new query. I didn't see how the two related to one another, but when I ran my new query (with your suggested code) it worked, but it only showed 3 levels. Currently in my db I have a 5 level chain. I figured out how to nest the inner joins and now when I run the query I do see my 5 level chain. in re-re-reading everything, I'm thinking that the suggested querySQL was not meant to be added directly into a query but that is what would be added once the BuildQuerySQL function was referenced. I added a command button and on the OnClick added an event procedure to call the docmd.openmodule "TransLookup", "BuildQuerySQL". TransLookup is what I called the module since there were several functions provided. When I click on my command button it just takes me to the module but no errors pop up...thinking I'm still missing a piece. The search continues... ooo, I was right! the querySQL is an output when you run the BuildQuerySQL. I was able to add, and run, the Sub test () and totally see how this works. Now how to get it to ask for, or look for, the starting transid. current code forces it to #4, which I can change in the code and run to view, but how to pass this value to the function. Getting close... Glad to hear that you got there in the end. To prompt the user to supply an appropriate transaction ID, you could use a basic VBA InputBox, but this is unprofessional in my opinion; I would instead suggest prompting the user with an MS Access form in which they may either specify a transaction ID in an edit box, or select a valid transaction ID from a list box or combo box. You can then easily reference the content of the form control. thank you so much for your assistance! The function is working beautifully!
common-pile/stackexchange_filtered
batch file for merging large CSV in one excel sheet I have large CSV multiple file say 20-30mb which has same header however the number rows of those files are different. I need a batch file which will copy the content of all the CSV file in one excel sheet. Hope you guys will help me in creating a batch file please.. I tried creating macros but ends with wrong or improper data. kindly help me please type *.csv >newfile.csv & newfile.csv ? hi stephan, i tried this but it is copying the headers of all the files..as the headers are same so i want one single sheet with header and contents of files..hope u understood... for %%a in (*.txt) do @type %%a|find /v "Header line" >newfile.csv rem open in excel: newfile.csv @echo off for %%a in (*.csv) do set /P "header=" < "%%a" & goto continue :continue ( echo %header% for %%a in (*.csv) do findstr /V /C:"%header%" < "%%a" ) > large.txt ren large.txt large.csv EDIT: Below there is an example of what this program do: C:\Users\Antonio\Documents >type file1.csv Common header for all files File One line one File One line two File One line three C:\Users\Antonio\Documents >type file2.csv Common header for all files File Two line one File Two line two File Two line three C:\Users\Antonio\Documents >type file3.csv Common header for all files File Three line one File Three line two File Three line three C:\Users\Antonio\Documents >test C:\Users\Antonio\Documents >type large.csv Common header for all files File One line one File One line two File One line three File Two line one File Two line two File Two line three File Three line one File Three line two File Three line three hi all, the above all code is not working..could you please help me with more suggestions... See the added example above. What exactly you mean with "is not working"? Got you errors? Got you wrong result? If the CSV files have less than 65K lines in them then this will work: The final CSV file can have more than 65K lines. @echo off set "flag=" for %%a in (*.csv) do ( if not defined flag ( copy "%%a" temp.tmp & set flag=1 ) else ( more +2 "%%a" >>temp.tmp ) ) ren temp.tmp "newfile.csv"
common-pile/stackexchange_filtered
"Biztalk projects" icon missing in Visual Studio I have Biztalk 2002 and Visual Studio 2003. In Visual Studio I create a blank solution, I right click on the new solution to add a new project, which I want to select "Biztalk Projects". However, the BizTalk Projects selection is missing from my environment. Only C#, C++ Projects etc shows up. I've also re-installed Biztalk 2002 (complete install, including tools for developers) but these Biztalk templates are still missing. What do I need to do? BTS 2002 has it's own developer tools. It is not supported in VS 2003
common-pile/stackexchange_filtered
Need help wiring a new double pole line voltage thermostat [ Just bought my first home and this is my first time posting, so please forgive me if my terminology is incorrect. I currently have bedrooms upstairs each with 1 baseboard heater and thermostat for each. The circuit breaker is off and I've undone most of the wiring to it. The thermostat is an analog, single pole line voltage. I'd like to upgrade to a digital double pole. It looks like there is 3 wires (really groups of wires, I don't know the term for this), possibly 10-3 or 12-3 coming into the junction box. I didn't specifically look that the gauge. It might actually be 10-2 or 12-2. Do I simply need to connect 2 hots and 2 neutrals to the thermostat and I am set? Can you provide photos of the insides of the boxes? The images I have are too big. Can you get us another photo with the black bundle out of the way? Hopefully that picture is a little better, each yellow bundle has three wires. A bare ground, one white neutral, and one black hot. There are three yellow bundles coming to the junction box. The neutrals are all tied together with the wire nut, one hot leg from two separate yellow bundles go to the thermostat. And lastly one ground ties to the thermostat itself. Is the breaker a single handle or double handle? From what we can see here it should be single handle or single pole. Depending on how your double pole new thermostats get power for their own electronics you may or may not be able to use them here as single pole devices. Electric panel is not labeled. My guess is single pole and I may not be able to use double pole is what I was starting to think also. In years past many 240 v baseboard heaters used thermostats that only broke 1 leg this makes a potentially dangerous situation as there was always 120 on the heater. You really need to know what the voltage is. OK, quick terminology issue: Single-pole and double-pole. The poles are channels, which could have any purpose. A single-pole switches one channel; a double-pole switches two. (ignore the "st"). (source) For a thermostat, one pole is sufficient to turn the heaters on and off. For the other pole, you'd simply bind the wires together - and I think that's what's been done with the white wires. You say this powers 2 heaters, and that's the dead giveaway. The power supply would be one group of wires, and the outputs would be two groups. Now look at what's going on with that switch: you have one wire spliced into the red thermostat wire (that must be the power supply) and two wires spliced into the black wires (those must be the heaters). Follow the one wire and it goes to the Romex on the right. That Romex goes to the power source, clearly, and its wires should be considered "LINE" (always-on). Which means the white wire in that bundle is the other pole. The other Romex cables go to the heaters, and they are "LOAD" (switched). This wire is /2 Romex since there's no red wire. (ground is not counted, so /2 means black and white). The yellow sheath suggests 12/ since some manufacturers recently adopted that as a color code. The markings on the sheath say for sure. Are the white wires hot (240V) or neutral (120V)? We can't tell. It would be wired the same either way. 240V heaters don't need neutral, so they use 12/2 or 10/2 wire, and re-designate and supposedly, re-mark the white as another "hot". Somebody went to a lot of trouble to put red tape on the Romex cables... shrug. In the old days, marking wasn't required if the use was obvious. So we must go down to the breaker panel. Looking at the layout, it should be obvious that there's a unit of "space". If the breaker takes 2 spaces, it is a 240V circuit. There won't be many of those. Simply, turn off one at a time and see what it knocks out. Generally there is one thing on each 240V circuit (well, oven and stove may share a circuit). This is a good time to mark those breakers once you figure what they control. Not least it helps you eliminate; heaters are very annoying to test because they take a long time to make noticeable heat. If it's a 240V breaker, obviously, these are 240V heaters. Although the smart thermostat may not care if it's 120V or 240V. It needs to power itself, but it may be inherently multi-voltage. Many things are nowadays. It goes without saying that you have to find the breaker in order to change the thermostat. If you don't realize that, you should not be doing electrical work. The OP actually says there's one thermostat per heater - I think it's likely these are 120V heaters and the second wire on the thermostat is for other outlets. I unintentionally downvoted but will remove that if I can, I don't think I can unless this post is edited. @batsplatsterson You will be able to if the post is edited. Hold on... Yeah my ipad does that all the time... If I am reading this question correctly, there is just one heater per thermostat. There are three cables in the box, the yellow jacket tells me 99% certain they are 12/2. I think it's most likely that one cable is the feed / source, one is the heater, and one continues to other outlets - lights or receptacles. So I'd figure these are 120V heaters; two blacks spliced to the black lead on the thermostat are the source and other outlets, and the black spliced to the red lead is the heater. This is easy enough to confirm, if the breaker for the circuit supplying the heaters is a single pole breaker, it's a 120V circuit. If not, stop now, disregard the rest of this answer. One remark: I would not use a two pole thermostat with a 120V heater. A two pole thermostat may make sense with a 240V heater, but I don't like the idea of switching the neutral on a 120V heater. If however these are 120V heaters but you still want a two pole thermostat, to install a two pole thermostat, basically you just have to separate the white wires just as the black wires are separated. This is what I'd do: Before taking anything apart, label the cable sheaths with a sharpie, A B and C, take a picture, and make a sketch what went where before you started. Let's say number the two on the left side of the box in the picture which are spliced to the black lead A and B, and the cable with the black wire spliced to the red lead C. This is super important if anything goes wrong. Just because I have seen a lot of junky yellow wire nuts out there, buy some top quality wire nuts rated for three #12 solid wires. I like the tan Ideal Twisters. If you're not familiar with wire nut splices, do a little homework and practice on some scrap. Heaters are heavy loads and good splices are critical. Verify which side is the source. Remove the thermostat leads from the splices and replace the wire nuts. Turn the breaker on temporarily, test with a non contact voltage tester, then turn the breaker back off. With the thermostat removed and breaker on the A and B black wires should be hot, the C black wire should be dead, and the white wires and grounds should be dead. If this is not the case, stop, put everything back as it was, and consider calling an electrician. If it is as expected, proceed - but don't forget to turn the breaker off first. Review the instructions and labeling of the double pole thermostat. Identify the Line leads which go to the source, and the load leads which go to the heater - probably one black and one red line, one black and one red load. Splice the A and B blacks to the line voltage black, the A and B whites to the line voltage red; splice the C black to the load black, the C white to the load red. Close up the box and see if everything is working as expected, heaters, receptacles, lights, etc. OP bought the wrong thermostat. You cannot substitute a double pole thermostat for an original single pole thermostat.The number of "poles" on the thermostat must match those of the breaker. One pole or space it takes up in the breaker panel is 120 volt, 2 poles is either 208 or 240 volt in the context of a wall heater. (There are, as an aside 30, 40 50 plus double pole breakers for other uses). So tell us how many poles and the amp rating of the heater breaker and go but the appropriate thermostat. From there we can help you with the wiring. The wiring in the picture does not look like a pro did it. 1. Not enough twists in the wire. 2. Very long Romex sheathing extending into the box, which is a no-no. Both are potential fire hazards and need to be addressed, IMHO. Can you explain why the 2 issues you've identified are issues? I've seen professional electricians not twist the wires at all except that which comes from twisting the wire nut on. And can you explain why having that much sheathing in the box is bad? Is it a code violation? Is it just bad workmanship? Telling a rookie that something is wrong doesn't help them much without explaining why it's wrong and how to fix it. A DP bimetal (electromechanic) thermostat is perfectly happy on a 120V system, simply connect the poles in series...(likewise, you can use a SP thermostat on 240V, just by having the other hot leg spliced through unswitched) I was called out for both during electrical inspections. I cannot cite chapter and verse of the code. The wires need to be twisted to ensure contact and that they won't easily come undone. I think that some inspectors look for the number of twists which may be an indicator that the job was done right. I was told once that there should be no more than a 1/4-inch sheathing extending into the box past the clamp. Just trying to share what I know to be helpful, not be a critic. It appears I accidentally commented on my own post and so this explanation got lost in what appeared to be a double post.
common-pile/stackexchange_filtered
Firebase check if a value exists without reading a snapshot or trying a write (for unique usernames)? I've been stuck on this problem for many hours now, so any help is appreciated. Trying to make an Android app with Firebase for user authentication (simple-login email and password) along with unique usernames. I have my sign-up screen fields laid out on a single screen e.g.: "Enter Username" "Enter Email Address" "Enter Password" I'm very confused as how how to query the database to check if the username exists or not without reading a database snapshot and without attempting to write the username to the database (because this is happening while the user is in state auth == null, so while on the sign-up page before the user has created his account I want to inform the user whether his username is taken or not). I mean, this feels like it should be very simple, just a simple query to Firebase with a string and just getting Firebase to return True or False, but after hours of googling I could find nothing. The reason I don't want to use a snapshot to do this is because I do not want to expose all my user's names and their UIDs to the public by setting "read" to true (I followed this guide so my security rules are set up just like this, along with my database structure Firebase android : make username unique). Here are my rules, and they work currently (I don't like the fact that the read is set to True which is why I'm asking the question though): { "rules": { "usernames": { ".read": true, "$username": { ".write": "auth !== null && !data.exists()" } }, "users": { "$uid": { ".write": "auth !== null && auth.uid === $uid && !data.exists()", ".read": "auth !== null && auth.provider === 'password' && auth.uid === $uid", "username": { ".validate": "(!root.child('users').child(newData.val()).exists() || root.child('usernames').child(newData.val()).val() == $uid)" } } } } } And this is my data: { "usernames" : { "abcd" : "some-user-uid" }, "users" : { "\"some-user-uid\"" : { "username" : "abcd" } } } Thanks! There is unfortunately, no way to test whether the data exists without actually downloading it via the SDK. Data structures are going to be supreme here (recommended reading: NoSQL Data Structures and you shouldn't be afraid to denormalize a bit of data when optimization and scale are critical. Generally speaking, you should keep your data well structured so payloads are small and fetch it. If you're fetching something that can't wait for the bytes to be fetched (e.g. games, strange one-off admin ops on very large data sets, et al) then here are a few reasonable approaches to simulate this: Fetching a list of keys via the REST API Using the attribute shallow=true in a call to the REST API will prevent loading of a large data set and return only the keys at that path. Note that if you store a million records, they still have to be loaded into memory on the server (slow) and you still have to fetch a million strings (expensive). So one way to check the existence of data at a path, without actually downloading the data, would be to make a call to the path, such as https://<YOUR-FIREBASE-APP>.firebaseio.com/foo.json?shallow=true, and check whether any keys are returned. Creating a denormalized index you can query instead If you really need to squeeze some extra performance and speed out of your Firebase Database (hint: you don't need this unless you're running millions of queries per minute and probably only for gaming logic and similar), you can dual-write your records (i.e. denormalize) as follows: /foo/data/$id/... data goes here... /foo/index/$id/true (just a boolean value) To dual write, you would use the update command, and a write similar to the following (Android SDK sample): public void addRecord(Map<String, Object> data) { DatabaseReference db = FirebaseDatabase.getInstance().getReference(); // create a new record id (a key) String key = db.child("foo").push().getKey(); // construct the update map Map<String, Object> dualUpdates = new HashMap<>(); dualUpdates.put("/data/" + key, /* data here */); dualUpdates.put("/index/" + key, true); // save the new record and the index at the same time db.child("foo").updateChildren(dualUpdates); } Now to determine if a record exists, without actually downloading the data, I can simply query against /foo/index/$id and try DataSnapshot.exists(), at the cost of downloading a single boolean. Thanks for the answer! What solution do you suggest for maximum security of the data? I'm alright with my current setup (because it works) but the read = true is slightly unnerving because then anyone can see all my users' usernames and their UIDs, correct? The best security would be to set read: true on the specific records, but not allow read of the parent path. That would prevent anyone from browsing the uids; they would need to know a user's id to look them up. I don't know what your use case is here, so I can't really offer any specific advice. But you may want to read up on the XY problem, as you may be asking the wrong questions.
common-pile/stackexchange_filtered
jConfirmation on top of dialog I'm new to html& jquery. I'm having a dialog and while trying to close it, I need to ask a confirmation message, which should be displayed on top of the existing dialog. I tried using jconfirmation, but it comes up after closing the existing dialog. But I need the confirmation to come on top of the existing dialog. How can I do it? $("#ref").load('myTest.html').dialog({ create:function(e,u) { // ETC }, close:function(e,u){ //ADD CODE TO SHOW CONFIRMATION ON TOP } }); Hi Dialog will fire close callback after it is closed. Try using beforeClose event. You should be able to use the same call back that you are using for close with it $("#ref").load('myTest.html').dialog({ create:function(e,u) { // ETC }, beforeClose:function(e,u){ //ADD CODE TO SHOW CONFIRMATION ON TOP } }); http://docs.jquery.com/UI/API/1.8/Dialog#event-beforeClose
common-pile/stackexchange_filtered
SyncFusion WPF ComboBox in Grid- How to set display text on OnCommitCellInfo event I have a SyncFusion ComboBox dynamically added in SynckFusion:GridControl with following code: SchoolGrid.Model[rowIndex, columnIndex].CellType = "ComboBox"; SchoolGrid.Model[rowIndex, columnIndex].ItemsSource = itemSource; SchoolGrid.Model[rowIndex, columnIndex].DisplayMember = "FullDistrictName"; SchoolGrid.Model[rowIndex, columnIndex].ValueMember = "FullDistrictName"; SchoolGrid.Model[rowIndex, columnIndex].CellValue = cellValue; SchoolGrid.Model[rowIndex, columnIndex].DropDownStyle = GridDropDownStyle.Exclusive; What I want to achieve is: 1)Items in combobox I want to show in "Gujarat/Surat" format. when user select any item, the value that I want to be shown is only "Surat", not "Gujarat/Surat". 2) When user open dropdown list, the selected item should have focus. In QueryCellInfo event, I've specified value for this column as "District"- property of my model. In CommitCellInfo event, I am fetching and assigning the values to model properties. So point 1) is working as required. But I am not able to make point 2) working. I've tried using OnCurrentCellShowingDropDown, GotFocus events, but no luck. How can I make it working? We have prepared the sample with your code snippet and checked the reported issue of “Focusing the selected item of ComboBox ”, but we were unable to reproduce the issue. Please find the sample link below: Sample: GridControl If the issue still reproduces at your end, please modify the above sample to reproduce the issue and update us with the replication procedure. So that we will be able to analyze the issue better and update you with better solution.
common-pile/stackexchange_filtered
Basic circuit analysis question Why current is negative in this situation? Because EMF and current directions are the opposites? Can someone give me a good explanation on relationship between current and EMF? When the current is negative it means that it is actually flowing in the opposite direction of the arrow. For instance if you travel -20 feet in the "up" direction, that means the same thing as traveling 20 feet in the "down" direction. Either way it means the same thing, but one of them is kind of a double negative. As you are setting up a problem, it's less confusing if you point your current arrows in the direction you know the current will be moving. But sometimes you don't know ahead of time, so you end up with a negative current for an answer. That just means the current is going the opposite direction that the arrow is pointing. The current always flows from the more positive voltage to the more negative voltage (aka emf), so in this problem current will flow in the opposite direction of the arrow. As detailed above, electrons actually move the opposite direction as the current -- the movement of negative electrons in one direction is the same thing as positive charge moving in the opposite direction. Don't think about this too hard before you master the basics, if you can help it. Just imagine that there are positive charges moving the same direction as the current, and that's all there is to it (even though it's a lie). I'm sure other questions address this better so I will be brief: EMF is voltage, which you can think of as being like water pressure. Current is how much charge is flowing though your circuit each second, like how much water is flowing through a pipe. A large resistor is like a small opening the current passes through and a small resistor is like a large opening the current passes through -- the smaller the resistor the more current can push its way through for a given voltage. Ohms law describes this relationship mathematically. The conventional current idea is that current flows from the positive to negative terminals of a supply. However conventional current assumes the flow of positive particles, which is not actually correct. As you should know the flow of real current is by electrons which are negative particles. So the real current (of electrons) actually flows from the negative terminal to the positive terminal of a supply. In calculating the basic function of electrical circuits the actual flow is not so important as long as you stick to one consistant convention. When getting into semiconductor theory you will hear the term "the flow of holes", this also implies the flow of positive particles, though as above that is not really what happens. The true flow is still by electrons. (To add a bit more confusion, another idea is that the flowing "electrons" fill these "holes" as they flow. So you might visualize that the so called holes flow in one direction as the electrons flow in the opposite direction.) All in all, unless you're working deeply in semiconductor physics, just stick to the conventional current flow, (flow of a theoretical positive particle) and all will work out. This is mixed up. Electric current is the flow of electric charge. Electron current is the flow of electrons. The flow of electrons is, due to the sign of the charge carried by electrons, opposite the flow of the electric current. To say that "the flow of real current" is by electrons is at best misleading but, in general, just plain wrong. Consider, for the example, the 'real current' in the electrolyte of a battery or in a plasma. Does the flow of positively charged protons and/or ions not count as a 'real current'?
common-pile/stackexchange_filtered
Elasticsearch + Kibana, no logstash, web issue I have a AWS instance, set up a log aggregator. I would like to setup Kibana and Elasticsearch there. Kibana went up and configured itself, but it doesn't connect to Elasticsearch, which is running on the same machine. The error in /var/log/elasticsearch/elasticsearch.log says: "Kibana: Unable to create Kibana index ".kibana" Error: IndexCreationException[[.kibana] failed to create index]; nested: NoClassDefFoundError[Could not initialize class org.elasticsearch.index.codec.postingsformat.PostingFormats]; at respond (http://<IP_ADDRESS>/index.js?_b=5930:81566:15) at checkRespForFailure (...) at wrappedErrback (...) at wrappedErrback (...) at wrappedErrback (...) at Scope.$eval (...) at Scope.$digest (...) at Scope.$apply (...) Is everything running the same elasticsearch version (plugins, kibana, etc)? KIbana is 4.0.1. elasticsearch is 1.4.4. I found that they are compatibile.
common-pile/stackexchange_filtered
Unable to use wagtail with multiple databases As the title suggests, I'm finding it difficult to use multiple databases with Wagtail. My Objective is simple: Implementation of a scenario where all the Django as well as Wagtail tables will be created in the sqlite database for now rather than in the postgreSQL db. The Why: Cause I'd like the postgreSQL DB to remain uncluttered as well as utilise it for search/select purposes using the inspectdb command. The Error generated: relation "wagtailcore_page" does not exist Cause for concern: In the default wagtail home app, migrations folder, there's a file: 0002_create_homepage.py whose contents look like: from django.db import migrations def create_homepage(apps, schema_editor): # Get models ContentType = apps.get_model('contenttypes.ContentType') Page = apps.get_model('wagtailcore.Page') Site = apps.get_model('wagtailcore.Site') So makes me wonder: is this an error that happens because Wagtail already has its own initial migration in the home app or am I doing something wrong? Better yet, how would I implement this concept with wagtail. Here's my code: base.py- database section DATABASES = { 'sqlite': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }, 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'OPTIONS': { 'options': '-c search_path=test_schema,public' }, 'NAME': os.environ.get('DBWORKNAME'), 'USER': os.environ.get('DBWORKUSER'), 'PASSWORD': os.environ.get('DBWORKPASSWORD'), 'HOST': os.environ.get('DBWORKHOST'), } } DATABASE_ROUTERS = [ 'school.router.NonPersonalDBAttributeRouter' # Router's module path ] my_project_dir/router.py class NonPersonalDBAttributeRouter: """ Connects the app to the preferred database """ non_personal_db_attribute_tables = [ 'auth', 'admin', 'contenttypes', 'sessions', 'messages', 'staticfiles', 'migrations', 'wagtailadmin', 'wagtailcore', 'wagtaildocs', 'wagtailembeds', 'wagtailforms', 'wagtailimages', 'wagtailredirects', 'wagtailsearch', 'wagtailusers' ] def db_for_read(self, model, **hints): if model._meta.app_label in self.non_miner_dev_attribute_tables: return 'sqlite' return None # returns the External db def db_for_write(self, model, **hints): if model._meta.app_label in self.non_miner_dev_attribute_tables: return 'sqlite' return None # returns the External db def allow_relation(self, obj1, obj2, **hints): if obj1._meta.app_label in self.non_miner_dev_attribute_tables or obj2._meta.app_label in self.non_miner_dev_attribute_tables: return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label in self.non_miner_dev_attribute_tables: return db == 'sqlite' return None The problem comes in when I run the initial migration. The Error: makemigrations Process finished with exit code 0 manage.py@school_src > makemigrations Tracking file by folder pattern: migrations No changes detected Process finished with exit code 0 migrate manage.py@stuff_src > migrate "C:\Program Files\JetBrains\PyCharm 2018.1.4\bin\runnerw.exe" C:\baronprojects\pythonprojects\djangoprojects\school_management_project\school_src\my_venv\Scripts\python.exe "C:\Program Files\JetBrains\PyCharm 2018.1.4\helpers\pycharm\django_manage.py" migrate C:/baronprojects/pythonprojects/djangoprojects/school_management_project/school_src Tracking file by folder pattern: migrations Operations to perform: Apply all migrations: admin, auth, contenttypes, home, sessions, taggit, wagtailadmin, wagtailcore, wagtaildocs, wagtailembeds, wagtailforms, wagtailimages, wagtailredirects, wagtailsearch, wagtailusers Running migrations: Applying home.0001_initial...Traceback (most recent call last): File "C:\Python36\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "wagtailcore_page" does not exist The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Program Files\JetBrains\PyCharm 2018.1.4\helpers\pycharm\django_manage.py", line 52, in <module> run_command() File "C:\Program Files\JetBrains\PyCharm 2018.1.4\helpers\pycharm\django_manage.py", line 46, in run_command run_module(manage_file, None, '__main__', True) File "C:\Python36\lib\runpy.py", line 205, in run_module return _run_module_code(code, init_globals, run_name, mod_spec) File "C:\Python36\lib\runpy.py", line 96, in _run_module_code mod_name, mod_spec, pkg_name, script_name) File "C:\Python36\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "C:/baronprojects/pythonprojects/djangoprojects/school_management_project/school_src\manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "C:\Python36\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Python36\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Python36\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "C:\Python36\lib\site-packages\django\core\management\base.py", line 364, in execute output = self.handle(*args, **options) File "C:\Python36\lib\site-packages\django\core\management\base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "C:\Python36\lib\site-packages\django\core\management\commands\migrate.py", line 234, in handle fake_initial=fake_initial, File "C:\Python36\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Python36\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Python36\lib\site-packages\django\db\migrations\executor.py", line 247, in apply_migration migration_recorded = True File "C:\Python36\lib\site-packages\django\db\backends\base\schema.py", line 110, in __exit__ self.execute(sql) File "C:\Python36\lib\site-packages\django\db\backends\base\schema.py", line 137, in execute cursor.execute(sql, params) File "C:\Python36\lib\site-packages\django\db\backends\utils.py", line 99, in execute return super().execute(sql, params) File "C:\Python36\lib\site-packages\django\db\backends\utils.py", line 67, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "C:\Python36\lib\site-packages\django\db\backends\utils.py", line 76, in _execute_with_wrappers return executor(sql, params, many, context) File "C:\Python36\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\Python36\lib\site-packages\django\db\utils.py", line 89, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "C:\Python36\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: relation "wagtailcore_page" does not exist Why don't you make sqlite the default db? Since your want postgres database not to be managed by Django (Model.Meta.managed=False). Seems logical to make Postgres database the 'other' option. Did that. Problem is: sqlite does work in that sense except inspectdb which is the aim of this whole thing seems to only work on the default database(in this case, postgresql). Hence why I'm conflicted on finding out why it doesn't work. Actually, I was able to sort it out by using sqlite as the default. I then used the command inspectdb followed by the name of the database, i.e: postgres as per the documentation thereby achieving my objective: Keeping the external DB clean. Here's the Code: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }, 'postgres': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'OPTIONS': { 'options': '-c search_path=test_schema,public' }, 'NAME': os.environ.get('DBWORKNAME'), 'USER': os.environ.get('DBWORKUSER'), 'PASSWORD': os.environ.get('DBWORKPASSWORD'), 'HOST': os.environ.get('DBWORKHOST'), } } Command used: manage.py@reverse_src > inspectdb --database postgres Tracking file by folder pattern: migrations # This is an auto-generated Django model module. # You'll have to do the following manually to clean this up: # * Rearrange models' order # * Make sure each model has one field with primary_key=True # * Make sure each ForeignKey has `on_delete` set to the desired behavior. # * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table # Feel free to rename the models, but don't rename db_table values or field names. from django.db import models class DjangoMigrations(models.Model): app = models.CharField(max_length=255) name = models.CharField(max_length=255) applied = models.DateTimeField() class TblCountry(models.Model): name = models.CharField(max_length=-1, blank=True, null=True) class Meta: managed = False db_table = 'tbl_country' NB, TblCountry was just a test table I created within postgresql to see whether it would work. Also notice, there was no need for the router.py file as well as its configuration
common-pile/stackexchange_filtered
using the same linker ld script file target for two files lets assume I have a memory allocation that looks like this: MEMORY { firstfile : ORIGIN = 0x00000000, LENGTH = 0x2000 secondfile : ORIGIN = 0x00002000, LENGTH = 0x6000 } now I want to use the same ld script for two different files. 'firstfile.c' and 'secondfile.c' how to I make firstfile entire allocation go under 'firstfile' section, and the second file under 'secondfile' section? currently .text all goes under secondfile section. using special attribute section on each of the functions in firstfile.c doesnt help In your linker script fragment firstfile and secondfile are MEMORY regions not SECTIONS, so the section attributes will (I guess) be ignored because the sections do not exist. You must create the MEMORY regions, in which you place SECTIONS, then you assign sections defined in the object code to sections declared in the linker script. Note that it is the object code that is located, not the source file - the linker knows nothing about source files: Something like: MEMORY { FIRST_MEMORY : ORIGIN = 0x00000000, LENGTH = 0x2000 SECOND_MEMORY : ORIGIN = 0x00002000, LENGTH = 0x6000 } SECTIONS { .firstsection : { . = ALIGN(4); *firstfile.o (.text .text*) /* Locate firstfile text sections here */ } > FIRST_MEMORY .secondsection : { . = ALIGN(4); *secondfile.o (.text .text*) /* Locate secondfile text sections here */ } > SECOND_MEMORY } You can then locate any number of modules explicitly to each section. You might want a default location to place modules not explicitly located. In which case you should add: *(.text) /* .text sections (code) */ *(.text*) /* .text* sections (code) */ to one of the sections (or create a separate default .text section). Also if you add: *(.firstsection*) /* Locate anything with firstsection attribute here */ or *(.secondsection*) /* Locate anything with secondsection attribute here */ to the respective sections you can use __section__ attributes in the code to locate specific functions (or data) to to these sections as you attempted previously. But locating an entire module is preferable as it does not require code modification and maintenance.
common-pile/stackexchange_filtered
Mod Rewriting directory structure to appear differently I hate having to ask for help, but editing .htaccess is one of those things in life that I cannot and will not ever wrap my head around. I've been at this for months trying to learn, and I've got nowhere. I finally admit defeat and come seeking help! I have a directory:- http://example.com/images/blog/year/month/anyfilename.jpg Which I would like, if it's possible. To always appear as:- http://example.com/pix/anyfilename.jpg I would then continue to upload files in the correct year/month directories, which would only be visible to me. Externally to visitors, they would see the latter url if they viewed the image (I can take care of parsing the links in the PHP pages to match the rewritten "virtual" directory, myself so that wont be a problem). The times I've come close to having it working, the images were no longer visible, which makes sense, but I thought the point of being able to rewrite URL's was to avoid having to move files too? I have RewriteEngine on, and Options +FollowSymlinks and I know it's all setup correctly as other rules and redirects work. It's just this that doesn't want to play. I have no examples to show as I have no examples that work. I've searched everywhere, come close to an answer but never anything close enough to what I'm needing, to actually work for me. I'm out of ideas. Help me Obi-Wan Overflow, you're my only hope. You can't do what you are trying to do with just mod-rewrite. The problem is you have multiple locations where the file could live and your rewrite rule doesn't accept any kind of input of where to find it. You could do something like http://www.example.com/pix-month-year/anyfilename.jpg. Mod-rewrite isn't a scripting language. Alternatively, you could create a PHP script which you pass in a file name, and it could search through the image directories until it finds a match, and pass through the image data to the browser. (Remember to account for the same filename in multiple folders.) Your mod_rewrite would simply be something like this. RewriteRule ^pix/(.*)$ find-pix.php?filename=$1
common-pile/stackexchange_filtered
Styling md-tooltip (Angular Material 1.1.3) I have a mat-tooltip that I was styling through a CSS like this: mat-tooltip .mat-content { // custom values, styling is not applied } However since 1.1.2 release of angular material this styling is not being applied to my tooltips. Has anybody encountered a similar issue? If you want to style all your tooltips, just override .md-tooltip class: (JsFiddle) .md-tooltip { height: 35px !important; background-color: red !important; color: white !important; border-radius: 5px; } If you want particularly style some tooltips, use a custom class over md-tooltip element: (jsFiddle) HTML <md-tooltip class="custom-tooltip"> I'm a custom tooltip </md-tooltip> CSS .custom-tooltip { top: 25px !important; height: 35px !important; background-color: red !important; color: white !important; border-radius: 5px; } I read in this post that since Angular Material 1.1.1 the class name temporally starts with an underscore... md-tooltip ._md-content { height: auto; }. Maybe could be that too. Oooohh :) In any case your answered worked, thank you The.Bear! @The.Bear Is it possible to apply the md-tooltip css to only one tooltip in my page? You have to add your custom class into a md-tooltip element. For instance: <md-tooltip class="custom-tooltip"></md-tooltip>. JSFIDDLE
common-pile/stackexchange_filtered
How can I extract a NSDictionary from an NSDictionary on a lower level I have an NSDictionary that contains an NSDictionary which also contains NSDictionaries. Now I have code to extract what I need when I only have the website. This is my code. NSInteger selectedRow = [self.myTableView selectedRow]; NSString *currentName = [self.theFullArray objectAtIndex:selectedRow]; NSMutableArray *theOriginalArray = [self.theDictionary.allKeys mutableCopy]; if ([self.theDictionary.allKeys containsObject:@"#"]) { [theOriginalArray removeObject:@"#"]; } NSMutableArray *sortedKeys = [[theOriginalArray sortedArrayUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"self" ascending:YES]]] mutableCopy]; if ([self.theDictionary.allKeys containsObject:@"#"]) { [sortedKeys addObject:@"#"]; } NSArray *theFullDictObjects = sortedKeys; NSUInteger theFullDictCount = [theFullDictObjects count]; NSDictionary *currentInfo = nil; int firstI = 0; while (firstI < theFullDictCount) { NSString *currentFullDictObject = [theFullDictObjects objectAtIndex:firstI]; NSDictionary *theSubDict = [self.theDictionary objectForKey:currentFullDictObject]; NSArray *theSubDictObjects = [theSubDict allKeys]; NSUInteger theSubDictCount = [theSubDictObjects count]; int secondI = 0; while (secondI < theSubDictCount) { NSString *currentDictObject = [theSubDictObjects objectAtIndex:secondI]; if ([currentName isEqualToString:currentDictObject]) { NSDictionary *theDict = [theSubDict objectForKey:currentDictObject]; currentInfo = theDict; break; } secondI++; } if (currentInfo) { break; } firstI++; } NSLog(@"currentInfo: %@", currentInfo); Now this works but it's kinda slow when you have really big lists of NSDictionaries. Is there another code to do this more effectively or not. So let's says I have the value "www.adobe.com" then how can I get <dict> <key>Name</key> <string>Adobe</string> <key>Website</key> <string>www.adobe.com</string> <key>Sub Category</key> <string>Technology</string> <key>Category</key> <string>Account</string> <key>PRLCountry</key> <string>Belgium</string> </dict> If you look at the image, you can see how the dictionary is build. Thanks in advance. Could you specify what's the value you want at the end? I think you are too much extra code. What's the criteria to get only "www.adobe.com" ? And why do you have an extra key which already seems to hold the url value? @Larme sorry if I am not fully clear, so I have for example the value @"www.adobe.com", how can i get the dictionary that is underneat it? You can see what I need abode the picture I added NSString *toSearch = @"www.adobe.com"; NSDictionary *fullDictionary; //From plist for (NSString *aLetterKey in fullDictionary) { NSDictionary *letterDictionary = fullDictionary[aLetterKey]; if (letterDictionary[toSearch]){ return letterDictionary[toSearch];}}? @Larme this is deffinitly a better aproach then mine, I will use this instead but is this an effective way or are there better ways? I think the computer needs to do a lot of work doing like this If the website always start with the good letter, meaning that the first letter of the URL (after "www.") is always the one of the keys, you can retrieve it easily and then skip a for loop. @Larme yeah I tought of that to, but that's not the case so I guess this is my only option Since I see NSInteger selectedRow = [self.myTableView selectedRow]; NSString *currentName = [self.theFullArray objectAtIndex:selectedRow]; at start, I'm wondering how you got theFullArray first, and how you populated the TableView. I needed to put everything in one array so i created a function that does output like A, www.adobe.com, B, www.belfius.com etc. This way I was able to create a header like option for my tableview since NSTableView is totally different the UITableView What about reading that array instead and which the selected row you do the same?
common-pile/stackexchange_filtered
Laravel + vuejss app Api not working in Subdomain subdirectory in live I am trying to deploy code to a live server built in laravel vuejs.i have subdomain.and in sub domain i have created a subfolder. I have followed this link .The issue is that the project runs but any api is not working. It gives 404. From the console I can see that it goes to subdomain not to subdomain sub directory. So I have changed the code . this is api call in index.vue getSchools () { this.loading = true this.schools = [] localStorage.setItem("filtersTableSchools", JSON.stringify(this.filters)); axios.post(`/subfoldername/api/schools/filtersuper?page=${this.filters.pagination.current_page}`, this.filters) .then(response => { this.schools = response.data.schools.data; this.plans = response.data.plans; this.currency = response.data.currency; this.billing_cycle = response.data.billing_cycle; delete response.data.data; this.filters.pagination = response.data this.loading = false }) }, restoreOriginalPlan() { var original_plan = null; for (var i = 0; i < this.plans.length; i++) { if (this.plans[i].id == this.selectedschool.plan_id){ original_plan = this.plans[i]; break; } } this.selectedschool.plan = original_plan; }, This is the rout i called // api Route::group(['prefix' => 'subfolder/api/schools'], function() { Route::post('/filter', 'SchoolsController@filter'); Route::delete('/{school}', 'SchoolsController@destroy'); Route::post('/store', 'SchoolsController@store'); Route::post('/filtersuper', 'SchoolsController@filtersuper'); Route::post('/storesuper', 'SchoolsController@storesuper'); }); After change in code i have rebuild using following command npm run development still axios post goes to /api/schools/filtersuper. This happened in the entire project.So any one can tell what needs to change to make it work. have you checked the app url inside the env for laravel api
common-pile/stackexchange_filtered
How to disable css warning "Unknown property" in Eclipse Mars? I get many "Unknown property" warnings in my css files. This might be due to the fact that I have e(fx)clipse 2.0 and the Eclipse Web Developer Tools installed. If I open the css files with the e(fx)clipse css editor and add /SuppressWarnings/ the warning icon changes its color (see figure below). However: the Problems view still shows the warning and the default css Editor shows the warning, too. I do not want to add /SuppressWarnings/ since the css files are automatically generated with WinLess. How can I disable the "Unknown property" warnings for specific files or at all? My css files are not located under "src" but under a folder "help". That help folder contains html files for my Eclipse plugin and corresponding css files. =>Those files are not used for JavaFx/e(fx)clipse. Here is a related article that did not really help me but might give you further information: https://www.eclipse.org/forums/index.php/t/515810/ Screenshot that shows the warnings and the Problem view (click to enlarge) I have the same issue with E(fx)clipse 2.0 Mars. All CSS properties are showing up as warnings in the IDE. I have my CSS under src/main/resources - would love to get a solution to this before rolling the project out to more people. I filed an e(fx)clipse bug [1] and uninstalled e(fx)clipse for the time being. The main reason why I had installed e(fx)clipse at the beginning was to get rid of the access restriction warnings related to jfxrt.jar (also see [2]). Now I use additonal access rules for the JRE container in my classpath file instead of using e(fx)eclipse: <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8"> <attributes> <attribute name="maven.pomderived" value="true"/> </attributes> <accessrules> <accessrule kind="accessible" pattern="javafx/**"/> <accessrule kind="accessible" pattern="com/sun/javafx/**"/> </accessrules> </classpathentry> [1] https://bugs.eclipse.org/bugs/show_bug.cgi?id=475347 [2] Using JavaFX in JRE 8 Also see this related question for maven projects: https://stackoverflow.com/questions/32565193/how-to-define-access-rules-for-classpath-entries-in-maven-pom-xml-file-for-eclip You can go to the Problems View Options, select Show items that match any configuration checked bellow and deselect Xtext Check (fast) Type in all Configurations Screenshot: How locate Option in Problems view The option disables the css warning in the Problems View. This is very helpful. Unfortunately the warning icons are still present in the package explorer and in the editors. This is ok to me, but this is "Xtext ..." at the end of the option list, not "Text .." I really wish I could comment... So I'm using Luna, where everything works fine. However, I had problems with Angular validation in Luna and figured out a way to work around that. So, maybe this could help you. Right-click on your project and select Properties Under Validation, check the Enable project specific settings box. Scroll down and select Web Resources Validator. If there is an Include Group and it contains File extension: css, try removing it an then re-validating your project. If the rule is not there, then Add Rule into the existing Include Group, or make a new Include Group. Maybe you've already tried something like this. Thank you for your suggestion. I don't have the option "Web Resources Validator". I tried to disable all my Validators in the project specific settings. The warnings are still present. That's unfortunate, sorry it didn't help. This should start getting more attention as people move from Luna to Mars.
common-pile/stackexchange_filtered
using parameter text file in bash How can I change 3rd field of records by depending on another file? Is it possible to use awk? Sorry I am new to this Example: Records xxxx xxxx 1234 xxxx xxxx xxxx 5678 xxxx Parameter (another file) 1234,9001 5678,9020 My expected output is xxxx xxxx 9001 xxxx xxxx xxxx 9020 xxxx Glimpse of my code #!/usr/bin/ksh SRC=/home FILE_LIST=`sqlplus -s idmp_stg/idmp_stg@DTPMPDR07_SUDB << EOF set echo off head off feed off pagesize 0 trimspool on linesize 1000 colsep , spool output.csv SELECT * from USAGE_TYPE_PARAM; spool off; exit; EOF` #Using while loop read values into variables from CSV file and create flat file for each records counter=1 while IFS=, read V1 V2 do echo "${V1} ${V2}" > param_${counter}.txt counter=$(( counter + 1 )) done < output.csv cd $SRC ls D* | while read FILES do #--this supposed to change the 3rd field of the file but it doesn't show #--an output, just zero byte file awk 'NR==FNR{a[$1]=$2;next}{$3=a[$3]}1' FS="," output.csv FS=" " $FILES > final_output.txt done` Yes, already updated. $ awk 'NR==FNR{a[$1]=$2;next} {$3=a[$3];print}' <(tr , " " <Parameter) Records xxxx xxxx 9001 xxxx xxxx xxxx 9020 xxxx Explanation: Taking it one piece at a time: NR==FNR{a[$1]=$2;next} awk is processing two files, one after the other, one line at a time. NR is the total number of lines read and FNR is the number of lines read in the current file. So, when NR==FNR, we are in the first file which, in this case, is Parameter. These commands are therefore executed only while reading Parameter. a[$1]=$2 creates a dictionary whose keys are the first field and whose corresponding values are the second field of Parameter. The next command tells awk to ignore the remaining awk commands and skip to the next line. {$3=a[$3];print} Because of the next statement above, these commands are only executed when reading the second file. They change the third field to its new value and print the line. <(tr , " " <Parameter) Unlike Records, the file Parameter is comma-separated. Here, the translate command, tr, is used to convert it from comma-separated to space-separated before awk reads it. The <(...) construct is known as process substitution. POSIX or mksh or pdsh Process substitution is a bash/ksh/zsh extension not supported by all shells. To run this without process substitution: $ tr , " " <Parameter | awk 'NR==FNR{a[$1]=$2;next} {$3=a[$3];print}' - Records xxxx xxxx 9001 xxxx xxxx xxxx 9020 xxxx In this command, the first file argument to awk is - which means stdin. The output of tr is piped into awk to provide this stdin. This works the same as the previous solution but avoids process substitution. It gives me this $ awk 'NR==FNR{a[$1]=$2;next} {$3=a[$3];print}' <(tr , " " <output.csv) /idmp/MJMN/SUN_DR_CALL_TYPE/arc ksh: syntax error: `(' unexpected @Vision111 I looked it up and "AT&T ksh{88,93} (but not pdksh/mksh) support process substitution" as well as bash and zsh. Are you using pdksh or mksh? Regardless, I added a solution to the answer that avoids process substitution. Let me know what happens. $ cat sample 500000000000925577733300000000000000000000942136326600000GS515050901966485 00*HOME<PHONE_NUMBER>08504800000000000000 00000<PHONE_NUMBER>000000000000000000000000000001 1000<PHONE_NUMBER>0 NN N N<PHONE_NUMBER> RESULT $ tr , " " <output.csv | awk 'NR==FNR{a[$1]=$2;next} {$3=a[$3];print}' - /idmp/MJMN/SUN_DR_CALL_TYPE/src/sample 500000000000925577733300000000000000000000942136326600000GS515050901966485 00*HOME 00000<PHONE_NUMBER>000000000000000000000000000001 1000 00000000 NN N N<PHONE_NUMBER> @Vision111 Did<PHONE_NUMBER>08504800000000000000 appear as a first column in output.csv? Using awk: $ cat Records xxxx xxxx 1234 xxxx xxxx xxxx 5678 xxxx $ cat Parameter 1234,9001 5678,9020 $ awk 'NR==FNR{a[$1]=$2;next}{$3=a[$3]}1' FS="," Parameter FS=" " Records xxxx xxxx 9001 xxxx xxxx xxxx 9020 xxxx Set the Field Separator variable at the end before the file name to set it for that particular file.
common-pile/stackexchange_filtered
Is there any function similar to stristr() in PHP 5.2 Is there any function similar to stristr()? I want to use stristr(), but I can't because my PHP version is 5.2.9. So I need a similar function which gives the same functionality. <?php $email =<EMAIL_ADDRESS>echo stristr($email, 'e'); // outputs<EMAIL_ADDRESS>echo stristr($email, 'e', true); // As of PHP 5.3.0, outputs US ?> How can i do this? Use stripos and substr: echo substr($email, 0, stripos($email, 'e')); If you want to use the 'before needle' functionality, this is trivial to implement yourself using the 2 parameter version.... function stristr_bn($haystack, $needle) { $post=stristr($haystack, $needle); if ($post===false) return false; return substr($haystack, 0, strlen($haystack)-strlen($post)-strlen($needle)); } However this a very messy solution to the problem of parsing an ADRR_SPEC (regardless of implementation).
common-pile/stackexchange_filtered
RegEx: How to match a whole string with fixed-length region with negative look ahead conditions that are overriden afterwards? The strings I parse with a regular expression contain a region of fixed length N where there can either be numbers or dashes. However, if a dash occurs, only dashes are allowed to follow for the rest of the region. After this region, numbers, dashes, and letters are allowed to occur. Examples (N=5, starting at the beginning): 12345ABC 12345123 1234-1 1234--1 1----1AB How can I correctly match this? I currently am stuck at something like (?:\d|-(?!\d)){5}[A-Z0-9\-]+ (for N=5), but I cannot make numbers work directly following my region if a dash is present, as the negative look ahead blocks the match. Update Strings that should not be matched (N=5) 1-2-3-A ----1AB --1--1A You could assert that the first 5 characters are either digits or - and make sure that there is no - before a digit in the first 5 chars. ^(?![\d-]{0,3}-\d)(?=[\d-]{5})[A-Z\d-]+$ ^ Start of string (?![\d-]{0,3}-\d) Make sure that in the first 5 chars there is no - before a digit (?=[\d-]{5}) Assert at least 5 digits or - [A-Z\d-]+ Match 1+ times any of the listed characters $ End of string Regex demo If atomic groups are available: ^(?=[\d-]{5})(?>\d+-*|-{5})[A-Z\d_]*$ ^ Start of string (?=[\d-]{5}) Assert at least 5 chars - or digit (?> Atomic group \d+-* Match 1+ digits and optional - | or -{5} match 5 times - ) Close atomic group [A-Z\d_]* Match optional chars A-Z digit or _ $ End of string Regex demo Thank you, but unfortunately, this does not obey the condition that a single dash within the region prohibits any following digits within. I updated the question with some examples of strings not to match. @fbindel Did you check the latest update? https://regex101.com/r/JxbIuM/1/ Your updates do help and match everything, thank you. I lack the reputation to upvote or accept an answer. What I do not understand: playing around with these expressions, I see that the + or * at the end are necessary for a match even if only a single character follows my region (i. e. 123--A is only matched by your answer if the + before $ is left intact). This surprises me. Why is there a difference between matching at least once (+) and exactly once? @fbindel In the first expression, the first 2 parts are assertions that do not match( consume) characters. If those assertions are both true, then this part [A-Z\d-]+ actually consumes 1 or more characters. In the second expression, there are already either 5 dashes or digits followed by dashes matched, and the [A-Z\d_]* matches optional characters from the character class so that exactly 5 chars are also matched. Use a non-word-boundary assertion \B: ^[-\d](?:-|\B\d){4}[A-Z\d-]*$ A non word-boundary succeeds at a position between two word characters (from \w ie [A-Za-z0-9_]) or two non-word characters (from \W ie [^A-Za-z0-9_]). (and also between a non-word character and the limit of the string) With it, each \B\d always follows a digit. (and can't follow a dash) demo Other way (if lookbehinds are allowed): ^\d*-*(?<=^.{5})[A-Z\d-]*$ demo I never tried \B. That's an interesting way of doing it and works well with my set of strings. I will keep it in mind, thank you. (I cannot currently upvote or accept an answer)
common-pile/stackexchange_filtered
Responsive website: why would touchstart be needed instead of click? I'm developping a complex Single-Page-Application using ReactJS. This page was initially a desktop browser application with lots of "onclick" listeners everywhere, including internal code, but also external plugins/libs that we can't modify easily. But now we made it responsive, and it is available in both a mobile website and a Cordova/Phonegap app. Just making the CSS responsive produces a nice result, without introducing touchstart event at all. When the user touch an element with a click listener, the listener is called and the click event bubbles correctly (except on iOS but it can be solved) So, unless I'm trying to implement touch specific complex features like drag&drop with touch, or special "synthetic events" like press, pinch, tap, swipe, (often provided by mobile-specific libraries), why would I need to use touchstart in any way? For example I often see people trying to mix both click and touchstart in applications according to the device capabilities. But if click works, why would I need to care about touchstart? What are the advantages of touchstart that are not handled by click already? Note: this is NOT at all about the 300ms click delay which can be solved in other ways. The only reason we use touchstart/touchmove are for drag events, such as scrolling/inner-scolling detection. For example, we want to detect the end of a scroll for infinite scroll. On desktop we can use: $('.whatever').scroll({ blahhhh but on mobile we use: $('.whatever').on('touchmove', blahhhh Also you should definitely checkout How to bind 'touchstart' and 'click' events but not respond to both? Thanks glad to know. By the way, the link you give me is already included in my question, and does not really answer it :) @SebastienLorber haha I didn't even notice that! My bad!
common-pile/stackexchange_filtered
Unable to load static file in django 1.8 Here the relevant configuration for settings.py: import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'marcador' ) STATIC_URL = '/static/' #STATICFILES_DIR = ( # os.path.join(BASE_DIR, 'static'), #) STATIC_ROOT = (os.path.join(BASE_DIR, 'static')) In project urls.py; from django.conf.urls import include, url from django.contrib import admin from django.core.urlresolvers import reverse_lazy from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^', include('marcador.urls')), url(r'^login/$', 'django.contrib.auth.views.login', {'template_name': 'login.html'}, name='mysite_login'), url(r'^logout/$', 'django.contrib.auth.views.logout', {'next_page': reverse_lazy('marcador_bookmark_list')}, name='mysite_logout'), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) in marcador app urls.py; urlpatterns = [ url(r'^user/(?P<username>[-\w]+)/$', 'marcador.views.bookmark_user', name='marcador_bookmark_user'), url(r'^$', 'marcador.views.bookmark_list', name='marcador_bookmark_list'), ] in templates/base.html (extract); <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <title>Marcador - {% block title %}{% endblock %}</title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="apple-touch-icon" href="{% static 'apple-touch-icon.png' %}"> <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}"> <style> body { padding-top: 50px; padding-bottom: 20px; } </style> <link rel="stylesheet" href="{% static 'css/bootstrap-theme.min.css' %}"> <link rel="stylesheet" href="{% static 'css/main.css' %}"> <script src="{% static 'js/vendor/modernizr-2.8.3-respond-1.4.2.min.js' %}"></script> </head> Here my directory structure (project called marca and application is called marcador); +-- marca +-- marcador | +-- migrations | +-- templates | +-- marcador +-- static | +-- admin | | +-- css | | +-- img | | | +-- gis | | +-- js | | +-- admin | +-- css | +-- img | +-- js | +-- vendor +-- templates Here a printout of the variable; Python 2.7.6 (default, Jun 22 2015, 17:58:13) [GCC 4.8.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import settings >>> print settings.BASE_DIR /home/fabrice/Documents/Programing/django/marca >>> print settings.PROJ_DIR /home/fabrice/Documents/Programing/django/marca/marca >>> print settings.STATIC_URL /static/ >>> print settings.STATICFILES_DIR ('/home/fabrice/Documents/Programing/django/marca/marca/static',) >>> print settings.STATIC_ROOT /home/fabrice/Documents/Programing/django/marca/static >>> Content the page is diaplayed correctly but bootstap is not loading because the server return the 404 errors; [20/Sep/2015 16:09:53] "GET / HTTP/1.1" 200 4822 [20/Sep/2015 16:09:54] "GET /static/css/bootstrap.min.css HTTP/1.1" 404 1676 [20/Sep/2015 16:09:54] "GET /static/css/bootstrap-theme.min.css HTTP/1.1" 404 1694 [20/Sep/2015 16:09:54] "GET /static/js/vendor/modernizr-2.8.3-respond-1.4.2.min.js HTTP/1.1" 404 1751 [20/Sep/2015 16:09:54] "GET /static/css/main.css HTTP/1.1" 404 1649 [20/Sep/2015 16:09:54] "GET /static/js/vendor/bootstrap.min.js HTTP/1.1" 404 1691 [20/Sep/2015 16:09:54] "GET /static/js/main.js HTTP/1.1" 404 1643 [20/Sep/2015 16:09:54] "GET /static/js/vendor/bootstrap.min.js HTTP/1.1" 404 1691 [20/Sep/2015 16:09:54] "GET /static/js/main.js HTTP/1.1" 404 1643 I have read a few posts on the same issue but still can't get it working when I print the BASE_DIR variable I can see that the path is correct. The only way I can get this working correctly is when I copy the bootstrap static files in; /usr/local/lib/python2.7/dist-packages/django/contrib/admin/static/css/ I just don't get it and spent quite some tim on it already. Any suggestion? for information I am doing this tutorial http://django-marcador.keimlink.de/en/ You should take a look at Django documentation. There is a specific page about managing static files: https://docs.djangoproject.com/en/1.8/howto/static-files/ During development your project urls.py should be: from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^', include('marcador.urls')), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) But in production, a common practice is to use you http server to handle your static files. The answer for a production configuration is to broad since it will depends on your stack. set your STATIC_ROOT to be os.path.join(BASE_DIR, 'static') and probably remove the setting STATICFILES_DIR Still the same, no bootstrap, I must be doing something wrong Have you tried to put move your static folder to your marcador app folder? I know this is too late to answer but I found that if I use STATICFILES_DIRS like below and comment STATIC_ROOT, it works correctly STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),) Your STATICFILES_DIR contains a wrong value. You use os.path.join(BASE_DIR, '/static'). Citing the documentation for join: If a component is an absolute path, all previous components are thrown away and joining continues from the absolute path component. Please have a look at the following code example: >>> os.path.join('/a', 'b', '/c', 'd') '/c/d' Solution: remove the leading slash in '/static': os.path.join(BASE_DIR, '/static') Sorry Matthias there was a typo in my file, I have tried many things and forgot to remove the "/" Let's see... When you create a new project marca, you get a subfolder marca that contains your settings.py, wsgi.py etc. Usually, I create a static folder here for my non-app specific static files. I can then have a settings.py PROJ_DIR to target that e.g. PROJ_DIR = os.path.dirname(os.path.abspath(__file__)) Now I have a PROJ_DIR pointing at my subfolder marca in addition to BASE_DIR. Now to more settings. STATIC_URL = '/static/' #pretty much ok STATICFILES_DIR = ( os.path.join(PROJ_DIR, 'static'), #additional location of static files ) STATIC_ROOT = os.path.join(BASE_DIR, 'static') Files in STATIC_ROOT will be served at STATIC_URL (/static/ in your case), usually by a separate static file server like nginx. It should be empty initially. To get your files into STATIC_ROOT, run python manage.py collectstatic which will look in your app static folders and all paths in STATICFILES_DIR and create a directory structure ready to be served. In your template, base.html, you'll need to add {% load staticfiles %} I expect you'll get an error if you don't. Basically, I'm proposing this new structure to you. manage.py +-- static (your STATIC_ROOT is currently pointing here. empty initially but check after running collectstatic +-- marca settings.py wsgi.py urls.py +-- static | +-- css | +-- img | +-- gis | +-- js +-- templates +-- marcador | +-- migrations | +-- templates | +-- marcador Done as requested but still same issue, also note the output from collectstatic "0 static files copied to '/home/fabrice/Documents/Programing/django/marca/static', 62 unmodified." Also as metioned only when I copy file in /usr/local/lib/python2.7/dist-packages/django/contrib/admin/static/ it work as expected Do you have Debug=False? You may want to set it to True while using the development server. 0 copied because you already have those files in there, you may just delete and run collectstatic again. debug is set to true, I have removed the files and run collect static again but still no luck. Also collecstatic created a folder admin inside the folder static. I still can't figure out what is wrong I changed STATIC_ROOT, it is not a tuple. I must have done copy and paste from your original code. This may just be the problem you had. ok, the change to STATIC_ROOT does not really have much effect though. Is admin the only folder inside static? if that's the case, it can't find the other files in STATICFILES_DIR i.e. os.path.join(PROJ_DIR, 'static') where you should have your bootstrap files and other static files that are not app specific. Right now I have no admin folder in there but I did before. I have updated my original post with a print out of the variables from settings.py
common-pile/stackexchange_filtered
Construct a monotonic function $f$ on $\Bbb R$ so that $f'(x)$ exists (finitely) for every $x\in \Bbb R$ but $f'$ is not a continuous function. This is an exercise from Rudin's Real and Complex Analysis book. Construct a monotonic function $f$ on $\Bbb R$ so that $f'(x)$ exists (finitely) for every $x\in \Bbb R$ but $f'$ is not a continuous function. How can I construct such a function? What does this question have to do with measure theory? Discontinuous in how many points? @Omnomnomnom Maybe the function is almost an integral or something like that? I don't know. It is in a measure theory book. @YiorgosS.Smyrlis At least one, I think @YiorgosS.Smyrlis Well it has to be a finite amount otherwise $f^\prime$ wouldn't exist over every $x\in \mathbb R$. However one should work. @Omnomnomnom: Maybe Rudin had some Cantor function shenanigans in mind? Example $$ f(x)=\left\{ \begin{array}{ccc} 2x & \text{if} & x\le 0,\\ 2x+x^2+x^2\sin(1/x) & \text{if} & x> 0. \end{array} \right. $$ Then $$ f'(x)=\left\{ \begin{array}{ccc} 2 & \text{if} & x\le 0,\\ 2+2x+2x\sin(1/x)-\sin(1/x) & \text{if} & x> 0. \end{array} \right. $$ Clearly $f$ is increasing and differentiable everywhere, but $f'$ is discontinuous at $x=0$. Start with $$f(x)=\begin{cases} x^2\sin(1/x) & x\neq 0\\ 0 & x=0 \end{cases}$$ It is well known that $$f'(x)=\begin{cases} 2x\sin(1/x) -\cos(1/x) & x\neq 0 \\ 0 & x = 0 \end{cases} $$ is discontinous at $x=0$. However $f'(x)$ is bounded. So let $C$ be some lower bound of $f'$. Define $g(x)=f(x)+Cx$. Then $g'(x)=f'(x)+C > 0$ everywhere and thus by the first derivative test $g$ is increasing yet $g'$ is still discontinous at $x=0$. I would like to accept your answer too, but Yiorgos had this idea first, although your answer is more simple. Thanks man +1
common-pile/stackexchange_filtered
Confusion about setting something.prototype.__proto__ In the code for the Express module for Node.js I came across this line, setting inheritance for the server: Server.prototype.__proto__ = connect.HTTPServer.prototype; I'm not sure what this does - the MDC docs (https://developer.mozilla.org/en/JavaScript/Guide/Inheritance_Revisited#prototype_and_proto) seem to say that I could just do: Server.prototype = connect.HTTPServer.prototype; Indeed, I did this test: var parent = function(){} parent.prototype = { test: function(){console.log('test')}; } var child1 = function(){}; child1.prototype = parent.prototype; var instance1 = new child1(); instance1.test(); // 'test' var child2 = function(){}; child2.prototype.__proto__ = parent.prototype; var instance2 = new child2(); instance2.test(); // 'test' Looks to be the same? So yah, I'm wondering what setting object.prototype.__proto is for. Thanks! Possible duplicate of __proto__ VS. prototype in JavaScript Have a look at the diagram on this page (mckoss.com) that shows the prototype, constructor, __proto__ relations for a small hierarchy. Also the code below the diagram describes the relation quite well. When you have a function Base, and set the prototype of the function object defined, the statement Derived.prototype = new Base; sets the __proto__ (actually the internal [[prototype]]) of Derived.prototype to Base.prototype automatically, making Derived itself a class that you can instantiate objects from. This seems the be a more standards compliant way of defining a derived class. From what I read, __proto__ is a non-standard way of accessing the internal [[prototype]] of an object. It seems to be well supported, but I am not sure if it should be trusted. In any case, your example Server.prototype.__proto__ = connect.HTTPServer.prototype; seems to do the derivation the other way around: first define an object, Server by defining the constructor and the proto, and then hook up the internal [[prototype]] manually to morph it into a class derived from HTTPServer. As for your suggested alternative, Server.prototype = connect.HTTPServer.prototype;: that is a bad idea. Here, you are setting the prototype of Server to be the same object as the prototype of HTTPServer. So any changes you make to Server class will be directly reflected in HTTPServer, and will be accessible from other derived classes of HTTPServer. You can imageine the chaos if two classes derived from HTTPServer try to define the same member. Thanks for the mckoss article link - just one clarification before we wrap up, I think I have this correct: my suggested alternative (Derived.prototype = Base.prototype) is fine if nobody screws with the prototype, the reason why we want to do "Derived.prototype = new Base" (which will set the prototype of Derived to a new object that has its [[prototype]] set to Base.prototype), is to make damned sure that any modifications to Derived's prototype CANNOT affect Base's prototype. Your understanding and mine are the same. Since I am not very well-versed in Javascript, there may be some other subtleties I've missed, though. Also, if you need to instantiate the derived class, Derived.prototype.constructor will be Base.prototype.constructor, so it will call the wrong function if you use new Derived. I think. The non-standard property __proto__ lets you set the prototype of an existing object. In your example, both version will achieve the same effect, but there is a difference: child1's prototype is the same as parent's prototype, whereas child2's prototype is an empty object and this empty object's prototype is the same as parent's prototype. Of course as child2 and its prototype don't have a method test, this method will be looked up further up in the prototype chain. Also consider this: You want to create only one object that should inherit from another object. Now, you could write a constructor function, but JavaScript has object literal notation to create objects directly and you want to use it. If you have a constructor function, letting the new objects inherit from another object is as easy a setting the prototype of the constructor function to that object. Obviously this does not work for object literals. But in Firefox you can use __proto__ to set it: var server = { __proto__: connect.HTTPServer.prototype, other: properties }; As this property is not standard, you should avoid using it. Thanks Felix, your's + Dysaster's answers combined really clarified things, wish I could mark both of them Actually, proto is in the ECMAScript 6 standard, it's also very well supported across modern browsers (IE9+)
common-pile/stackexchange_filtered
Whats missing in this code, and is it right? I have to write a code in c, where the user can type numbers above 0. If the user types a number below or = 0, then following will be the output: the minimum of the numbers, the maximum, the average, the sum and the quantity of the numbers. I have to use the scanf function in a while loop. I tried to write the code, but i need help at some point of the code. #include <stdio.h> #include <stdlib.h> int main(void) { int i = 1, number = 0, min = 0, max = 0, average = 0, sum = 0; while(i > 0) { printf("Enter a number: "); scanf("%d", &i); } if (i <= 0) { i++; sum += i; } return EXIT_SUCCESS; } I'm stuck at the part where the "if" starts. What am i supposed to write, to receive the minimum, maximum, sum, average and the quantity of my typed numbers. And also, is the rest of my code right? Or am i missing something? If you start with i == 0, then will the loop ever run? I recommend that you learn about rubber duck debugging. You need to do each of these tasks as you read in the numbers. As it stands now, the only information you have after the loop is the last number you entered. There's A LOT missing in the while loop and the if statment is not necessary. You should ask your teacher for help. Your program does not make sense. For example this loop while(i > 0) { printf("Enter a number: "); scanf("%d", &i); } calculates nothing. The program can look the following way #include <stdio.h> int main(void) { int n = 0, min = 0, max = 0, sum = 0; int number; printf( "Enter a seria of numbers (0 or a negative number means exit)\n" ); while ( scanf( "%d", &number ) == 1 && number > 0 ) { ++n; sum += number; if ( min == 0 || number < min ) min = number; if ( max < number ) max = number; } printf( "The quantity of numbers: %d\n" "the minimum number: %d\n" "the maximum number: %d\n" "their sum : %d\n" "the average: %d\n", n, min, max, sum, n == 0 ? 0 : sum / n ); return 0; } Its output might look like for example Enter a seria of numbers (0 or a negative number means exit) 1 2 3 4 5 6 7 8 9 0 The quantity of numbers: 9 the minimum number: 1 the maximum number: 9 their sum : 45 the average: 5
common-pile/stackexchange_filtered
Openstack: Are components related to a keystone::project auto garbage-collected upon project deletion? Hello dear community, in the research of how to properly delete projects and their resources via the OpenStack API I was only able to find a hint in the official python sdk, the project_purge.py (docs). Here deletion is handled for "servers, images, volumes, snapshots, backups", but not for networks, subnetworks, floating_ip, ports, which are linked to projects and have dependencies to each other the more or less. Following that, are stale resources garbage collected after time if they are not bound to a project, user , etc? No, they are not. You need to remove every component manually, and in the correct order (a network can't be removed as long as the attached subnet exists etc.). Thanks a lot Gerald, I learned the same from some consultants now. I will wait if some more answers pop up and then accept your response it that is ok?
common-pile/stackexchange_filtered
Azure Logic App office 365 outlook connection issue I am unable to create office 365 outlook connection in azure logic app. It shows me following error-: Create and authorize OAuth connection failed. Connection test uniqueness failed. Can anyone please help me to resolve this issue. One of the reasons you are receiving this is because the logic app doesn't recognize the connector to be unique and the connection name already exists. Try navigating to your resource group. Make sure you don't have an API connection the same as the one that you have created. You can also troubleshoot this using Developer tools. While entering your details and submitting the form, you will be returned with certain response codes. Depending on the response codes you can troubleshoot further. Here is a similar issue that you can refer to Connection test uniqueness failed If you are returned with 202 the issue is with the connection name being already in use, try deleting the already existing connections from your resource group and add again. By any means, if you receive 503, connection creation is no longer possible and you can raise a support ticket. NOTE:- Make sure you are using a Work or School account and not a personal account.
common-pile/stackexchange_filtered
How do I suppress the "Save a local copy" prompt in clear case? Background In clearcase, whenever you uncheckout, or check in files, you get a prompt that says: Save private copy of <file> ? [yes] For each individual file. Problem I am trying to check in hundreds of files at once with a script and I know I don't want to save a private copy of any of them. How do I suppress this prompt so I don't have to manually enter n or no for each file? In your script, you can cleartool checkout -rm or cleartool checkout -keep in order to not save, or save a copy of the file. By using those options, you will get a non-interactive command and won't have to enter y/n for each file.
common-pile/stackexchange_filtered
recordFetchedBlock on CKQueryOperation not being called I need to query for CKRecords of the recordType "Event". When I call recordFetchedBlock, I will add those records to my array. However, recordFetchedBlock is never getting called. Please help! Thank you: //TODO: Query for all Event records var database: CKDatabase = CKContainer.defaultContainer().privateCloudDatabase let truePredicate = NSPredicate(value: true) let eventQuery = CKQuery(recordType: "Event", predicate: truePredicate) let queryOperation = CKQueryOperation(query: eventQuery) queryOperation.recordFetchedBlock = { (record : CKRecord!) in self.eventsArray.append(record) println("recordFetchedBlock: \(self.eventsArray)") } queryOperation.queryCompletionBlock = { (cursor : CKQueryCursor!, error : NSError!) in println("queryCompletionBlock: \(self.eventsArray)") } database.addOperation(queryOperation) So I just realized my error. I was accidentally calling the query on the private database (as opposed to the public). Currently kicking myself..
common-pile/stackexchange_filtered
How to prove that, if two numbers are equal $\mod2$ and$\mod3$ ,they are equal$\mod 6 $? I was wondering if it could be proved without using the Chinese remainder theorem, arithmetically. Thank you If $2\mid a-b$ and $3\mid a-b$, then $6\mid a-b$ Technically you don't need the full power of the Chinese remainder theorem. You can make an argument from a simple lemma involving prime divisors and/or prime factorizations. $2,3$ are relatively prime so $2|(m-n)$, $3|(m-n)$ implies $6|(m-n)$ meaning $m\equiv n \mod 6$. If $c$ is a common multiple of $a$ and $b$, then $c$ is a multiple of their least common multiple $\operatorname{lcm}(a,b)$. Apply this to $c=m-n$ and $a=2$ and $b=3$.
common-pile/stackexchange_filtered
iOS FCM token issue "NotRegistered" I am attempting to call the API "https://fcm.googleapis.com/fcm/send" using my server key to send an FCM to a specific token. However, I am encountering an issue with the following response. Request: { "to": "<MY TOKEN>", "data": { "body": "Test Notification !!!", "title": "Test Title !!!" }, "notification": { "body": "Testing notification", "title": "Amit Kava" } } Response: { "multicast_id":<PHONE_NUMBER>850074558, "success": 0, "failure": 1, "canonical_ids": 0, "results": [ { "error": "NotRegistered" } ] } can you check on app side, firebase is initializing properly and getting correct token from firebase? Checked, initialized properly. did you requested permission for ios device ? without it will not generate any token : https://firebase.google.com/docs/cloud-messaging/flutter/client The error message says that the value you are passing is not registered as an FCM token in the project. Make sure you use the value you get back from getToken and that your client and server-side code are connected to the same project. @HardikMehta Permission is given still it showing error, As per knowledge if permission is not given then notification will not but api give success. @AmitKava : token generation may need that permission @HardikMehta It's already given. Without it, I can not able to create a token. @AmitKava : Please do check this once : https://stackoverflow.com/questions/77493709/flutter-firebasemessaging-token-not-registered-error
common-pile/stackexchange_filtered
How do I move my IIS web site to be under the Default Web Site? I have the Default Web Site in the IIS, i have a second web site that i want to use the same binding as the default. Right now it creates a second website. As is I want move the website to be under the default web site like the one below. To be I hope i made sense. If you open applicationHost.config, then what you will do is 1) copy the default <application> tag from the second site to the first site. 2) change the application path there as the first site also as a default <application> tag. 3) delete the second site if you need. You can add application by right click default web site. Then fill the alias and set physical path to your second application's folder. At last, you can access the second site by http://localhost/alias.
common-pile/stackexchange_filtered
Visual Studio Code Ethereum tutorial Are there any tutorials on how to use MS Visual Studio Code to write contracts in solidity? Not sure on specific VS tutorials, but this is a generic tutorial for solidity: http://solidity.readthedocs.org/en/latest/ which should work on: https://visualstudiogallery.msdn.microsoft.com/96221853-33c4-4531-bdd5-d2ea5acc4799 Thanks Nikhil this will do for now, though I hoped to get a video tutorial For Visual Studio Code, there is an extension which provide syntax highlighting. To install: Press Ctrl + P and type "ext install ". Note: The trailing space. Type "Solidity", click in the extension and you are done. You can find it also in the Visual Studio Code Marketplace This is an example using the Theme Dark+ Note: The bug on the Linux version of Visual Studio Code, has been fixed in the latest version. Many thanks to @dotnetjunkie for your help. To install the latest version: Press F1 Type ext update Select solidity More info on the fix here: Syntax highlighting for Solidity VS Code extension not working on linux Hey Juan... I did install the extension although its not looking colorful as yours Change your theme to Dark+, go to File -> Preferences -> Themes ->Dark+ Still no difference. My file is saves with the .sol extension as well but nothing is happening Are you using Visual Studio Code? or Visual Studio? The OP is for visual studio code... but the accepted answer points to the extension of Visual Studio (just checking we are talking about the same thing :) ) Yes I am using Visual Studio Code Version 0.10.11. Check it out here -> [url=http://postimg.org/image/w0d18qr0j/] ah great, if you press F1 again and type ext, you will have an option to see installed extensions. It might not installed correctly. Let us continue this discussion in chat. @JuanBlanco With the latest VS Code, it cannot find the Solidity extension, any ideas? @JuanBlanco Nevermind, Looks like I had an ancient VS Code @JuanBlanco thanks for the extention but on windows and VS Code I am currently experiencing an issue command "solidity.compile.active" not found, I havent installed any command line tools, should I install any command line extensions? You can find a tutorial for this on my msdn blog. Also some quick videos on this as well: Installing the VSIX package How to use the tooling Typically on StackExchange, we prefer to not have "link-only" answers. However, since the poster was literally asking for this, I'm not sure how to handle it. Please, don't make a habit of this & if you could possibly expand on your answer (what does the tutorial cover, etc) that would be great. Thank you. Hi the OP refers to Visual Studio Code not Visual Studio there is another Q&A for that http://ethereum.stackexchange.com/questions/2463/how-to-install-solidity-in-visual-studio/2495, you should add that info on the other post, good tutorial :) Welcome to Ethereum! A link alone is not considered a good answer. Links may break and the answer becomes worthless later even if the linked material answered the question initially. At least if you include a summary, the answer can somewhat stand on its own.
common-pile/stackexchange_filtered
Is reaching the end of a C array legal from the standard view point? Today, I encountered a piece of C code that looked pretty much like this: void my_func(unsigned int *); int main() { unsigned int a[8]; // init_a(a); => a is properly initialized my_func(a); } void my_func(unsigned int * a) { unsigned int * array_begin = a; a += 8; // HERE while (a-- > array_begin) { unsigned int tmp = *a; *a = (tmp >> 1); // other stuff } } From my understanding, the line a += 8 brings the pointer right after the end of the array. Then, in the loop condition, the pointer is decremented from this "past array address", dereferenced in the loop body. No problem, because at this point the pointer is back inside the array. The code compiled and ran without any problems, unit tests were successful. Still, my question is : is it legal C to move the pointer after the array, and then decrement it to be back inside the allocated object, or is this an undefined behavior ? You can set a pointer to anything you want at any time. You can only dereference it within allowed bounds. @tadman But pointer arithmetic can produce UB if you go too far. 1 past the end is allowed, though. C11 6.5.6 quoted in this answer is what you're looking for. Open the text of the standard. Search for the phrase "one past".
common-pile/stackexchange_filtered
What is the equivalent to a VirtualBox setting in Qemu? I'm trying to create a Packer template that has both a VirtualBox and a Qemu builder for the same thing. The VirtualBox one works fine, but with Qemu, I'm having some difficulty figuring out how to setup the networking properly. More specifically, in the VirtualBox section, I have "vboxmanage": [ ... ["modifyvm", "{{.Name}}", "--nic2", "nat"], ["modifyvm", "{{.Name}}", "--cableconnected2", "on"], ["modifyvm", "{{.Name}}", "--nic3", "null"], ["modifyvm", "{{.Name}}", "--cableconnected3", "off"] ], "vboxmanage_post": [ ["modifyvm", "{{.Name}}", "--nic1", "hostonly"], ["modifyvm", "{{.Name}}", "--hostonlyadapter1", "VirtualBox Host-Only Ethernet Adapter"], ["modifyvm", "{{.Name}}", "--cableconnected1", "on"] ], I tried to initially just configure at least the second NIC with "qemuargs": [ [ "-netdev", "user,id=mynet0,net=<IP_ADDRESS>/24,host=<IP_ADDRESS>,dns=<IP_ADDRESS>,dhcpstart=<IP_ADDRESS>"], ["-m", "128M"] ] But Packer says there's an error when invoking Qemu with that command. What am I doing wrong? And also, how would I create a host-only adapter when I later run the created image? OK, I kind of managed to solve my original problem. The problem was that both -netdev and -device are required AND (the thing that really tripped me up) their order is important: "-netdev" first, and "-device" second. Furthermore, Packer seems to overwrite its own first interface, which in turn requires its explicit redefinition. That explicit redefinition needs two hostfwd-ed ports. I'm guessing Packer uses one of them as its source port. So: "ssh_host_port_min": 3213, "ssh_host_port_max": 3214, "qemuargs": [ ["-netdev", "user,id=user.0,hostfwd=tcp::3213-:22,hostfwd=tcp::3214-:22,net=<IP_ADDRESS>/24"], ["-device", "virtio-net,netdev=user.0"], ["-netdev", "user,id=user.1"], ["-device", "virtio-net,netdev=user.1"], ["-netdev", "user,id=user.2"], ["-device", "virtio-net,netdev=user.2"], ["-m", "128M"] ], This is not an equivalent of the above VirtualBox setup, but at least it's enough to make Packer create the image successfully. Actually running the image properly afterwards is a separate problem.
common-pile/stackexchange_filtered
How to put condition based query for MySQL I want to create a forum. Scenario: When a user click on question list from forum, It will redirect a page where he can find the respective Question and list of answer, Whenever i used below mentioned query, I found the question from the question table (im_forum_question) on the new page. 'SELECT q.id, q.forum_question, q.forum_question_point FROM im_forum_question as q '+ WHERE q.id='+"'"+req.params.id+"' " But when i mix above code with answer fetching query below mentioned, I only get the already answered question. For an unanswered question it is showing an error. 'SELECT q.id, q.forum_question, q.forum_question_point, qa.forum_answer, qa.user_name_answer FROM im_forum_question as q INNER JOIN im_forum_question_answer as qa ON qa.question_id = q.id WHERE q.id='+"'"+req.params.id+"' " Because if no one answered that question, it will not be stored in answer table (im_forum_question_answer). Is there any way if number 2 query (Above mentioned) failed the number 1 query (Above mentioned) will execute. (if, else) If no answer found form answer table only question should show. exports.get_question_answer = function(req, res, next){ db.sequelize.query( 'SELECT q.id, q.forum_question, q.forum_question_point, qa.forum_answer, qa.user_name_answer FROM im_forum_question as q '+ ' INNER JOIN im_forum_question_answer as qa ON qa.question_id = q.id '+ ' WHERE q.id='+"'"+req.params.id+"' " ).then(function(data){ console.log('Logs for Data', data); var arr = data[0]; res.render('forum/question.ejs',{ success:'', error:'', session: req.session.user, data:arr }) }) } Your code is vulnerable to SQL injection. After a quick look, I think that the reason why you don't get an answer is because you use an INNER JOIN. An inner join returns only the rows that are common in both tables so when the specific id is not found in the answers table the row is skipped entirely in the returned table (for a nice explanation of joins see here). To achieve what you want you should use a LEFT JOIN instead. This will return all the matched records from the left table (in this case your questions table). For the cases that no matching answer is found, the entries will be null. The second thing that you could fix is that error you get. This is most probably due to the fact that you are returning var arr = data[0]; However, in cases that the array is empty this will be undefined. This could lead to an error if you don't take this into account in your code. Thank you so much MrfksIV for clear and correct solution, I have replaced INNER JOIN with LEFT JOIN, and it is working.
common-pile/stackexchange_filtered
How deep should a squat be? Recently, I've read some articles that suggest that you should go below 90 degrees. On the other hand, I've talked with a trainer in my gym, and he usually places a bench behind him so that he couldn't go below 90. What is your take? Below 90 or 90? Note: When I'm talking about degrees, I mean the angle your shin bone and femur makes. @friz is right. Although you should be careful that your knees don't stick out father than your toes, your knees will by necessity move forward a bit when you squat. Because of that, stopping when you reach a 90 degree angle between your shins and femur would mean that you actually don't quite reach parallel with the ground. A proper squat involves the hip joint ending up below the knee joint as seen from the side (see the image above). This is called squatting "below parallel". Many studies indicate that "squats, when performed correctly and with appropriate supervision, are not only safe, but may be a significant deterrent to knee injuries". A look at weight training injury rates and using common sense when thinking about the third world squat, how you sit on any low surface (e.g. toilet), and the fact that olympic weightlifters - who routinely squat crazy loads WAY below parallel - can still walk should also be fairly convincing. Yes I totally agree with this. You should break 90 degrees on your squat, or go below parallel for it to count. Agree. Squatting below parallel is a natural motion practiced by humans of all ages all over the world. A lifetime of chair sitting is what is dangerous. This is the answer that should have been accepted. Thanks for the "third world squat" article. A good read. It's not about anyone's personal "take" on the subject. It's about what your knees can handle. People who hurt themselves doing deep knee bend squats are either not flexible enough to do them, or are using bad technique. As a blanket rule, we just say not to go past 90 degrees because just about anyone's knee will bend to 90 degrees with weight without risk of injury. If you want to go further, go further but do so with caution, a small amount at a time (low or no weight is suggested while training for deep knee bend squats). This will ensure that your ligaments and muscles are prepared for the extra strain. Going below a 90 degree bend will cause quite a bit of extra stress on an exponential curve (the deeper you go, the higher stress coming back up). If you feel any pain or "stretching" in the knees, you're going too far. Technique: Stand with feet slight more than shoulder width apart, toes pointed outward slightly. Keep your knees lined up with your toes and your back straight, bending at the knees and hips and lowering yourself toward the ground. Raise yourself back up placing the pressure on the heel of your foot. To avoid injury: Don't let your knees flex inward. Keep them bent outward from your sides. Try lifting your toes off the ground to get the hang of placing pressure on your heel coming back up. Make sure you're properly stretched before working out. If you feel joint or ligament pain, intense stretching, or just "something wrong" in the knees, drop backward to a sitting position and stand up from there, do not try to lift yourself up by completing the squat. Not squatting to parallel is what causes knee injury, and that is information coming from Glen Pendlay (US Olympic coach) and Mark Rippetoe (strength training coach since the 70s). In order to get to parallel, you have to perform proper stretching to get the flexibility you need. Also, deload to a weight you can do full squats with and increase from there. Your knee is designed to squat low. Babies learning to stand squat well below parallel. Usually the problem from squat depth is not the knees but the lower back. As you get lower, your hamstrings stretch to the point that your hips are pulled. The first thing noticed is that your lower back is losing concavity. So I would say that you can go deep until your lower back rounds. Work on getting this as low as possible, to increase your strength and flexibility. Agree with everything md5sum says. Also would like to add one more technique to the list: when you go down into your squat, don't think of letting gravity pull you down or the weight of the bar pushing you down. Visualize using your muscles and core tension to pull yourself down into the squat. This will maintain a muscular tension throughout your body that will not only help you lift more, but also help avoid injury. Agreed 100% - at no part of a squat should your muscles be in a relaxed state. This includes the end of the lift when you are standing upright - if the muscles in your legs are relaxed, that means you are standing with your knees locked holding way more weight than you are accustomed to holding. Stay tensed up during the entirety of a set. Squats that aren't low enough usually involves more weights, which for a lot of people give a lot more pressure on the back. If done properly, ATG (all the way to the ground) squats are excellent. The problem is that the majority of people don't know proper squat form, so I wouldn't recommend this until a person has learned good form. Here are some resources that have really helped me a lot: Part 1 of a 4 part series on squatting - "So You Think You Can Squat". Also, one great way to increase strength safely is to do a box-squat, which is essentially what your trainer is doing. If you are using a bench for box squats, this is generally slightly above parallel. Fantastic video! Just adding to the mix here. Personally, I go as deep as possible with my lighter weights as I am warming up. I start with the bar only, then add a 45 on each side. I squat until my butt hits my ankles. Once I get to 225 or greater (2 45s on each side), then I only go down roughly parallel to the floor. Use your better judgement on this. If you feel like you are about to blow out a knee or break something by going down further - DON'T! I don't really understand your statement, @friz. Just stand in front of a mirror while doing squats, and you can get pretty close. I don't worry if I've over-extended to 91° or if I cheated myself by only going to 89°. I always use proper form. This is a short, useful video that gives some tips on squats. Would still be good to hear all your comments on whether the full range of squat motion is advised or not. Here are some of the most important tips from the video: Bring your elbows BELOW the bar (or even slightly ahead) Become more flexible at your shoulders so you can stretch it to the maximum to achieve tip #1 Initiate the movement by bending the knees, go all the way down and all the way back up Go for full range of motion which helps train the full leg and the glutes Drive up with your legs. Do not lean forward as the hip goes up.
common-pile/stackexchange_filtered
Bind Tooltip Visibility to variable so that it shows text conditionally in code-behind If I have a class that holds a static variable that will contain the Visiblity status of a Tooltip, how would I write the code-behind to dynamically change the Tooltip visiblity when the visiblity variable changes? i.e. When Tooltip option is disabled, no Tooltips should be shown, but when Tooltip option is enabled, Tooltips should show up. (Tooltip option is held in a static variable in a different class) The Tooltip and the control it is connecting onto are dynamically created. Pseudocode: ToolTip myToolTip = new ToolTip(); Visiblity tooltipVis = Visibility.Visible; Bind myToolTip.Visiblity to toolTipVis //Any control with ToolTip should now show their respective ToolTip messages. ... tooltipVis = Visibility.Hidden; //Any control with ToolTip should now have ToolTip messages disabled Attempt at binding to TreeViewItem: TreeViewItem tvi = new TreeViewItem() { Header = tviHeader }; ToolTip x = new System.Windows.Controls.ToolTip(); x.Content = "This is text."; Binding binder = new Binding { Source = EnvironmentalVariables.ToolTipVisibility, Path = new PropertyPath("Visibility") }; x.SetBinding(VisibilityProperty, binder); user.ToolTip = x; public class EnvironmentalVariables { public static Visibility ToolTipVisibility { get; set; } } This doesn't seem to bind the Visiblity to the EnvironmentalVariables.ToolTipVisibility variable. @LPL Not unless you're talking about building a template. I'm sticking to what I know better, hence the code-behind, but if its somehow possible to do it from XAML, I'm all for it. Any reason your ToolTipVisibility is static? If not, you can switch it back to normal, make it fire PropertyChanged and work with this You could use ToolTipService.IsEnabled Attached Property for this. <TextBlock Text="Example" ToolTip="This is an example" ToolTipService.IsEnabled="{Binding TooltipEnabled, Source={x:Static Application.Current}}"> Because you can't bind to a static property (in WPF Version 4.5 you can) I would use this workaround to access the property from everywhere public partial class App : Application, INotifyPropertyChanged { private bool _tooltipEnabled; public bool TooltipEnabled { get { return _tooltipEnabled; } set { if (_tooltipEnabled != value) { _tooltipEnabled = value; RaiseNotifyPropertyChanged("TooltipEnabled"); } } } private void RaiseNotifyPropertyChanged(string property) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(property)); } } public event PropertyChangedEventHandler PropertyChanged; } Is there a cleaner way to implement this? The reason its a static is because its used across multiple projects and I don't want to create an instance of it in every location. I ended up using an INotifyPropertyChanged inheritance on a Singleton to achieve what I was looking for. Just delete the Path property in the Binding object you create. That's all it needs to work. EnvironmentalVariables.ToolTipVisibility = System.Windows.Visibility.Collapsed; var b = new Button () { Content = "test" }; var x = new ToolTip(); x.Content = "This is text."; var binding = new Binding { Source = EnvironmentalVariables.ToolTipVisibility, }; x.SetBinding(VisibilityProperty, binding); b.ToolTip = x; If you want to change the ToolTipVisibility dynamically at runtime you have to implement a property notification though. How would I build the property notification? Since EnvironmentalVariables.ToolTipVisibility is a static. You could change the class EnvironmentalVariables to work with the Singleton pattern. That way you can implement INotifyPropertyChanged for the singleton instance. You can Access the property like that e.g. EnvironmentalVariables.Instance.ToolTipVisibility.
common-pile/stackexchange_filtered
Truecrypt compromised? (Coldboot attack) In light of recent developments in computer forensics and "password recovery" utilities, can encryption technologies such as TrueCrypt still be relied on for a high degree of protection? It would seem to me as though the ability to retrieve decryption keys from a device's RAM (even after shutdown) means that hardware-based encryption solutions will be the way to go in the future. "In forensics, we have known about this for years" This isn't a new attack. It's obvious that TrueCrypt fails if the attacker gains access to a running computer with unlocked encrypted volumes. So you need to power-off your comp or at least unlock the encrypted volumes when police knock down your front door, or whatever your attack scenario is. | Hardware based encryption has its share of issues too, and I don't really trust it either. But if you're paranoid, you can use both at the same time ;) To me, the question is squarely off-topic, and belongs to security.se. Also, the attack linked to in the question does not "retrieve decryption keys from a device's RAM (even after shutdown)"; as far as I understand, it retrieves the keys either from a running computer using a well-know attack using DMA-thru-Firewire (which is highly system-specific), or from an hibernation file when the computer was hibernated with the volume mounted; I'm not sure what are the fine prints for the later to work. Don't forget about freezing the RAM. http://www.zdnet.com/blog/security/cryogenically-frozen-ram-bypasses-all-disk-encryption-methods/900 As of 5/2014 Truecrypt "is not secure as it may contain unfixed security issues" http://truecrypt.sourceforge.net/ can encryption technologies such as TrueCrypt still be relied on for a high degree of protection? Yes, provided you understand exactly what protection you're getting from Truecrypt. Encryption is not access control and it does not protect your system whilst it is powered on. Once you put the key material anywhere near the computer (e.g. typing it in, loading it into memory) you should treat the computer as containing the key material because it does. Therefore, anything that can extract your computer's RAM can read this key material. This should not be remotely surprising in any way. I have looked through the truecrypt driver code in a fairly extensive way (I don't approve of the statically allocated stack buffers they use, they should prefer ExAllocatePoolWithTag, but what do I know?) and it would not be all that difficult to write a driver to pull the volume keys out of memory on a system which has truecrypt running. If you want encryption of your disks to be effective, you must do two things: Ensure that you do not attach the key material to the system when you can be observed by somebody you wish to prevent from accessing your data. Have the system powered down when the data is stolen. Against a casual, opportunistic thief, point 1 happens by default since the thief in question is almost never there when you are using your device. This makes disk encryption a good defence against stolen laptops, for example, since opportunistic thieves who steal powered down laptops get some hardware, but not some data. The determined attacker, or what cyber-literature refers to as an advanced persistent threat, however, may have the resources to observe 1. This could be through several means: Bugging the locations you input the key material including hardware keyloggers, cameras and whatnot. Exploiting the good old remove the RAM, freeze it and whatever techniques preserve system memory after power down. Compromising your system whilst it is powered on - firewire, malware, whatever. This has been the case for as long as disk encryption has been in use and will be the case for as long as disk encryption is in use in its current form. Encryption does not protect you against these threats - for these, you need good access control, good auditing procedures, good security practises to prevent malware access, good physical security etc. Slight update, for extra fun: Hibernation is a known attack vector in modern operating systems which depending on your implementation stuffs up secure boot entirely. The work done on this was derived from the fact it was possible to bypass Patchguard by altering the page file to load code. The motto of the story in these two cases is that the operating system cannot trust the state it loads from disk unless it has control of the CPU. How does hibernating affect your in-memory key? That depends on whether the hibernation file exists on the encrypted drive or not. If it does, good - you'll need to re-enter the key to decrypt it (and you'll have prevented the hibernation file attack vector, too). If it doesn't, then if the key is written out into the hibernation file you are in trouble. If it isn't, you're still not massively safe, as a sufficiently determined attacker with serious resources can probably take advantage of that.
common-pile/stackexchange_filtered
How do I return an index of where a number should go if it isn't found in a Binary Search in JAVA So I have a binary search code that finds where a number should be placed to maintain sorted order. I've been at this for a little over an hour and a half so far trying to figure this out so I could use a push along. What value would I return at the end of the method if the value is not found in the array, but the place it should be placed is found? Basically a value that says the index where this number belongs is within +/- 1 of the mid value. Here is the binary search, i'm not looking to change it but rather just looking for the variable to return where the _____ is. private static int bsearch( int[] arr, int count, int key ) { if (count==0) return -1; int lo = 0, hi = count - 1, mid; while(hi >= lo) { mid = (lo + hi) / 2; if(arr[mid] == key) return mid; if ( key < arr[mid] ) hi = mid-1; else lo = mid+1; } return _____; } Think about it like this: if the search value is higher than the last mid you find, itd be mid +1 right? And if its lower shouldnt it be mid -1? Most methods return the bitwise negation of the index where to place the element, thus ~idx. Binary search makes the assumption that all elements before lo are less than the key and analogue for hi. In case hi < lo, it means that hi was set to mid-1 and mid was equal to lo (because hi and lo differ at most one) or analogue to lo. Thus the location where the element must be placed is at lo. One thus returns: return ~lo; An optimized version of the algorithm is thus: private static int bsearch( int[] arr, int count, int key) { if (count==0) return -1; int lo = 0, hi = count - 1, mid = hi>>1; while(hi >= lo) { mid = (lo + hi) >> 1; if ( key < arr[mid] ) hi = mid-1; else if ( key > arr[mid] ) lo = mid+1; else return mid; } return ~lo; } As a testcase: for(int i = 0; i <= 22; i++) { int r = bsearch(new int[] {2,3,7,9,11,15,21},7,i); System.out.println(""+i+" -> "+r+" "+(~r)); } gives: 0 -> -1 0 1 -> -1 0 2 -> 0 -1 3 -> 1 -2 4 -> -3 2 5 -> -3 2 6 -> -3 2 7 -> 2 -3 8 -> -4 3 9 -> 3 -4 10 -> -5 4 11 -> 4 -5 12 -> -6 5 13 -> -6 5 14 -> -6 5 15 -> 5 -6 16 -> -7 6 17 -> -7 6 18 -> -7 6 19 -> -7 6 20 -> -7 6 21 -> 6 -7 22 -> -8 7 x -> i j with i the result and j the bitwise negative (used as insertion index in case i is negative). online JDoodle demo. It results in -1. So you can check first if it is less than 0 and if so, again use the bitwise negation to calculate the insertion position is 0. See Arrays.binarySearch. return -low - 1; A negative number, at most -1. As mid (the insertion point) ranges from 0. returns index of the search key, if it is contained in the array; otherwise, (-(insertion point) - 1). The insertion point is defined as the point at which the key would be inserted into the array: the index of the first element greater than the key, or a.length if all elements in the array are less than the specified key. Note that this guarantees that the return value will be >= 0 if and only if the key is found. With this I get an error that tells me that mid was never initialized, which makes sense because mid is only being initialized within the while loop, how would I deal with this? @NoivernEvo: you must initialize mid before the while loop. For instance with (lo+hi)>>1. Yes you have to initialize mid to 0. Especially for the case of a zero length array. You could also use lo. @JoopEggen: a testcase with {2,3,7,9,11,15,21} gives the wrong result for 22. One expects -8 (-7-1). But it gives -7. Shouldn't one use the low? Definitely. I generally write the loop differently. Corrected it. The actually code is return -1. But I'm confused your description. What's the "if the value is not found in the array, but the place it should be placed is found?" meaning? The value is either found in the array or not. It's not found before while, which means it's not in the array, so you should return -1. Binary search normally returns the betwise negation of the index where to place the value. The friend who asked the question wrote the wrong code with mid, I ignored his code. But in the binary search return -1 is common sense, ohhhh, what do you want get if the method don't find the value in the array? well Java's binary search doesn't use this common sense, but uses the insert index. It's only if the list is not ordered (as is for instance the case in searching a char in a string), -1 is returned.
common-pile/stackexchange_filtered
ADB Batch Script I really need some help with my syntax and getting this to run right. So im trying to automate an entire kodi, and llama install just by entering your ip into a batch file. Any assistance would be much appreciated. cls echo. echo You will install an app echo The app need to be in your ADB-Folder echo Before you hit enter INSTALL "iKoNo"" on your FireTV echo. pause echo. echo You can find your IP by going to Settings > About > Network on your device set /p ip=Enter the IP of your FireTV or FireTVStick: adb kill-server adb connect 192.168.137.%ip% adb install "%UserProfile%\Desktop\FireTV\kodi.apk" adb install "%UserProfile%\Desktop\FireTV\settings.apk" adb install "%UserProfile%\Desktop\FireTV\llama.apk" adb push "%UserProfile%\Desktop\FireTV\busybox" /data/local/tmp/ adb shell chmod 755 /data/local/tmp/busybox adb shell "%UserProfile%\Desktop\FireTV\busybox" --install -s /data/local/tmp adb push "%UserProfile%\Desktop\FireTV\adbfw128\events\llamakodi\linkiko" /sdcard/Llama/ adb push "%UserProfile%\Desktop\FireTV\adbfw128\events\llamakodi\linkiko\Llama_Profiles.txt" -> /sdcard/Llama/Llama_Profiles.txt adb push "%UserProfile%\Desktop\FireTV\adbfw128\events\llamakodi\linkiko\Llama_NfcNames.txt" -> /sdcard/Llama/Llama_NfcNames.txt adb push "%UserProfile%\Desktop\FireTV\adbfw128\events\llamakodi\linkiko\Llama_IgnoredCells.txt" -> /sdcard/Llama/Llama_IgnoredCells.txt adb push "%UserProfile%\Desktop\FireTV\adbfw128\events\llamakodi\linkiko\Llama_Events.txt" -> /sdcard/Llama/Llama_Events.txt adb push "%UserProfile%\Desktop\FireTV\adbfw128\events\llamakodi\linkiko\Llama_Areas.txt" -> /sdcard/Llama/Llama_Areas.txt adb shell rm -r /sdcard/.imagecache/com.amazon.venezia/org.ikonotv.smarttv adb shell mkdir -p /sdcard/.imagecache/com.amazon.venezia/org.ikonotv.smarttv adb push "%UserProfile%\Desktop\FireTV\adbfw128\icons\ikokodi.icon" /sdcard/.imagecache/com.amazon.venezia/org.ikonotv.smarttv adb push "%UserProfile%\Desktop\FireTV\adbfw128\icons\ikokodi.icon\B00NEJS7ZO\thumbnail_bfc0289736b3b0fbd3e32dec9d5d44c9dbe7cef5a082645ab0af157c6f3f600b.png" -> /sdcard/.imagecache/com.amazon.venezia/org.ikonotv.smarttv/B00NEJS7ZO/thumbnail_bfc0289736b3b0fbd3e32dec9d5d44c9dbe7cef5a082645ab0af157c6f3f600b.png adb push "%UserProfile%\Desktop\FireTV\adbfw128\icons\icons\ikokodi.icon\B00NEJS7ZO\preview_5dd7e33b605bec171c4bba546e5b35c783feb32a53c44227249ad52f653dc49c.png" -> /sdcard/.imagecache/com.amazon.venezia/org.ikonotv.smarttv/B00NEJS7ZO/preview_5dd7e33b605bec171c4bba546e5b35c783feb32a53c44227249ad52f653dc49c.png adb kill-server echo. echo Done! for some reason its not working right im trying to use the same process adbfire does! In this code --> https://github.com/Jocala/adbFire/blob/master/mainwindow.cpp What does "it's not working right" mean in detail? The > symbols in your batch file are interpreted by CMD.exe as redirection of output to a file. Escape them with ^ so each -> should be written as -^> if you need this symbol passed as a parameter. However ADB PUSH local_file remote_file syntax doesn't require use of these symbols, so just don't use -> at all. you missed the point. all lines in that block of code containing -> are redundant and should be deleted altogether. there are few other errors there as well
common-pile/stackexchange_filtered
Creating csv file in Scala I am trying to to create a csv file in Scala by getting data in the form of JsValue from a third part API. My method to save data to CSV file is : def saveToCSV(str:Seq[JsValue]) = { val outputFile = new BufferedWriter(new FileWriter("Result.csv")) val csvWriter = new CSVWriter(outputFile) val data = str.head data match { case JsObject(fields) => { var listOfRecords = new ListBuffer[Array[String]]() //val csvFields = Array("Open","High","Low","Close","Volume") //listOfRecords += csvFields fields.values.foreach(value => { val jsObject = value.asJsObject() val nameList = List(jsObject.fields("1. open").toString,jsObject.fields("2. high").toString,jsObject.fields("3. low").toString,jsObject.fields("4. close").toString,jsObject.fields("5. volume").toString) listOfRecords += Array(nameList.toString) csvWriter.writeAll(listOfRecords.toList.asInstanceOf) println("Written!") outputFile.close() }) } case JsNull => println("Null") } In the above code on line **csvWriter.writeAll(listOfRecords.toList.asInstanceOf)** I am getting this exception. Exception in thread "main" java.lang.ClassCastException: class scala.collection.immutable.$colon$colon cannot be cast to class scala.runtime.Nothing$ (scala.collection.immutable.$colon$colon and scala.runtime.Nothing$ are in unnamed module of loader 'app') On removing asInstanceOf from csvWriter.writeAll(listOfRecords.toList.asInstanceOf) this line, I get a compile time error on writeAll() method saying that it expects parameter of type util.List[Array[String]] Could anyone please help me to solve this problem? You have several mistakes in your code. asJsObject() is a method that does not exist in JsValue. Instead you should use value.as[JsObject]. jsObject.fields is of type Seq[(String, JsValue)], so you can't call jsObject.fields("1. open"). Instead you should call: jsObject("1. open").toString Calling listOfRecords.toList.asInstanceOf returns null. You should specify what you want to convert it to. But in order to convert it into a java type, you can just call: listOfRecords.toList.asJava. Don't forget: import scala.jdk.CollectionConverters._ The complete method is: import com.opencsv.CSVWriter import play.api.libs.json.{JsNull, JsObject, JsValue} import java.io.{BufferedWriter, FileWriter} import scala.collection.mutable.ListBuffer import scala.jdk.CollectionConverters._ def saveToCSV(str: Seq[JsValue]) = { val outputFile = new BufferedWriter(new FileWriter("Result.csv")) val csvWriter = new CSVWriter(outputFile) val data = str.head data match { case JsObject(fields) => { var listOfRecords = new ListBuffer[Array[String]]() //val csvFields = Array("Open","High","Low","Close","Volume") //listOfRecords += csvFields fields.values.foreach(value => { val jsObject = value.as[JsObject] val nameList = List(jsObject("1. open").toString, jsObject("2. high").toString, jsObject("3. low").toString, jsObject("4. close").toString, jsObject("5. volume").toString) listOfRecords += Array(nameList.toString) csvWriter.writeAll(listOfRecords.toList.asJava) println("Written!") outputFile.close() }) } case JsNull => println("Null") } } This will work under the assumption that the head of str contains a JsObject, with the fields: "1. open" "2. high" "3. low" "4. close" Are you deliberately taking only the first element of the input to this function? Please note that str.head is unsafe, in case the sequence is empty. Thanks. Now while calling this method I am using following code: val str = EntityUtils.toString(entity,"UTF-8") val jsonParser = Json.parse(str) SaveService.saveToCSV(jsonParser.as[JsObject].fields(1). Can you help me how can I now modify the code that you have sent above?
common-pile/stackexchange_filtered
Getting value from contenteditable div Up to this point, I've been using a textarea as the main input for a form. I've changed it to use a contenteditable div because I wanted to allow some formatting. Previously, when I had the textarea, the form submitted fine with Ajax and PHP. Now that I've changed it to use a contenteditable div, it doesn't work anymore and I can't tell why. HTML: <form> <div name="post_field" class="new-post post-field" placeholder="Make a comment..." contenteditable="true"></div> <input name="user_id" type="hidden" <?php echo 'value="' . $user_info[0] . '"' ?>> <input name="display_name" type="hidden" <?php echo 'value="' . $user_info[2] . '"' ?>> <ul class="btn-toggle format-post"> <button onclick="bold()"><i class="fa-icon-bold"></i></button> <button onclick="italic()"><i class="fa-icon-italic"></i></button> </ul> <div class="post-buttons btn-toggle"> <button class="btn-new pull-right" type="submit">Submit</button> </div> </form> JQuery Ajax: $(document).ready(function() { $(document).on("submit", "form", function(event) { event.preventDefault(); $.ajax({ url: 'php/post.php', type: 'POST', dataType: 'json', data: $(this).serialize(), success: function(data) { alert(data.message); } }); }); }); PHP (post.php): Just your typical checks and echo a message back. This is just a snippet of the code. <?php $user_id = $_POST["user_id"]; $display_name = $_POST["display_name"]; $post_content = $_POST["post_field"]; $array = array('message' => $post_content); echo json_encode($array); ?> For some reason, it's not sending back the post content anymore ever since I added the contenteditable div. Please help! You will probably have to bind the content in the contentEditable div to a hidden field in the form and send that to the ajax call Can you try making the an or a ? I think they are more designed for use with forms. The contents of the div are not serialized. You would have to add them on your own. var data = $(this).serialize(); data += "post_field=" + encodeURIComponent($("[name=post_field]").html()); Not my question but +1 for that data += string. Nice bit of code @AndyHolmes a big part of this site is upvoting other peoples' questions I tried what you suggested but it's still not working. Here's what I've added: http://pastebin.com/hc7bfDit Nevermind, I just changed the line to data: $(this).serialize() + "&post_field=" + $('[name=post_field]').html(),. Thanks for helping me out.
common-pile/stackexchange_filtered
Purpose of storing variables in web.xml? A lot of the advice on the web on storing variables which may change depending on the env/other conditions is to put them in web.xml, but isn't the web.xml within the war file? even if you find the exploded war and change it, wouldn't it get overriden if you update the war file? Or does the webcontainer provide any method to configure the web.xml without tinkering with the war file? The irony of Enterprise Configuration: Make a complex framework for the configuration which reads from an XML file because "it shouldn't be hardcoded since maybe you want to change it without rebuilding the whole thing", then you spec it so that you have to make a new artifact whenever you need to reconfigure something. The lolz. @gustafc exactly, it seems we always need just one more abstraction layer The web.xml variables are of very limited use, in my experience - the only advantage is that it's a standard location to look for hard-coded "configuration". There are several common solutions to get a more sensible way to configure web apps, none of which is standard: Use system properties (which usually involves fiddling around with startup scripts, and it can be hard to get a good overview of your entire config) Use environment variables (same drawbacks as system properties) Read a config file from a predefined location; often from the classpath by using getResourceAsStream (IIRC that usually means putting the config files in Tomcat's lib directory) You can also use JNDI, which has the disadvantage of being rather heavy-weight both to set up and read (if you're using vanilla Java, anyways - Spring for example has rather good support for reading from JNDI). However, JNDI is rather good because it's per-application, and not a process-global setting. If you need to run several instances of the same app on the same server, JNDI is pretty much the only option (although you can use it to just point out a config file somewhere, which makes things easier to work with). This may be relevant to your interests: How can I store Java EE configuration parameters outside of an EAR or WAR? Using JNDI to locate a constant file makes sense. Googling tomcat+jndi config shows results which put jndi config inside web.xml env-entry or META-INF/context.xml, I know that's the not the only way to do it, but still, The lolz. Advantages of specifying Parameter Values in web.xml Using your own settings file requires additional coding and management. Hard-coding parameter values directly into your application code makes them more difficult to change in the future, and more difficult to use different settings for different deployments (eg: JDBC settings, mail server address). Other developers using your code will be able to find any relevant parameters more easily, as this is a standard location for such parameters to be set. See also: Advantages of specifying Parameter Values in web.xml Web.xml.EnvEntry Referencing Environment Variables in web.xml All the points can also be applied to a xyzConstants.java file which just declares all the constants as static Strings etc, how is web.xml declaration better than a constants file? @Rnet You can inherit and override them. As far as I know web.xml does not provide ability to store custom variables. Typical way to configure your web application is to store configuration in database, separate properties/xml/json/other file, get configuration from separate web service or provide it through environment variables. Often a mixture of all these is used. For example you can add system variable using -D switch when running your container. This variable will contain path to file or URL where your configuration can be found. You can supply parameters using OS environment. You choice should depend on how many parameters do you have, what kind of application are you developing and how can you configure application server or computer OS. For example if you a hosting application on server you cannot configure these ways are not for you, so DB or web service are your only ways. Yes, I may not be able to access OS env variables on production, even if I did, it can be easily changed by any other application, script etc. DB/web service is a luxury which small applications may not have. System variable -D might work, but doesn't seem clean it feels like enforcing something on the whole server startup cause of your webapp, if there are lots of webapps in the same server and each one specifies many variables it gets messy fast. The folks that work on the Tomcat container recognize the irony that you have identified and have implemented a way to work-around the issue. The solution that they implemented for the issues that you have alluded to is to create another xml file... the context.xml file, which is read by the server. It appears that you can edit this file and have the new values read by the Tomcat without a restart... as long as you keep the elements out of the server.xml. I do not use Tomcat so I might be mis-interpreting the docs The GlassFish web container supports a similar feature, but does it via a couple admin cli command (asadmin): set-web-env-entry set-web-context-param There is probably web admin console support and you can set them up by editing the domain.xml. It seems like it isn't as flexible as the Tomcat implementation... but it does make it really easy to use. You need to disable and then enable your application for the changed values to 'take'. Do not redeploy you app, since that will delete the value that you just set.
common-pile/stackexchange_filtered
Stringgrid with buttons 1st Question: How do you call the part in stringgrid that is not visible? You need to scroll to see it. For example: There are 20 rows in a stringgrid but you can see only 10 at a time. You need to scroll to see other 10. How are the "hidden" ones called? 2nd Question: I know this is probably not the right way to do it so some pointers would be appreciated. I have a string grid with 1 fixed row. I add ColorButtons at runtime. So I populate 1 column with buttons. I use this buttons to "insert/delete" rows. As long as all of the grid is in the "visible" part this works well. Problem occcurs when I "insert" new rows and move the buttons to the "hidden" part. The last button is then drawn to Cell[0,0]. Other buttons in the "hidden" part are drawn correctly. Any idea why this happens? Should I find a way to manage this problem in the OnDraw method or is there a better (correct) way to do this? Code: procedure Tform1.addButton(Grid : TStringGrid; ACol : Integer; ARow : Integer); var bt : TColorButton; Rect : TRect; index : Integer; begin Rect := Grid.CellRect(ACol,ARow); bt := TColorButton.Create(Grid); bt.Parent := Grid; bt.BackColor := clCream; bt.Font.Size := 14; bt.Width := 50; bt.Top := Rect.Top; bt.Left := Rect.Left; bt.Caption := '+'; bt.Name := 'bt'+IntToStr(ARow); index := Grid.ComponentCount-1; bt :=(Grid.Components[index] as TColorButton); Grid.Objects[ACol,ARow] := Grid.Components[index]; bt.OnMouseUp := Grid.OnMouseUp; bt.OnMouseMove := Grid.OnMouseMove; bt.Visible := true; end; procedure MoveRowPlus(Grid : TStringGrid; Arow : Integer; stRow : Integer); var r, index : Integer; bt : TColorButton; Rect : TRect; begin Grid.RowCount := Grid.RowCount+stRow; for r := Grid.RowCount - 1 downto ARow+stRow do begin Grid.Rows[r] := Grid.Rows[r-StRow]; end; index := Grid.ComponentCount-1; for r := Grid.RowCount - 1 downto ARow+stRow do begin bt :=(Grid.Components[index] as TColorButton); Rect := Grid.CellRect(10,r); bt.Top := Rect.Top; bt.Left := Rect.Left; Grid.Objects[10,r] := Grid.Components[index]; dec(index); end; for r := ARow to (ARow +stRow-1) do begin Grid.Rows[r].Clear; end; end; procedure MoveRowMinus(Grid : TStringGrid; Arow : Integer; stRow : Integer); var r, index : Integer; bt : TColorButton; Rect : TRect; begin for r := ARow to Grid.RowCount-stRow-1 do begin Grid.Rows[r] := Grid.Rows[r+StRow]; end; index := ARow-1; for r := ARow to Grid.RowCount-stRow-1 do begin Rect := Grid.CellRect(10,r); bt :=(Grid.Components[index] as TColorButton); bt.Top := Rect.Top; bt.Left := Rect.Left; Grid.Objects[10,r] := Grid.Components[index]; bt.Visible := true; inc(index); end; for r := Grid.RowCount-stRow to Grid.RowCount-1 do begin Grid.Rows[r].Clear; end; Grid.RowCount := Grid.RowCount-stRow; end; Ok, I've tryed accessing the buttons in the OnDrawCell but I get "Access denied" error. I tryed docking buttons to Grid cells, but then the last visible buttons height gets reduced to the visible part of the Grid. And of course the last button is drawn to Cell[0,0]. For the visible part there exist the VisibleRowCount and VisibleColCount properties. The TGridAxisDrawInfo record type names the visible part Boundary and all parts together Extent (or vice versa, I never remember). So there is no specific by the VCL declared name for the unvisible part of a string grid. It just is the unvisible part. I think you are making a logical error: the buttons are not moved when you scroll the grid. Though it may seem like they move, that is just the result of moving the device context contents due to an internal call to ScrollWindow. The scroll bars in the string grid component are custom added, and do not work like those of e.g. a TScrollBox. To always show all buttons on the locations where they really are, repaint the string grid in the OnTopLeftChanged event: procedure TForm1.StringGrid1TopLeftChanged(Sender: TObject); begin StringGrid1.Repaint; end; When the row heights of all rows and the height of string grid never change, then it is sufficient to create all buttons only once, and let them stay where they are. This means that every button no longer is "attached" to a row, and storing them in the Objects property has no significance any more. When a button is pressed, simply calculate the intended row index from the position of the button in combination with the TopRow property of the string grid which specifies the index of the first visible scrollable row in the grid. If the grid can resize, e.g. by anchors, then update the button count in the parent's OnResize event. And if the row count of the string grid may become less then the maximum visible row count, then also update the (visible) button count. If you want more of an answer, then please update your question and explain how the MoveRowPlus and the MoveRowMinus routines are called due to interaction with the grid and or buttons, because now I do not fully understand what it is that you want. And about CellRect giving the wrong coordinates: that is because CellRect only works on full (or partial) visible cells. To quote the documentation: If the indicated cell is not visible, CellRect returns an empty rectangle. Addition due to OP's comments I think the following code does what you want. The original row index of every button is stored in the Tag property. unit Unit1; interface uses Windows, Classes, Controls, Forms, StdCtrls, Grids; type TForm1 = class(TForm) Grid: TStringGrid; procedure GridTopLeftChanged(Sender: TObject); procedure FormCreate(Sender: TObject); private FPrevTopRow: Integer; procedure CreateGridButtons(ACol: Integer); procedure GridButtonClick(Sender: TObject); procedure RearrangeGridButtons; function GetInsertRowCount(ARow: Integer): Integer; function GridButtonToRow(AButton: TButton): Integer; procedure MoveGridButtons(ButtonIndex, ARowCount: Integer); end; implementation {$R *.dfm} type TStringGridAccess = class(TStringGrid); procedure TForm1.FormCreate(Sender: TObject); begin FPrevTopRow := Grid.TopRow; CreateGridButtons(2); end; procedure TForm1.CreateGridButtons(ACol: Integer); var R: TRect; I: Integer; Button: TButton; begin R := Grid.CellRect(ACol, Grid.FixedRows); Inc(R.Right, Grid.GridLineWidth); Inc(R.Bottom, Grid.GridLineWidth); for I := Grid.FixedRows to Grid.RowCount - 1 do begin Button := TButton.Create(Grid); Button.BoundsRect := R; Button.Caption := '+'; Button.Tag := I; Button.ControlStyle := [csClickEvents]; Button.OnClick := GridButtonClick; Button.Parent := Grid; Grid.Objects[0, I] := Button; OffsetRect(R, 0, Grid.DefaultRowHeight + Grid.GridLineWidth); end; end; procedure TForm1.GridButtonClick(Sender: TObject); var Button: TButton absolute Sender; N: Integer; I: Integer; begin N := GetInsertRowCount(Button.Tag); if Button.Caption = '+' then begin Button.Caption := '-'; Grid.RowCount := Grid.RowCount + N; for I := 1 to N do TStringGridAccess(Grid).MoveRow(Grid.RowCount - 1, GridButtonToRow(Button) + 1); MoveGridButtons(Button.Tag, N); end else begin Button.Caption := '+'; for I := 1 to N do TStringGridAccess(Grid).MoveRow(GridButtonToRow(Button) + 1, Grid.RowCount - 1); Grid.RowCount := Grid.RowCount - N; MoveGridButtons(Button.Tag, -N); end; end; procedure TForm1.GridTopLeftChanged(Sender: TObject); begin RearrangeGridButtons; FPrevTopRow := Grid.TopRow; end; procedure TForm1.RearrangeGridButtons; var I: Integer; Shift: Integer; begin Shift := (Grid.TopRow - FPrevTopRow) * (Grid.DefaultRowHeight + Grid.GridLineWidth); for I := 0 to Grid.ControlCount - 1 do begin Grid.Controls[I].Top := Grid.Controls[I].Top - Shift; Grid.Controls[I].Visible := Grid.Controls[I].Top > 0; end; end; function TForm1.GetInsertRowCount(ARow: Integer): Integer; begin //This function should return the number of rows which is to be inserted //below ARow. Note that ARow refers to the original row index, that is: //without account for already inserted rows. For now, assume three rows: Result := 3; end; function TForm1.GridButtonToRow(AButton: TButton): Integer; begin for Result := 0 to Grid.RowCount - 1 do if Grid.Objects[0, Result] = AButton then Exit; Result := -1; end; procedure TForm1.MoveGridButtons(ButtonIndex, ARowCount: Integer); var I: Integer; begin for I := 0 to Grid.ControlCount - 1 do if Grid.Controls[I].Tag > ButtonIndex then Grid.Controls[I].Top := Grid.Controls[I].Top + ARowCount * (Grid.DefaultRowHeight + Grid.GridLineWidth); end; end. But may I say that this is also possible without the use of button controls: I suggest drawing fake button controls in the string grid's OnDrawCell event. (Comment 1/2) Thank you for your answer. I will try it today. I see I was a bit unclear on what I want to achieve. I want to fill the grid with data and buttons. When user clicks on a button (caption := '+') MoveRowPlus is called with parameters: Grid, ARow(row where button is) and stRow(number of rows that need to be inserted under ARow). Example: I have 20 rows with 20 buttons. I click on button in row 3., Rows 4 to 20 are moved for stRow. If stRow is 2 then row 4 becomes row 6 and so on till the end of the grid. (buttons move with their assigned rows) 2 empty rows are then populated (Comment 2/2) ..2 empty rows are then populated with a "subquery". Number of buttons remains the same. When I click again on button (now with caption := '-') MoveRowMinus is called and Grid is returned to inital state. (subquery closes). I hope I was clear enough on what I want to acheive. Do you think this could be achieved without using Object property? (at NGLN - sorry the atName doesn't seem to work) (atNGLN) Thank you. This is exactly what I need. I was considering drawing fake buttons myself, but this solution seems so much better. I am intersted in "pros and cons" of using this method. Why do you recommend using onDraw? Thank you for your time and intel. I.Bagon @user805528 Pro's of drawing buttons yourself: no need for rearrangement of controls due to scrolling, rows can have different heights, less resources needed, less flickering of the grid, easier handling of rowcount changes, row insertion and row deletion, and easier to implement in custom derivative. this working good but my app crashed when StringGrid had 10000 row!! @peimanF. This isn't the right solution for you. You need a virtual approach, or you need to draw the buttons in de OnDrawCell event. You may even need to re-evaluate your GUI design requirements, because such a number of controls is unrealistic for programs and users, isn't it?
common-pile/stackexchange_filtered
How to manipulate iOS conversation's streams? I found two very useful topics here and here. But I need somehow to change speaker/mic stream. For example, apply some effects or stop audio from being played to user at all. So my question is not about recording, but about manipulation of audio in real. Is there the way I can achieve that? Thanks. You can use my code and instead of saving samples to a file you can manipulate it somehow. My code hooks resampling process so you have full access to realtime audio streams. @creker, I tried not to call AudioUnitProcess_orig, but user still hear sounds. So decided AudioUnitProcess is not even important fore MobilePhone and conversation. What do u think about that?
common-pile/stackexchange_filtered
Python3 reques with cert and key "verified fail" I'm trying to request data from endpoints, I can do that with curl -k --key a-key.pem --cert a.pem https://<endpoint> But when I using python3 to do that, I failed every time Examples: With curl: root@control-plane-0:~# curl -k --key /etc/kubernetes/a-key.pem --cert /etc/kubernetes/a.pem https://<IP_ADDRESS>:6443/api/ { "kind": "APIVersions", "versions": [ "v1" ], "serverAddressByClientCIDRs": [ { "clientCIDR": "<IP_ADDRESS>/0", "serverAddress": "<IP_ADDRESS>:6443" } ] } With python: (code): from flask import Flask, render_template import requests from ast import literal_eval app = Flask(__name__) @app.route('/metrics') def metrics(): data = requests.get("https://<IP_ADDRESS>:6443/api/, cert=('/etc/kubernetes/a.pem', '/etc/kubernetes/a-key.pem')) print(data) return data if __name__ == '__main__': app.run(host='<IP_ADDRESS>',port="5001", debug=True) Result: r = adapter.send(request, **kwargs) File "/usr/local/lib/python3.9/site-packages/requests/adapters.py", line 514, in send raise SSLError(e, request=request) requests.exceptions.SSLError: HTTPSConnectionPool(host='<IP_ADDRESS>', port=6443): Max retries exceeded with url: / (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1121)'))) Are there any problems with requests libs ? I can't find a way to make it work Have you got your certificates verified using openssl verify -CAfile your-cert.pm I got the same Problem and solved by using full-chain certificates.please see your certificate contains fullchain(root,intermediate). And you can try like import requests test=request.get("url",verify="certificate-with-path") Ok I found out, I need to combine both verify = ca.pem and cert = cert, key since my cert is self-signed
common-pile/stackexchange_filtered
How can i associate a library symbol with an existing class I am using Flash Develop for compilation ( Not Flash IDE ) Here is a sample code : [Embed(source = 'assets.swf', symbol = 'app.view.CustomButton') var customButton_Class:Class ; var customButton_Instance ; customButton_Instance = new customButton_Class(); The problem is that this "customButton_Instance" doesnot know anything about app.view.CustomButton ?? ( Actually this means there is no sense in setting the class as app.view.CustomButton in the assets.fla library ) The workaround i am following is : var customButton:CustomButton = new CustomButton(); customButton.setView( customButton_Instance ) But i wanted somehow, the customButton_Instance should automatically associate itself with the customButton class. Any ideas pls ? why there is no type in customButton_instance? surely it is at least one of base types, e.g. Sprite, MovieClip. In you r example it looks like you have access to the class referenced as symbol in embed tag, why not, load assets.swf to you app domain and getdefinition for that class? Ya.. I too tried to do so ( using app.view.CustomButton), but I get error when using type for customButton_Instance . also, i actually wanted to experiment it with "embed" rathar than using "load" :) sure, but load doesnt increase the SWF size, embed does:) cast it like so - app.view.CustomButton(customButton_Instance) to make it of that type, that's a horrible naming convention might I add. casting too results in runtime error. What i have concluded with this is : EMBED is not a suggested way to use symbols with their class name. It' cannot be done without workarounds. I think, the only proper way is to use "swc" or dynamic loading via "load" When using Embed you lose the symbol's associated class. That's how it works. Instead, if you're using Flash Pro, choose to Publish a SWC that you can then add to your FlashDevelop project (in FlashDevelop: right-click > Add to Library), and then all the symbols will be visible in code completion like any class and you can just write new app.view.CustomButton() or create a custom class extending it. ya.. i noticed that. Embed has this disadvantage.
common-pile/stackexchange_filtered
No module named (image_dehazer) I was loading image_dehazer library, but it didn't work.... this is part of the error message and I don't know what to do !! Collecting image_dehazer Using cached image_dehazer-0.0.4.tar.gz (5.0 kB) Using cached image_dehazer-0.0.3.tar.gz (4.9 kB) Using cached image_dehazer-0.0.2.tar.gz (4.9 kB) Using cached image_dehazer-0.0.1.tar.gz (4.9 kB) ERROR: Cannot install image-dehazer==0.0.1, image-dehazer==0.0.2, image-dehazer==0.0.3, image-dehazer==0.0.4 and image-dehazer==0.0.5 because these package versions have conflicting dependencies. The conflict is caused by: image-dehazer 0.0.5 depends on numpy==1.19.0 image-dehazer 0.0.4 depends on numpy==1.19.0 image-dehazer 0.0.3 depends on numpy==1.19.0 image-dehazer 0.0.2 depends on numpy==1.19.0 image-dehazer 0.0.1 depends on numpy==1.19.0 To fix this you could try to: 1. loosen the range of package versions you've specified 2. remove package versions to allow pip attempt to solve the dependency conflict ERROR: ResolutionImpossible: for help visit https://pip.pypa.io/en/latest/user_guide/#fixing-conflicting-dependencies when I checked the numpy library, it was 1.20.3 Try this in order: pip uninstall numpy pip install numpy==1.19.0 pip install image-dehazer error when tried installation https://drive.google.com/file/d/19r_xw6LSQCwqptKd-YObVFNGHGciZo5U/view?usp=sharing
common-pile/stackexchange_filtered
Multiplicative even and odd functions? An even function satisfies $$ f_e(x) = f_e(-x) $$ and a odd function $$ f_o(x) = -f_o(-x) $$ Every function can be split into an even and an odd part $$ f(x) = f_e(x) + f_o(x) = \frac{1}{2}(f(x)+f(-x)) + \frac{1}{2}(f(x)-f(-x)) $$ Now even and odd functions are basically related to the operation of addition and the inverse of addition. I wonder if it would make sense to define even and odd functions related to multiplication and the inverse of multiplication. So I imagine a multiplicative even function would satisfy $$ f_{me}(x)=f_{me}\left(\frac{1}{x}\right) $$ and a multiplicative odd function $$ f_{mo}(x)=\frac{1}{f_{mo}\left(\frac{1}{x}\right)} $$ Are these functional equations the correct generalizations of even and off functions to the operation of multiplication? If so, what functions can fulfill these equations? Is it possible to split each function into a multiplicative even and odd part? Do you know what a group is? For functions $\mathbb{R}^_+ \rightarrow \mathbb{R}^+$ it makes sense, and you would get $f{me}(x) = \sqrt{f(x)f(1/x)}$ and $f_{mo}(x) = \sqrt{f(x)/f(1/x)}$, but I have never seen anyone use such notions. I haven't gone into the details but i would think you can split a function into the product of m-odd and m-even functions, where the m-even function is the geometric mean if f(x) and f(1/x), and the m-odd is the GM of f(x) and 1/f(1/x). How usefil this would be, i don't know, and certainly there would be several divide-by-zero gotchas to look out for. Hang on, does this mean a m-even function is one whose logarithm is additively-even? You can generalize even and odd functions $\mathbb{R}\to\mathbb{R}$ in a natural way in the setting of functions $G_1\to G_2$ between groups. If $f:G_1\to G_2$, then $f$ would be "even" if $f(x^{-1})=f(x)$ for all $x\in G_1$ and $f$ would be "odd" if $f(x^{-1})=f(x)^{-1}$ for all $x\in G_1$. Your example is precisely this construction with $G_1=G_2=\mathbb{R}^\times$, the group of nonzero real numbers under multiplication, or $G_1=G_2=(0,\infty)$, the multiplicative group of positive real numbers. Note that this avoids the problem of potentially dividing by zero. I think that in this generality, it is probably not possible to split every function into a product (or sum, if you like, if $G_2$ is additive) of "even" and "odd" parts. In order to do this for functions $\mathbb{R}\to\mathbb{R}$, we have to take advantage of some extra multiplicative structure to divide $f(x)+f(-x)$ and $f(x)-f(-x)$ by $2$. The most obvious way to symmetrize $f$, $f(x)f(x^{-1})$, does not even work if $G_2$ is not abelian. In analogy with the $G_1=G_2=\mathbb{R}$ example, if we assume that $G_2$ is abelian, then $E(x):=f(x)f(x^{-1})$ is an "even" function and $O(x)=f(x)f(x^{-1})^{-1}$ is an "odd" function. We have $E(x)O(x)=f(x)^2$. So in your $\mathbb{R}^\times$ example, you can at least write the square of any function as the product of an even and odd function. This further implies that if $f:(0,\infty)\to(0,\infty)$, then $f$ can be written as the product of an "even" and an "odd" function by setting $g=\sqrt{f}$, $E(x)=g(x)g(x^{-1})$, and $O(x)=g(x)g(x^{-1})^{-1}$, so that $f(x)=g(x)^2=E(x)O(x)$.
common-pile/stackexchange_filtered
How to export an encrypted non-seedless electrum wallet into bitcoin-qt? How to export an encrypted non-seedless electrum wallet into bitcoin-qt? Is it even possible? Cheers Does this answer your question? Migrating from Electrum => Bitcoin core You'll have to import the addresses. See electrum2core.
common-pile/stackexchange_filtered
Rich Text Editor with extra or external plugins support I am looking for a free rich text editor which supports extra or external plugins like MathType and Chemtype. I tried with CKEditor5 via its official documentation in Angular 13, but it gives some build errors, and conflicts after executing the program installation. You can try Syncfusion Angular RichTextEditor https://www.syncfusion.com/angular-ui-components/angular-wysiwyg-rich-text-editor Syncfusion offers a free community license also. https://www.syncfusion.com/products/communitylicense Note: I work for Syncfusion
common-pile/stackexchange_filtered
How to properly use Dagger 2 to callback from adapter to activity/fragment? I'm talking about the new architecture that was presented on the last Google IO. Now I have the next implementation: public class ThumbnailsAdapterViewModel extends ViewModel { MutableLiveData<ThumbnailSelected> thumbnailSelectedMutableLiveData = new MutableLiveData<>(); @Inject public ThumbnailsAdapterViewModel() { } public LiveData<ThumbnailSelected> getSelectedThumbnail() { return thumbnailSelectedMutableLiveData; } public void setThumbnailSelected(ThumbnailSelected thumbnailSelected) { thumbnailSelectedMutableLiveData.setValue(thumbnailSelected); } } MyFragment: @Inject ThumbnailsAdapter thumbnailsAdapter; // onCreateView ThumbnailsAdapterViewModel thumbnailsAdapterViewModel = ViewModelProviders.of(this, viewModelFactory).get(ThumbnailsAdapterViewModel.class); thumbnailsAdapterViewModel.getSelectedThumbnail().observe(this, new Observer<ThumbnailSelected>() { @Override public void onChanged(@Nullable ThumbnailSelected thumbnailSelected) { if (thumbnailSelected != null) { Snackbar.make(getView(), "Thumbnail #" + thumbnailSelected.getPosition() + " is selected", Snackbar.LENGTH_SHORT).show(); } } }); thumbnailsAdapter.setViewModel(thumbnailsAdapterViewModel); ThumbnailsAdapter: public class ThumbnailsAdapter extends RecyclerView.Adapter<ThumbnailsAdapter.ViewHolder> { List<Thumbnail> thumbnails; private ThumbnailsAdapterViewModel viewModel; @Inject public ThumbnailsAdapter(List<Thumbnail> thumbnails) { this.thumbnails = thumbnails; } public void setViewModel(ThumbnailsAdapterViewModel viewModel) { this.viewModel = viewModel; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_thumbnail, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(ViewHolder holder, int position) { holder.bindData(thumbnails.get(position), position); } @Override public int getItemCount() { return thumbnails.size(); } class ViewHolder extends RecyclerView.ViewHolder { // ... implementation public void bindData(final Thumbnail thumbnail, final int position) { imageThumbnail.setImageResource(R.drawable.ic_thumbnail); imageThumbnail.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { viewModel.setThumbnailSelected(new ThumbnailSelected(thumbnail, position)); } }); } } } The main disadvantage: I'm passing ViewModel into Adapter but it would be ideal to inject it, but I cannot (at least I don't know how to do it properly). I guess that ViewModel is just created with some another scope. I tried to create it in the next class: @Module public class ActivityModuleScopeMain { @Provides List<Thumbnail> provideThumbnails() { List<Thumbnail> thumbnails = new ArrayList<>(); // here the list for adapter is created return thumbnails; } } One more dagger module to present whole (I hope) picture: @Module public abstract class ActivityModuleMain { @ContributesAndroidInjector(modules = ActivityModuleScopeMain.class) abstract MainFragment contributeMainFragment(); } If it's not enough I'm ready to post more code. It's working solution but I'm not satisfied. can you look into my tutorial https://github.com/saveendhiman/SampleApp @Saveen sure, could you tell me where exactly should I look?
common-pile/stackexchange_filtered
how to store multilevel JSON in powershell I want store JSON in powershell variable so that i can use them in Invoke-Request GET,POST,etc. like below $body = @{ username = 'some username' password = 'some password' } $body = $body | ConvertTo-Json it gives me JSON like { "username" : "some username" "password" : "some password" } But now i want to get output like below [ { "op":"set", "member":"disks", "value":[ { "diskId":"0:0", "sizeGB":1 }, { "diskId":"0:1", "sizeGB":2 }, { "diskId":"0:2", "sizeGB":16 }, { "path":"/extra", "sizeGB":"20", "type":"partitioned" } ] } ] how can i store this multilevel JSON in powershell variable Thanks You can nest hashtables and arrays in PowerShell. Here an example: $body = @{ 'op' = 'set' 'member' = 'disks' 'value' = @( @{ 'diskId' = '0:0' 'sizeGB' = '1' }, @{ 'diskId' = '0:1' 'sizeGB' = '2' } @{ 'diskId' = '0:2' 'sizeGB' = '16' } @{ 'path' = '/extra' 'sizeGB' = '20' 'type' = 'partitioned' } ) } Note that valueis an Array (using @()) of hashtables. i converted it to JSON using ConvertTo-JSON call but converted JSON failed to parse { "op": "set", "value": [ { "sizeGB": "1", "diskId": "0:0" }, { "sizeGB": "2", "diskId": "0:1" }, { "sizeGB": "16", "diskId": "0:2" }, { "path:": "/extra", "sizeGB": "20", "type": "partitioned" } ], "member": "disk" } above is the JSON converted from your solution expected is [ { "op":"set", "member":"disks", "value":[ { "diskId":"0:0", "sizeGB":1 }, { "diskId":"0:1", "sizeGB":2 }, { "diskId":"0:2", "sizeGB":16 }, { "path":"/extra", "sizeGB":"20", "type":"partitioned" } ] } ] The output is valid JSON (checked with Json validator). The [brackets are generated if you have an array of these settings thanks jisaak, How can i get it like exact above expected. Why do you want that? You already have valid Json! If you have to, you could use something like '[{0}]' -f $body | ConvertTo-Json Actually i am sending request to cloud with REST api and it is expected JSON format above in documentaion and its failing with error "An error occured while deserializing the request JSON content." ah, maybe because i have :in path and wrote diskinstead of disks. I updated my answer, try again. Let us continue this discussion in chat.
common-pile/stackexchange_filtered
fetch data from two tables but only from first table sql i have two tables(foregin key) first is 'question' and second is 'answer' it's like a quiz. 'question' table have only question's and 'answer' tables have only options. now i want to fetch data from both tables but from first table i want only one row (ex. id = 4) and from second table all the related rows(id=4). help for related query i also did sql joins. SELECT t1.id, t2.* FROM ...... SELECT * FROM t1 JOIN t2 USING(id) WHERE id = 4 You can use the following SQL and enhance it as per your needs:- SELECT question.column_name_1, question.column_name_2, option.column_name_3, option.column_name_4 from question, option WHERE question.id = option.question_id_column_name; hello nandal Thanx for help,But i'm already did this query. now suppose 'question' table have only one row of id=4, and 'answer' table have 4 rows of id=4 I do not have the clear scenario of your database tables , still I'm writing a query for you , if you have some other names for fields , please use those accordingly . $sql = "select * from question as 'qst' inner join answer as 'ans' on ans.question_id = qst.id where qst.id = 1" ; Use proper field names and you will get the desired output .
common-pile/stackexchange_filtered
Any difference between DOMAIN\username and<EMAIL_ADDRESS>I'm trying to troubleshoot an obscure authentication error and need some background information. Is there any difference between how Windows (and programs like Outlook) process DOMAIN\username and<EMAIL_ADDRESS>What are the proper terms for these two username formats? Edit: In particular, are there any differences in how Windows authenticates the two username formats? You might be interested in one of my previous questions. Assuming you have an Active Directory environment: I believe the backslash format DOMAIN\USERNAME will search domain DOMAIN for a user object whose SAM Account Name is USERNAME. The UPN format username@domain will search the forest for a user object whose User Principle Name is username@domain. Now, normally a user account with a SAM Account Name of USERNAME has a UPN of USERNAME@DOMAIN, so either format should locate the same account, at least provided the AD is fully functional. If there are replication issues or you can't reach a global catalog, the backslash format might work in cases where the UPN format will fail. There may also be (abnormal) conditions under which the reverse applies - perhaps if no domain controllers can be reached for the target domain, for example. However: you can also explicitly configure a user account to have a UPN whose username component is different from the SAM Account Name and whose domain component is different from the name of the domain. The Account tab in Active Directory Users and Computers shows the UPN under the heading "User logon name" and the SAM Account Name under the heading "User logon name (pre-Windows 2000)". So if you are having trouble with particular users I would check that there aren't any discrepancies between these two values. Note: it is possible that additional searches are done if the search I describe above doesn't find the user account. For example, perhaps the specified username is converted into the other format (in the obvious way) to see if that produces a match. There must also be some procedure for finding accounts in trusted domains that are not in the forest. I don't know where/whether the exact behaviour is documented. Just to further complicate troubleshooting, Windows clients will by default cache information about successful interactive logons, so that you may be able to log into the same client even if your user account information in the Active Directory is inaccessible. I like this answer better than mine. Nicely done. If you're querying AD with ldapsearch you'll find the down-level login name in the msDS-PrincipalName attribute, which you need to request explicitly since it's an "operational attribute". I may get corrected on this, but there's not really much of a difference. Domain\User is the "old" logon format, called down-level logon name. Also known by the names SAMAccountName and pre-Windows 2000 logon name. <EMAIL_ADDRESS>is a UPN - User Principal Name. It's the "preferred", newer logon format. It's an Internet-style login name, that should map to the user email name. (Ref. at MSDN) The reasons for logging in with UPNs I think are mostly cosmetic - they hypothetically give your users in your company a single name with which to log on to their workstations which can also act as their corporate email address. edit: More elaboration - another advantage of UPNs is that you can setup more than one valid UPN for your users to logon with. Again, largely cosmetic. But the important thing is that not all applications are compatible with UPNs, and that might be what you're experiencing. edit #2: I like Harry Johnston's answer below about the two slightly different search formats performed. It makes sense, and most importantly it might actually explain your problem. :) There is no mention of UPNs in RFC 822, "Standard for the format of ARPA Internet text messages". UPNs are an Active Directory "invention" that binds together Kerberos and LDAP information in order to provide Single-Sign-On services (SSO) across a domain (or "realm") of associated computer systems. Ah, sorry -- I was getting my info from http://msdn.microsoft.com/en-us/library/windows/desktop/ms680857(v=vs.85).aspx ... I'll edit my answer if I find the right one. @adaptr RFC 822 was obsoleted 10 years ago - see rfc 2822. @Ryan, I think the Active Directory is searched in different ways for the two different formats - see my answer. @JimB I think you'll find that no, RFC822 is NOT obsolete; both RFC2822 and the current RFC 5322 refer to it, as well as a multitude of other mail- and content-related RFCs (5321 for starters). perhaps you have a different definition of "obsolete" then the rest of the world, both 2822 and 5322 refer to 822 as obsolete, from 5322: "This specification is a revision of Request For Comments (RFC) 2822, which itself superseded Request For Comments (RFC) 822, "Standard for the Format of ARPA Internet Text Messages", updating it to reflect current practice and incorporating incremental changes that were specified in other RFCs" The "old logon format" is also called a "Down-level logon name" The slashed format (DOMAIN\username) is actually the NetBIOS equivalent of the domain's DNS name (domain.mycompany.local). The NetBIOS name is limited to 15 characters and cannot contain dots, underscores etc. This page explains in more detail: Jeff Schertz, 2012-08-20, Understanding Active Directory Naming Formats As mentioned by @harry-johnston above, its really just the old NT4 and Windows 2000 compatible format but it seems to have stuck as a favorite format (its less to type!). Eventually, support for the legacy format may go from Windows. It's probably a good idea to get users into the habit of using the UPN format as it also avoids issues where they are having problems to log in to a PC with their username and don't realise that the Windows login box has defaulted to the local PC domain (eg. pc01\fred) or when they connect to different remote desktop hosts and have to remember to include the domain as well as their username because the Remote Desktop Client may cache another previously used domain name. Sticking to the UPN format every time just makes for less support calls in the end. It's unlikely that the "old format" would go away, as that's still in use for non-AD environments. (As Host\username of course, no domains without AD) There is definelty a difference between those two only 99% of the users won't have a problem with it. I will try to explain the difference and when such a problem may occure. If you use domain\username when you try to access a fileshare then DNS will first resolve the domain and then check the username. If you use username@domain then it will directly check if the user is on the ACL (access control list ) and has access. So what does it matter you might think... well, picture this: 1 domain controller with name DC01 and all the clients get dns and are in this domain. You want to migrate and someone added another server with the same name. The latter server will also become a DC so the local SAM won't be used anymore and also has a file share. When the users will connect to the server they are prompted for credentials. If you use domain\username it will first check the current domain instead of using the new domain and we used accounts from the new domain on the file share. So once it has found the current dc and checks the username it can't be found. ( even if the username and password are found and are exact the same it won't work as it won't use the username to verify if it is allowed in the ACL but it will use the SID. The sid will be created at the user creation time in AD and you have a change of 1 in a trillion that it is the same, great huh:-P ). -1. I really can't follow what you're saying here. Where you say "When the users will connect to the server" which server do you mean, the old DC01, or the new DC01? What happened to the old DC01 anyway, was it decommissioned, renamed, removed from the domain, or what? Was it properly demoted first? What do you mean by "new domain", since you didn't describe the creation of a new domain at any point? If you use "domain\username" it should always search the domain you explicitly specified, are you describing a case where it doesn't? Also, "it won't use the username to verify if it is allowed in the ACL but it will use the SID" is the expected behaviour - it should always do that, regardless of whether you use domain\username or username@domain. Are you talking about a case where there are two domains with the same name, or something similarly pathological? DNS will first resolve the domain and then check the username. DNS will check the username? What?
common-pile/stackexchange_filtered
Create a regular expression in htaccess for seemingly complicated subdomain with folder I have many URLs like this: http://blog.domain.org/blog/bid/365332/a-page-here The number folder after "bid" changes and is random for every URL and "a-page-here" is different for every URL. I need the regex to direct this type of URL to the following: http://www.domain.org/blogs/a-page-here Any help is appreciated as I do not know where to begin with this regex expression. In the document root of your "blog.domain.org" domain, add: RewriteEngine On RewriteCond %{HTTP_HOST} ^blog\.domain\.org$ [NC] RewriteRule ^blog/bid/[0-9]+/(.*)$ http://www.domain.org/blogs/$1 [L,R] to redirect. @josephthrive This handles everything after that bunch of numbers, anything can be after that it it'll get passed to the redirect. Great! Would there be a way to handle the first domain beginning each word with a capitol letter such as "A-Page-Here" to all lowercase such as "a-page-here"? @josephthrive if you want to force lowercase, you'll need to have access to your server's vhost config in order to declare a rewrite map I have this access. Do you know how to achieve this?
common-pile/stackexchange_filtered
access session data of opencart through php file I am new to opencart. I have my basic php code at http://localhost/testphp and my opencart is installed at http://localhost/opencart. What I want to do is that in testphp, I have a page in which I want to check that if any user is logged in or not at opencart. If it is logged in then I want to perform x function and It not logged in then want to perform y function I have tried to logged in to opencart and tried to print_r($_SESSION) in testphp. It is returning blank. How can I perform this ? Please help me There is a customer_online table in OpenCart database. see getCustomersOnline function in admin\model\report\customer.php If you are using localhost then you can try this. or same hosting account or cpanel Go to catalog/controller/common/header.php Before "public function index() {" Add this code class ControllerCommonHeader extends Controller { public function index() { session_start(); $_SESSION['opencart'] = $this->session->data; You Have to Print Array in http://localhost/testphp Code : <?php session_start(); echo '<pre>'; print_r($_SESSION); echo '</pre>'; ?> Your Output Will be Array ( [opencart] => Array ( [language] => en-gb [currency] => USD [customer_id] => 2 [shipping_address] => Array ( [address_id] => 2 [firstname] => Prashant [lastname] => Bhagat [company] => [address_1] => Surat [address_2] => [postcode] => 395003 [city] => Surat [zone_id] => 1485 [zone] => Gujarat [zone_code] => GU [country_id] => 99 [country] => India [iso_code_2] => IN [iso_code_3] => IND [address_format] => [custom_field] => ) ) )
common-pile/stackexchange_filtered
How can I enter number digit by digit in field /selenium So I have verification code that contains 7 fields and I have verification code itself. How can I enter this code by number in every field? I tried to do List, but my skills are not that good. Is it possible to share any screenshot? so that we will able to help you to resolve that issue added screenshot It is totally dependent on how you application looks and what the DOM structure is. I could help you with the following piece of code that shows how you can automate the verification code field. Execute the below code and see how it works. driver.get("https://codepen.io/DaniRC/pen/PowwwjZ"); List<String> data = new ArrayList<String>(); data.add("5"); data.add("4"); data.add("3"); data.add("5"); int counter = 0; driver.switchTo().frame("result"); List<WebElement> elements = driver.findElement(By.id("form")).findElements(By.xpath("input[@type='text']")); for(WebElement element : elements) { element.sendKeys(data.get(counter)); counter++; } Thread.sleep(10000); driver.close(); I suggest you to not use a list. For every field you should use another function. Because in time, devs will delete or rename or move.. any field and your test will failed because they do a simple action with just one of field. So I think you should use one function for each field. typeDigital(String number){ driver.findElemeny(By.css("css"))).sendKeys(number));} here you will set your number from parapeter. If you have more question about this write me.
common-pile/stackexchange_filtered
Wordpress :Error in site title with multi language I have site with 3 language 1- Arabic 2- English 3- France The problem is in page title,i set the title for all language like : مجمع البحوث العربية This title work good in Arabic language , but when open as English is show me like: طھظپط³ظٹط± ط§ظ„ط¹ط´ط± ط§ظ„ط£ط®ظٹط± What can do to solve it Is your site UTF-8 Encoded? yes its UTF-8 Encoded check this out: http://www.wpbeginner.com/beginners-guide/how-to-easily-create-a-multilingual-wordpress-site/
common-pile/stackexchange_filtered
Mod_Rewrite URL Current URL: http://localhost/blog/profile.php?username=Username&page_type=following I want it to be: http://localhost/blog/profile/Username/following Current .htaccess: RewriteEngine On CheckCaseOnly On CheckSpelling On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-l RewriteRule ^profile/(.*)$ /blog/profile.php?username=$1&page_type=$2 [QSA,L] Is it possible to rewrite it this way? Or are there a better way? You don't have a $2 for the page_type in the RewriteRule pattern RewriteRule ^profile/(.*?)/(.*)$ /blog/profile.php?username=$1&page_type=$2 [QSA,L] You need two capture groups: RewriteRule ^profile/(.*?)/(.*)$ /blog/profile.php?username=$1&page_type=$2 [QSA,L]
common-pile/stackexchange_filtered
ArcGIS Pro will not display symbols on map Using ArcGIS Pro with an imported data file of state plane UTMS. The file imports nicely, but I can not get symbols to display. I have applied simple black circle symbols, but they do not display. If I select a point in the attribute table, the selection will show on the map. If a apply labels, they are displayed correctly. If I change the symbol size, the symbols still do not display, but the labels will shift to account for the change in the symbol size. What happens if you zoom to layer? What if you select a few records and zoom to selected features? I tried that, it doesn't work. It sounds like you have transparency set to 100% for that layer. Select the layer in the contents pane. Select the Feature Layer tab. Set Transparency to 0%.
common-pile/stackexchange_filtered
Cleaning rat poison? (UK) So i rent a studio in an old house, carpets everywhere, barely got through to the landlord to change the kitchen to anything but carpet.... Been here for like 5 years, about 2 years ago i though i had a mouse/rat problem. placed poison around it was never touched, but there are definitely holes, since before i've been here. I definitely heard & saw one last Saturday (9 days ago) - same day i noticed it started eating some of the 2 year old poison packets, but ate through 4 of them, which are supposed to be single-feed kill, without dying for a week... Placed some fresh ones next to the old ones without cleaning anything 5 days ago, haven't heard of it for over two days and the old nor the new poison have been touched. Plugged any holes I found... (off-topic) Do you think it's gone? But to the main question, some of the poison that's been nibbled on and powderised along with untouched pellets being spilled around, I want to clean it up. Given that the poison says your skin shouldn't touch it, i'm scared that vacuuming it up will throw it up in the air and inhaling it is worse, since it's on carpet i have very few ideas as to how to clean it out, any ideas? Reads like a horror story. They will usually make it back to the nest and die there. You will know it by rotting smell Hopefully there's no nest in my walls It seems that the old stuff has lost its potency, so the powder is probably not a hazard. The active ingredient "warfarin" is not a cumulative poison so a small exposure will not pose any long term hazard. consider other means of collecting the dust, (eg: use a brush or a damp paper towel)
common-pile/stackexchange_filtered
How to round a datatime LocalTime to the onkly datatime. Not to the time with hours I have got a code: DateTime dzienStart1; DateTime dzienStop1; dzienStart1 = dzienStart.ToLocalTime(); dzienStop1 = DateTime.Now.ToLocalTime().AddMonths(-2).AddDays(-1.0); Whem I look at a date in debbuger i getting in first date +2 hours. And in secound is good server date: Please help me. How to add rounded data time to days. My suggestion is to you can do with string format like this... string DateWithHours = String.Format("{0:yyyy-MM-dd H}", yourDateParameter); if you round hours then u can manually check by extract minute part from date. if minute is > 30 then add 1 hour to date.. For more details see these links... http://www.csharp-examples.net/string-format-datetime/ http://mikeinmadison.wordpress.com/2008/03/12/datetimeround/ I write this code: dt = dzienStart; String.Format("{0:yyyy-mm-dd}", dt); item["Dzien"] = dt;, and i still have got 02:00 Hours. Ok I Can geret I getted 00:00 from this code: dt = dzienStart; dtString =String.Format("{0:yyyy-MM-dd}", dt); item["Dzien"] =Convert.ToDateTime(dtString); .Net doesn't have a type for only date without time, but you can get a DateTime with no time set from any DateTime by accessing it's Date property. If you want to "round" it to the next day if past noon then add 12 hours before getting Date. Hello Per, but I always want to take a rounded time, I don't want to adding 12 hours. I always wont to have time 00:00
common-pile/stackexchange_filtered
dynamically set checkbox checked if value present in database How to dynamically checked checkbox based on database value which are present or not null @foreach (abc.Models.xyz entry in entrydetails) { <div style="height:auto !important;max-height:160px; overflow-y:auto;width:79%;"> @{ List<abc.Models.Singer> singerobjlist = abc.Service.Class1.singerlist(); } @foreach (abc.Models.Singer singerobj in singerobjlist) { <div class="boxcheck"> <input type="checkbox"<EMAIL_ADDRESS>name="Singer1l"/> <EMAIL_ADDRESS> </div> } </div> } Dear All... I have declared foreach loop at the top which contain all entry in database corresponding to singer1-singer7. Now below foreach loop I have declared another foreach loop which will dynamically display all singer name in view page. I want to do that all those singer whose not null in outer foreach loop that singer name must be checked by inner foreach loop. Try this <input type="checkbox"<EMAIL_ADDRESS>name="Singer1l" @(singerobj.Singer1!=null ? Html.Raw(" checked=\"checked\"") : null) /> Works fine, tanks Use this <div class="boxcheck"> @Html.CheckBoxFor(m=>m.singerobj.Singer1) <EMAIL_ADDRESS></div> my all singer name should be displayed which are checked or unchecked... please help to us
common-pile/stackexchange_filtered
Using If statement to add a timestamp if a tick box has been ticked I have a sheet which contains a tick box (cell C36). I have changed the data validation so when ticked, the cell = 1 and when un-ticked it = 0. Now i would like a script that when C36 = 1, it puts a time stamp (HH:mm) in B39 without using the NOW() function and when C36 = 0, it B39 should be blank/empty. I have tried using the NOW() function but that updates every time something is changed on the page and i want it static from the time it is ticked. I have used an If/else script but it either doesn't input anything in the cell or it will always have the time, even if the box is not ticked. function onEdit() { var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Page 1'); var time = ss.getRange('B39'); var tick = ss.getRange('C36'); if(tick =='1'){ time.setValue(new Date()).setNumberFormat("HH:mm"); } else if (tick =='0'){ time.setValue(""); } } How does one tick a tick box? Does the tick bite? This should do exactly what you want: function onEdit(e){ var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Page 1'); var range = e.range; Logger.log(range.getColumn()+ " "+range.getRow()) if (range.getColumn() != 3) {Logger.log("wrong column") return;} if (range.getRow() != 36) return; var prettyTime= Utilities.formatDate(new Date(),'America/Los_Angeles', "HH:mm" ); var B39 = ss.getRange(39,2); if (range.getValue() == true) B39.setValue(prettyTime); if (range.getValue()== false) B39.setValue("n/a"); Your problem before is that it was doing stuff regardless of which cell was edited. That's brilliant! Thank you very much. So this does work, however, i have 2x tickboxes which i want to use it in and when i duplicate it to the 2nd , only 1 will work at a time.
common-pile/stackexchange_filtered
Partial Derivative Of An Exponential Gaussian Function When trying to find the first partial derivatives for the function $\psi(x,t)=ae^{-(bx+ct)^2}$, I am getting the following answers: $$\frac{ \partial \psi}{\partial x}=2bae^{-(bx+ct)^2}$$ and $$\frac{ \partial \psi}{\partial t}=2cae^{-(bx+ct)^2} $$ This does not appear to be correct. Could someone please explain what I am doing wrong? You need also the derivative of $(bx+ct)^2$ to appear. Use chain rule,\begin{align}\frac{ \partial \psi}{\partial x}&=ae^{-(bx+ct)^2}\frac{\partial}{\partial x}(-(bx+ct)^2)\\&=ae^{-(bx+ct)^2}(-2(bx+ct))\frac{\partial}{\partial x}(bx+ct)\\&=ae^{-(bx+ct)^2}(-2b(bx+ct)) \end{align} Similarly for $\frac{ \partial \psi}{\partial t}.$ Thank you for your response and clarification. I can see where I went wrong now. If I need to take the second partial derivative and so on, does that mean I need to use product rule then chain rule? Yes. Also note that $\frac{\partial \psi}{\partial x} = \psi (-2b(bx+ct))$ to cut down repeated computation.
common-pile/stackexchange_filtered
In XSLT how do you test to see if a variable is set? When using XSLT how does one test to see if a variable has a value? Or more specifically, how do you properly nest the xsl:value-of method below so that it returns '' rather than failing to transform, when a value has not been assigned? Declaration options could potentially be either... <xsl:variable name="ID" select="//MessageID"/> <xsl:variable name="ID" select=""/> What needs to be added to this so that it does not to fail the transform? <Container> <xsl:attribute name="ID" select="$ID"/> </Container> Desired output: <Container ID=""/> Currently, the transform will fail if the variable's select statement does not find the referenced node. I have tried several different approaches: <xsl:if test="$ID"><xsl:value-of select="$ID"/></xsl:if> <xsl:if test="string-length($ID)&gt;0"><xsl:value-of select="$ID"/></xsl:if> <xsl:if test="count($ID)&gt;0"><xsl:value-of select="$ID"/></xsl:if> <xsl:if test="($ID) !=''"><xsl:value-of select="$ID"/></xsl:if> and I have even attempted declaring an empty variable for comparison: <xsl:variable name="empty_string"/> <xsl:if test="($ID) != $empty_string"><xsl:value-of select="$ID"/></xsl:if> I find this question to be very similar, but distinctly different than: In XSLT how do you test to see if a variable exists? An empty select expression as in <xsl:value-of select=""/> does not compile so it is not clear what you want to achieve there. Can you post a minimal but complete sample that gives you an error, together with the exact error message and a description of the XSLT processor? Great answer! Not sure how I overlooked that. Still not sure what the problem is, other than that <xsl:variable name="ID" select=""/> will not compile. You need to have an attribute value for the select attribute that is an XPath expression. Please try to put <xsl:choose> inside your variable as below: <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:output method="xml" indent="no"/> <xsl:template match="/"> <xsl:variable name="ID"> <xsl:choose> <!--check if path exists and if value is not empty--> <xsl:when test="//MessageID and string-length(//MessageID) &gt;0"> <xsl:value-of select="//MessageID"/> </xsl:when> <!--otherwise it will be assigned blank value--> <xsl:otherwise> <xsl:value-of select="''"/> </xsl:otherwise> </xsl:choose> </xsl:variable> <Container> <xsl:attribute name="ID"> <xsl:value-of select="$ID"/> </xsl:attribute> </Container> </xsl:template> </xsl:stylesheet> So in case that input: <Main> <Test> <MessageID>123</MessageID> </Test> </Main> Your output will be: <Container ID="123"/> And in case of below inputs: <?xml version="1.0" encoding="UTF-16"?> <Main> <Test> <MessageID></MessageID> </Test> </Main> OR <?xml version="1.0" encoding="UTF-16"?> <Main> <Test> </Test> </Main> Your output will be: <Container ID=""/> Hope it helped. If a variable exists at all in XSLT, then it has a value. What you are asking is how to test whether it has some particular special value. I normally encourage people to avoid declarations like <xsl:variable name="ID"><xsl:value-of select="//MessageID"/></xsl:variable> in favour of <xsl:variable name="ID" select="//MessageID"/> because it's much simpler and faster. But let's suppose you have some good reason for using the more complex form. In that case the value of the variable in XSLT 1.0 will be a "result tree fragment" containing either a single text node child, or no child at all in the case where the xsl:value-of instruction creates a zero-length text node. You can test whether the string value of the result tree fragment is zero length by testing <xsl:if test="string($ID)"/>. However, this will also return false, for example, for an RTF whose content is an element node with a zero-length string value. Unfortunately you can't do very much with an RTF without using the node-set() extension function. If you have access to the node-set() extension function, you can do which tests whether the root node of the RTF has a child node. All very messy. Suggestions: (a) Try to use the form of xsl:variable binding with a select attribute whenever you can. (b) Isn't it time you moved to XSLT 2.0+? I'll update the question to follow the format you recommended, you're right it would certainly be easier to read. Hi Michael, you answered a similar question here (https://stackoverflow.com/questions/12387653/xslt-difference-between-value-of-select-and-variable-select) and unless I am misreading (entirely possible :P) it seems you gave the opposite answer that the complex form forces a string and the simpler form returns a result-tree. Could you confirm which one it is? :) NOTE: I am no XSL expert :) I am having to update / maintain some XSL 1.0 files after the switch from Xalan XSLJ to the JDK embedded Xalan XSLC (same version) started failing on unchanged XSL files. :/ In that question, the user wanted to select nodes, and the "complex form" flattened those nodes to strings by using xsl:value-of. However, if you're touching legacy XSLT 1.0 code at all, then doesn't it make sense to move forward to XSLT 2.0+ while you're about it? Also, please note, asking questions using comments on an old answer to a different question really doesn't work well in SO: better to raise a new question.
common-pile/stackexchange_filtered
Azure Devops deploy docker image to ACR using deployment job I'm trying to deploy a docker image to Azure Container Registry via an Azure Devops pipeline. Now this works fine when I run it with this script: trigger: - master variables: # Container registry service connection established during pipeline creation dockerRegistryServiceConnection: 'some_id' imageRepository: 'worker' containerRegistry: 'microcontainerapptest.azurecr.io' dockerfilePath: '$(Build.SourcesDirectory)/Dockerfile' tag: '$(Build.BuildId)' # Agent VM image name vmImageName: 'ubuntu-latest' stages: - stage: Build displayName: Build and push stage jobs: - job: Build displayName: Build pool: vmImage: $(vmImageName) steps: - task: Docker@2 displayName: Build and push an image to container registry inputs: command: buildAndPush repository: $(imageRepository) dockerfile: $(dockerfilePath) containerRegistry: $(dockerRegistryServiceConnection) tags: | $(tag) However, I want to actually use a deployment job so I can run the pipeline in different environments. Therefore I updated the .yml like this: trigger: - master variables: # Container registry service connection established during pipeline creation dockerRegistryServiceConnection: 'some_id' imageRepository: 'worker' containerRegistry: 'microcontainerapptest.azurecr.io' dockerfilePath: '$(Build.SourcesDirectory)/Dockerfile' tag: '$(Build.BuildId)' # Agent VM image name vmImageName: 'ubuntu-latest' stages: - stage: Build displayName: Build and push stage jobs: - deployment: displayName: Build docker image environment: $(DEPLOY_ENVIRONMENT) strategy: runOnce: deploy: steps: - task: Docker@2 displayName: Build and push an image to container registry inputs: command: buildAndPush repository: $(imageRepository) dockerfile: $(Build.SourcesDirectory)/Dockerfile containerRegistry: $(dockerRegistryServiceConnection) tags: | $(tag) Making a deployment job out of this. Now when I run the pipeline like this I get an error Unhandled: No Dockerfile matching /home/vsts/work/1/s/Dockerfile was found. So it seems like the dockerfilePath is not valid anymore when I run it as a deployment job. I have searched but don't have a clue as to why this would be the case, does anybody know the answer to this? You need to explicitly check out your source code, because: A deployment job doesn't automatically clone the source repo. You can checkout the source repo within your job with checkout: self. Deployment jobs only support one checkout step. strategy: runOnce: deploy: steps: - checkout: self - task: Docker@2 displayName: Build and push an image to container registry inputs: command: buildAndPush repository: $(imageRepository) dockerfile: $(Build.SourcesDirectory)/Dockerfile containerRegistry: $(dockerRegistryServiceConnection) tags: | $(tag)
common-pile/stackexchange_filtered
Search and replace strings that are not substrings of other strings I have a list of replacements like so: search_and -> replace big_boy -> bb little_boy -> lb good_dog -> gd ... I need to make replacements for the above, but at the same time avoid matching strings that are longer like these: big_boys good_little_boy I tried this: sed -i -r "s/$(\W){search}(\W)/$\1{replacement}\2/g" But the above does not work when the string ("good_dog" in this case) occurs at the end of a line like so: Mary had a 'little_boy', good_little_boy, $big_boy, big_boys and good_dog Mary had a 'lb', good_little_boy, $bb, big_boys and good_dog And I doubt the above would work when the string occurs at the start of the line too. Is there a good way to do the search and replacement? If you're using GNU sed (which bare -i suggests you are), there is a "word boundary" escape \b: sed -i "s/\b$SEARCH\b/$REPLACE/g" \b matches exactly on a word boundary: the character to one side is a "word" character, and the character to the other is not. It is a zero-width match, so you don't need to use capturing subgroups to keep the value with \1 and \2. There is also \B, which is exactly the opposite. If you're not using GNU sed, you can use alternation with the start and end of line in your capturing subpatterns: (\W|^). That will match either a non-word character or the start of a line, and (\W|$) will match either a non-word character or the end of a line. In that case you still use \1 and \2 as you were. Some non-GNU seds do support \b anyway, at least in an extended mode, so it's worth giving that a try regardless. That's awesome! Thanks for the quick response :) @Michael Homer: What sed version support \b except GNU sed? I was thinking mostly of Busybox's sed, I think, but of course that's GNU-based anyway. If you want more portable, you can use \< and \>: sed -i "s/\<$SEARCH\>/$REPLACE/g" file \< and \> work in gsed, ssed, sed15, sed16, sedmod. \b and \B work in gsed only. In Mac OSX, you must use this syntax: sed -i '' -e "/[[:<:]]$SEARCH[[:>:]]/$REPLACE/g" file You could also use perl, which should support \b on all platforms. Assuming your list of replacements is in the format you show (separated by ->), you could do: perl -F"->" -ane 'chomp;$rep{$F[0]}=${$F[1]}; END{open(A,"file"); while(<A>){ s/\b$_\b/$rep{$_}/g for keys(%rep); print } }' replacements Explanation The -a makes perl run like awk, automatically splitting fields into the array @F so $F[0] is the 1st field, $F[1] the second etc. The -F sets the input field separator, just like -F in awk. The -n means "read the input file, line by line and apply the script given by -e to each line". chomp : removes newlines (\n) from the end of the line. $rep{$F[0]}=${$F[1]}; : this populates the hash %rep making the pattern to be replaced (the first field, $F[0]) the key and the replacement ($F[1]) the value. *END{} : this is executed after the input file (replacements) has been read. open(A,"file") : open the file file for reading with filehandle A. while (<A>) : read the file line by line. s/// for keys(%rep) : this will iterate through all the keys of the %rep hash, saving each key as the special variable $_. The s/// is the substitution operator and is making the same substitution as explained in Michael's answer. You could also read through the file and use sed as shown in the other answers: $ sed 's/->/\t/' replacements | while IFS=$'\t' read from to; do sed -i "s/\b$from\b/$to/g" file; done
common-pile/stackexchange_filtered
Comparing register values in x64 Assembly I'm trying to figure out a puzzle based on the existing values in the assembly registries. I keep running into trouble at this line cmp %sil,0x12(%rdi) jne ... The 12th offset for %rdi and %sil do in fact contain the same values when I examine them in the debugger, but the program still jumps because the values are considered not equal. The only thing I can think of is that the previous comparisons were using cmpb instead of cmp and that %sil being the 1-byte version for %rsiis being compared against an 8-byte value. Can someone tell me if I'm thinking about this correctly? If so, the input for the solution is a string so how would I change the input to accommodate for this? 0x12 (hex) is not 12 (decimal). It's the 18th byte after (%rdi). This cmp is a cmpb, the byte operand-size is implied by the register operand so the disassembler omitted it. ohhhhhhhhhhhhh, I see. Thank you 0x12(%rdi) Is the hex representation for a decimal not the offset itself
common-pile/stackexchange_filtered
Calling javascript function within angular controller? I have a Angular controller showing a Google Map (via NgMap). On the map i can add markers by clicking on the map. When clicking, a marker is set at the position and a infoWindows is opened. The window contains a link to a javascript function. My problem is, that i can only get this to work, as long as my function (goto) is outside of my angular controller. But i need to reference some angular methods and properties within my goto function (like $scope etc.). What am i missing? My code: (function () { 'use strict'; myApp.controller('myController', function myController($scope, $http, $window, NgMap) { var vm = this; NgMap.getMap({ id: 'myMap' }).then(function (map) { var layer = new google.maps.FusionTablesLayer({ query: { select: 'geometry', from: 'myid' } map: map, suppressInfoWindows: true }); layer.addListener('click', function (e) { var marker = new google.maps.Marker({ position: e.latLng, map: map }); map.panTo(e.latLng); windowControl(e, infoWindow, map, marker); }); }); function windowControl(e, infoWindow, map, marker) { geocoder.geocode({ 'latLng': e.latLng }, function (results, status) { var location; if (status == google.maps.GeocoderStatus.OK) { if (results[0]) { location = results[0].formatted_address; var windowcontent = location + "<br/><br/>"; windowcontent += "<button data-latlng='" + e.latLng + "' data-location='" + location + "' onclick='goto(this);'>GO</button>"; infoWindow.setOptions({ content: windowcontent }); infoWindow.open(map, marker); } else { location = "No results"; } } else { location = status; } }); } }); })(); function goto(thisObj) { var latLng = thisObj.getAttribute( "data-latlng" ); var location = thisObj.getAttribute( "data-location" ); console.log(latLng + ' - ' + location); } Can you make JS Fiddle for It This does not work: http://jsfiddle.net/asctujo8/1/. This does work: http://jsfiddle.net/asctujo8/2/ onclick="goto()" expects a global(!) function. If you define it within the controller it's not global. You can declare a global variable first and then assign a function expression to it: //Data var cities = [ ... ]; var goto; //<-- make goto global! //Angular App Module and Controller angular.module('mapsApp', []) .controller('MapCtrl', function ($scope) { ... goto = function() { //<- assign the function created within the controller alert('goto called'); } You can get $scope variables from within plain javascript and change their values as well. //get the $scope by adding a 'class' selector, that exists into your controller template. var myScope = angular.element($(".anyclass-Selector")).scope(); //change $scope value and call $apply to update the value to the controller myScope.$apply(function () { myScope.vm = 'test'; //assign $scope.vm new value }); Update you can change the route and add parameters , like : $state.go('floorplan', { 'activeEventId': result.data.newEvent, 'activeHallId': result.data.hall1, 'activeHallVariant': 0 }); or javascript way function ChangeUrl(page, url) { if (typeof (history.pushState) != "undefined") { var obj = {Page: page, Url: url}; history.pushState(obj, obj.Page, obj.Url); } else { window.location.href = "homePage"; // alert("Browser does not support HTML5."); } } ChangeUrl('Page1', 'homePage'); Hmm, yeah okay. What i actually want to do, in the function, is use ui-router, to route to a new route, set a couple of angular variables and some parameters in the state? Thank you for the update. But i am unsure as to why the code in my initial post, does not work? Would make it easier, if i could just call the required code directly from my javascript call within the Infowindow?
common-pile/stackexchange_filtered
Relating scaling and critical exponents in the Ising model I'm reading the chapter about the renormalization group in Yeoman's book "Statistical mechanics of phase transitions" and I'm puzzled about how the author relates the scaling of the RG with the critical exponents. We have some RG map on the Hamiltonian $H\rightarrow R(H)$. We suppose that we are close to the fixed point $H^* $, so $$H'=R(H^*+\delta H)=H^* + A(H^*)\delta H$$ where $A$ is a matrix and $\delta H$ is seen as a vector with the coupling constants as components. This matrix can be diagonalized and we can write $$ A(H^*)\delta H= A(H^*)\sum_k\mu_k \Phi_k=\sum_k\lambda_k\mu_k \Phi_k\tag {$\star$}$$ where $\Phi_k$ are functions of the lattice and $\lambda_k$ are the eigenvalues of $A$. It's easy to argue that they must have the form $$ \lambda_k=b^{y_k}$$ where $b$ is the scaling factor of the map. No problem until here. If $y_k>0$ we call it relevant, otherwise irrelevant. Consider the 2D Ising model $$ H_I=-\beta J \sum_{\langle i,j\rangle}s_is_j-\beta h\sum_i s_i$$ We know that one of the two relevant direction is $t\sim \frac{T-T_c}{T_c}$ as temperature controls the phase transition and $t$ must vanish at $T_c$, and the other can be identified with the magnetic field $h$. The author then gives the scaling form of the free energy, which I agree with $$ f(t,h,g_3,g_4,\dots)=b^{-d}f(b^{y_T}t,b^{y_h}h, b^{y_3}g_3,\dots)$$ differentiating twice wrt $t$ $$ f_{tt}(t,0,0,0,\dots)=b^{2y_T-d}f_{tt}(b^{y_T}t,0, 0,\dots)$$ from this the author wants to extract the critical exponents for the specific heat capacity, she writes (page 116) this can be done because the scaling factor $b$ is arbitrary. Choosing $b^{y_1}|t|=1$ transfers all the temperature dependence to the prefactor and leaves it multiplied by a function of constant argument $$f_{tt}(t,0,0,0,\dots)=|t|^{(d-2y_T)/y_T}f_{tt}(\pm 1,0, 0,\dots) $$ and here I'm completely lost: what happened? The scaling factor is not arbitrary - it depends on my choice of renormalization map (for example, choice of block size). Much less it is dependent on $|t|$! In fact the whole $b^{y_T}$ cannot depend on $|t|$, because it is an eigenvalue of a matrix that's independent of the Ising model or its temperature. How can I make sense of all this? The argument is easier to follow from the continuous RG point of view (a la Wilson), though it can be adapted in the block spin picture. I'll take the former point of view here. The RG procedure gives rise to a flow of the Hamiltonian, $H_s$, with $H_{s_0}$ the initial Hamiltonian, and $\partial_s H_s = R(H_s)$ (to connect with the OP notations $b=e^{s}$). Assume that $H_{s_0}$ is fine-tuned such that the flow brings $H_s$ very close to the fixed point Hamiltonian $H^*$, and call $s^*$ a RG time at which the distance between $H_s$ and $H^*$ is small enough so that we can linearize the flow. We find that for $s$ not too far from $s^*$, $$ H_s=H^*+\sum_k \mu_k(s) \Phi_k, $$ with $\mu_k(s)=e^{(s-s^*)y_k}\mu_k(s^*)$. Assume that there is only one relevant direction, parametrized by the term $k=1$. Physically, we know that if the system was at $T=T_c$, the flow would go to the fixed point, and therefore, $\mu_1(s^*)$ must vanish with $t=(T-T_c)/T_c$. Assume that it does so linearly, then $\mu_1(s)=a e^{(s-s^*)y_k} t$, with $a$ a constant. In principle, $\mu_{k>1}(s^*)$ will also depend on $t$ (i.e. on the initial condition of the flow), but they do not have to vanish to get to the fixed point, so we can forget about this dependence. Now, for the linearization to be valid, we need to stay close to the fixed point, this means that we need both $|t|\lesssim 1$ (to be close to the fixed point at $s^*$) and $e^{(s-s^*)y_1} t\lesssim1$, assuming that $a$ is of order one, so that the flow is still close to the fixed point. The free energy scales as $$ f(t) = e^{-s d} f(\mu_k(s)), $$ where we only write its dependence on $t$ in the rhs of the equation. Assuming we can linearize the flow as discussed above, we have $$ f(t) = e^{-sd}f(e^{(s-s^*)y_1} t, \ldots). $$ Now using the fact that $s$ is arbitrary, and choosing $s=(s^*-\log(|t|))/y_1$ which is ok (as we are somewhat still in the regime of linearizability of the flow), we find $$ f(t) \propto |t|^{d/y_1}, $$ where the proportionality constant is $e^{-s^*d/y_1}f(\pm1,\ldots)$, which is finite for all $t$ (since $s^*$ is just a finite non-universal RG time, and $f(\pm1,\ldots)$ is finite and depends on $|t|^{y_k/y_1}\mu_k(s^*)$, $k>1$, which vanishes for $t$ small enough). (However, if one of the irrelevant coupling is dangerously so, one must be more careful.) The scaling relation must hold for arbitrary scaling factors $b$ and thus it must also hold for the specific choice $$b = |t|^{-\frac{1}{y_{T}}} .$$ Inserting this into the scaling relation you get the above form. I would say this is somewhat similar to parametrising a function of two arguments $f(x,y)$ via setting $y=y(x)$ and effectively getting a function $g(x)=f(x,y(x))$ depending only on $x$. Since the relation holds for all $b$, we can also choose it to be temperature dependent. I hope this helps.
common-pile/stackexchange_filtered
Timezone for my country doesn't give correct answer I am trying to echo date, simple code, but result is not correct for my country. Result is 04.10.2014 and it should be 03.10.2014 Here is my code PHP <?php date_default_timezone_set("Europe/Sarajevo"); $my_date = date("d.m.Y"); echo $my_date; ?> adjust time on server. may be it is wrong. It works fine for me. As @mithunsatheesh says, the problem seems to be that your server's time is wrong. I am using "localhost", could u explain me how to change server time? :) You should run NTP on your machine to keep its clock correct. What server/os are you using. Are you running xampp? Yeah, i am using xampp It works as expected at my side. Check your server time. Navigate to C:\xampp\php\php.ini or your path, open it. Find: date.timezone = "<something>" Change it to date.timezone = "Europe/Sarajevo" Restart your XAMPP Make sure your server's timezone is set correctly because PHP always uses the default sever time as a reference. Check if correct by: echo date_default_timezone_get . ' ' . date('Y-m-d H:i:s); You'll know if your server's time zone is messed up if the above code returns something unexpected. If it is messed up, you'll just have to adjust your timezone offset manually. If you need to change your timezone, just change this via system settings on Windows/Mac. If you're on Linux try these: Ubuntu: dpkg-reconfigure tzdata Redhat: redhat-config-date CentOS/Fedora: system-config-date FreeBSD/Slackware: tzselect Hope this helps! This is result i got "2014-10-04 04:32:23" it should be "2014-10-03 19:32:23 Yes, that means you need to change your system time. What's your operating system? My System is WIndows 7 Follow steps indicated here: http://windows.microsoft.com/en-ph/windows/set-clock#1TC=windows-7 Then adjust your timezone to your correct location.
common-pile/stackexchange_filtered
Node.js: OAuth2Strategy requires a clientID option I am setuping the MERN stack project, which was created by another developer and I am getting the error: node_modules/passport-oauth2/lib/strategy.js:82 [0] if (!options.clientID) { throw new TypeError('OAuth2Strategy requires a clientID option'); } [0] ^ [0] [0] TypeError: OAuth2Strategy requires a clientID option If I understand correctly, there should be clientID in .env file and there's no such file in the project, right? A couple of questions for you: 1) what is the passport strategy you are using? Is it perhaps passport-linkedin-oauth2 or else? 2) did you set the clientID inside the passport strategy, as for the clientID from the oauth2's provider? Share some code to reproduce the error I have the same error did you manage to solve it @Ahmed check my answer For me, I did something like this passport.use( new FacebookStrategy( { clientID: config.FACEBOOK_APP_ID, clientSecret: config.FACEBOOK_CONSUMER_SECRET, callbackURL: config.FACEBOOK_REDIRECT_URL, profileFields: ['id', 'displayName', 'email'] }, But I forgot to add my FACEBOOK_APP_ID in my config file. Just make sure that your clientId being passed is not null or undefined Be sure to npm install dotenv, and add require('dotenv').config(); to the top of your app.js file. While the answer from @ColsonRice wasn't exactly the reason I received the above error OAuth2Strategy requires a clientID option, it did point me in the right direction. In trying to get my Typescript version of my NodeJs express server working on Heroku I had changed (10 commits back), my package.json start script from "start": "node -r dotenv/config ./dist/index.js", to "start": "node dist/index.js", Change the development start up to use an alternative start command with the dotenv/config option back in resolved my issue. The last 4 lines of my scripts section of package.json are as follows: "dev": "nodemon --exec npm run restart", "restart": "rimraf dist && npm run build && npm run devstart", "devstart": "node -r dotenv/config ./dist/index.js", "start": "node dist/index.js", So for me, the negative score for Colson is unjustified as it indirectly helped me resolve my issue. Be sure to npm install dotenv, and add require('dotenv').config(); to the top of your app.js file. Your answer could be significantly improved if you added a few more details around your solution. Also you could explain what caused the error exactly - the poster does not seem to be very sure about it. The Problem is config.FACEBOOK_CLIENT_ID instead of config.FACEBOOK_APP_ID Error Strategy: passport.use( new FacebookStrategy( { clientID: config.FACEBOOK_CLIENT_ID, clientSecret: config.FACEBOOK_CONSUMER_SECRET, callbackURL: config.FACEBOOK_REDIRECT_URL, profileFields: ['id', 'displayName', 'email'] }, Correct Strategy: passport.use( new FacebookStrategy( { clientID: config.FACEBOOK_APP_ID, clientSecret: config.FACEBOOK_CONSUMER_SECRET, callbackURL: config.FACEBOOK_REDIRECT_URL, profileFields: ['id', 'displayName', 'email'] },
common-pile/stackexchange_filtered
How to train GPT2 with Huggingface trainer I am trying to fine tune GPT2, with Huggingface's trainer class. from datasets import load_dataset import torch from torch.utils.data import Dataset, DataLoader from transformers import GPT2TokenizerFast, GPT2LMHeadModel, Trainer, TrainingArguments class torchDataset(Dataset): def __init__(self, encodings): self.encodings = encodings self.len = len(encodings) def __getitem__(self, index): item = {torch.tensor(val[index]) for key, val in self.encodings.items()} return item def __len__(self): return self.len def print(self): print(self.encodings) # HYPER PARAMETERS EPOCHS = 5 BATCH_SIZE = 2 WARMUP_STEPS = 5000 LEARNING_RATE = 1e-3 DECAY = 0 # Model ids and loading dataset model_id = 'gpt2' # small model # model_id = 'gpt2-medium' # medium model # model_id = 'gpt2-large' # large model dataset = load_dataset('wikitext', 'wikitext-2-v1') # first dataset # dataset = load_dataset('m-newhauser/senator-tweets') # second dataset # dataset = load_dataset('IsaacRodgz/Fake-news-latam-omdena') # third dataset print('Loaded dataset') # Dividing dataset into predefined splits train_dataset = dataset['train']['text'] validation_dataset = dataset['validation']['text'] test_dataset = dataset['test']['text'] print('Divided dataset') # loading tokenizer tokenizer = GPT2TokenizerFast.from_pretrained(model_id, # bos_token='<|startoftext|>', eos_token='<|endoftext|>', pad_token='<|pad|>' ) print('tokenizer max length:', tokenizer.model_max_length) train_encoding = tokenizer(train_dataset, padding=True, truncation=True, max_length=1024, return_tensors='pt') eval_encoding = tokenizer(validation_dataset, padding=True, truncation=True, max_length=1024, return_tensors='pt') test_encoding = tokenizer(test_dataset, padding=True, truncation=True, max_length=1024, return_tensors='pt') print('Converted to torch dataset') torch_dataset_train = torchDataset(train_encoding) torch_dataset_eval = torchDataset(eval_encoding) torch_dataset_test = torchDataset(test_encoding) # Setup training hyperparameters training_args = TrainingArguments( output_dir='/model_dump/', num_train_epochs=EPOCHS, warmup_steps=WARMUP_STEPS, learning_rate=LEARNING_RATE, weight_decay=DECAY ) model = GPT2LMHeadModel.from_pretrained(model_id) model.resize_token_embeddings(len(tokenizer)) trainer = Trainer( model=model, args=training_args, train_dataset=train_encoding, eval_dataset=eval_encoding ) trainer.train() # model.save_pretrained('/model_dump/') But with this code I get this error The batch received was empty, your model won't be able to train on it. Double-check that your training dataset contains keys expected by the model: input_ids,past_key_values,attention_mask,token_type_ids,position_ids,head_mask,inputs_embeds,encoder_hidden_states,encoder_attention_mask,labels,use_cache,output_attentions,output_hidden_states,return_dict,labels,label,label_ids. When I use the variables torch_dataset_train and torch_dataset_eval in Trainer's arguments, the error I get is: TypeError: vars() argument must have __dict__ attribute This typeError is the same I get if as dataset I use the WikiText2 from torchtext. How can I fix this issue? How did you solve this problem ? I didn't solve this problem actally, but I found out that Trainer implements a pytorch train loop so I used this tutorial that implemented a train loop in pytorch and this worked can you please post the updated code as the correct answer?
common-pile/stackexchange_filtered
How to get value inside <td> which is inside tr[2] by finding a text whose <th> is inside tr[1] using java I am new to selenium and I need to get the value £1000 which is inside td class='ng-ngclass' /td and i need to find that by finding text 'Wrapper1' from th class="ng-ngclass" colspan="3" - Wrapper1 - /th I should pass the text 'Wrapper1' in %s in the below constant I've tried the below one private static final String WRAPPER_VALUE = "//th[@class='ng-ngclass'and contains(text(), %s)] and //td[@class='ng-ngclass']" in FirePath but it is returning me 1 number: NaN in firefox console.. What does that really mean? Please help me. Any help will be appreciated. <div id="summaryEncash" class="body scroll-body" ng-class=" {clsOnlyAdPlan: hasOverview === false}"> <!-- ngRepeat: asset in assetTypes --> <table class="data-stripe ng-scope" ng-repeat="asset in assetTypes" analytics="homePortfolioTap" ng-click="showAssetDetail(0)" cellspacing="0" cellpadding="0"> <tbody> <tr ng-show="isCurrentValue"> <th class="ng-ngclass" colspan="3">Wrapper1</th> </tr> <tr class="summary-value" ng-show="isCurrentValue"> <td class="ng-ngclass">£1000</td> <td/> <td class="arrow"> <i class="next next-arrow"/> </td> </tr> I could be wrong, but this appears to be JavaScript and not Java. Using the correct tags improves your chances of getting good help. The Xpath expression //td[@class='ng-ngclass'] returns the td element with its text node. The Xpath expression //td[@class='ng-ngclass']/text() should return the text value of td element. So the string £1000. Then you have to parse it to get a number. Thanks :) i tried your suggested one in firepath now in the matching node console it is saying me 1 Number.. and the number is NaN @phico Is that returning me the number required.. i need not get the parsed number i just need £1000. Can anyone say the meaning of NaN? @phico Depending of the parser used, the expression //td[@class='ng-ngclass']/text() should return a string value or an object. So it is not a number (NaN means Not a Number). Print it to know the type returned and then parse it or get the string value out of it.
common-pile/stackexchange_filtered
ReactJs dynamic html, binding values to the child class I'm trying to create a plugin for an audio player where the user can specify their own optional html. The html that the user does specify should have certain properties that are defined in the player file. At the moment in the plugin, the render method looks like this (cut for brevity example): player.js: render(){ return ( <div id="player"> <a class="jp-play" style={this.state.playStyle} onClick={this.play}> <i class="fa fa-play"></i> </a> <div class="jp-current-time">{this.state.currentTime}</div> </div> ); Instead of hardcoding the JSX html in the plugin render (player.js) method I want to do something like this: render(){ return ( {this.props.playerHtml} ); where the parent calls this like so: app.js: render( <Player playerHtml={getHtml()} /> , document.getElementById("app")); function getHtml(){ <div id="player"> <a class="jp-play" style={this.state.playStyle} onClick={this.play}> <i class="fa fa-play"></i> </a> <div class="jp-current-time">{this.state.currentTime}</div> </div> } So the user can specify their own html for the plugin. This way instad of passing a fa-play icon within jp-play they can pass whatever they want. The problem is that the onClick event handler and states passed through will no longer work properly as this.state.playStyle and this.state.currentTime will point to app.js file and not player.js. My question is, how do I allow the user to supply their own html like this but bind the values of the html the user passes and the events to values and functions in my player.js? I could do this easily by modifying the dom but I don't think this is the react way. You can pass the function to generate the player elements in a prop. The important thing is that it has to be binded to the Player component instance before being called. Here there is a working version of your code. Take into account that you are returning a JSX element inside getHtml, not pure HTML, so be sure to change class for className and so on. Important: I hope you understand the security implications of what you are trying to do. class Player extends React.Component { constructor(props) { super(); this.state = { playStyle: { background: 'red' }, currentTime: new Date() } } render() { return ( <div> Player: { this.props.playerHtml.bind(this)() } </div> ); } }; function getHtml() { return ( <div id="player"> <a className="jp-play" style={this.state.playStyle} onClick={this.play}> <i className="fa fa-play">Play</i> </a> <div className="jp-current-time">{this.state.currentTime.toString()}</div> </div> ); } ReactDOM.render( <Player playerHtml={getHtml} /> , document.getElementById("app") ); <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="app"></div> Perfect, thanks, the key here was not calling getHtml() right away. It's not the actual end user that's specifying the html btw. It's any developer that's using this player plugin, so there won't be any security issues such as XSS. I probably explained that poorly.
common-pile/stackexchange_filtered
How can I manage browser cache in PHP? My idea is simple, take all css files and generate one minified in a time of change in some css file. Then tell the browser to clear the cache. If there is an unchanged file in browser cache then use it - so user don't need to redownload it every time. I'm using the following snip of code to do that. But the part with using cache is a bit buggy, most of time it works but sometimes it tell the browser to use the cached version (as there is no change) and browser is using the old one and user must do client side cache refresh. Could you give me some advice how to do that, so it would refresh client side browser cache everytime when the change occurs and if there is no change just use the cache? $cssFiles = getCssFiles(); $fm = new FileMinifier(FileMinifier::TYPE_CSS); $lastModified = $fm->lastModification($cssFiles); $savedLastModified = DateUtils::convertToTimestamp($this->system->systemSettings['cssLastChange']); $etagFile = md5('css-file'); header("Content-type: text/css"); header("Pragma: public"); header('Cache-Control: public'); header("Last-Modified: " . gmdate("D, d M Y H:i:s", $lastModified) . " GMT"); header("Etag: $etagFile"); // if there is a change - generate new minified css if ($lastModified > $savedLastModified) { // take files minify them, save it and redirect to output, update last change time ... } // or use already generated else { $ifModifiedSince = (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? $_SERVER['HTTP_IF_MODIFIED_SINCE'] : 0); $etagHeader = (isset($_SERVER['HTTP_IF_NONE_MATCH']) ? trim($_SERVER['HTTP_IF_NONE_MATCH']) : false); // if it is in chache use it! - no need for redownloading if (strtotime($ifModifiedSince) == $lastModified || $etagHeader == $etagFile) { header("HTTP/1.1 304 Not Modified"); exit; } $this->data['text'] = file_get_contents(SystemInfo::getServerRoot() . '/public/css/minified.css'); } 99% of the time the browser does a fine job all by itself, what are you trying to solve here? I've another experience, if I wanted to update some css file a lot of people didn't see the chagnes. So I started doing something like ...css?v=2 Which forces browser to recache it, but I wanted to automatize that process so I've tried the solution above. You can use header perhaps. With need to re-validate or no-cache. The problem is I think in the HTTP_IF_MODIFIED_SINCE header which is probably giving a bad informations, because it says that there is no change so the header Not modified is sent and therefore browser will use cache. I need some condition in there because other ways browser will redownload it everytime. I don't have much experience in caching and I've tried many solutions and this one I think is the best. But maybe I'm doing it wrong so I hope somebody will give me some advices or links to study. What you're trying to do is admirable, but it's a bit of re-inventing the wheel. As far as CSS files, JavaScript files, etc are concerned, modern browsers already do a fine job of pulling unchanged files from the cache. Manipulating the HTTP headers to notify the browser of a file change is do-able, but there are browser differences (especially older browsers) in how the headers are interpreted which makes that approach fraught with nuance. It is far easier to accomplish your goal by versioning your CSS includes. A change in file version will prompt the browser to re-download the file. Example: Before file change: <link href="http://yourwebsite.com/file.css?_=<IP_ADDRESS>" rel="stylesheet" type="text/css"> After file change: <link href="http://yourwebsite.com/file.css?_=<IP_ADDRESS>" rel="stylesheet" type="text/css"> All browsers will interpret the change in URI parameter as a new file and will re-download it. It's also possible to automate the versioning so that you don't need to manually edit the include line after every change. Here's one way to do it... Example: <?php $ver = filemtime($filename); echo '<link href="http://yourwebsite.com/file.css?_='.$ver.'" rel="stylesheet" type="text/css">'; ?> That code will place append modified date of the file (Unix timestamp format) to the URI of the file include. Okay, I'll change the mechanism, so the script will just generate the minified file but it will not redirect it to output. I'll use ` It will be much easier than telling browser what to do. I was using versioning before but I didn't get this idea. Thanks for inspiration! Upvoted specifically for the automated versioning via timestamp. Great technique!
common-pile/stackexchange_filtered
Transfer data between forms in borland c++ builder I designed two forms in c++ builder: TfrmMain TfrmChooseName In TfrmMain class I have button named btnNext. when btnNext is clicked, code below runs and creates new TfrmChooseName. frmChooseName = new TfrmChooseName(this); this->Hide(); frmChooseName->ShowModal(); this->Show(); delete frmChooseName; frmChooseName = NULL; also in TfrmMain I have TEdit control named txtInput. In costructor of TfrmChooseName I want to get text of txtInput and set it as a caption of form but access volation error occured! I also made both classes friend! Please show your code for the TfrmChooseName constructor. The best way to handle this is to pass the desired Caption value to the constructor itself, rather than code it to hunt for the value, eg: __fastcall TfrmChooseName(TComponent *Owner, const String &ACaption) : TForm(Owner) { Caption = ACaption; } . frmChooseName = new TfrmChooseName(this, txtInput->Text); Alternatively, you can set the Caption after the constructor exits, eg: frmChooseName = new TfrmChooseName(this); frmChooseName->Caption = txtInput->Text; Thanks!You right. After creating new object from TfrmChooseName class I did what you say and problem solved! Thanks very much! I think it's not possible to detect the exact problem without seeing more of the code. Making the classes friends shouldn't be necessary, since components added using the form designer have public access anyway. Have you removed TfrmChooseName from Auto-Create forms? If not, and if frmChooseName is the global variable pointing to the auto-created form, that might cause the Access Violation. The RADStudio Documentation article Creating Forms Dynamically says: Note: If you create a form using its constructor, be sure to check that the form is not in the Auto-create forms list on the Project > Options > Forms page. Specifically, if you create the new form without deleting the form of the same name from the list, Delphi creates the form at startup and this event-handler creates a new instance of the form, overwriting the reference to the auto-created instance. The auto-created instance still exists, but the application can no longer access it. After the event-handler terminates, the global variable no longer points to a valid form. Any attempt to use the global variable will likely crash the application. You may also want to take a look at Creating a Form Instance Using a Local Variable.
common-pile/stackexchange_filtered
ambari-agent can not reach ambari-server When I finished install ambari-server with httpd local repository and Comfire Hosts on webUI, I got some error as follow: INFO 2018-05-27 15:39:16,776 NetUtil.py:70 - Connecting to https://master:8440/ca ERROR 2018-05-27 15:39:16,787 NetUtil.py:96 - [Errno 8] _ssl.c:493: EOF occurred in violation of protocol ERROR 2018-05-27 15:39:16,788 NetUtil.py:97 - SSLError: Failed to connect.Please check openssl library versions. Refer to: https://bugzilla.redhat.com/show_bug.cgi?id=1022468 for more details. WARNING 2018-05-27 15:39:16,789 NetUtil.py:124 - Server at https://master:8440 is not reachable, sleeping for 10 seconds... INFO 2018-05-27 15:39:26,793 NetUtil.py:70 - Connecting to https://master:8440/ca ERROR 2018-05-27 15:39:26,799 NetUtil.py:96 - [Errno 8] _ssl.c:493: EOF occurred in violation of protocol ERROR 2018-05-27 15:39:26,799 NetUtil.py:97 - SSLError: Failed to connect. Please check openssl library versions.Refer to: https://bugzilla.redhat.com/show_bug.cgi?id=1022468 for more details. WARNING 2018-05-27 15:39:26,801 NetUtil.py:124 - Server at https://master:8440 is not reachable, sleeping for 10 seconds... My environment message as follow: CentOS Linux release 7.5.1804 (Core) Python2.7.5 Java1.8.0_171 OpenSSL1.0.2k Ambari<IP_ADDRESS> HDP-<IP_ADDRESS> On my other amabri-agent nodes, I can reach master on 8440 port as follow: [root@slave2 ~]# telnet master 8440 Trying <IP_ADDRESS>... Connected to master. Escape character is '^]'. Please give me some help, thanks a lot! Did you manage to resolve this? I am having the same issue and the answer below did not help. I am also getting the same issue. This worked for me. In /etc/ambari-agent/conf/ambari-agent.ini Add this line below [security] force_https_protocol=PROTOCOL_TLSv1_2 In /etc/python/cert-verification.cfg [https] verify=disable (change from default to disable) Please check JAVA_HOME and openSSL version in your setup
common-pile/stackexchange_filtered
Reading the contents of a file whose name is stored in a variable The following code first creates a list of all the files in a folder called films, then attempts to access the contents of a specific file. I know how to do this if the file's name is a literal, but can someone please explain how this can be done if the name of the file or the directory is a variable? path = 'films' from os import walk f = [] for (filenames) in walk(path): f.extend(filenames) break listoffiles = f[2] print("listoffiles: ",listoffiles) read = open('films/{listoffiles[0]}',"r") print("read: ",str(read.read())) just change it to be read = open(f'films/{listoffiles[0]}',"r") If the "file name is a variable" it is representing the string. So you can do the following: with open(filenames) as open_file: print(open_file.readlines()) (Or in your case extend) path = 'films' from os import walk f = [] for (filenames) in walk(path): f.extend(filenames) break listoffiles = f[2] print("listoffiles: ",listoffiles) read = open('sentences/'+listoffiles[0],"r") print("read: ",str(read.read())) Not sure of your logic, but you can compose a string using the + operator.
common-pile/stackexchange_filtered
how to pivot a table in excel? I have my data in excel in the following presentation: As you may see, in the first column I have the date and in the second column I have some values. However, I would like to have my data like this: I would like to have my data grouped by month and year and shown in the image below. I've tried to use the pivot function but it seems not to be working. I would really appreciate your help and thanks in advance. before you can use a pivot table you need to add a few extra columns to your source data. year and month, like this: date | close | year | month 01/01/2020 34,32 =TEXT(A2,"yyyy") =TEXT(B2,"mmm") then mark all the data in all 4 columns and go to insert -> pivottable. in the pivottable field list add month to rows, year to columns and close to values It seems not to be working. It works for month and year, but when I try to set close to values, in the table it appears a bunch of 1's. make sure that close is not a text type in your original data, but a number. and make sure that the pivot table is set to summarize values by sum (right click menu on the piviot table) it sound like it is set to count
common-pile/stackexchange_filtered
Get MAC addresses for all clients in AD I would like to extract from an Active Directory the MAC Address of every hostname/client. Actually use this command but what's necessary to add to see the MAC Address? Get-ADComputer -Filter * -Properties OperatingSystem,IPv4Address,MACAddress | select Name, IPv4Address, OperatingSystem And from DHCP: Get-DhcpServerv4Scope | Get-DhcpServerv4Lease | Where { $_.AddressState -eq 'Active' } | select IPAddress,HostName,AddressState,ClientId It's possible to merge both queries? Thanks in advance According to the MS Docs MacAddress isn't an available property from Get-ADComputer. You would need to use some other method of resolving the Mac Address as it doesn't appear to be available in ActiveDirectory AFAIK, macAddress attribute is not updated automatically. What's more, it seems to allow only a single address, which wouldn't even work for multihomed hosts. Try querying your DHCP server, or if there's an IPAM product, its config. thanks! I update my previous message. merge them how? Combining cmdlet results is a very common thing. What did you search for? combining PowerShell cmdlet results
common-pile/stackexchange_filtered
Degrees of Freedom as Defined by Discipline I've just begun a machine learning course and I've been confused over my professors use of the degrees of freedom terminology. I've picked up that while in statistics talking about degrees of freedom typically assumes you are referencing the degrees of freedom of the error term (observations not taken up by your estimated parameters), machine learning uses degrees of freedom in almost the opposite sense (DoF being the number of parameters you have). It bothers me a bit, because although I see post after post claiming machine learning is NOT statistics (in fact when asked about this, my professor's default response was "I am not a statistician"), I still fail to see how machine learning could exist without statistics, and so it surprises me that one would completely disregard the terminology (as far as almost choosing an opposite definition), of an more established discipline. Can anyone provide some insight into this lexicographic quirk? Thanks! Doesn't it just depend on one's perspective? That is, DoF typically is the dimension of a space and when there are several spaces around (such as the space of data and parameter space in a statistical problem) one has to choose the space that's relevant for a particular concept. In fact, one can discern two distinct DoF concepts in many statistical problems: it is a bit of an accident that their values often coincide. See https://stats.stackexchange.com/a/17148/919. @whuber Thanks for the response and the link is very helpful. Perhaps my understanding isn't nuanced enough, or is focusing too much on the usage of the word "freedom". Parameter estimation is its own dimension of space, but I do not see those estimators as being free to vary (rather determined by the data) . I admit, this is perhaps only a semantical problem, not a statistical one.
common-pile/stackexchange_filtered
How to log the sdk ver of VungleAdsSDK(7.1.0) in obj-c ,i used the VungleAdsSDKVersionNumber & VungleAdsSDKVersionString[] but not getting crrct ver updated vunglesdk to vungleadssdk , but not able to log its sdk version in xcode obj-c i tried using these 2 methods specified in the header file . but not correct version coming up FOUNDATION_EXPORT double VungleAdsSDKVersionNumber; FOUNDATION_EXPORT const unsigned char VungleAdsSDKVersionString[];
common-pile/stackexchange_filtered
Where can I post a question about a problem with mobile phone? Where can I ask questions about a problem with Samsung J7 mobile phone? Android Enthusiasts is the right place for you, as Samsung J7 is an Android phone. I am an experienced user on Android Enthusiasts, and before you post your question, please make sure It's not about developing or debugging an application. You should instead navigate to Stack Overflow. You're not asking for software/application recommendation. We are there to solve problems or provide help and hints there. If you're very sure that you want an app as a solution, please navigate to Software Recommendations. You're not asking for shopping recommendation, or looking for marketing data or statistics. We want to help problems with your phone, not your business. And please notice that: We can provide different solutions or partial help to extreme or weird cases, like controlling Android phone with broken screen. However, we can't fix your broken screen or repair a faulty camera. The aftersale stations and repair shops in your local area may be able to provide better help in these cases. Stack Exchange is not a series of sites for seeking urgent or timely helps. Android Enthusiasts may not provide any answers/tips/hints in a few hours. If your problem is too rare, you can get a small Tumbleweed badge :) We already have a bunch of nice questions on various issues (with good answers!). You can search for existing posts about your problem. If none of them solves your problems, feel free to ask a new one. Samsung J7 is an Android mobile. If your problem is related to software, ask it on Android Enthusiasts. If that is a hardware problem (like screen crashed/ USB port damaged), there is no site for you to ask. Since you said that you have a problem with Samsung J7, I hope it is not related to programming or any third party applications. Read their How to Ask section before asking it on Android Enthusiasts. I have the links directing to What's-on-topic? in my answer. The How-to-Ask page is almost the same across all SE sites.
common-pile/stackexchange_filtered
How to get into Dart Docker container's shell? I'm trying to access the my Dart Docker container's shell $ docker-compose exec dartserver sh but I'm getting this error message: OCI runtime exec failed: exec failed: container_linux.go:380: starting container process caused: exec: "sh": executable file not found in $PATH: unknown Any idea? Dockerfile FROM dart:stable AS build # Resolve app dependencies. WORKDIR /app COPY pubspec.* ./ RUN dart pub get # Copy app source code (except anything in .dockerignore) and AOT compile app. COPY . . RUN dart compile exe bin/server.dart -o bin/server # Build minimal serving image from AOT-compiled `/server` # and the pre-built AOT-runtime in the `/runtime/` directory of the base image. FROM scratch COPY --from=build /runtime/ / COPY --from=build /app/bin/server /app/bin/ # Start server. EXPOSE 8080 CMD ["/app/bin/server"] The scratch image default don't have shell in it. If you really want to access shell, what I suggest is to use busybox image. See busybox dockerfile: FROM scratch ADD busybox.tar.xz / CMD ["sh"] It's also based on scratch, but with shell enable, additionally it's still very small. Where do you get the busybox.tar.xz from? I'm getting file does not exist with the ADD command. I found this: https://github.com/docker-library/busybox/tree/ecf0f5ecd9697ac16b9662679511bd5e011d34b4/unstable/uclibc
common-pile/stackexchange_filtered
if a balloon full of warm air was placed in a refrigerator, what is the result? If a balloon full of warm air was placed in a refrigerator, What will happen to the Ballon ? What do expect from Charles law? How is volume related to temperature? LOL -- Not being exposed to the UV rays of the sun means that the ballon will degrade much more slowly in the dark. The balloon will shrink and get smaller as the gas inside it gets cooler, the pressure inside the balloon falls. You might also have seen that a bottle partially filled with warm water kept in a refrigerator squeezes a bit because of the air pressure inside the bottle falls. This result directly follows from the gas laws.
common-pile/stackexchange_filtered
how to prevent reopening new window using jQuery? I've recently posted a new question in How jQuery can prevent reopening a new window?. At that post, I mentioned to my need for something on F2 key. Now I want to ask another question similar to the question above; This time for clicking on a link. I have a link that opens a new window using window.open. I want to prevent user to reopening new window when he clicks on the list if the previous window is still opened. What is your suggestion? You could do: var childWin; function winOpen(url) { //check if child window is already open if (childWin &! childWin.closed && childWin.focus){ childWin.focus(); } else { childWin = window.open(url,'','width=800,height=600'); } } Did you mean something like this No new window is coming. Even if we click the link for first time, it is opening in the same window. You can try this, it will help you to open and observe multiple windows, check here Javascript var windows = {}; $('a').click(function(e){ var url = $(this).attr('href'); var name = $(this).attr('id'); if(windows.hasOwnProperty(name) && !windows[name].closed ) { windows[name].focus(); } else { windows[name]=window.open (url,name,"status=1,width=300,height=300"); } }); Your Links <a href="http://google.com" id="google">Google</a> <a href="http://yahoo.com" id="yahoo">Yahoo</a>​ DEMO.
common-pile/stackexchange_filtered
GTK applications looking bad I'm running ArchLinux and gnome shell 3.16.1. GTK+ theme: Evopop-gtk-theme Icons: Adwaita Global dark theme. Running applications like nautilus, gnome-tweak-tool, dconf, system-monitor, gnome-terminal I get the style I have configured. The problem is when I run other applications like Filezilla, Thunderbird, Caja, Terminator, Eclipse, Wireshark ... Then I get an old style looking and I don't know what is happening. If I run other window manager like awesome-wm or i3 I get a default adwaita style in all applications. Let me show you an example: And here is some basic config: /home/n/.config/gtk-3.0 settings.ini [Settings] gtk-application-prefer-dark-theme=1 gtk.css .header-bar.default-decoration { padding-top: 3px; padding-bottom: 3px; } .header-bar.default-decoration .button.titlebutton { padding-top: 2px; padding-bottom: 2px; } /home/n/.config/gtk-2.0 empty As far as I know Adwaita GTK theme is for both GTK3 and GTK2, but the theme you installed (Evopop-gtk-theme) seems to work only for GTK3. So that's why GTK2 applications look ugly. The way to fix it is to install lxappearance (or any other GTK2 config tool, but this one is lightweight and has no dependencies) and set GTK2 theme to something similar to your current GTK3 theme. This helped me. Finally I decided to change the theme for GTK 2 and 3. I chose Libra instead of Evopop.
common-pile/stackexchange_filtered