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 |
End of preview. Expand
in Data Studio
README.md exists but content is empty.
- Downloads last month
- 21