qid
int64
1
74.7M
question
stringlengths
0
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
2
48.3k
response_k
stringlengths
2
40.5k
58,876,225
How to integrate screen time/ Parental control API in iOS app. Is screen time api available? I tried with MDM(Mobile device management) but I am unable to create the MDM CSR. As there is no option for this certificate on developer account. Please guide me if you have any solution. Basically I want to create an app having restrictions like screen time in iPhone or parental control app.
2019/11/15
[ "https://Stackoverflow.com/questions/58876225", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9858609/" ]
In my case the issue was solved by adding `DEBUG` as the **debug Active Compilation Condition**. I know it's already specified when you create a new project, but I don't remember if me or another team's member removed it (and why!). So I decided to put it here just in case someone else is facing the same scenario [![DEBUG specification in Active Compilation Conditions](https://i.stack.imgur.com/UigeJ.png)](https://i.stack.imgur.com/UigeJ.png)
`DEBUG` is the only default swift flag on a new project. You can create your own in your project build settings, `Other Swift Flags`. Otherwise: ``` #if DEBUG // This code will be run while installing from Xcode #else // This code will be run from AppStore, Adhoc ... #endif ```
57,742,783
I'm new to a large AWS deployment where stuff is mostly deployed through CloudFormation (and some through Terraform). But there are always cases where something has been deployed manually and not through code. Is there a reliable way to quickly figure out if a resource (say, an EC2 instance) already existing in the deployment was deployed through IaC or manually? A CloudFormation-specific answer will be good enough for now. Going through literally hundreds of CloudFormation stacks manually and looking for the resource is not an option.
2019/09/01
[ "https://Stackoverflow.com/questions/57742783", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6629280/" ]
You can identify the resources created by cloudformation. Cloudformation applies few default tags as mentioned here ``` aws:cloudformation:logical-id aws:cloudformation:stack-id aws:cloudformation:stack-name ``` You can run a script to check whether the resource contain one/all of these tags to update your count. [Offical documentation on resource tags](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html)
Unfortunately looking at an AWS resource you don't see how it got created. While some resources might have been tagged by CloudFormation indicating that they got created by a CloudFormation stack, that's only valid for a subset of resources. The only reliable way to figure out whether or not a resource got created via a CloudFormation stack is to go through all CloudFormation stacks and check whether or not the resource in question is a part of it. While that might be cumbersome when doing manually, it's also something you can automate using the AWS CLI.
52,767
I am currently studying for an exam in Quantum Mechanics and came across a solution to a problem I have trouble with understanding. The Problem: A Particle sits in an infinite potential well described by \begin{align} V(x) &= 0, & 0 \leq x \leq L \\ V(x) &= \infty, & \text{otherwise} \end{align} We know that the energies are given by $E\_n = \dfrac{n^2 \pi^2 \hbar^2}{2 m L^2}$ and $\Psi(x) = A\_n \sin(n \pi x /L)$. At time $t\_0$ the potential well is suddenly doubled in size, such that the potential is now \begin{align} V(x) &= 0, & 0 \leq x \leq 2L \\ V(x) &= \infty, & \text{otherwise} \end{align} So the energies are now given by $\tilde{E}\_n = \dfrac{n^2 \pi^2 \hbar^2}{2 \cdot 4 m L^2}$ and $\tilde{\Psi}(x) = \tilde{A}\_n \sin(n \pi x /2L)$. 1. If the particle is in the ground state of the potential well before the change, what is the probability to find the particle in the ground state of the new potential after the change? *This is absolutely clear to me. We find a non vanishing probability as a result. But now it gets tricky:* 1. What is the expectation value of the energy of the particle directly after the change? How does the expectation value of the energy evolve in time? *The solution suggests that the expectation value of the energy does not evolve in time, which is clear to me, since the Hamiltonian is time independent and thus energy is conserved. But it also suggests that the expectation value does not change after we double the width of the potential wall which I understand from the argument of energy conservation but not in terms of quantum mechanics. If the probability that the particle is in the state $\tilde{\Psi}$ does not vanish the particle could have the energy $\tilde{E}\_n$ which is lower than $E\_n$ and this would mean that the expectation value of energy could change (with a given probability).* What am I missing here, where is my mistake? Any help is appreciated!
2013/02/01
[ "https://physics.stackexchange.com/questions/52767", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/20486/" ]
The expectation value of the energy stays the same after the doubling of size but it doesn't mean that the spectrum is the same. For a normalized $\psi$, the expectation value of the energy is simply $$ \int\_{-L}^{+L}dx\,\psi^\* \left( -\frac{\hbar^2}{2m}\frac{\partial^2}{\partial x^2} + V(x) \right) \psi $$ because the integral may be reduced to the interval as the wave function vanishes outside the interval. Now, immediately when you double the size of the well, the value of $\psi(x)$ remains the same so it still vanishes outside the interval $(-L,L)$ and makes the integrand vanish as well (even though the second derivative could refuse to vanish). That's why the integral above may still be rewritten as $$ \int\_{-2L}^{+2L}dx\,\psi^\* \left( -\frac{\hbar^2}{2m}\frac{\partial^2}{\partial x^2} + V(x) \right) \psi $$ without any change. It's the expectation value of the new Hamiltonian. Note that $V(x)=0$ wherever $\psi(x)\neq 0$ so the potential term may be omitted. You're right that there is some probability that in the larger well, the particle sits at a lower-than-the-initial-energy-eigenvalue value of energy. However, there is some probability that the energy is raised as well – the wave packet is unnecessarily squeezed in a small part of the well which adds more kinetic energy than the minimum possible one. These positive and negative changes cancel in the expectation value of the energy: the calculation above showed that it stayed constant. The expectation value of the energy stays constant when the particle evolves according to the larger-well Hamiltonian, too. The probabilities for each energy eigenvalue are constant for all $t<0$ and then for $t>0$ but there is a discontinuity at $t=0$. However, as the simple calculation above shows, in the expectation value of the energy itself, the change of the spectrum etc. at $t=0$ cancels when it comes to the expectation value of the energy.
Under sudden perturbation the state does not change, but the basis does. This state gets expanded in the new basis whose coefficients evolve correspondingly. Normally it is covered in chapters with the time-dependent perturbation theory $\hat{V} = \hat{V}(t)$. If the potential is time-dependent, the energy is not conserved in general case. In your case the energy from certain becomes uncertain.
22,020,452
Suppose this situation, you have a function that return void and the method is mostly gonna be the only statement of a if ``` if(condition) someVoidMethod(); ``` Since certain language will not continue the evaluation of a boolean expression of concatenated and's if any of them return false. We are wondering what are the optimization implied by changing the return type to int (or bool/boolean) and writing this instead ``` condition && someIntMethod(); ``` without any assignation. We understand that programmers shouldn't focus in micro-optimization but it's really just for academic purpose.
2014/02/25
[ "https://Stackoverflow.com/questions/22020452", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
The compiler will generate the same code for both alternatives with any reasonable level of optimization. The logic behind both statements is exactly the same, because `&&` produces a branching behavior in both C and C++ for short-circuiting. I verified this using two programs: Program 1: ``` #include <stdio.h> int foo() {printf("foo\n");} int main() { int i; scanf("%d", &i); // Prevent from optimizing out the "if" if (i) foo(); return 0; } ``` Program 2: ``` #include <stdio.h> int foo() {printf("foo\n");} int main() { int i; scanf("%d", &i); // Prevent from optimizing out the "if" i && foo(); return 0; } ``` I compiled both programs on my mac with -O3 level \*, and compared the output: ``` gcc -c -O3 a.c gcc -c -O3 b.c cmp a.o b.o ``` `cmp` produced no output, so the files were identical. Compiling without -O3 flag produced different outputs. --- \* `gcc --version` command prints > > `Apple LLVM 5.0 (clang 500.2.79) (based on llvm 3.3svn)` > > >
It would take a smarter compiler to figure out that it can ignore the return value from `someIntMethod` (although I suspect most compilers would do so). But more seriously if the function isn't `inline` it would *have* to take extra cycles to pass the value back even if it's going to be discarded, so the first is possibly more efficient. That said the only way to know for sure is to compile both with your compiler and options consistent with a release build and see what assembly it generates.
36,862,683
I am getting an exception, but it isn't a code problem, it is a settings/dependencies problem. I have a work and home computer. The project files are synced via OneDrive. Both computers are running Mac OSX 10.11.4, jdk1.8.0\_66.jdk and IntelliJ IDEA 2016.1.1 The code works at my work but at home I get the exception: ``` Exception in thread "main" java.lang.NoClassDefFoundError: org/jvnet/staxex/XMLStreamReaderEx at com.sun.xml.stream.buffer.stax.StreamReaderBufferCreator.storeElementAndChildren(StreamReaderBufferCreator.java:195) at com.sun.xml.stream.buffer.stax.StreamReaderBufferCreator.storeDocumentAndChildren(StreamReaderBufferCreator.java:179) at com.sun.xml.stream.buffer.stax.StreamReaderBufferCreator.store(StreamReaderBufferCreator.java:160) at com.sun.xml.stream.buffer.stax.StreamReaderBufferCreator.create(StreamReaderBufferCreator.java:103) at com.sun.xml.stream.buffer.MutableXMLStreamBuffer.createFromXMLStreamReader(MutableXMLStreamBuffer.java:134) at com.sun.xml.stream.buffer.XMLStreamBuffer.createNewBufferFromXMLStreamReader(XMLStreamBuffer.java:419) at com.sun.xml.ws.api.addressing.WSEndpointReference.<init>(WSEndpointReference.java:183) at com.sun.xml.ws.api.addressing.WSEndpointReference.<init>(WSEndpointReference.java:175) at com.sun.xml.ws.api.addressing.AddressingVersion.<init>(AddressingVersion.java:443) at com.sun.xml.ws.api.addressing.AddressingVersion.<init>(AddressingVersion.java:72) at com.sun.xml.ws.api.addressing.AddressingVersion$1.<init>(AddressingVersion.java:74) at com.sun.xml.ws.api.addressing.AddressingVersion.<clinit>(AddressingVersion.java:74) at com.sun.xml.ws.security.addressing.policy.WsawAddressingPrefixMapper.<clinit>(WsawAddressingPrefixMapper.java:63) at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Class.java:348) ...... ``` I have stax2-api.jar and stax-api.jar in the library/provided of my project. I have VPN'd to work and looked at the project setup and can't see any differences. How can I work out what the difference is between the two machines to get the code to work at home?
2016/04/26
[ "https://Stackoverflow.com/questions/36862683", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1490306/" ]
There's no proper way to do it if you don't have indication, when row was added.
You can try to access the transaction log and get a list of all insert-transactions sorted by time stamp. Then find the time stamp of the last inserted row of the last month. These will lead you (hopefully) at the end to the last inserted row of last month (all rows with higher ID will be the data your are looking for). Step by step (maybe you need to make some adjustments to the queries depending on your situation): Get the transactions: ``` declare @TableName sysname set @TableName = 'Table_1' select [Current LSN], [Operation], [Transaction ID], [Parent Transaction ID], [Begin Time], [Transaction Name], [Transaction SID] from fn_dblog(null, null) where [Operation] = 'LOP_BEGIN_XACT' and [Transaction ID] in ( -- get transaction id's from your table (inserts) SELECT [Transaction ID] FROM fn_dblog(NULL, NULL) WHERE Operation = 'LOP_INSERT_ROWS' and AllocUnitName LIKE '%' + @TableName + '%' ) order by [Begin Time] ASC ``` Get the last transaction: ``` SELECT * FROM fn_dblog(NULL, NULL) WHERE Operation = 'LOP_INSERT_ROWS' and [Transaction ID] = 'XXX' -- your transaction id ``` In den Row Log Content Rows you find the value of your data of the last inserted row of the last month. Now you only need to convert the inserted data into "readable" data according to the following website: <http://www.sqlshack.com/reading-sql-server-transaction-log/> Now after converting the inserted data back into "readable" data, you should be able to find the relevant last row of last month inserted in your table. All rows with higher ID than that are inserted later and therefore the data you are looking for.
1,217,460
I have a multiline Bash variable: `$WORDS` containing one word on each line. I have another multiline Bash variable: `$LIST` also containing one word on each line. I want to purge `$LIST` from any word present into `$WORDS`. I currently do that with a `while read` and `grep` but this is not sexy. ``` WORDS=$(echo -e 'cat\ntree\nearth\nred') LIST=$(echo -e 'abcd\n1234\nred\nwater\npage\ncat') while read -r LINE; do LIST=$(echo "$LIST" | grep -v "$LINE") done <<< "$WORDS" echo "$LIST" ``` I think I can do it with `awk` but did not managed to make it work. Can someone explain me how to do it with awk?
2017/06/08
[ "https://superuser.com/questions/1217460", "https://superuser.com", "https://superuser.com/users/124122/" ]
This should accomplish what you're trying to do. ``` WORDS=$(echo -e 'cat\ntree\nearth\nred') LIST=$(echo -e 'abcd\n1234\nred\nwater\npage\ncat') echo "$LIST" | awk -v WORDS="$WORDS" ' BEGIN { split(WORDS,w1,"\n") for (w in w1) { w2[w1[w]] = 1 } } { if (w2[$0] != 1) { print $0 } }' ``` Here's how it works. First I'm using the `-v` option on the awk command line to pass the list of words as a variable. This variable will be visible inside the awk program with the name WORDS. The BEGIN block gets executed before any input is processed. It contains two lines ``` split(WORDS,w1,"\n") ``` This split command takes the WORDS list and turns it into an array called w1. ``` for (w in w1) { w2[w1[w]] = 1 } ``` This for loop walks through the w1 array and generates an associative array called w2. Converting the array to an associative array will improve performance. Next we have the main body of the loop that processes the LIST. ``` if (w2[$0] != 1) { print $0 } ``` This will check each line of input against our associative array and only print the line if the word was not found. Since we assigned each key to be 1 in our BEGIN block, we need only check to see if the value of that key equals 1 to know if it is defined.
I suggest ``` echo "$LIST" | grep -vf <(echo "$WORDS") ```
21,739,350
When I try to set an adapter to list like `list.setAdapter(adapter);` I get an exception because list is null at this line of execution in FromPageActivity.java. If my understanding is right, since I am using Roboguice, @ViewById should initialize that in R.java. **FromPageActivity.java** ``` @RoboGuice @EActivity(R.layout.from_page) public class FromPageActivity extends SherlockListActivity { @ViewById ListView list; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); String[] values = new String[] { "Android", "iPhone", "WindowsMobile", "Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X", "Linux", "OS/2", "Ubuntu", "Windows7", "Max OS X", "Linux", "OS/2", "Ubuntu", "Windows7", "Max OS X", "Linux", "OS/2", "Android", "iPhone", "WindowsMobile" }; final List<String> ls = (List<String>)Arrays.asList(values); final StableArrayAdapter adapter = new StableArrayAdapter(this, android.R.layout.simple_list_item_1, (List<String>) ls); list.setAdapter(adapter); } ``` **StableArrayAdapter:** ``` public class StableArrayAdapter extends ArrayAdapter<String> { HashMap<String, Integer> mIdMap = new HashMap<String, Integer>(); public StableArrayAdapter(Context context, int textViewResourceId, List<String> objects) { super(context, textViewResourceId, objects); for (int i = 0; i < objects.size(); ++i) { mIdMap.put(objects.get(i), i); } } @Override public long getItemId(int position) { String item = getItem(position); return mIdMap.get(item); } @Override public boolean hasStableIds() { return true; } } ``` **from\_page.xml:** ``` <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical"> <ListView android:id="@android:id/list" android:layout_width="match_parent" android:layout_height="wrap_content" android:clickable="true" android:text="@string/hello" /> </LinearLayout> ``` What am I missing out?
2014/02/12
[ "https://Stackoverflow.com/questions/21739350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1733310/" ]
You should set the id of your ListView with: ``` android:id="@+id/list" ``` The + symbol indicates that this is a new resource to be defined in your application's namespace, i.e. added to R.java. What you currently have: ``` android:id="@android:id/list" ``` ...refers to a pre-defined id within the Android framework.
There is a saying that, if you can't create file in R.Java, it means there is a problem with XML. If you look at your listview, you have "android:id="@android:id/list", this should have been ``` "@+id/your_idname". ``` Hopefully this should resolve the problem. Let me if its still not working!!
21,739,350
When I try to set an adapter to list like `list.setAdapter(adapter);` I get an exception because list is null at this line of execution in FromPageActivity.java. If my understanding is right, since I am using Roboguice, @ViewById should initialize that in R.java. **FromPageActivity.java** ``` @RoboGuice @EActivity(R.layout.from_page) public class FromPageActivity extends SherlockListActivity { @ViewById ListView list; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); String[] values = new String[] { "Android", "iPhone", "WindowsMobile", "Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X", "Linux", "OS/2", "Ubuntu", "Windows7", "Max OS X", "Linux", "OS/2", "Ubuntu", "Windows7", "Max OS X", "Linux", "OS/2", "Android", "iPhone", "WindowsMobile" }; final List<String> ls = (List<String>)Arrays.asList(values); final StableArrayAdapter adapter = new StableArrayAdapter(this, android.R.layout.simple_list_item_1, (List<String>) ls); list.setAdapter(adapter); } ``` **StableArrayAdapter:** ``` public class StableArrayAdapter extends ArrayAdapter<String> { HashMap<String, Integer> mIdMap = new HashMap<String, Integer>(); public StableArrayAdapter(Context context, int textViewResourceId, List<String> objects) { super(context, textViewResourceId, objects); for (int i = 0; i < objects.size(); ++i) { mIdMap.put(objects.get(i), i); } } @Override public long getItemId(int position) { String item = getItem(position); return mIdMap.get(item); } @Override public boolean hasStableIds() { return true; } } ``` **from\_page.xml:** ``` <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical"> <ListView android:id="@android:id/list" android:layout_width="match_parent" android:layout_height="wrap_content" android:clickable="true" android:text="@string/hello" /> </LinearLayout> ``` What am I missing out?
2014/02/12
[ "https://Stackoverflow.com/questions/21739350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1733310/" ]
You should set the id of your ListView with: ``` android:id="@+id/list" ``` The + symbol indicates that this is a new resource to be defined in your application's namespace, i.e. added to R.java. What you currently have: ``` android:id="@android:id/list" ``` ...refers to a pre-defined id within the Android framework.
@ViewById is not a RoboGuice annotation. Looks like you're mixing your libraries. You want @InjectView.
21,739,350
When I try to set an adapter to list like `list.setAdapter(adapter);` I get an exception because list is null at this line of execution in FromPageActivity.java. If my understanding is right, since I am using Roboguice, @ViewById should initialize that in R.java. **FromPageActivity.java** ``` @RoboGuice @EActivity(R.layout.from_page) public class FromPageActivity extends SherlockListActivity { @ViewById ListView list; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); String[] values = new String[] { "Android", "iPhone", "WindowsMobile", "Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X", "Linux", "OS/2", "Ubuntu", "Windows7", "Max OS X", "Linux", "OS/2", "Ubuntu", "Windows7", "Max OS X", "Linux", "OS/2", "Android", "iPhone", "WindowsMobile" }; final List<String> ls = (List<String>)Arrays.asList(values); final StableArrayAdapter adapter = new StableArrayAdapter(this, android.R.layout.simple_list_item_1, (List<String>) ls); list.setAdapter(adapter); } ``` **StableArrayAdapter:** ``` public class StableArrayAdapter extends ArrayAdapter<String> { HashMap<String, Integer> mIdMap = new HashMap<String, Integer>(); public StableArrayAdapter(Context context, int textViewResourceId, List<String> objects) { super(context, textViewResourceId, objects); for (int i = 0; i < objects.size(); ++i) { mIdMap.put(objects.get(i), i); } } @Override public long getItemId(int position) { String item = getItem(position); return mIdMap.get(item); } @Override public boolean hasStableIds() { return true; } } ``` **from\_page.xml:** ``` <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical"> <ListView android:id="@android:id/list" android:layout_width="match_parent" android:layout_height="wrap_content" android:clickable="true" android:text="@string/hello" /> </LinearLayout> ``` What am I missing out?
2014/02/12
[ "https://Stackoverflow.com/questions/21739350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1733310/" ]
There is a saying that, if you can't create file in R.Java, it means there is a problem with XML. If you look at your listview, you have "android:id="@android:id/list", this should have been ``` "@+id/your_idname". ``` Hopefully this should resolve the problem. Let me if its still not working!!
@ViewById is not a RoboGuice annotation. Looks like you're mixing your libraries. You want @InjectView.
20,488,756
I use the code below for sending ajax request to get more products on scroll down event. However it also sends ajax request when I scroll up, which is not intended. How can I modify it so that it will send a request only when I scroll it to the bottom? ``` _debug = true; function dbg(msg) { if (_debug) console.log(msg); } $(document).ready(function () { $(".item-block img.lazy").lazyload({ effect: "fadeIn" }); doMouseWheel = 1; $("#result").append("<p id='last'></p>"); dbg("Document Ready"); var scrollFunction = function () { dbg("Window Scroll Start"); /* if (!doMouseWheel) return;*/ var mostOfTheWayDown = ($('#last').offset().top - $('#result').height()) * 2 / 3; dbg('mostOfTheWayDown html: ' + mostOfTheWayDown); dbg('doMouseWheel html: ' + doMouseWheel); if ($(window).scrollTop() >= mostOfTheWayDown) { $(window).unbind("scroll"); dbg("Window distanceTop to scrollTop Start"); $('div#loadMoreComments').show(); doMouseWheel = 1; dbg("Another window to the end !!!! " + $(".item-block:last").attr('id')); $.ajax({ dataType: "html", url: "search_load_more.php?lastComment=" + $(".item-block:last").attr('id') + "&" + window.location.search.substring(1), success: function (html) { doMouseWheel = 0; if (html) { $("#result").append(html); dbg('Append html: ' + $(".item-block:first").attr('id')); dbg('Append html: ' + $(".item-block:last").attr('id')); $("#last").remove(); $("#result").append("<p id='last'></p>"); $('div#loadMoreComments').hide(); $("img.lazy").lazyload({ effect: "fadeIn" }); $(window).scroll(scrollFunction); } else { //Disable Ajax when result from PHP-script is empty (no more DB-results ) $('div#loadMoreComments').replaceWith("<center><h1 style='color:red'>No more styles</h1></center>"); doMouseWheel = 0; } } }); } }; $(window).scroll(scrollFunction); }); ```
2013/12/10
[ "https://Stackoverflow.com/questions/20488756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2667210/" ]
Here is another way using jQuery ``` var checkout = $(".calendar").datepicker({}); $( "#myModal" ).scroll(function() { $('.calendar').datepicker('place') }); ```
Solution provided by rab works but still not perfect as the datepicker flickers on scroll of bootstrap modal. So I used the jquery's scroll event to achieve smooth position change of datepicker. Here's my code: ``` $( document ).scroll(function(){ $('#modal .datepicker').datepicker('place'); //#modal is the id of the modal }); ```
20,488,756
I use the code below for sending ajax request to get more products on scroll down event. However it also sends ajax request when I scroll up, which is not intended. How can I modify it so that it will send a request only when I scroll it to the bottom? ``` _debug = true; function dbg(msg) { if (_debug) console.log(msg); } $(document).ready(function () { $(".item-block img.lazy").lazyload({ effect: "fadeIn" }); doMouseWheel = 1; $("#result").append("<p id='last'></p>"); dbg("Document Ready"); var scrollFunction = function () { dbg("Window Scroll Start"); /* if (!doMouseWheel) return;*/ var mostOfTheWayDown = ($('#last').offset().top - $('#result').height()) * 2 / 3; dbg('mostOfTheWayDown html: ' + mostOfTheWayDown); dbg('doMouseWheel html: ' + doMouseWheel); if ($(window).scrollTop() >= mostOfTheWayDown) { $(window).unbind("scroll"); dbg("Window distanceTop to scrollTop Start"); $('div#loadMoreComments').show(); doMouseWheel = 1; dbg("Another window to the end !!!! " + $(".item-block:last").attr('id')); $.ajax({ dataType: "html", url: "search_load_more.php?lastComment=" + $(".item-block:last").attr('id') + "&" + window.location.search.substring(1), success: function (html) { doMouseWheel = 0; if (html) { $("#result").append(html); dbg('Append html: ' + $(".item-block:first").attr('id')); dbg('Append html: ' + $(".item-block:last").attr('id')); $("#last").remove(); $("#result").append("<p id='last'></p>"); $('div#loadMoreComments').hide(); $("img.lazy").lazyload({ effect: "fadeIn" }); $(window).scroll(scrollFunction); } else { //Disable Ajax when result from PHP-script is empty (no more DB-results ) $('div#loadMoreComments').replaceWith("<center><h1 style='color:red'>No more styles</h1></center>"); doMouseWheel = 0; } } }); } }; $(window).scroll(scrollFunction); }); ```
2013/12/10
[ "https://Stackoverflow.com/questions/20488756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2667210/" ]
Here is another way using jQuery ``` var checkout = $(".calendar").datepicker({}); $( "#myModal" ).scroll(function() { $('.calendar').datepicker('place') }); ```
I too faced the same issue while using bootstrap datepicker in my project. I used an alternate method where in i created a hidden transparent layer inside the datepicker template inside *bootstrap-datepicker.js* (with classname *'hidden-layer-datepicker'*) and gave fixed position and occupying full height and width of the html. ``` DPGlobal.template = '<div class="datepicker">'+ '<span class="hidden-layer-datepicker"></span><div class="datepicker-days"> ``` Now when the datepicker modal pops up, the newly created layer will occupy the entire page width and height and when the user scrolls since the modal is appended to body, the datepicker modal too scrolls with it. With the introduction of the new layer, the inner scroll of the container in which the datepicker input field is present, will be negated while the modal is open. One more thing to do is to update the datepicker modal closing event when clicking on the hidden layer and that is done using the below code inside *bootstrap-datepicker.js*. ``` // Clicked outside the datepicker, hide it if (!( this.element.is(e.target) || (this.picker.find(e.target).length && e.target.className != "hidden-layer-datepicker") || this.picker.is(e.target) || this.picker.find(e.target).length )){ this.hide(); } ```
20,488,756
I use the code below for sending ajax request to get more products on scroll down event. However it also sends ajax request when I scroll up, which is not intended. How can I modify it so that it will send a request only when I scroll it to the bottom? ``` _debug = true; function dbg(msg) { if (_debug) console.log(msg); } $(document).ready(function () { $(".item-block img.lazy").lazyload({ effect: "fadeIn" }); doMouseWheel = 1; $("#result").append("<p id='last'></p>"); dbg("Document Ready"); var scrollFunction = function () { dbg("Window Scroll Start"); /* if (!doMouseWheel) return;*/ var mostOfTheWayDown = ($('#last').offset().top - $('#result').height()) * 2 / 3; dbg('mostOfTheWayDown html: ' + mostOfTheWayDown); dbg('doMouseWheel html: ' + doMouseWheel); if ($(window).scrollTop() >= mostOfTheWayDown) { $(window).unbind("scroll"); dbg("Window distanceTop to scrollTop Start"); $('div#loadMoreComments').show(); doMouseWheel = 1; dbg("Another window to the end !!!! " + $(".item-block:last").attr('id')); $.ajax({ dataType: "html", url: "search_load_more.php?lastComment=" + $(".item-block:last").attr('id') + "&" + window.location.search.substring(1), success: function (html) { doMouseWheel = 0; if (html) { $("#result").append(html); dbg('Append html: ' + $(".item-block:first").attr('id')); dbg('Append html: ' + $(".item-block:last").attr('id')); $("#last").remove(); $("#result").append("<p id='last'></p>"); $('div#loadMoreComments').hide(); $("img.lazy").lazyload({ effect: "fadeIn" }); $(window).scroll(scrollFunction); } else { //Disable Ajax when result from PHP-script is empty (no more DB-results ) $('div#loadMoreComments').replaceWith("<center><h1 style='color:red'>No more styles</h1></center>"); doMouseWheel = 0; } } }); } }; $(window).scroll(scrollFunction); }); ```
2013/12/10
[ "https://Stackoverflow.com/questions/20488756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2667210/" ]
There is option `datepicker('place')` to update position . I have updated [jsfiddle](http://jsfiddle.net/csrA5/2/) ``` var datePicker = $(".calendar").datepicker({}); var t ; $( document ).on( 'DOMMouseScroll mousewheel scroll', '#myModal', function(){ window.clearTimeout( t ); t = window.setTimeout( function(){ $('.calendar').datepicker('place') }, 100 ); } ); ```
I dont know why, but positioning is based on scrolling so you need to find this code in bootstrap-datepicker.js ``` scrollTop = $(this.o.container).scrollTop(); ``` and rewrite it to ``` scrollTop = 0; ``` This helped me, i hope it will help another people.
20,488,756
I use the code below for sending ajax request to get more products on scroll down event. However it also sends ajax request when I scroll up, which is not intended. How can I modify it so that it will send a request only when I scroll it to the bottom? ``` _debug = true; function dbg(msg) { if (_debug) console.log(msg); } $(document).ready(function () { $(".item-block img.lazy").lazyload({ effect: "fadeIn" }); doMouseWheel = 1; $("#result").append("<p id='last'></p>"); dbg("Document Ready"); var scrollFunction = function () { dbg("Window Scroll Start"); /* if (!doMouseWheel) return;*/ var mostOfTheWayDown = ($('#last').offset().top - $('#result').height()) * 2 / 3; dbg('mostOfTheWayDown html: ' + mostOfTheWayDown); dbg('doMouseWheel html: ' + doMouseWheel); if ($(window).scrollTop() >= mostOfTheWayDown) { $(window).unbind("scroll"); dbg("Window distanceTop to scrollTop Start"); $('div#loadMoreComments').show(); doMouseWheel = 1; dbg("Another window to the end !!!! " + $(".item-block:last").attr('id')); $.ajax({ dataType: "html", url: "search_load_more.php?lastComment=" + $(".item-block:last").attr('id') + "&" + window.location.search.substring(1), success: function (html) { doMouseWheel = 0; if (html) { $("#result").append(html); dbg('Append html: ' + $(".item-block:first").attr('id')); dbg('Append html: ' + $(".item-block:last").attr('id')); $("#last").remove(); $("#result").append("<p id='last'></p>"); $('div#loadMoreComments').hide(); $("img.lazy").lazyload({ effect: "fadeIn" }); $(window).scroll(scrollFunction); } else { //Disable Ajax when result from PHP-script is empty (no more DB-results ) $('div#loadMoreComments').replaceWith("<center><h1 style='color:red'>No more styles</h1></center>"); doMouseWheel = 0; } } }); } }; $(window).scroll(scrollFunction); }); ```
2013/12/10
[ "https://Stackoverflow.com/questions/20488756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2667210/" ]
Here is another way using jQuery ``` var checkout = $(".calendar").datepicker({}); $( "#myModal" ).scroll(function() { $('.calendar').datepicker('place') }); ```
I ran into this problem aswell with Stefan Petre's version of Bootstrap-datepicker (<https://www.eyecon.ro/bootstrap-datepicker>), the issue is the Datepicker element is attached to the body which means it will scroll with the body, fine in most cases but when you have a scrollable modal you need to attach the Datepicker to the scrollable modal's div instead, so my fix was to change Stefan's bootstrap-datepicker.js as follows - line 28, change ``` .appendTo('body') ``` to ``` .appendTo(element.offsetParent) ``` and line 153, change ``` var offset = this.component ? this.component.offset() : this.element.offset(); ``` to ``` var offset = this.component ? this.component.position() : this.element.position(); ``` Early tests shows it scrolls perfectly. In addition you may need to change the z-order of the Datepicker element to make it sit above the modal (this was my initial fix which did not deal with scrolling, I have not backed this change out yet so dont know if its still needed) I haven'y checked but I suspect the Github version of Bootstrap-datepicker.js is doing the same thing (the sourcecode is much different to what I have from Stefan though)
20,488,756
I use the code below for sending ajax request to get more products on scroll down event. However it also sends ajax request when I scroll up, which is not intended. How can I modify it so that it will send a request only when I scroll it to the bottom? ``` _debug = true; function dbg(msg) { if (_debug) console.log(msg); } $(document).ready(function () { $(".item-block img.lazy").lazyload({ effect: "fadeIn" }); doMouseWheel = 1; $("#result").append("<p id='last'></p>"); dbg("Document Ready"); var scrollFunction = function () { dbg("Window Scroll Start"); /* if (!doMouseWheel) return;*/ var mostOfTheWayDown = ($('#last').offset().top - $('#result').height()) * 2 / 3; dbg('mostOfTheWayDown html: ' + mostOfTheWayDown); dbg('doMouseWheel html: ' + doMouseWheel); if ($(window).scrollTop() >= mostOfTheWayDown) { $(window).unbind("scroll"); dbg("Window distanceTop to scrollTop Start"); $('div#loadMoreComments').show(); doMouseWheel = 1; dbg("Another window to the end !!!! " + $(".item-block:last").attr('id')); $.ajax({ dataType: "html", url: "search_load_more.php?lastComment=" + $(".item-block:last").attr('id') + "&" + window.location.search.substring(1), success: function (html) { doMouseWheel = 0; if (html) { $("#result").append(html); dbg('Append html: ' + $(".item-block:first").attr('id')); dbg('Append html: ' + $(".item-block:last").attr('id')); $("#last").remove(); $("#result").append("<p id='last'></p>"); $('div#loadMoreComments').hide(); $("img.lazy").lazyload({ effect: "fadeIn" }); $(window).scroll(scrollFunction); } else { //Disable Ajax when result from PHP-script is empty (no more DB-results ) $('div#loadMoreComments').replaceWith("<center><h1 style='color:red'>No more styles</h1></center>"); doMouseWheel = 0; } } }); } }; $(window).scroll(scrollFunction); }); ```
2013/12/10
[ "https://Stackoverflow.com/questions/20488756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2667210/" ]
There is option `datepicker('place')` to update position . I have updated [jsfiddle](http://jsfiddle.net/csrA5/2/) ``` var datePicker = $(".calendar").datepicker({}); var t ; $( document ).on( 'DOMMouseScroll mousewheel scroll', '#myModal', function(){ window.clearTimeout( t ); t = window.setTimeout( function(){ $('.calendar').datepicker('place') }, 100 ); } ); ```
Here is another way using jQuery ``` var checkout = $(".calendar").datepicker({}); $( "#myModal" ).scroll(function() { $('.calendar').datepicker('place') }); ```
20,488,756
I use the code below for sending ajax request to get more products on scroll down event. However it also sends ajax request when I scroll up, which is not intended. How can I modify it so that it will send a request only when I scroll it to the bottom? ``` _debug = true; function dbg(msg) { if (_debug) console.log(msg); } $(document).ready(function () { $(".item-block img.lazy").lazyload({ effect: "fadeIn" }); doMouseWheel = 1; $("#result").append("<p id='last'></p>"); dbg("Document Ready"); var scrollFunction = function () { dbg("Window Scroll Start"); /* if (!doMouseWheel) return;*/ var mostOfTheWayDown = ($('#last').offset().top - $('#result').height()) * 2 / 3; dbg('mostOfTheWayDown html: ' + mostOfTheWayDown); dbg('doMouseWheel html: ' + doMouseWheel); if ($(window).scrollTop() >= mostOfTheWayDown) { $(window).unbind("scroll"); dbg("Window distanceTop to scrollTop Start"); $('div#loadMoreComments').show(); doMouseWheel = 1; dbg("Another window to the end !!!! " + $(".item-block:last").attr('id')); $.ajax({ dataType: "html", url: "search_load_more.php?lastComment=" + $(".item-block:last").attr('id') + "&" + window.location.search.substring(1), success: function (html) { doMouseWheel = 0; if (html) { $("#result").append(html); dbg('Append html: ' + $(".item-block:first").attr('id')); dbg('Append html: ' + $(".item-block:last").attr('id')); $("#last").remove(); $("#result").append("<p id='last'></p>"); $('div#loadMoreComments').hide(); $("img.lazy").lazyload({ effect: "fadeIn" }); $(window).scroll(scrollFunction); } else { //Disable Ajax when result from PHP-script is empty (no more DB-results ) $('div#loadMoreComments').replaceWith("<center><h1 style='color:red'>No more styles</h1></center>"); doMouseWheel = 0; } } }); } }; $(window).scroll(scrollFunction); }); ```
2013/12/10
[ "https://Stackoverflow.com/questions/20488756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2667210/" ]
There is option `datepicker('place')` to update position . I have updated [jsfiddle](http://jsfiddle.net/csrA5/2/) ``` var datePicker = $(".calendar").datepicker({}); var t ; $( document ).on( 'DOMMouseScroll mousewheel scroll', '#myModal', function(){ window.clearTimeout( t ); t = window.setTimeout( function(){ $('.calendar').datepicker('place') }, 100 ); } ); ```
I ran into this problem aswell with Stefan Petre's version of Bootstrap-datepicker (<https://www.eyecon.ro/bootstrap-datepicker>), the issue is the Datepicker element is attached to the body which means it will scroll with the body, fine in most cases but when you have a scrollable modal you need to attach the Datepicker to the scrollable modal's div instead, so my fix was to change Stefan's bootstrap-datepicker.js as follows - line 28, change ``` .appendTo('body') ``` to ``` .appendTo(element.offsetParent) ``` and line 153, change ``` var offset = this.component ? this.component.offset() : this.element.offset(); ``` to ``` var offset = this.component ? this.component.position() : this.element.position(); ``` Early tests shows it scrolls perfectly. In addition you may need to change the z-order of the Datepicker element to make it sit above the modal (this was my initial fix which did not deal with scrolling, I have not backed this change out yet so dont know if its still needed) I haven'y checked but I suspect the Github version of Bootstrap-datepicker.js is doing the same thing (the sourcecode is much different to what I have from Stefan though)
20,488,756
I use the code below for sending ajax request to get more products on scroll down event. However it also sends ajax request when I scroll up, which is not intended. How can I modify it so that it will send a request only when I scroll it to the bottom? ``` _debug = true; function dbg(msg) { if (_debug) console.log(msg); } $(document).ready(function () { $(".item-block img.lazy").lazyload({ effect: "fadeIn" }); doMouseWheel = 1; $("#result").append("<p id='last'></p>"); dbg("Document Ready"); var scrollFunction = function () { dbg("Window Scroll Start"); /* if (!doMouseWheel) return;*/ var mostOfTheWayDown = ($('#last').offset().top - $('#result').height()) * 2 / 3; dbg('mostOfTheWayDown html: ' + mostOfTheWayDown); dbg('doMouseWheel html: ' + doMouseWheel); if ($(window).scrollTop() >= mostOfTheWayDown) { $(window).unbind("scroll"); dbg("Window distanceTop to scrollTop Start"); $('div#loadMoreComments').show(); doMouseWheel = 1; dbg("Another window to the end !!!! " + $(".item-block:last").attr('id')); $.ajax({ dataType: "html", url: "search_load_more.php?lastComment=" + $(".item-block:last").attr('id') + "&" + window.location.search.substring(1), success: function (html) { doMouseWheel = 0; if (html) { $("#result").append(html); dbg('Append html: ' + $(".item-block:first").attr('id')); dbg('Append html: ' + $(".item-block:last").attr('id')); $("#last").remove(); $("#result").append("<p id='last'></p>"); $('div#loadMoreComments').hide(); $("img.lazy").lazyload({ effect: "fadeIn" }); $(window).scroll(scrollFunction); } else { //Disable Ajax when result from PHP-script is empty (no more DB-results ) $('div#loadMoreComments').replaceWith("<center><h1 style='color:red'>No more styles</h1></center>"); doMouseWheel = 0; } } }); } }; $(window).scroll(scrollFunction); }); ```
2013/12/10
[ "https://Stackoverflow.com/questions/20488756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2667210/" ]
There is option `datepicker('place')` to update position . I have updated [jsfiddle](http://jsfiddle.net/csrA5/2/) ``` var datePicker = $(".calendar").datepicker({}); var t ; $( document ).on( 'DOMMouseScroll mousewheel scroll', '#myModal', function(){ window.clearTimeout( t ); t = window.setTimeout( function(){ $('.calendar').datepicker('place') }, 100 ); } ); ```
Try to add the event scroll in bootstrap-datepicker.js, in function "Datepicker.prototype" ``` [$(window), { resize: $.proxy(this.place, this), scroll: $.proxy(this.place, this) }] ```
20,488,756
I use the code below for sending ajax request to get more products on scroll down event. However it also sends ajax request when I scroll up, which is not intended. How can I modify it so that it will send a request only when I scroll it to the bottom? ``` _debug = true; function dbg(msg) { if (_debug) console.log(msg); } $(document).ready(function () { $(".item-block img.lazy").lazyload({ effect: "fadeIn" }); doMouseWheel = 1; $("#result").append("<p id='last'></p>"); dbg("Document Ready"); var scrollFunction = function () { dbg("Window Scroll Start"); /* if (!doMouseWheel) return;*/ var mostOfTheWayDown = ($('#last').offset().top - $('#result').height()) * 2 / 3; dbg('mostOfTheWayDown html: ' + mostOfTheWayDown); dbg('doMouseWheel html: ' + doMouseWheel); if ($(window).scrollTop() >= mostOfTheWayDown) { $(window).unbind("scroll"); dbg("Window distanceTop to scrollTop Start"); $('div#loadMoreComments').show(); doMouseWheel = 1; dbg("Another window to the end !!!! " + $(".item-block:last").attr('id')); $.ajax({ dataType: "html", url: "search_load_more.php?lastComment=" + $(".item-block:last").attr('id') + "&" + window.location.search.substring(1), success: function (html) { doMouseWheel = 0; if (html) { $("#result").append(html); dbg('Append html: ' + $(".item-block:first").attr('id')); dbg('Append html: ' + $(".item-block:last").attr('id')); $("#last").remove(); $("#result").append("<p id='last'></p>"); $('div#loadMoreComments').hide(); $("img.lazy").lazyload({ effect: "fadeIn" }); $(window).scroll(scrollFunction); } else { //Disable Ajax when result from PHP-script is empty (no more DB-results ) $('div#loadMoreComments').replaceWith("<center><h1 style='color:red'>No more styles</h1></center>"); doMouseWheel = 0; } } }); } }; $(window).scroll(scrollFunction); }); ```
2013/12/10
[ "https://Stackoverflow.com/questions/20488756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2667210/" ]
There is option `datepicker('place')` to update position . I have updated [jsfiddle](http://jsfiddle.net/csrA5/2/) ``` var datePicker = $(".calendar").datepicker({}); var t ; $( document ).on( 'DOMMouseScroll mousewheel scroll', '#myModal', function(){ window.clearTimeout( t ); t = window.setTimeout( function(){ $('.calendar').datepicker('place') }, 100 ); } ); ```
I too faced the same issue while using bootstrap datepicker in my project. I used an alternate method where in i created a hidden transparent layer inside the datepicker template inside *bootstrap-datepicker.js* (with classname *'hidden-layer-datepicker'*) and gave fixed position and occupying full height and width of the html. ``` DPGlobal.template = '<div class="datepicker">'+ '<span class="hidden-layer-datepicker"></span><div class="datepicker-days"> ``` Now when the datepicker modal pops up, the newly created layer will occupy the entire page width and height and when the user scrolls since the modal is appended to body, the datepicker modal too scrolls with it. With the introduction of the new layer, the inner scroll of the container in which the datepicker input field is present, will be negated while the modal is open. One more thing to do is to update the datepicker modal closing event when clicking on the hidden layer and that is done using the below code inside *bootstrap-datepicker.js*. ``` // Clicked outside the datepicker, hide it if (!( this.element.is(e.target) || (this.picker.find(e.target).length && e.target.className != "hidden-layer-datepicker") || this.picker.is(e.target) || this.picker.find(e.target).length )){ this.hide(); } ```
20,488,756
I use the code below for sending ajax request to get more products on scroll down event. However it also sends ajax request when I scroll up, which is not intended. How can I modify it so that it will send a request only when I scroll it to the bottom? ``` _debug = true; function dbg(msg) { if (_debug) console.log(msg); } $(document).ready(function () { $(".item-block img.lazy").lazyload({ effect: "fadeIn" }); doMouseWheel = 1; $("#result").append("<p id='last'></p>"); dbg("Document Ready"); var scrollFunction = function () { dbg("Window Scroll Start"); /* if (!doMouseWheel) return;*/ var mostOfTheWayDown = ($('#last').offset().top - $('#result').height()) * 2 / 3; dbg('mostOfTheWayDown html: ' + mostOfTheWayDown); dbg('doMouseWheel html: ' + doMouseWheel); if ($(window).scrollTop() >= mostOfTheWayDown) { $(window).unbind("scroll"); dbg("Window distanceTop to scrollTop Start"); $('div#loadMoreComments').show(); doMouseWheel = 1; dbg("Another window to the end !!!! " + $(".item-block:last").attr('id')); $.ajax({ dataType: "html", url: "search_load_more.php?lastComment=" + $(".item-block:last").attr('id') + "&" + window.location.search.substring(1), success: function (html) { doMouseWheel = 0; if (html) { $("#result").append(html); dbg('Append html: ' + $(".item-block:first").attr('id')); dbg('Append html: ' + $(".item-block:last").attr('id')); $("#last").remove(); $("#result").append("<p id='last'></p>"); $('div#loadMoreComments').hide(); $("img.lazy").lazyload({ effect: "fadeIn" }); $(window).scroll(scrollFunction); } else { //Disable Ajax when result from PHP-script is empty (no more DB-results ) $('div#loadMoreComments').replaceWith("<center><h1 style='color:red'>No more styles</h1></center>"); doMouseWheel = 0; } } }); } }; $(window).scroll(scrollFunction); }); ```
2013/12/10
[ "https://Stackoverflow.com/questions/20488756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2667210/" ]
Here is another way using jQuery ``` var checkout = $(".calendar").datepicker({}); $( "#myModal" ).scroll(function() { $('.calendar').datepicker('place') }); ```
I dont know why, but positioning is based on scrolling so you need to find this code in bootstrap-datepicker.js ``` scrollTop = $(this.o.container).scrollTop(); ``` and rewrite it to ``` scrollTop = 0; ``` This helped me, i hope it will help another people.
20,488,756
I use the code below for sending ajax request to get more products on scroll down event. However it also sends ajax request when I scroll up, which is not intended. How can I modify it so that it will send a request only when I scroll it to the bottom? ``` _debug = true; function dbg(msg) { if (_debug) console.log(msg); } $(document).ready(function () { $(".item-block img.lazy").lazyload({ effect: "fadeIn" }); doMouseWheel = 1; $("#result").append("<p id='last'></p>"); dbg("Document Ready"); var scrollFunction = function () { dbg("Window Scroll Start"); /* if (!doMouseWheel) return;*/ var mostOfTheWayDown = ($('#last').offset().top - $('#result').height()) * 2 / 3; dbg('mostOfTheWayDown html: ' + mostOfTheWayDown); dbg('doMouseWheel html: ' + doMouseWheel); if ($(window).scrollTop() >= mostOfTheWayDown) { $(window).unbind("scroll"); dbg("Window distanceTop to scrollTop Start"); $('div#loadMoreComments').show(); doMouseWheel = 1; dbg("Another window to the end !!!! " + $(".item-block:last").attr('id')); $.ajax({ dataType: "html", url: "search_load_more.php?lastComment=" + $(".item-block:last").attr('id') + "&" + window.location.search.substring(1), success: function (html) { doMouseWheel = 0; if (html) { $("#result").append(html); dbg('Append html: ' + $(".item-block:first").attr('id')); dbg('Append html: ' + $(".item-block:last").attr('id')); $("#last").remove(); $("#result").append("<p id='last'></p>"); $('div#loadMoreComments').hide(); $("img.lazy").lazyload({ effect: "fadeIn" }); $(window).scroll(scrollFunction); } else { //Disable Ajax when result from PHP-script is empty (no more DB-results ) $('div#loadMoreComments').replaceWith("<center><h1 style='color:red'>No more styles</h1></center>"); doMouseWheel = 0; } } }); } }; $(window).scroll(scrollFunction); }); ```
2013/12/10
[ "https://Stackoverflow.com/questions/20488756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2667210/" ]
Here is another way using jQuery ``` var checkout = $(".calendar").datepicker({}); $( "#myModal" ).scroll(function() { $('.calendar').datepicker('place') }); ```
Try to add the event scroll in bootstrap-datepicker.js, in function "Datepicker.prototype" ``` [$(window), { resize: $.proxy(this.place, this), scroll: $.proxy(this.place, this) }] ```
4,422,664
(Not to be confused with [Catalan's constant](https://en.wikipedia.org/wiki/Catalan%27s_constant)) > > Evaluate the infinite sum $$S = \sum\_{n=0}^\infty \frac{(-1)^{T\_n}}{(2n+1)^2} = 1 - \frac1{3^2} - \frac1{5^2} + \frac1{7^2} + \frac1{9^2} - \frac1{11^2} - \frac1{13^2} + \frac1{15^2} + \cdots$$ > where $T\_n = \frac{n(n+1)}2$ is the $n$-th triangular number. > > > Equivalently, with $\omega = e^{i\frac\pi4}$, we can write the series as $$S = \frac1{2\sqrt2} \sum\_{n=1}^\infty \frac{\omega^n - \omega^{3n} - \omega^{5n} + \omega^{7n}}{n^2}$$ or $$S = \sum\_{n=1}^\infty \frac{a\_n}{n^2} \quad \text{ where } \quad \begin{cases}a\_{8n}=a\_{8n+2}=a\_{8n+4}=a\_{8n+6}=0\\a\_{8n+1}=a\_{8n+7}=+1\\a\_{8n+3}=a\_{8n+5}=-1\end{cases}$$ I see a linear combination of $\mathrm{Li}\_2(\cdot)$ terms but I'm not aware of or otherwise familiar with any identities that might be helpful in simplifying the sum. --- Borrowing inspiration from some other questions, I am hoping to cook up a periodic function $f(x)$ so that I can exploit its Fourier series to evaluate $S$. Or possibly the sums that make up $S$. For instance, I've started the hunt with the cosine expansion of $f(x)=\cos\left(\frac x8\right)$ on $[-\pi,\pi]$, given by $$\cos\left(\frac x8\right) = \frac8\pi \sin\left(\frac\pi8\right) - \frac8\pi \sin\left(\frac\pi8\right) \sum\_{n=1}^\infty \left(\frac{(-1)^n}{8n-1} - \frac{(-1)^n}{8n+1}\right) \cos(nx)$$ as well as $\cos\left(\frac{3x}8\right)$, which has an expansion containing denominators with $8n\pm3$. I don't know whether having $8n-1$ and $8n-3$ will be a problem, since there is some correspondence between $8n-1$ and $8n+7$, as well as $8n-3$ and $8n+5$. For posterity, I also considered the sine expansion of $f$ as well as the co/sine expansions of $\sin\left(\frac x8\right)$. $$\begin{align\*} \cos\left(\frac x8\right) &= \frac8\pi \sum\_{n=1}^\infty \left(\frac{1-(-1)^n \cos\left(\frac\pi8\right)}{8n-1} + \frac{1-(-1)^n \cos\left(\frac\pi8\right)}{8n+1}\right) \sin(nx) \\[1ex] \sin\left(\frac x8\right) &= \frac{16}\pi \sin^2\left(\frac\pi{16}\right) - \frac8\pi \sum\_{n=1}^\infty \left(\frac{1-(-1)^n \cos\left(\frac\pi8\right)}{8n-1} - \frac{1 - (-1)^n \cos\left(\frac\pi8\right)}{8n+1}\right) \cos(nx)\\[1ex] \sin\left(\frac x8\right)&= -\frac8\pi \sin\left(\frac\pi8\right) \sum\_{n=1}^\infty \left(\frac{(-1)^n}{8n-1} + \frac{(-1)^n}{8n+1}\right) \sin(nx) \end{align\*}$$ --- Next I looked at $x \cos\left(\frac x8\right)$ in an attempt to get the squared denominators, with e.g. cosine expansion $$\begin{align\*} x\cos\left(\frac x8\right) &= \frac8\pi \left(8\cos\left(\frac\pi8\right)+\pi\sin\left(\frac\pi8\right)-8\right) \\ & \qquad - 8\sin\left(\frac\pi8\right) \sum\_{n=1}^\infty \left(\frac{(-1)^n}{8n-1} - \frac{(-1)^n}{8n+1}\right) \cos(nx) \\ & \qquad - \frac{64}\pi \sum\_{k=1}^n \left(\frac{1 - (-1)^n \cos\left(\frac\pi8\right)}{(8n-1)^2} + \frac{1 - (-1)^n \cos\left(\frac\pi8\right)}{(8n+1)^2}\right) \cos(nx) \\[1ex] (x-\pi) \cos\left(\frac x8\right) &= \frac{64}\pi \left(\cos\left(\frac\pi8\right)-1\right) - \frac{64}\pi \sum\_{n=1}^\infty \left(\frac{1 - (-1)^n \cos\left(\frac\pi8\right)}{(8n-1)^2} + \frac{1 - (-1)^n \cos\left(\frac\pi8\right)}{(8n+1)^2}\right) \cos(nx) \end{align\*}$$ The next move would be to pick a value of $x$ to recover some numerical series, but the right choice - if there is one - isn't obvious to me. I can nearly recover two that I want, namely $$\sum\_{n=0}^\infty \left(\frac1{(8n+1)^2} + \frac1{(8n+7)^2}\right)$$ but still have to deal with their alternating variants. Presumably I can do something similar with $\cos\left(\frac{3x}8\right)$, but one thing at a time. --- I'm open to other methods for evaluating the series, but I'm more interested in the Fourier approach, if it's tenable.
2022/04/07
[ "https://math.stackexchange.com/questions/4422664", "https://math.stackexchange.com", "https://math.stackexchange.com/users/170231/" ]
For reference, here is a solution using [dilogarithm identities](https://en.wikipedia.org/wiki/Spence%27s_function#Identities) $$\newcommand{\dilog}{\operatorname{Li}\_2}\dilog(z)+\dilog(-z)=\frac12\dilog(z^2),\qquad\dilog(z)+\dilog(z^{-1})=-\frac{\pi^2}{6}-\frac{\log^2(-z)}{2},$$ with the principal value of the logarithm. Starting with the identity from the OP (with $\omega=e^{i\pi/4}$): \begin{align\*} 2S\sqrt2&=\dilog(\omega)-\dilog(\omega^3)-\dilog(\omega^5)+\dilog(\omega^7) \\&=\dilog(\omega)-\dilog(-\omega)+\dilog(\omega^{-1})-\dilog(-\omega^{-1}) \\&=2\dilog(\omega)-\frac12\dilog(i)+2\dilog(\omega^{-1})-\frac12\dilog(-i) \\&=-\frac32\frac{\pi^2}{6}-\underbrace{\log^2(-\omega)}\_{=(-3i\pi/4)^2}+\frac14\underbrace{\log^2(-i)}\_{=(-i\pi/2)^2}=\frac{\pi^2}{4}. \end{align\*} Thus $S=\pi^2/(8\sqrt{2})$.
Just to clarify $$\sum\limits\_{n=0}^\infty\frac{(-1)^{n (n+1)/2}}{(2 n+1)^s}\tag{1}$$ is equivalent to $$\sum\limits\_{n=1}^{\infty }\frac{\chi\_{8,2}(n)}{n^s}=L\_{8,2}(s)=8^{-s} \left(\zeta \left(s,\frac{1}{8}\right)-\zeta \left(s,\frac{3}{8}\right)-\zeta \left(s,\frac{5}{8}\right)+\zeta \left(s,\frac{7}{8}\right)\right)\tag{2}$$ where $\chi\_{8,2}(n)$ is the Dirichlet character $\{1,0,-1,0,-1,0,1,0\}$ and $L\_{8,2}(s)$ is the associated Dirichlet series leading to $$\sum\limits\_{n=0}^\infty\frac{(-1)^{n (n+1)/2}}{(2 n+1)^2}=L\_{8,2}(2)=\frac{\pi^2}{8 \sqrt{2}}.\tag{3}$$
4,422,664
(Not to be confused with [Catalan's constant](https://en.wikipedia.org/wiki/Catalan%27s_constant)) > > Evaluate the infinite sum $$S = \sum\_{n=0}^\infty \frac{(-1)^{T\_n}}{(2n+1)^2} = 1 - \frac1{3^2} - \frac1{5^2} + \frac1{7^2} + \frac1{9^2} - \frac1{11^2} - \frac1{13^2} + \frac1{15^2} + \cdots$$ > where $T\_n = \frac{n(n+1)}2$ is the $n$-th triangular number. > > > Equivalently, with $\omega = e^{i\frac\pi4}$, we can write the series as $$S = \frac1{2\sqrt2} \sum\_{n=1}^\infty \frac{\omega^n - \omega^{3n} - \omega^{5n} + \omega^{7n}}{n^2}$$ or $$S = \sum\_{n=1}^\infty \frac{a\_n}{n^2} \quad \text{ where } \quad \begin{cases}a\_{8n}=a\_{8n+2}=a\_{8n+4}=a\_{8n+6}=0\\a\_{8n+1}=a\_{8n+7}=+1\\a\_{8n+3}=a\_{8n+5}=-1\end{cases}$$ I see a linear combination of $\mathrm{Li}\_2(\cdot)$ terms but I'm not aware of or otherwise familiar with any identities that might be helpful in simplifying the sum. --- Borrowing inspiration from some other questions, I am hoping to cook up a periodic function $f(x)$ so that I can exploit its Fourier series to evaluate $S$. Or possibly the sums that make up $S$. For instance, I've started the hunt with the cosine expansion of $f(x)=\cos\left(\frac x8\right)$ on $[-\pi,\pi]$, given by $$\cos\left(\frac x8\right) = \frac8\pi \sin\left(\frac\pi8\right) - \frac8\pi \sin\left(\frac\pi8\right) \sum\_{n=1}^\infty \left(\frac{(-1)^n}{8n-1} - \frac{(-1)^n}{8n+1}\right) \cos(nx)$$ as well as $\cos\left(\frac{3x}8\right)$, which has an expansion containing denominators with $8n\pm3$. I don't know whether having $8n-1$ and $8n-3$ will be a problem, since there is some correspondence between $8n-1$ and $8n+7$, as well as $8n-3$ and $8n+5$. For posterity, I also considered the sine expansion of $f$ as well as the co/sine expansions of $\sin\left(\frac x8\right)$. $$\begin{align\*} \cos\left(\frac x8\right) &= \frac8\pi \sum\_{n=1}^\infty \left(\frac{1-(-1)^n \cos\left(\frac\pi8\right)}{8n-1} + \frac{1-(-1)^n \cos\left(\frac\pi8\right)}{8n+1}\right) \sin(nx) \\[1ex] \sin\left(\frac x8\right) &= \frac{16}\pi \sin^2\left(\frac\pi{16}\right) - \frac8\pi \sum\_{n=1}^\infty \left(\frac{1-(-1)^n \cos\left(\frac\pi8\right)}{8n-1} - \frac{1 - (-1)^n \cos\left(\frac\pi8\right)}{8n+1}\right) \cos(nx)\\[1ex] \sin\left(\frac x8\right)&= -\frac8\pi \sin\left(\frac\pi8\right) \sum\_{n=1}^\infty \left(\frac{(-1)^n}{8n-1} + \frac{(-1)^n}{8n+1}\right) \sin(nx) \end{align\*}$$ --- Next I looked at $x \cos\left(\frac x8\right)$ in an attempt to get the squared denominators, with e.g. cosine expansion $$\begin{align\*} x\cos\left(\frac x8\right) &= \frac8\pi \left(8\cos\left(\frac\pi8\right)+\pi\sin\left(\frac\pi8\right)-8\right) \\ & \qquad - 8\sin\left(\frac\pi8\right) \sum\_{n=1}^\infty \left(\frac{(-1)^n}{8n-1} - \frac{(-1)^n}{8n+1}\right) \cos(nx) \\ & \qquad - \frac{64}\pi \sum\_{k=1}^n \left(\frac{1 - (-1)^n \cos\left(\frac\pi8\right)}{(8n-1)^2} + \frac{1 - (-1)^n \cos\left(\frac\pi8\right)}{(8n+1)^2}\right) \cos(nx) \\[1ex] (x-\pi) \cos\left(\frac x8\right) &= \frac{64}\pi \left(\cos\left(\frac\pi8\right)-1\right) - \frac{64}\pi \sum\_{n=1}^\infty \left(\frac{1 - (-1)^n \cos\left(\frac\pi8\right)}{(8n-1)^2} + \frac{1 - (-1)^n \cos\left(\frac\pi8\right)}{(8n+1)^2}\right) \cos(nx) \end{align\*}$$ The next move would be to pick a value of $x$ to recover some numerical series, but the right choice - if there is one - isn't obvious to me. I can nearly recover two that I want, namely $$\sum\_{n=0}^\infty \left(\frac1{(8n+1)^2} + \frac1{(8n+7)^2}\right)$$ but still have to deal with their alternating variants. Presumably I can do something similar with $\cos\left(\frac{3x}8\right)$, but one thing at a time. --- I'm open to other methods for evaluating the series, but I'm more interested in the Fourier approach, if it's tenable.
2022/04/07
[ "https://math.stackexchange.com/questions/4422664", "https://math.stackexchange.com", "https://math.stackexchange.com/users/170231/" ]
For reference, here is a solution using [dilogarithm identities](https://en.wikipedia.org/wiki/Spence%27s_function#Identities) $$\newcommand{\dilog}{\operatorname{Li}\_2}\dilog(z)+\dilog(-z)=\frac12\dilog(z^2),\qquad\dilog(z)+\dilog(z^{-1})=-\frac{\pi^2}{6}-\frac{\log^2(-z)}{2},$$ with the principal value of the logarithm. Starting with the identity from the OP (with $\omega=e^{i\pi/4}$): \begin{align\*} 2S\sqrt2&=\dilog(\omega)-\dilog(\omega^3)-\dilog(\omega^5)+\dilog(\omega^7) \\&=\dilog(\omega)-\dilog(-\omega)+\dilog(\omega^{-1})-\dilog(-\omega^{-1}) \\&=2\dilog(\omega)-\frac12\dilog(i)+2\dilog(\omega^{-1})-\frac12\dilog(-i) \\&=-\frac32\frac{\pi^2}{6}-\underbrace{\log^2(-\omega)}\_{=(-3i\pi/4)^2}+\frac14\underbrace{\log^2(-i)}\_{=(-i\pi/2)^2}=\frac{\pi^2}{4}. \end{align\*} Thus $S=\pi^2/(8\sqrt{2})$.
Using the function suggested in comments (one of which contains a typo; $29$ should have been $28$), I arrive at the identity $$\pi^2 \left(\left(x - \frac12\right)^2 - \frac{21}{256}\right) = \\ \cos(2\pi x) \sum\_{k=0}^\infty \frac{(-1)^k}{(8k+1)^2} + \cos(4\pi x) \sum\_{k=0}^\infty \frac{(-1)^k}{(8k+2)^2} + \cdots + \cos(14\pi x) \sum\_{k=0}^\infty \frac{(-1)^k}{(8k+7)^2}$$ For $m\in\{1,2,\ldots,7\}$, let $$S\_m = \sum\_{k=0}^\infty \frac1{(8k+m)^2} \text{ and } {S\_m}' = \sum\_{k=0}^\infty \frac{(-1)^k}{(8k+m)^2}$$ Evaluating both sides of the identity with $x\in\left\{\frac18,\frac38,\frac58,\frac78\right\}$ yields $S\_4=\frac{\pi^2}{256}$, and more importantly the relation $${S\_1}'-{S\_3}'-{S\_5}'+{S\_7}' = \boxed{\frac{\pi^2}{8\sqrt2}}$$ and from here it's easy to show that the left side is the same as $S\_1-S\_3-S\_5+S\_7$, the sum we want.
4,422,664
(Not to be confused with [Catalan's constant](https://en.wikipedia.org/wiki/Catalan%27s_constant)) > > Evaluate the infinite sum $$S = \sum\_{n=0}^\infty \frac{(-1)^{T\_n}}{(2n+1)^2} = 1 - \frac1{3^2} - \frac1{5^2} + \frac1{7^2} + \frac1{9^2} - \frac1{11^2} - \frac1{13^2} + \frac1{15^2} + \cdots$$ > where $T\_n = \frac{n(n+1)}2$ is the $n$-th triangular number. > > > Equivalently, with $\omega = e^{i\frac\pi4}$, we can write the series as $$S = \frac1{2\sqrt2} \sum\_{n=1}^\infty \frac{\omega^n - \omega^{3n} - \omega^{5n} + \omega^{7n}}{n^2}$$ or $$S = \sum\_{n=1}^\infty \frac{a\_n}{n^2} \quad \text{ where } \quad \begin{cases}a\_{8n}=a\_{8n+2}=a\_{8n+4}=a\_{8n+6}=0\\a\_{8n+1}=a\_{8n+7}=+1\\a\_{8n+3}=a\_{8n+5}=-1\end{cases}$$ I see a linear combination of $\mathrm{Li}\_2(\cdot)$ terms but I'm not aware of or otherwise familiar with any identities that might be helpful in simplifying the sum. --- Borrowing inspiration from some other questions, I am hoping to cook up a periodic function $f(x)$ so that I can exploit its Fourier series to evaluate $S$. Or possibly the sums that make up $S$. For instance, I've started the hunt with the cosine expansion of $f(x)=\cos\left(\frac x8\right)$ on $[-\pi,\pi]$, given by $$\cos\left(\frac x8\right) = \frac8\pi \sin\left(\frac\pi8\right) - \frac8\pi \sin\left(\frac\pi8\right) \sum\_{n=1}^\infty \left(\frac{(-1)^n}{8n-1} - \frac{(-1)^n}{8n+1}\right) \cos(nx)$$ as well as $\cos\left(\frac{3x}8\right)$, which has an expansion containing denominators with $8n\pm3$. I don't know whether having $8n-1$ and $8n-3$ will be a problem, since there is some correspondence between $8n-1$ and $8n+7$, as well as $8n-3$ and $8n+5$. For posterity, I also considered the sine expansion of $f$ as well as the co/sine expansions of $\sin\left(\frac x8\right)$. $$\begin{align\*} \cos\left(\frac x8\right) &= \frac8\pi \sum\_{n=1}^\infty \left(\frac{1-(-1)^n \cos\left(\frac\pi8\right)}{8n-1} + \frac{1-(-1)^n \cos\left(\frac\pi8\right)}{8n+1}\right) \sin(nx) \\[1ex] \sin\left(\frac x8\right) &= \frac{16}\pi \sin^2\left(\frac\pi{16}\right) - \frac8\pi \sum\_{n=1}^\infty \left(\frac{1-(-1)^n \cos\left(\frac\pi8\right)}{8n-1} - \frac{1 - (-1)^n \cos\left(\frac\pi8\right)}{8n+1}\right) \cos(nx)\\[1ex] \sin\left(\frac x8\right)&= -\frac8\pi \sin\left(\frac\pi8\right) \sum\_{n=1}^\infty \left(\frac{(-1)^n}{8n-1} + \frac{(-1)^n}{8n+1}\right) \sin(nx) \end{align\*}$$ --- Next I looked at $x \cos\left(\frac x8\right)$ in an attempt to get the squared denominators, with e.g. cosine expansion $$\begin{align\*} x\cos\left(\frac x8\right) &= \frac8\pi \left(8\cos\left(\frac\pi8\right)+\pi\sin\left(\frac\pi8\right)-8\right) \\ & \qquad - 8\sin\left(\frac\pi8\right) \sum\_{n=1}^\infty \left(\frac{(-1)^n}{8n-1} - \frac{(-1)^n}{8n+1}\right) \cos(nx) \\ & \qquad - \frac{64}\pi \sum\_{k=1}^n \left(\frac{1 - (-1)^n \cos\left(\frac\pi8\right)}{(8n-1)^2} + \frac{1 - (-1)^n \cos\left(\frac\pi8\right)}{(8n+1)^2}\right) \cos(nx) \\[1ex] (x-\pi) \cos\left(\frac x8\right) &= \frac{64}\pi \left(\cos\left(\frac\pi8\right)-1\right) - \frac{64}\pi \sum\_{n=1}^\infty \left(\frac{1 - (-1)^n \cos\left(\frac\pi8\right)}{(8n-1)^2} + \frac{1 - (-1)^n \cos\left(\frac\pi8\right)}{(8n+1)^2}\right) \cos(nx) \end{align\*}$$ The next move would be to pick a value of $x$ to recover some numerical series, but the right choice - if there is one - isn't obvious to me. I can nearly recover two that I want, namely $$\sum\_{n=0}^\infty \left(\frac1{(8n+1)^2} + \frac1{(8n+7)^2}\right)$$ but still have to deal with their alternating variants. Presumably I can do something similar with $\cos\left(\frac{3x}8\right)$, but one thing at a time. --- I'm open to other methods for evaluating the series, but I'm more interested in the Fourier approach, if it's tenable.
2022/04/07
[ "https://math.stackexchange.com/questions/4422664", "https://math.stackexchange.com", "https://math.stackexchange.com/users/170231/" ]
For reference, here is a solution using [dilogarithm identities](https://en.wikipedia.org/wiki/Spence%27s_function#Identities) $$\newcommand{\dilog}{\operatorname{Li}\_2}\dilog(z)+\dilog(-z)=\frac12\dilog(z^2),\qquad\dilog(z)+\dilog(z^{-1})=-\frac{\pi^2}{6}-\frac{\log^2(-z)}{2},$$ with the principal value of the logarithm. Starting with the identity from the OP (with $\omega=e^{i\pi/4}$): \begin{align\*} 2S\sqrt2&=\dilog(\omega)-\dilog(\omega^3)-\dilog(\omega^5)+\dilog(\omega^7) \\&=\dilog(\omega)-\dilog(-\omega)+\dilog(\omega^{-1})-\dilog(-\omega^{-1}) \\&=2\dilog(\omega)-\frac12\dilog(i)+2\dilog(\omega^{-1})-\frac12\dilog(-i) \\&=-\frac32\frac{\pi^2}{6}-\underbrace{\log^2(-\omega)}\_{=(-3i\pi/4)^2}+\frac14\underbrace{\log^2(-i)}\_{=(-i\pi/2)^2}=\frac{\pi^2}{4}. \end{align\*} Thus $S=\pi^2/(8\sqrt{2})$.
I will provide a computation without the need for special functions. Let us define a complex valued function with the poles and residues necessary to reconstruct our sum of interest. We start with a composition of periodic functions \begin{equation} f(z)= \underbrace{\frac{1}{\sin(8 \pi z)}}\_{\substack{\text{provides} \\ \text{singularities}\\ \text{except}\,\,z=0} } \cdot \underbrace{\sin(4 \pi z)}\_{\substack{\text{cancels} \\ \text{unnecessary} \\ \text{singularities}}} \cdot \underbrace{\sin(2 \pi z)}\_{\substack{\text{adjusts} \\ \text{signs}\\ \text{of residues}}} \end{equation} now we combine this with the power law present in the target sum which also provides a singularity at $z=0$. \begin{equation} g(z)=\frac{f(z)}{z^2} \end{equation} we have (left as an exercise to the reader, essentially this boils down to the fact that $|\sin(a z)| \sim e^{\Re(a z)} $ for large $z$): $|g(z)|\sim Const/|z^2|$ if $z \in \mathbb{C}/\{2 \mathbb{Z}+1 ,0\}$ and $|z| \rightarrow \infty$. As an integration contour we choose a large circle $C$ centered at zero such that it's boundary is always located between two singular points. In the limit of infinite circle radius we get by the residue theorem: \begin{equation} 0=\oint\_C g(z)dz = 2 \pi i \text{res}(g(z),z=0)+2 \pi i \sum\_{m\in 2 \mathbb{Z}+1 } \text{res}(g(z),z=m/8)\quad \,\, (1) \end{equation} the residues of $g(z)$ correspond to a lot of first order singularities and can therefore calculated mechanically ($n\in \mathbb{Z}/0$): \begin{equation} \text{res}(g(z),z=m/8)=-\frac{4 \sqrt{2}}{\pi}\frac{a\_m}{ m^2} \,\, \quad (2) \end{equation} \begin{equation} \text{res}(g(z),z=0)=\pi \quad \quad \quad \quad \quad \quad (3) \end{equation} with \begin{equation} a\_m= \left\{\begin{array}{lr} +1, & \text{if } m \in \{8n+1,8n+7\} \\ -1, & \text{if } m \in \{8n+3,8n+5\} \end{array} \right\} \end{equation} we can now put (2) and (3) into (1) and obtain, using parity: > > \begin{equation} > \frac{\pi^2}{8 \sqrt{2}}=\sum\_{m\in 2 \mathbb{N}+1 } \frac{a\_m}{ m^2} > \end{equation} > > > where the rhs is equal to the third representation of the sum in the OP
4,422,664
(Not to be confused with [Catalan's constant](https://en.wikipedia.org/wiki/Catalan%27s_constant)) > > Evaluate the infinite sum $$S = \sum\_{n=0}^\infty \frac{(-1)^{T\_n}}{(2n+1)^2} = 1 - \frac1{3^2} - \frac1{5^2} + \frac1{7^2} + \frac1{9^2} - \frac1{11^2} - \frac1{13^2} + \frac1{15^2} + \cdots$$ > where $T\_n = \frac{n(n+1)}2$ is the $n$-th triangular number. > > > Equivalently, with $\omega = e^{i\frac\pi4}$, we can write the series as $$S = \frac1{2\sqrt2} \sum\_{n=1}^\infty \frac{\omega^n - \omega^{3n} - \omega^{5n} + \omega^{7n}}{n^2}$$ or $$S = \sum\_{n=1}^\infty \frac{a\_n}{n^2} \quad \text{ where } \quad \begin{cases}a\_{8n}=a\_{8n+2}=a\_{8n+4}=a\_{8n+6}=0\\a\_{8n+1}=a\_{8n+7}=+1\\a\_{8n+3}=a\_{8n+5}=-1\end{cases}$$ I see a linear combination of $\mathrm{Li}\_2(\cdot)$ terms but I'm not aware of or otherwise familiar with any identities that might be helpful in simplifying the sum. --- Borrowing inspiration from some other questions, I am hoping to cook up a periodic function $f(x)$ so that I can exploit its Fourier series to evaluate $S$. Or possibly the sums that make up $S$. For instance, I've started the hunt with the cosine expansion of $f(x)=\cos\left(\frac x8\right)$ on $[-\pi,\pi]$, given by $$\cos\left(\frac x8\right) = \frac8\pi \sin\left(\frac\pi8\right) - \frac8\pi \sin\left(\frac\pi8\right) \sum\_{n=1}^\infty \left(\frac{(-1)^n}{8n-1} - \frac{(-1)^n}{8n+1}\right) \cos(nx)$$ as well as $\cos\left(\frac{3x}8\right)$, which has an expansion containing denominators with $8n\pm3$. I don't know whether having $8n-1$ and $8n-3$ will be a problem, since there is some correspondence between $8n-1$ and $8n+7$, as well as $8n-3$ and $8n+5$. For posterity, I also considered the sine expansion of $f$ as well as the co/sine expansions of $\sin\left(\frac x8\right)$. $$\begin{align\*} \cos\left(\frac x8\right) &= \frac8\pi \sum\_{n=1}^\infty \left(\frac{1-(-1)^n \cos\left(\frac\pi8\right)}{8n-1} + \frac{1-(-1)^n \cos\left(\frac\pi8\right)}{8n+1}\right) \sin(nx) \\[1ex] \sin\left(\frac x8\right) &= \frac{16}\pi \sin^2\left(\frac\pi{16}\right) - \frac8\pi \sum\_{n=1}^\infty \left(\frac{1-(-1)^n \cos\left(\frac\pi8\right)}{8n-1} - \frac{1 - (-1)^n \cos\left(\frac\pi8\right)}{8n+1}\right) \cos(nx)\\[1ex] \sin\left(\frac x8\right)&= -\frac8\pi \sin\left(\frac\pi8\right) \sum\_{n=1}^\infty \left(\frac{(-1)^n}{8n-1} + \frac{(-1)^n}{8n+1}\right) \sin(nx) \end{align\*}$$ --- Next I looked at $x \cos\left(\frac x8\right)$ in an attempt to get the squared denominators, with e.g. cosine expansion $$\begin{align\*} x\cos\left(\frac x8\right) &= \frac8\pi \left(8\cos\left(\frac\pi8\right)+\pi\sin\left(\frac\pi8\right)-8\right) \\ & \qquad - 8\sin\left(\frac\pi8\right) \sum\_{n=1}^\infty \left(\frac{(-1)^n}{8n-1} - \frac{(-1)^n}{8n+1}\right) \cos(nx) \\ & \qquad - \frac{64}\pi \sum\_{k=1}^n \left(\frac{1 - (-1)^n \cos\left(\frac\pi8\right)}{(8n-1)^2} + \frac{1 - (-1)^n \cos\left(\frac\pi8\right)}{(8n+1)^2}\right) \cos(nx) \\[1ex] (x-\pi) \cos\left(\frac x8\right) &= \frac{64}\pi \left(\cos\left(\frac\pi8\right)-1\right) - \frac{64}\pi \sum\_{n=1}^\infty \left(\frac{1 - (-1)^n \cos\left(\frac\pi8\right)}{(8n-1)^2} + \frac{1 - (-1)^n \cos\left(\frac\pi8\right)}{(8n+1)^2}\right) \cos(nx) \end{align\*}$$ The next move would be to pick a value of $x$ to recover some numerical series, but the right choice - if there is one - isn't obvious to me. I can nearly recover two that I want, namely $$\sum\_{n=0}^\infty \left(\frac1{(8n+1)^2} + \frac1{(8n+7)^2}\right)$$ but still have to deal with their alternating variants. Presumably I can do something similar with $\cos\left(\frac{3x}8\right)$, but one thing at a time. --- I'm open to other methods for evaluating the series, but I'm more interested in the Fourier approach, if it's tenable.
2022/04/07
[ "https://math.stackexchange.com/questions/4422664", "https://math.stackexchange.com", "https://math.stackexchange.com/users/170231/" ]
Here's another way to evaluate this series. Since the series converges absolutely, $$ \begin{aligned} S&=\sum\_{n=0}^{\infty}\left(\frac{1}{(8n+1)^2}-\frac{1}{(8n+3)^2}-\frac{1}{(8n+5)^2}+\frac{1}{(8n+7)^2}\right) \\&=\frac{1}{64} \left(\psi ^{(1)}\left(\frac{1}{8}\right)-\psi ^{(1)}\left(\frac{3}{8}\right)-\psi ^{(1)}\left(\frac{5}{8}\right)+\psi ^{(1)}\left(\frac{7}{8}\right)\right) \end{aligned} $$. With the identity of PolyGamma $$ \psi ^{(1)}(1-x)+\psi ^{(1)}(x)=\pi ^2 \csc ^2(\pi x) $$ we get $$ \begin{aligned}S&=\frac{\pi^2}{64}\left(\csc^2\left(\frac{\pi^2}{8}\right)-\csc^2\left(\frac{3\pi^2}{8}\right)\right) \\&=\frac{\pi^2}{64}\cdot 4 \sqrt{2} \\&=\frac{\sqrt{2}}{16}\pi^2 \end{aligned} $$
Just to clarify $$\sum\limits\_{n=0}^\infty\frac{(-1)^{n (n+1)/2}}{(2 n+1)^s}\tag{1}$$ is equivalent to $$\sum\limits\_{n=1}^{\infty }\frac{\chi\_{8,2}(n)}{n^s}=L\_{8,2}(s)=8^{-s} \left(\zeta \left(s,\frac{1}{8}\right)-\zeta \left(s,\frac{3}{8}\right)-\zeta \left(s,\frac{5}{8}\right)+\zeta \left(s,\frac{7}{8}\right)\right)\tag{2}$$ where $\chi\_{8,2}(n)$ is the Dirichlet character $\{1,0,-1,0,-1,0,1,0\}$ and $L\_{8,2}(s)$ is the associated Dirichlet series leading to $$\sum\limits\_{n=0}^\infty\frac{(-1)^{n (n+1)/2}}{(2 n+1)^2}=L\_{8,2}(2)=\frac{\pi^2}{8 \sqrt{2}}.\tag{3}$$
4,422,664
(Not to be confused with [Catalan's constant](https://en.wikipedia.org/wiki/Catalan%27s_constant)) > > Evaluate the infinite sum $$S = \sum\_{n=0}^\infty \frac{(-1)^{T\_n}}{(2n+1)^2} = 1 - \frac1{3^2} - \frac1{5^2} + \frac1{7^2} + \frac1{9^2} - \frac1{11^2} - \frac1{13^2} + \frac1{15^2} + \cdots$$ > where $T\_n = \frac{n(n+1)}2$ is the $n$-th triangular number. > > > Equivalently, with $\omega = e^{i\frac\pi4}$, we can write the series as $$S = \frac1{2\sqrt2} \sum\_{n=1}^\infty \frac{\omega^n - \omega^{3n} - \omega^{5n} + \omega^{7n}}{n^2}$$ or $$S = \sum\_{n=1}^\infty \frac{a\_n}{n^2} \quad \text{ where } \quad \begin{cases}a\_{8n}=a\_{8n+2}=a\_{8n+4}=a\_{8n+6}=0\\a\_{8n+1}=a\_{8n+7}=+1\\a\_{8n+3}=a\_{8n+5}=-1\end{cases}$$ I see a linear combination of $\mathrm{Li}\_2(\cdot)$ terms but I'm not aware of or otherwise familiar with any identities that might be helpful in simplifying the sum. --- Borrowing inspiration from some other questions, I am hoping to cook up a periodic function $f(x)$ so that I can exploit its Fourier series to evaluate $S$. Or possibly the sums that make up $S$. For instance, I've started the hunt with the cosine expansion of $f(x)=\cos\left(\frac x8\right)$ on $[-\pi,\pi]$, given by $$\cos\left(\frac x8\right) = \frac8\pi \sin\left(\frac\pi8\right) - \frac8\pi \sin\left(\frac\pi8\right) \sum\_{n=1}^\infty \left(\frac{(-1)^n}{8n-1} - \frac{(-1)^n}{8n+1}\right) \cos(nx)$$ as well as $\cos\left(\frac{3x}8\right)$, which has an expansion containing denominators with $8n\pm3$. I don't know whether having $8n-1$ and $8n-3$ will be a problem, since there is some correspondence between $8n-1$ and $8n+7$, as well as $8n-3$ and $8n+5$. For posterity, I also considered the sine expansion of $f$ as well as the co/sine expansions of $\sin\left(\frac x8\right)$. $$\begin{align\*} \cos\left(\frac x8\right) &= \frac8\pi \sum\_{n=1}^\infty \left(\frac{1-(-1)^n \cos\left(\frac\pi8\right)}{8n-1} + \frac{1-(-1)^n \cos\left(\frac\pi8\right)}{8n+1}\right) \sin(nx) \\[1ex] \sin\left(\frac x8\right) &= \frac{16}\pi \sin^2\left(\frac\pi{16}\right) - \frac8\pi \sum\_{n=1}^\infty \left(\frac{1-(-1)^n \cos\left(\frac\pi8\right)}{8n-1} - \frac{1 - (-1)^n \cos\left(\frac\pi8\right)}{8n+1}\right) \cos(nx)\\[1ex] \sin\left(\frac x8\right)&= -\frac8\pi \sin\left(\frac\pi8\right) \sum\_{n=1}^\infty \left(\frac{(-1)^n}{8n-1} + \frac{(-1)^n}{8n+1}\right) \sin(nx) \end{align\*}$$ --- Next I looked at $x \cos\left(\frac x8\right)$ in an attempt to get the squared denominators, with e.g. cosine expansion $$\begin{align\*} x\cos\left(\frac x8\right) &= \frac8\pi \left(8\cos\left(\frac\pi8\right)+\pi\sin\left(\frac\pi8\right)-8\right) \\ & \qquad - 8\sin\left(\frac\pi8\right) \sum\_{n=1}^\infty \left(\frac{(-1)^n}{8n-1} - \frac{(-1)^n}{8n+1}\right) \cos(nx) \\ & \qquad - \frac{64}\pi \sum\_{k=1}^n \left(\frac{1 - (-1)^n \cos\left(\frac\pi8\right)}{(8n-1)^2} + \frac{1 - (-1)^n \cos\left(\frac\pi8\right)}{(8n+1)^2}\right) \cos(nx) \\[1ex] (x-\pi) \cos\left(\frac x8\right) &= \frac{64}\pi \left(\cos\left(\frac\pi8\right)-1\right) - \frac{64}\pi \sum\_{n=1}^\infty \left(\frac{1 - (-1)^n \cos\left(\frac\pi8\right)}{(8n-1)^2} + \frac{1 - (-1)^n \cos\left(\frac\pi8\right)}{(8n+1)^2}\right) \cos(nx) \end{align\*}$$ The next move would be to pick a value of $x$ to recover some numerical series, but the right choice - if there is one - isn't obvious to me. I can nearly recover two that I want, namely $$\sum\_{n=0}^\infty \left(\frac1{(8n+1)^2} + \frac1{(8n+7)^2}\right)$$ but still have to deal with their alternating variants. Presumably I can do something similar with $\cos\left(\frac{3x}8\right)$, but one thing at a time. --- I'm open to other methods for evaluating the series, but I'm more interested in the Fourier approach, if it's tenable.
2022/04/07
[ "https://math.stackexchange.com/questions/4422664", "https://math.stackexchange.com", "https://math.stackexchange.com/users/170231/" ]
Here's another way to evaluate this series. Since the series converges absolutely, $$ \begin{aligned} S&=\sum\_{n=0}^{\infty}\left(\frac{1}{(8n+1)^2}-\frac{1}{(8n+3)^2}-\frac{1}{(8n+5)^2}+\frac{1}{(8n+7)^2}\right) \\&=\frac{1}{64} \left(\psi ^{(1)}\left(\frac{1}{8}\right)-\psi ^{(1)}\left(\frac{3}{8}\right)-\psi ^{(1)}\left(\frac{5}{8}\right)+\psi ^{(1)}\left(\frac{7}{8}\right)\right) \end{aligned} $$. With the identity of PolyGamma $$ \psi ^{(1)}(1-x)+\psi ^{(1)}(x)=\pi ^2 \csc ^2(\pi x) $$ we get $$ \begin{aligned}S&=\frac{\pi^2}{64}\left(\csc^2\left(\frac{\pi^2}{8}\right)-\csc^2\left(\frac{3\pi^2}{8}\right)\right) \\&=\frac{\pi^2}{64}\cdot 4 \sqrt{2} \\&=\frac{\sqrt{2}}{16}\pi^2 \end{aligned} $$
Using the function suggested in comments (one of which contains a typo; $29$ should have been $28$), I arrive at the identity $$\pi^2 \left(\left(x - \frac12\right)^2 - \frac{21}{256}\right) = \\ \cos(2\pi x) \sum\_{k=0}^\infty \frac{(-1)^k}{(8k+1)^2} + \cos(4\pi x) \sum\_{k=0}^\infty \frac{(-1)^k}{(8k+2)^2} + \cdots + \cos(14\pi x) \sum\_{k=0}^\infty \frac{(-1)^k}{(8k+7)^2}$$ For $m\in\{1,2,\ldots,7\}$, let $$S\_m = \sum\_{k=0}^\infty \frac1{(8k+m)^2} \text{ and } {S\_m}' = \sum\_{k=0}^\infty \frac{(-1)^k}{(8k+m)^2}$$ Evaluating both sides of the identity with $x\in\left\{\frac18,\frac38,\frac58,\frac78\right\}$ yields $S\_4=\frac{\pi^2}{256}$, and more importantly the relation $${S\_1}'-{S\_3}'-{S\_5}'+{S\_7}' = \boxed{\frac{\pi^2}{8\sqrt2}}$$ and from here it's easy to show that the left side is the same as $S\_1-S\_3-S\_5+S\_7$, the sum we want.
4,422,664
(Not to be confused with [Catalan's constant](https://en.wikipedia.org/wiki/Catalan%27s_constant)) > > Evaluate the infinite sum $$S = \sum\_{n=0}^\infty \frac{(-1)^{T\_n}}{(2n+1)^2} = 1 - \frac1{3^2} - \frac1{5^2} + \frac1{7^2} + \frac1{9^2} - \frac1{11^2} - \frac1{13^2} + \frac1{15^2} + \cdots$$ > where $T\_n = \frac{n(n+1)}2$ is the $n$-th triangular number. > > > Equivalently, with $\omega = e^{i\frac\pi4}$, we can write the series as $$S = \frac1{2\sqrt2} \sum\_{n=1}^\infty \frac{\omega^n - \omega^{3n} - \omega^{5n} + \omega^{7n}}{n^2}$$ or $$S = \sum\_{n=1}^\infty \frac{a\_n}{n^2} \quad \text{ where } \quad \begin{cases}a\_{8n}=a\_{8n+2}=a\_{8n+4}=a\_{8n+6}=0\\a\_{8n+1}=a\_{8n+7}=+1\\a\_{8n+3}=a\_{8n+5}=-1\end{cases}$$ I see a linear combination of $\mathrm{Li}\_2(\cdot)$ terms but I'm not aware of or otherwise familiar with any identities that might be helpful in simplifying the sum. --- Borrowing inspiration from some other questions, I am hoping to cook up a periodic function $f(x)$ so that I can exploit its Fourier series to evaluate $S$. Or possibly the sums that make up $S$. For instance, I've started the hunt with the cosine expansion of $f(x)=\cos\left(\frac x8\right)$ on $[-\pi,\pi]$, given by $$\cos\left(\frac x8\right) = \frac8\pi \sin\left(\frac\pi8\right) - \frac8\pi \sin\left(\frac\pi8\right) \sum\_{n=1}^\infty \left(\frac{(-1)^n}{8n-1} - \frac{(-1)^n}{8n+1}\right) \cos(nx)$$ as well as $\cos\left(\frac{3x}8\right)$, which has an expansion containing denominators with $8n\pm3$. I don't know whether having $8n-1$ and $8n-3$ will be a problem, since there is some correspondence between $8n-1$ and $8n+7$, as well as $8n-3$ and $8n+5$. For posterity, I also considered the sine expansion of $f$ as well as the co/sine expansions of $\sin\left(\frac x8\right)$. $$\begin{align\*} \cos\left(\frac x8\right) &= \frac8\pi \sum\_{n=1}^\infty \left(\frac{1-(-1)^n \cos\left(\frac\pi8\right)}{8n-1} + \frac{1-(-1)^n \cos\left(\frac\pi8\right)}{8n+1}\right) \sin(nx) \\[1ex] \sin\left(\frac x8\right) &= \frac{16}\pi \sin^2\left(\frac\pi{16}\right) - \frac8\pi \sum\_{n=1}^\infty \left(\frac{1-(-1)^n \cos\left(\frac\pi8\right)}{8n-1} - \frac{1 - (-1)^n \cos\left(\frac\pi8\right)}{8n+1}\right) \cos(nx)\\[1ex] \sin\left(\frac x8\right)&= -\frac8\pi \sin\left(\frac\pi8\right) \sum\_{n=1}^\infty \left(\frac{(-1)^n}{8n-1} + \frac{(-1)^n}{8n+1}\right) \sin(nx) \end{align\*}$$ --- Next I looked at $x \cos\left(\frac x8\right)$ in an attempt to get the squared denominators, with e.g. cosine expansion $$\begin{align\*} x\cos\left(\frac x8\right) &= \frac8\pi \left(8\cos\left(\frac\pi8\right)+\pi\sin\left(\frac\pi8\right)-8\right) \\ & \qquad - 8\sin\left(\frac\pi8\right) \sum\_{n=1}^\infty \left(\frac{(-1)^n}{8n-1} - \frac{(-1)^n}{8n+1}\right) \cos(nx) \\ & \qquad - \frac{64}\pi \sum\_{k=1}^n \left(\frac{1 - (-1)^n \cos\left(\frac\pi8\right)}{(8n-1)^2} + \frac{1 - (-1)^n \cos\left(\frac\pi8\right)}{(8n+1)^2}\right) \cos(nx) \\[1ex] (x-\pi) \cos\left(\frac x8\right) &= \frac{64}\pi \left(\cos\left(\frac\pi8\right)-1\right) - \frac{64}\pi \sum\_{n=1}^\infty \left(\frac{1 - (-1)^n \cos\left(\frac\pi8\right)}{(8n-1)^2} + \frac{1 - (-1)^n \cos\left(\frac\pi8\right)}{(8n+1)^2}\right) \cos(nx) \end{align\*}$$ The next move would be to pick a value of $x$ to recover some numerical series, but the right choice - if there is one - isn't obvious to me. I can nearly recover two that I want, namely $$\sum\_{n=0}^\infty \left(\frac1{(8n+1)^2} + \frac1{(8n+7)^2}\right)$$ but still have to deal with their alternating variants. Presumably I can do something similar with $\cos\left(\frac{3x}8\right)$, but one thing at a time. --- I'm open to other methods for evaluating the series, but I'm more interested in the Fourier approach, if it's tenable.
2022/04/07
[ "https://math.stackexchange.com/questions/4422664", "https://math.stackexchange.com", "https://math.stackexchange.com/users/170231/" ]
Here's another way to evaluate this series. Since the series converges absolutely, $$ \begin{aligned} S&=\sum\_{n=0}^{\infty}\left(\frac{1}{(8n+1)^2}-\frac{1}{(8n+3)^2}-\frac{1}{(8n+5)^2}+\frac{1}{(8n+7)^2}\right) \\&=\frac{1}{64} \left(\psi ^{(1)}\left(\frac{1}{8}\right)-\psi ^{(1)}\left(\frac{3}{8}\right)-\psi ^{(1)}\left(\frac{5}{8}\right)+\psi ^{(1)}\left(\frac{7}{8}\right)\right) \end{aligned} $$. With the identity of PolyGamma $$ \psi ^{(1)}(1-x)+\psi ^{(1)}(x)=\pi ^2 \csc ^2(\pi x) $$ we get $$ \begin{aligned}S&=\frac{\pi^2}{64}\left(\csc^2\left(\frac{\pi^2}{8}\right)-\csc^2\left(\frac{3\pi^2}{8}\right)\right) \\&=\frac{\pi^2}{64}\cdot 4 \sqrt{2} \\&=\frac{\sqrt{2}}{16}\pi^2 \end{aligned} $$
I will provide a computation without the need for special functions. Let us define a complex valued function with the poles and residues necessary to reconstruct our sum of interest. We start with a composition of periodic functions \begin{equation} f(z)= \underbrace{\frac{1}{\sin(8 \pi z)}}\_{\substack{\text{provides} \\ \text{singularities}\\ \text{except}\,\,z=0} } \cdot \underbrace{\sin(4 \pi z)}\_{\substack{\text{cancels} \\ \text{unnecessary} \\ \text{singularities}}} \cdot \underbrace{\sin(2 \pi z)}\_{\substack{\text{adjusts} \\ \text{signs}\\ \text{of residues}}} \end{equation} now we combine this with the power law present in the target sum which also provides a singularity at $z=0$. \begin{equation} g(z)=\frac{f(z)}{z^2} \end{equation} we have (left as an exercise to the reader, essentially this boils down to the fact that $|\sin(a z)| \sim e^{\Re(a z)} $ for large $z$): $|g(z)|\sim Const/|z^2|$ if $z \in \mathbb{C}/\{2 \mathbb{Z}+1 ,0\}$ and $|z| \rightarrow \infty$. As an integration contour we choose a large circle $C$ centered at zero such that it's boundary is always located between two singular points. In the limit of infinite circle radius we get by the residue theorem: \begin{equation} 0=\oint\_C g(z)dz = 2 \pi i \text{res}(g(z),z=0)+2 \pi i \sum\_{m\in 2 \mathbb{Z}+1 } \text{res}(g(z),z=m/8)\quad \,\, (1) \end{equation} the residues of $g(z)$ correspond to a lot of first order singularities and can therefore calculated mechanically ($n\in \mathbb{Z}/0$): \begin{equation} \text{res}(g(z),z=m/8)=-\frac{4 \sqrt{2}}{\pi}\frac{a\_m}{ m^2} \,\, \quad (2) \end{equation} \begin{equation} \text{res}(g(z),z=0)=\pi \quad \quad \quad \quad \quad \quad (3) \end{equation} with \begin{equation} a\_m= \left\{\begin{array}{lr} +1, & \text{if } m \in \{8n+1,8n+7\} \\ -1, & \text{if } m \in \{8n+3,8n+5\} \end{array} \right\} \end{equation} we can now put (2) and (3) into (1) and obtain, using parity: > > \begin{equation} > \frac{\pi^2}{8 \sqrt{2}}=\sum\_{m\in 2 \mathbb{N}+1 } \frac{a\_m}{ m^2} > \end{equation} > > > where the rhs is equal to the third representation of the sum in the OP
63,433,654
I have this test snippet ``` while True: input("prompt> ") ``` On Windows, when I run this script with "py", I can use the arrow keys as expected. But when I try doing this in my ubuntu command line, it will show the following output: [![enter image description here](https://i.stack.imgur.com/EtWY6.png)](https://i.stack.imgur.com/EtWY6.png) How do I make it such that this code snippet is interactive for any python3 installation on any OS? Why is it only working on Windows now?
2020/08/16
[ "https://Stackoverflow.com/questions/63433654", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7579456/" ]
it's about OS - windows os is working differently from a based Linux-OS like ubuntu. you can try this: <https://stackoverflow.com/a/893200/9350669> by the way, I just install python3 in my VM-ubuntu and run your script and the arrow keys work well, so you can try reinstall python or update the os. [![enter image description here](https://i.stack.imgur.com/2dEW1.png)](https://i.stack.imgur.com/2dEW1.png)
``` python3 -i script.py ``` Apparently this solves the problem and makes the session interactive. Lol okay.
210,077
I am working on sharepoint server 2013 (on-premise & office 365). and sometime i have to write some custom JavaScripts and custom style which hide/relocate certain HTML components. Example of these include the following 2 cases:- 1- Inside the built-in discussion board view there is a link named "What's Hot" and i did not find any way to hide this link, other than writing this custom style:- ``` <style> a.ms-pivotControl-surfacedOpt[aria-label^='What'] { display:none !important; } </style> ``` 2- Inside the built-in create/edit discussion board forms, there is a check box named "Question", and to hide it i wrote the following custom javascript :- ``` <script> $( document ).ready(function() { $('.ms-formtable nobr:contains("Question")').closest('tr').hide(); }); </script> ``` keeping in mind that the question check box is disabled inside the Discussion content type (for a reason or another) so i can not hide it from the content type using the regular appraoch. now if i am building my own .net application i would write these custom javascript and style without any worry, since i own the markup. but in sharepoint i do not own the markup and from my own experience that this markup might chnage if we apply a CU or a single update to sharepoint. so i am not sure which appraoch can be considered valid in sharepoint:- 1. I should avoid writing such a custom javascripts and custom style in sharepoint, since the classes i am depending on can change in the future? 2. those customizations are valid and i am not doing any thing wrong,, but if these custom javascripts and/or cusotm style break after installing an update, then the normal process will be to update these custom javascripts and/or custom style to match the new classes names... i am asking this question, because currently i am preparing a document on how we need to manage updating sharepoint servers (including installing sharepoint CU and/or SP security updates). and i need to mention what we need to do in-case a cusotm JavaScript and/or cusotm style breaks.. so will the normal process be to update these cusotm scripts and style to match the new classes? or it is our problem from the beginning that we have defined these cusotm JavaScript and custom style ?
2017/03/08
[ "https://sharepoint.stackexchange.com/questions/210077", "https://sharepoint.stackexchange.com", "https://sharepoint.stackexchange.com/users/84413/" ]
It's not the greatest of practises - as you're aware you may come back to the project later and be unable to recall how you hid it - if at all not to mention if anyone else comes to the project or should you leave. You should be able to edit the itemstyle itself and create a custom layout for it so you can select it that way. Liekly the best solution. I can understand you not wanting to put it in the core css of the SP as youre unlikely to know any far reaching implications of your actions - you never know if SP is re-using those class names elsewhere.
I'm going to have to disagree with Daniel's answer: not only is it okay, I wish more developers would use Microsoft's OOB classes and IDs. They should be done with caution, and it is good to understand all the other places the classes and IDs might be in use - but that's the power of it: you can implement customizations that can be leveraged across your entire portal (or other SharePoint environments). If everyone did this, we could all be building on top of one another's work, instead of everyone always reinventing the wheel with every new solution. (After all, you're probably not the first person to want to hide the "What's Hot" link. :)) I do think it is a good idea to log these changes though, so you have a list of things to test after service packs or other upgrades (not that I've seen much in the way of HTML Class/ID changes during service packs).
210,077
I am working on sharepoint server 2013 (on-premise & office 365). and sometime i have to write some custom JavaScripts and custom style which hide/relocate certain HTML components. Example of these include the following 2 cases:- 1- Inside the built-in discussion board view there is a link named "What's Hot" and i did not find any way to hide this link, other than writing this custom style:- ``` <style> a.ms-pivotControl-surfacedOpt[aria-label^='What'] { display:none !important; } </style> ``` 2- Inside the built-in create/edit discussion board forms, there is a check box named "Question", and to hide it i wrote the following custom javascript :- ``` <script> $( document ).ready(function() { $('.ms-formtable nobr:contains("Question")').closest('tr').hide(); }); </script> ``` keeping in mind that the question check box is disabled inside the Discussion content type (for a reason or another) so i can not hide it from the content type using the regular appraoch. now if i am building my own .net application i would write these custom javascript and style without any worry, since i own the markup. but in sharepoint i do not own the markup and from my own experience that this markup might chnage if we apply a CU or a single update to sharepoint. so i am not sure which appraoch can be considered valid in sharepoint:- 1. I should avoid writing such a custom javascripts and custom style in sharepoint, since the classes i am depending on can change in the future? 2. those customizations are valid and i am not doing any thing wrong,, but if these custom javascripts and/or cusotm style break after installing an update, then the normal process will be to update these custom javascripts and/or custom style to match the new classes names... i am asking this question, because currently i am preparing a document on how we need to manage updating sharepoint servers (including installing sharepoint CU and/or SP security updates). and i need to mention what we need to do in-case a cusotm JavaScript and/or cusotm style breaks.. so will the normal process be to update these cusotm scripts and style to match the new classes? or it is our problem from the beginning that we have defined these cusotm JavaScript and custom style ?
2017/03/08
[ "https://sharepoint.stackexchange.com/questions/210077", "https://sharepoint.stackexchange.com", "https://sharepoint.stackexchange.com/users/84413/" ]
> > 1. I should avoid writing such a custom javascripts and custom style in > sharepoint, since the classes i am depending on can change in the > future? > 2. Those customizations are valid and i am not doing any thing wrong,, > but if these custom javascripts and/or cusotm style break after > installing an update, then the normal process will be to update these > custom javascripts and/or custom style to match the new classes > names... > > > Even Microsoft does not have all the answers to your questions yet. That is why **all** CSS or JavaScript branding in (SPOnline) Modern Experiences is currently disabled. They are working on technologies which will let you, partially, do customizations. But besides current terminology 'scenarios' and 'codeparts' we have no clue what will actually be possible, or how. The problem you describe is not new, even with .Net applications you could have problems when the OS was updated. Just try and run an 8 bit EXE, from 20 years ago, on a Windows 10 machine.. None of the Multimedia CD-ROMs I developed 2 decades ago, run on todays machines. Problem with the Cloud is that the 'OS' can update daily, and yes your custom applications on top of them **can** break. My personal opinion is that we have to learn to live with that. No one takes out a blowtorch on their Tesla, no one changes the UI color of Outlook, Word or Excel. Then why have we been so eager to take out the blowtorch on SharePoint for the past 10,15 years? I think that is why Microsoft is churning out applications like Teams, Planner, etc. ect. like crazy. (Office365) Users want simplicity. You want custom stuff? You can do everything you want with SPFx (the SharePoint FrameWork) **And** we have to learn to program for changes, the Cloud is conceptually the same as the OSes 20 years ago.. only difference is the Update Cycle is Continuous... Takes a different mind-set.. maybe even takes Programmers who never used .Net In synchronicity with the Google Cloud Next '17 Keynote playing on my second screen.. Paul Gaffney (HomeDepot): > > "To a modern view: Just assume that everything is going to fail" > > >
I'm going to have to disagree with Daniel's answer: not only is it okay, I wish more developers would use Microsoft's OOB classes and IDs. They should be done with caution, and it is good to understand all the other places the classes and IDs might be in use - but that's the power of it: you can implement customizations that can be leveraged across your entire portal (or other SharePoint environments). If everyone did this, we could all be building on top of one another's work, instead of everyone always reinventing the wheel with every new solution. (After all, you're probably not the first person to want to hide the "What's Hot" link. :)) I do think it is a good idea to log these changes though, so you have a list of things to test after service packs or other upgrades (not that I've seen much in the way of HTML Class/ID changes during service packs).
50,888,280
I'm having this error multiple times. How to fix it.. I have solved it without command line arguments but now this is giving me an error. How to solve it with `Integer.parseInt()`. > > > ``` > BubbleSort.java:24: error: incompatible types: String[] cannot be converted to String > int num[] = Integer.parseInt(args); > ^ > Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output 1 error > > ``` > > ``` class Demo { static void bubble(int[] list) { int temp = 0, k , j; int n = list.length; for(k = 0;k < n - 1;k++) { for(j = 0;j < n - k - 1;j++) { if(list[j] > list[j + 1]) { temp = list[j]; list[j] = list[j + 1]; list[j + 1] = temp; } } } } public static void main (String[] args) { int len=args.length; int num[] = Integer.parseInt(args); bubble(num); for(int i = 0;i < len; i++) { System.out.println("Array after bubble sort :" +args[i]); } } } ```
2018/06/16
[ "https://Stackoverflow.com/questions/50888280", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8178732/" ]
The line ``` int num[] = Integer.parseInt(args); ``` is wrong. Look at the error message, it clearly indicates this error: `parseInt(...)` does not take a string array but a single string instead. Replace the line with this: ``` int[] num = new int[args.length]; for (int i = 0; i < args.length; i++) { num[i] = Integer.parseInt(args[i]); } ```
Try this: ``` int num[]; for (int i = 0; i < len; i++) { num[i] = Integer.parseInt(args[i]); } ``` instead of: ``` int num[] = Integer.parseInt(args); ``` This is because `args` variable is an array of strings and the `Integer.parseInt` method take a single string as argument, not an array.
50,888,280
I'm having this error multiple times. How to fix it.. I have solved it without command line arguments but now this is giving me an error. How to solve it with `Integer.parseInt()`. > > > ``` > BubbleSort.java:24: error: incompatible types: String[] cannot be converted to String > int num[] = Integer.parseInt(args); > ^ > Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output 1 error > > ``` > > ``` class Demo { static void bubble(int[] list) { int temp = 0, k , j; int n = list.length; for(k = 0;k < n - 1;k++) { for(j = 0;j < n - k - 1;j++) { if(list[j] > list[j + 1]) { temp = list[j]; list[j] = list[j + 1]; list[j + 1] = temp; } } } } public static void main (String[] args) { int len=args.length; int num[] = Integer.parseInt(args); bubble(num); for(int i = 0;i < len; i++) { System.out.println("Array after bubble sort :" +args[i]); } } } ```
2018/06/16
[ "https://Stackoverflow.com/questions/50888280", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8178732/" ]
The line ``` int num[] = Integer.parseInt(args); ``` is wrong. Look at the error message, it clearly indicates this error: `parseInt(...)` does not take a string array but a single string instead. Replace the line with this: ``` int[] num = new int[args.length]; for (int i = 0; i < args.length; i++) { num[i] = Integer.parseInt(args[i]); } ```
`args` is not a single String. Its an array of Strings. You can use the following code to parse the String array args into an integer array: ``` int[] num= Arrays.stream(args) .mapToInt(Integer::parseInt) .toArray(); ```
60,744,855
I have a python program that runs another python script in a subprocess (yes I know this architecture is not ideal but the nature of the project makes it necessary). I am trying to: **1. send a sigint to the python subprocess (simulate a keyboard kill)** **2. catch the sigint in the subprocess and perform some cleanup before exit** The code follows this general pattern: A.py ``` import signal import subprocess import time proc = subprocess.Popen('python B.py', shell=True) time.sleep(1) proc.send_signal(signal.SIGINT) ``` B.py ``` try: while True: # some application logic pass except: # some cleanup logic print('bye') ``` **But when I run A.py, B.py never receives the signal or does it's cleanup logic. Any idea what is going on here?**
2020/03/18
[ "https://Stackoverflow.com/questions/60744855", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5360657/" ]
Maybe try: ``` #!/usr/local/cpython-3.8/bin/python3 import signal import subprocess import time proc = subprocess.Popen(['python3', 'B.py'], shell=False) time.sleep(1) proc.send_signal(signal.SIGINT) proc.wait() ``` ...as your A.py? I suspect the shell is ignoring SIGINT rather than passing it down to B.py.
Based on the comment below, I launched a Kubuntu VM and it works if you specify `bash` to be used and `shell=False`. The reason is given in the comment, but `/bin/sh` is aliased to `dash` on Debain/Ubuntu (perhaps other distros as well). To determine what your system uses, open a terminal and type `ls -l /bin/sh`. A.py ```py proc = subprocess.Popen(['/bin/bash', '-c', 'python3 B.py'], shell=False) ``` I ran the file with `python3 A.py`. Version: Python 3.6.7. **Prior Answer** It works for me. My thought is perhaps you need to use `python3` in your string. I'm on Arch Linux and `python` is actually `python3`. Here is what I have. A.py ```py proc = subprocess.Popen('python B.py', shell=True) time.sleep(1) proc.send_signal(signal.SIGINT) ``` B.py ```py import time try: while True: time.sleep(0.25) print('running B') except KeyboardInterrupt: print('bye') ``` Output: ```sh running B running B running B bye ```
175,850
Hobbyist here. I think my case/when logic needs to be cleaned up a bit. I'd also appreciate critique on the other parts...but I'm more interested in cleaning up the case/when statements... ``` puts "please assign an integer to x:" x = gets.chomp.to_i if (x > 0) value_of_x = true else value_of_x = false end puts "now please assign an integer to y:" y = gets.chomp.to_i if (y > 0) value_of_y = true else value_of_y = false end case when (value_of_x == true) && (value_of_y == true) puts "two variables are > 0" when ((value_of_x == true) && (value_of_y == false)) || ((value_of_x == false) && (value_of_y == true)) puts "at least one variable is > 0" else puts "no variables are > 0" end ```
2017/09/16
[ "https://codereview.stackexchange.com/questions/175850", "https://codereview.stackexchange.com", "https://codereview.stackexchange.com/users/147381/" ]
The following will simplify your boolean logic, remove repetition in your input processing, and better express what you're really doing: ``` puts "please assign an integer to x:" x = gets.chomp.to_i puts "now please assign an integer to y:" y = gets.chomp.to_i num_positive = (x > 0 ? 1 : 0) + (y > 0 ? 1 : 0) case num_positive when 2 puts "two variables are > 0" when 1 puts "at least one variable is > 0" else puts "no variables are > 0" end ```
`#to_i` is not that picky about trailing whitespace. You don't really need to `#chomp` the input. Your variables `value_of_x` and `value_of_y` are very misleadingly named. You can also simplify their assignment, since `(x > 0)` is a boolean expression that will evaluate to either `true` or `false`. I would rearrange the statements so that all of the input-accepting code appears first. It's a good habit to separate I/O from computation. The `((value_of_x == true) && (value_of_y == false)) || ((value_of_x == false) && (value_of_y == true))` case can be simplified, since the both-positive case has already been eliminated by that point. The `puts` can be factored out, to emphasize that you will print a string no matter which case is true. ``` puts "please assign an integer to x:" x = gets.to_i puts "now please assign an integer to y:" y = gets.to_i x_is_positive = (x > 0) y_is_positive = (y > 0) puts case when x_is_positive && y_is_positive "two variables are > 0" when x_is_positive || y_is_positive "at least one variable is > 0" else "no variables are > 0" end ``` Alternatively, just get rid of the `…_is_positive` variables altogether, for less clutter. ``` puts "please assign an integer to x:" x = gets.to_i puts "now please assign an integer to y:" y = gets.to_i puts case when (x > 0) && (y > 0) "two variables are > 0" when (x > 0) || (y > 0) "at least one variable is > 0" else "no variables are > 0" end ```
1,725,639
Looking at a very simple web project, hosted in IIS, with one simple aspx page, executing some code (get some data from a db and populate some controls), which of the following is true: each page request shares the same instance of the codebehind class. or each page request runs in its own instance of the codebehind class. Does one thread/instance run against each aspx page. Or does one thread/instance cover multiple pages? Im trying to understand, in a simple web project, that receives 100 page requests, will they run consecutively one after the other, or multiple instances/threads for each request?
2009/11/12
[ "https://Stackoverflow.com/questions/1725639", "https://Stackoverflow.com", "https://Stackoverflow.com/users/209978/" ]
* Each request gets a new instance of the code-behind class. * One instance of the code-behind class serves one request. * Two requests at different points in time may run on the same thread from the thread pool. * Two requests that runs in parallell gets one thread each (I think; not 100% sure on if there are some corner cases that I am not aware of regarding the threading). So, a web server can handle several requests in parallell, but there is of course a limit on how many requests that can be served at the same time.
Maybe take a look at asynchronous ASP.NET? <http://msdn.microsoft.com/en-us/magazine/cc163725.aspx> Normally a new thread is assigned to a new request. "A normal, or synchronous, page holds onto the thread for the duration of the request, preventing the thread from being used to process other requests."
1,725,639
Looking at a very simple web project, hosted in IIS, with one simple aspx page, executing some code (get some data from a db and populate some controls), which of the following is true: each page request shares the same instance of the codebehind class. or each page request runs in its own instance of the codebehind class. Does one thread/instance run against each aspx page. Or does one thread/instance cover multiple pages? Im trying to understand, in a simple web project, that receives 100 page requests, will they run consecutively one after the other, or multiple instances/threads for each request?
2009/11/12
[ "https://Stackoverflow.com/questions/1725639", "https://Stackoverflow.com", "https://Stackoverflow.com/users/209978/" ]
* Each request gets a new instance of the code-behind class. * One instance of the code-behind class serves one request. * Two requests at different points in time may run on the same thread from the thread pool. * Two requests that runs in parallell gets one thread each (I think; not 100% sure on if there are some corner cases that I am not aware of regarding the threading). So, a web server can handle several requests in parallell, but there is of course a limit on how many requests that can be served at the same time.
There is one instance of the code behind class for each request. Well, actually it's an instance of the aspx page class, that inherits from the code behind class. (That's why you are using the `protected` keyword for event handlers in code behind, so that the inheriting class can access them.) There is also the case where you do a `Server.Transfer` or `Server.Execute`, then the request is transfered to another page instance. There are several threads running in the IIS handling requests, and usually one request is handled in one thread, but a request can be moved from one thread to another in some situations. If 100 requests arrive at the server, it will start processing a few of them in separate threads, and put the rest of them in a queue. Noteworthy is that the server will only process one page at a time from each user, so unless you use sessionless pages (to make them anonymous) it will not process two pages for the same user in parallel threads, which makes the whole threading part a lot easier.
1,725,639
Looking at a very simple web project, hosted in IIS, with one simple aspx page, executing some code (get some data from a db and populate some controls), which of the following is true: each page request shares the same instance of the codebehind class. or each page request runs in its own instance of the codebehind class. Does one thread/instance run against each aspx page. Or does one thread/instance cover multiple pages? Im trying to understand, in a simple web project, that receives 100 page requests, will they run consecutively one after the other, or multiple instances/threads for each request?
2009/11/12
[ "https://Stackoverflow.com/questions/1725639", "https://Stackoverflow.com", "https://Stackoverflow.com/users/209978/" ]
There is one instance of the code behind class for each request. Well, actually it's an instance of the aspx page class, that inherits from the code behind class. (That's why you are using the `protected` keyword for event handlers in code behind, so that the inheriting class can access them.) There is also the case where you do a `Server.Transfer` or `Server.Execute`, then the request is transfered to another page instance. There are several threads running in the IIS handling requests, and usually one request is handled in one thread, but a request can be moved from one thread to another in some situations. If 100 requests arrive at the server, it will start processing a few of them in separate threads, and put the rest of them in a queue. Noteworthy is that the server will only process one page at a time from each user, so unless you use sessionless pages (to make them anonymous) it will not process two pages for the same user in parallel threads, which makes the whole threading part a lot easier.
Maybe take a look at asynchronous ASP.NET? <http://msdn.microsoft.com/en-us/magazine/cc163725.aspx> Normally a new thread is assigned to a new request. "A normal, or synchronous, page holds onto the thread for the duration of the request, preventing the thread from being used to process other requests."
2,923,450
thanks for checking my work! A deck of cards has 54 cards: 2,3, . . . ,10, Jacks, Queens, Kings, Aces of all four suits, plustwo Jokers. Jokers are assumed to have no suits. We’ll say that a combination of 5 cards is a **flush** if one ofthe following three conditions hold: * All five cards are of the same suit, OR * Four cards are of the same suit and the remaining card is a Joker, OR * Three cards are of the same suit and the remaining 2 cards are Jokers. Compute the probability that 5 randomly chosen cards from the deck give the flush combination. does my solution make sense? all combinations = $54\cdot53\cdot52\cdot51\cdot50$ 5 same suit = $\dbinom{4}{1} \cdot\dbinom{13}{5}$ 4 same suit 1 joker = $\dbinom{4}{1}\cdot\dbinom{13}{4}\cdot\dbinom{2}{1}$ 3 same suit 2 joker = $\dbinom{4}{1}\cdot\dbinom{13}{3}$ so... $\dfrac{\dbinom{4}{1}\cdot\dbinom{13}{5} + \dbinom{4}{1} \cdot\dbinom{13}{4} \cdot\dbinom{2}{1}+\dbinom{4}{1}\cdot\dbinom{13}{3}}{54\cdot53\cdot52\cdot51\cdot50}$
2018/09/20
[ "https://math.stackexchange.com/questions/2923450", "https://math.stackexchange.com", "https://math.stackexchange.com/users/198756/" ]
You have correctly counted combinations for the three favoured cases. Since you are counting combinations in the numerator, you should do so in the denominator too. $$\dfrac{\dbinom{4}{1}\left(\dbinom{13}5\dbinom{2}0+\dbinom{13}4\dbinom{2}1+\dbinom{13}3\dbinom{2}2\right)}{\dbinom{54}{5}}$$ --- Another way to count the numerator: a flush is formed when we select a suit, then select five cards from the fifteen cards that are either of that suit or of the jokers.$$\dfrac{\dbinom 41\dbinom{15}5}{\dbinom{54}5}$$ See also Vandermonde's Identity.
Your answer does make sense. But you should have ${54 \choose 5}$ possible combinations.
45,413,712
I am using `ImageDataGenerator().flow_from_directory(...)` to generate batches of data from directories. After the model builds successfully I'd like to get a two column array of True and Predicted class labels. With `model.predict_generator(validation_generator, steps=NUM_STEPS)` I can get a numpy array of predicted classes. Is it possible to have the `predict_generator` output the corresponding True class labels? To add: validation\_generator.classes does print the True labels but in the order that they are retrieved from the directory, it doesn't take into account the batching or sample expansion by augmentation.
2017/07/31
[ "https://Stackoverflow.com/questions/45413712", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7175454/" ]
You can get the prediction labels by: ``` y_pred = numpy.rint(predictions) ``` and you can get the true labels by: ``` y_true = validation_generator.classes ``` You should set `shuffle=False` in the validation generator before this. Finally, you can print confusion matrix by `print confusion_matrix(y_true, y_pred)`
There's another, slightly "hackier" way, of retrieving the true labels as well. **Note that this approach can handle when setting `shuffle=True` in your generator** (it's generally speaking a good idea to shuffle your data - either if you do this manually where you've stored the data, or through the generator, which is probably easier). You will need your model for this approach though. ``` # Create lists for storing the predictions and labels predictions = [] labels = [] # Get the total number of labels in generator # (i.e. the length of the dataset where the generator generates batches from) n = len(generator.labels) # Loop over the generator for data, label in generator: # Make predictions on data using the model. Store the results. predictions.extend(model.predict(data).flatten()) # Store corresponding labels labels.extend(label) # We have to break out from the generator when we've processed # the entire once (otherwise we would end up with duplicates). if (len(label) < generator.batch_size) and (len(predictions) == n): break ``` Your predictions and corresponding labels should now be stored in `predictions` and `labels`, respectively. Lastly, remember that we should NOT add data augmentation on the validation and test sets/generators.
45,413,712
I am using `ImageDataGenerator().flow_from_directory(...)` to generate batches of data from directories. After the model builds successfully I'd like to get a two column array of True and Predicted class labels. With `model.predict_generator(validation_generator, steps=NUM_STEPS)` I can get a numpy array of predicted classes. Is it possible to have the `predict_generator` output the corresponding True class labels? To add: validation\_generator.classes does print the True labels but in the order that they are retrieved from the directory, it doesn't take into account the batching or sample expansion by augmentation.
2017/07/31
[ "https://Stackoverflow.com/questions/45413712", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7175454/" ]
You can get the prediction labels by: ``` y_pred = numpy.rint(predictions) ``` and you can get the true labels by: ``` y_true = validation_generator.classes ``` You should set `shuffle=False` in the validation generator before this. Finally, you can print confusion matrix by `print confusion_matrix(y_true, y_pred)`
Using `np.rint()` method will get one hot coding result like [1., 0., 0.] which once I've tried creating a confusion matrix with `confusion_matrix(y_true, y_pred)` it caused error. Because `validation_generator.classes` returns class labels as a single number. In order to get a class number for example 0, 1, 2 as class label specified, I have found the selected answer in this topic useful. [here](https://stackoverflow.com/a/48909971/15510504)
45,413,712
I am using `ImageDataGenerator().flow_from_directory(...)` to generate batches of data from directories. After the model builds successfully I'd like to get a two column array of True and Predicted class labels. With `model.predict_generator(validation_generator, steps=NUM_STEPS)` I can get a numpy array of predicted classes. Is it possible to have the `predict_generator` output the corresponding True class labels? To add: validation\_generator.classes does print the True labels but in the order that they are retrieved from the directory, it doesn't take into account the batching or sample expansion by augmentation.
2017/07/31
[ "https://Stackoverflow.com/questions/45413712", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7175454/" ]
There's another, slightly "hackier" way, of retrieving the true labels as well. **Note that this approach can handle when setting `shuffle=True` in your generator** (it's generally speaking a good idea to shuffle your data - either if you do this manually where you've stored the data, or through the generator, which is probably easier). You will need your model for this approach though. ``` # Create lists for storing the predictions and labels predictions = [] labels = [] # Get the total number of labels in generator # (i.e. the length of the dataset where the generator generates batches from) n = len(generator.labels) # Loop over the generator for data, label in generator: # Make predictions on data using the model. Store the results. predictions.extend(model.predict(data).flatten()) # Store corresponding labels labels.extend(label) # We have to break out from the generator when we've processed # the entire once (otherwise we would end up with duplicates). if (len(label) < generator.batch_size) and (len(predictions) == n): break ``` Your predictions and corresponding labels should now be stored in `predictions` and `labels`, respectively. Lastly, remember that we should NOT add data augmentation on the validation and test sets/generators.
Using `np.rint()` method will get one hot coding result like [1., 0., 0.] which once I've tried creating a confusion matrix with `confusion_matrix(y_true, y_pred)` it caused error. Because `validation_generator.classes` returns class labels as a single number. In order to get a class number for example 0, 1, 2 as class label specified, I have found the selected answer in this topic useful. [here](https://stackoverflow.com/a/48909971/15510504)
172,261
I'm a relative newcomer to D&D 5th Ed. and am playing a druid fond of Wild Shape. I'd like to know in what ways it can be detected by NPCs (or even fellow PCs). It appears that this is a sort of debated subject, as to how and whether Detect Magic works on it or not. I read through the question, [Detecting Wild Shape with a Mythal](https://rpg.stackexchange.com/q/72009/1546), but I've no idea what a Mythal is. In portions of the question and its answers, there seems to be various interpretations of how Detect Magic might work (or not). It seems to me that the ability is a sort of innate or supernatural ability, and whether it is "magical" or not is somewhat ambiguous. My reason for asking is that Detect Magic seems to be a relatively low-level spell and thus makes Wild Shape (for espionage, surveillance, scouting, etc.) somewhat less dependable. In [another answer by Neil Slater](https://rpg.stackexchange.com/a/83496/1546), this excerpt seems applicable: > > ...the consensus in groups I have played in ... is that Detect Magic is equivalent to "Detect Spells, Spell-like Effects and Enchantments". That is, it will detect spells in progress, spell-like powers of monsters, and permanent enchantments on scrolls, and standard magic weapons. Under that interpretation, will not detect supernatural powers, such as a druid's Wild Shape... > > > Is there a more recent consensus on how this mechanic might work? Finally, Detect Magic aside, in what *other* ways can a druid's Wild Shape be detected or nullified?
2020/07/20
[ "https://rpg.stackexchange.com/questions/172261", "https://rpg.stackexchange.com", "https://rpg.stackexchange.com/users/1546/" ]
Truesight --------- > > A monster with Truesight can, out to a specific range, [...] perceive the original form of a Shapechanger or a creature that is transformed by magic. > > > This is supported by [this answer](https://rpg.stackexchange.com/a/96248/56975). Truesight can be obtained by casting the 6th level spell True Seeing, which lasts one hour without concentration. Needless to say this spell comes at a high cost and is the ultimate tool for finding a magically concealed intruder. Detect Magic ------------ Wild Shape is a magical effect: > > Starting at 2nd Level, you can use your action to **magically** assume the shape of a beast that you have seen before. > > > therefore it can be detected by Detect Magic, which unambiguously states the following: > > For the duration, you sense the presence of magic within 30 feet of you. If you sense magic in this way, you can use your action to see a faint aura around any visible creature or object in the area that bears magic, and you learn its school of magic, if any. > > > Is Wildshape useless for infiltration? -------------------------------------- No. The basic implication here is that Wildshape is not an effective tool against magic users that are *actively* looking for an intruder. This does not mean that it's useless. It's a pretty steep cost for a spell caster to continuously consume 6th level spell slots to cast True Seeing or 1st level spells slot to cast Detect Magic just in the off chance that a druid is nearby. A creature using the spell in this way is certain to run out of spell slots after a short period of time. If, instead, they're using ritual casting for Detect Magic, they'll be continuously occupied and there will be 10 minute gaps between each casting. These gaps could be the perfect time for a Druid to sneak past them. Patience is on the side of the Druid. They can simply wait while a spell caster exhausts both their time, resources, and patience looking for them, before casually sauntering past them in whatever discreet form they please.
It's a special case (it would only apply to some specific animal forms with an INT of 3 or lower), but casting *Detect Thoughts* could reveal that something is abnormal about the creature (though it wouldn't reveal a Druid in Wild Shape, specifically). Since *Detect Thoughts* has no effect on creatures with INT 3 or lower, casting the spell on such a creature would normally have no effect. But if you start actually detecting some thoughts, then some response may be warranted. This is an inferior solution to *Detect Magic*, already covered well by Andrendire, but for completeness' sake this is another (potentially) workable option.
28,259,498
I need to write logic to break down a 4 digit number into individual digits. On a reply here at SO to a question regarding 3 digits, someone gave the math below: ``` int first = 321/100; int second = (321/10)-first*10; int third = (321/1)-first*100-second*10; ``` Can someone help me? Thank you in advance!
2015/02/01
[ "https://Stackoverflow.com/questions/28259498", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4505832/" ]
Well, using the sample you found, we can quite easily infer a code for you. The first line says `int first = 321/100;`, which returns 3 (integer division is the euclidian one). 3 is indeed the first integer in 321 so that's a good thing. However, we have a 4 digit number, let's try replacing 100 with 1000: ``` int first = 4321/1000; ``` This does return 4 ! Let's try adapting the rest of your code (plus I put your four digit number in the variable `entry`). ``` int entry = 4321; int first = entry/1000; int second = entry/100 - first*10; int third = entry/10 - first*100 - second*10; int fourth = entry - first*1000 - second*100 - third*10; ``` `second` will be `entry/100` (43) minus `first*10` (40), so we're okay. `third` is then `432 - 400 - 30` which turns to 2. This also works till `fourth`. For more-than-four digits, you may want to use a for-loop and maybe some modulos though.
This snip of code counts the number of digits input from the user then breaks down the digits one by one: ``` PRINT "Enter value"; INPUT V# X# = V# DO IF V# < 1 THEN EXIT DO END IF D = D + 1 V# = INT(V#) / 10 LOOP PRINT "Digits:"; D FOR L = D - 1 TO 0 STEP -1 M = INT(X# / 10 ^ L) PRINT M; X# = X# - M * 10 ^ L NEXT END ```
575,880
In QED, when two photons collide, they can turn into an electron and positron pair. We know from $U(1)$ gauge symmetry that the total charge of the initial and final states must be conserved. On the other hand, I expect that the total spin must also be conserved. But I do not quite get the details of how this works. In this [post](https://physics.stackexchange.com/q/265215/) the total spin of two-photon-state is discussed. Based on the transversality argument, OP argues there are three distinct spin states associated with the two-photon system. Two of them correspond to the spin-0 representation and the remaining one corresponds to a spin-2 state. Based on the above argument, if the total spin in pair production is to be conserved, I would assume that the incoming photons must be in the spin-0 state, excluding the spin-2 state because the spin-state of the created electron-positron pair does not have a spin-2 representation. As far as I know, this spin state can have one spin-0 rep. and three spin-1 rep. **Edit**: Also, in Wikipedia [page](https://en.wikipedia.org/wiki/Landau%E2%80%93Yang_theorem) there is Landau–Yang theorem, stating that a massive particle with spin 1 cannot decay into two photons. I suspect this selection rule follows from the requirement of the conservation of the total spin. Because as suggested in the linked question two-photon state does not have a spin-1 rep. Is this reasoning correct? The second point is about symmetry. If the total spin is to be conserved, what is the associated symmetry? I am thinking it must the rotational invariance of pair production amplitude. But what do the generators of this rotational symmetry look like? and where do they act? These generators must not correspond to the ordinary rotations in space. Because this would correspond to the conservation of orbital angular momentum, not spin.
2020/08/27
[ "https://physics.stackexchange.com/questions/575880", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/105637/" ]
Spin angular momentum is not conserved; only the sum of spin and orbital angular momentum is conserved. As a trivial example of this, consider a hydrogen atom decaying from $2p$ to $1s$ by emitting a photon. The photon carries one unit of angular momentum, but the spin of the electron doesn't change; instead orbital angular momentum is lost. Furthermore, in many situations you can't even unambiguously define the two separately (how much of the proton's angular momentum is due to the angular momentum of its constituents?), so "conservation of spin" is not even meaningful. Conservation of total angular momentum is always meaningful, because it's the conserved quantity associated with rotational symmetry. > > Based on the above argument, if the total spin in pair production is to be conserved, I would assume that the incoming photons must be in the spin-0 state, excluding the spin-2 state because the spin-state of the created electron-positron pair does not have a spin-2 representation. As far as I know, this spin state can have one spin-0 rep. and three spin-1 rep. > > > No, because the electron and positron can come out in the $p$-wave, carrying orbital angular momentum. This is called $p$-wave annihilation, and it's not an exotic phenomenon; for instance, it shows up in the partial wave expansion in undergraduate quantum mechanics. > > Landau–Yang theorem, stating that a massive particle with spin 1 cannot decay into two photons. I suspect this selection rule follows from the requirement of the conservation of the total spin. > > > The Landau-Yang theorem doesn't state that spin is conserved. Essentially, it uses the fact that total angular momentum is conserved, along with the fact that in this simple situation, there is no orbital angular momentum: you can always go to the rest frame of the massive particle, and in that frame the photons always come out back to back.
In the Feynman diagram below time runs from left to right. Indeed a 2-spin state for two photons can have eigenvalues 2, 0, and-2. That is three eigenstates at least. I'm sure you are right we have to consider the combined (2-photon) state. If that's the case then this state **got** to have a spin-0, precisely because of the fact that the positron-electron-state *got* to be in a spin-0 state. When you consider the states of the photons separately (at the vertices) you have to consider the spins of two real and one virtual particle (the propagator electron-positron). In this case, too, it holds that the photons at both vertices **got** to be a spin-0 state. I'll don't bother you with the math. That would require too much space in this answer and it can be found in any book on QFT. [![enter image description here](https://i.stack.imgur.com/v0SMj.png)](https://i.stack.imgur.com/v0SMj.png) Considering your second question. What generator of which symmetry we have to consider? This symmetry obviously has got something to do with rotation (as spin does, intuitively, although spin isn't a rotation in common sense). Like @anna v rightly remarked it's the conservation of angular momentum one has to consider. If angular momentum is zero, as we assume in this case, to account for the spins one can't apply the normal generators for the conservation of angular momentum. So automatically the spin states will be as they are. And they are just as your reasoning told you (and us).
41,778,074
I want to save complete web page asp in local drive by `.htm` from [url](https://www.digikala.com/Search/Category-Motherboard/#!/Category-Electronic-Devices/Category-Computer-Parts/Category-Computer-Devices/Category-Motherboard/) or [url](https://www.digikala.com) but I did not success. **Code** ``` public StreamReader Fn_DownloadWebPageComplete(string link_Pagesource) { //--------- Download Complete ------------------ // using (WebClient client = new WebClient()) // WebClient class inherits IDisposable // { //client //HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(link_Pagesource); //webRequest.AllowAutoRedirect = true; //var client1 = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(link_Pagesource); //client1.CookieContainer = new System.Net.CookieContainer(); // client.DownloadFile(link_Pagesource, @"D:\S1.htm"); // } //--------- Download Page Source ------------------ HttpWebRequest URL_pageSource = (HttpWebRequest)WebRequest.Create("https://www.digikala.com"); URL_pageSource.Timeout = 360000; //URL_pageSource.Timeout = 1000000; URL_pageSource.ReadWriteTimeout = 360000; // URL_pageSource.ReadWriteTimeout = 1000000; URL_pageSource.AllowAutoRedirect = true; URL_pageSource.MaximumAutomaticRedirections = 300; using (WebResponse MyResponse_PageSource = URL_pageSource.GetResponse()) { str_PageSource = new StreamReader(MyResponse_PageSource.GetResponseStream(), System.Text.Encoding.UTF8); pagesource1 = str_PageSource.ReadToEnd(); success = true; } ``` Error : > > Too many automatic redirections were attempted. > > > Attemp by this codes but not successful. many url is successful with this codes but this url not successful.
2017/01/21
[ "https://Stackoverflow.com/questions/41778074", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7307673/" ]
here is the way ``` string url = "https://www.digikala.com/"; using (HttpClient client = new HttpClient()) { using (HttpResponseMessage response = client.GetAsync(url).Result) { using (HttpContent content = response.Content) { string result = content.ReadAsStringAsync().Result; } } } ``` and `result` variable will contains the page as `HTML` then you can save it to a file like this ``` System.IO.File.WriteAllText("path/filename.html", result); ``` **NOTE** you have to use the namespace ``` using System.Net.Http; ``` **Update** if you are using legacy VS then you can see this [answer](https://stackoverflow.com/questions/599275/) for using `WebClient` and `WebRequest` for the same purpose, but Actually updating your VS is a better solution.
``` using (WebClient client = new WebClient ()) { string htmlCode = client.DownloadString("https://www.digikala.com"); } ```
41,778,074
I want to save complete web page asp in local drive by `.htm` from [url](https://www.digikala.com/Search/Category-Motherboard/#!/Category-Electronic-Devices/Category-Computer-Parts/Category-Computer-Devices/Category-Motherboard/) or [url](https://www.digikala.com) but I did not success. **Code** ``` public StreamReader Fn_DownloadWebPageComplete(string link_Pagesource) { //--------- Download Complete ------------------ // using (WebClient client = new WebClient()) // WebClient class inherits IDisposable // { //client //HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(link_Pagesource); //webRequest.AllowAutoRedirect = true; //var client1 = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(link_Pagesource); //client1.CookieContainer = new System.Net.CookieContainer(); // client.DownloadFile(link_Pagesource, @"D:\S1.htm"); // } //--------- Download Page Source ------------------ HttpWebRequest URL_pageSource = (HttpWebRequest)WebRequest.Create("https://www.digikala.com"); URL_pageSource.Timeout = 360000; //URL_pageSource.Timeout = 1000000; URL_pageSource.ReadWriteTimeout = 360000; // URL_pageSource.ReadWriteTimeout = 1000000; URL_pageSource.AllowAutoRedirect = true; URL_pageSource.MaximumAutomaticRedirections = 300; using (WebResponse MyResponse_PageSource = URL_pageSource.GetResponse()) { str_PageSource = new StreamReader(MyResponse_PageSource.GetResponseStream(), System.Text.Encoding.UTF8); pagesource1 = str_PageSource.ReadToEnd(); success = true; } ``` Error : > > Too many automatic redirections were attempted. > > > Attemp by this codes but not successful. many url is successful with this codes but this url not successful.
2017/01/21
[ "https://Stackoverflow.com/questions/41778074", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7307673/" ]
here is the way ``` string url = "https://www.digikala.com/"; using (HttpClient client = new HttpClient()) { using (HttpResponseMessage response = client.GetAsync(url).Result) { using (HttpContent content = response.Content) { string result = content.ReadAsStringAsync().Result; } } } ``` and `result` variable will contains the page as `HTML` then you can save it to a file like this ``` System.IO.File.WriteAllText("path/filename.html", result); ``` **NOTE** you have to use the namespace ``` using System.Net.Http; ``` **Update** if you are using legacy VS then you can see this [answer](https://stackoverflow.com/questions/599275/) for using `WebClient` and `WebRequest` for the same purpose, but Actually updating your VS is a better solution.
``` using (WebClient client = new WebClient ()) { client.DownloadFile("https://www.digikala.com", @"C:\localfile.html"); } ```
11,342,371
I'm using a CDN (maxcdn.com) for js, css and images on a web site. I've noticed that from some ISP's, those resources either completely fail to load or load very slowly. However, local static serving from my server always works fine. Therefore, I want to be able to detect such resource loading failures and respond to them by falling back to local serving. I've found here several solutions for detecting js and css loading failures. The most common is to check for some js var and some cssRules from css using embedded js (positioned just before the , after the script and link tags). However, this doesn't allow to: 1. detect slow loading (fallback should start as soon as slowness is detected…) 2. detect load failures for images referenced from css. **Is there any simple, elegant way to detect resources loading failures/slowness and quickly fall back to local serving?**
2012/07/05
[ "https://Stackoverflow.com/questions/11342371", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1491837/" ]
As noted here <https://stackoverflow.com/a/2021325/745190> there's no way to disable a script after starting to load it. You could try loading a very small (.1kb) script initially from the cdn. Test that script after a very small space of time, if it downloads use javascript to append the other script tags to your page, if it doesn't it's a small file unnecessarily downloaded. Sadly this method has two major drawbacks. The first is that there's an extra query to the cdn, the second is that failure to load the small script altogether might lead your browser wheel to keep spinning. the test if you're unsure is something like this: ``` /* tiny-file.js */ var window.speedTest = true; ``` and ``` /* The test */ setTimeout(function(){ if (window.speedTest !== true) { //append local javascript } else { //append cdn javascript } }, 50); ```
I suspect that your issue will mostly occur with some ISPs. If your main goal is to achieve performance while keeping the CDN as the main solution, I can see tow options. The first, you try to identify failing ISPs but it might be pretty long and expensive. Another option is to "learn". Try to load a trivial JS setting a variable from the CDN. If it fails, you can assume there is a problem. Set a cookie and use it on the next page load to automatically load everything from your main server.
89,608
Suppose I want a line legend for a list plot: ``` dat = RandomReal[{.8, 1.2}, 40]*Range@40; ListPlot[Transpose@{Range@40, dat}, PlotLegends -> Placed[LineLegend[{Style["I want a line legend!!!", 18]}], {.4, .8}]] ``` However, the output doesn't show a line legend but something that looks like a point legend: [![enter image description here](https://i.stack.imgur.com/kJPdg.gif)](https://i.stack.imgur.com/kJPdg.gif) I use Mathematica 10.0.2 on Windows 7. Is this a bug?
2015/07/31
[ "https://mathematica.stackexchange.com/questions/89608", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/19991/" ]
~~This is not a bug.~~ I *think* that this is not a bug, see addendum. Based on my (limited!) experience, I believe that `LineLegend` and `PointLegend` are in fact the very same thing with differing default options. `LineLegend` has `Joined -> True` while `PointLegend` has `Joined -> False` by default, but otherwise they are identical. The syntax you used, i.e. `LineLegend[{"label1", "label2", ...}]` causes the legend to inherit the style from the plot, which means `Joined -> False`. You can fix this by specifying the option manually. ``` LineLegend[{Style["I want a line legend!!!", 18]}, Joined -> True] ``` If you use `PointLegend` instead, it will do the same thing. The only important factor is the values of the `Joined` option. If you use these legends outside of the `PlotLegends` option of some type of plot, they will not inherit any options and will behave as their name would suggest (and as determined by their default options). --- ### Addendum Harry points out that in version 9 these legends do not inherit the `Joined` option from the parent plot, thus `LineLegend` always gives a line and `PointLegend` always gives a point. Should we consider this behaviour change a breakage in v10? I don't think so because the v9 behaviour also causes problems. In v9, `ListPlot[Transpose@{Range@40, dat}, PlotLegends -> {"label"}, Joined -> True]` uses a point legend, even though the plot has a line. This seems to have been fixed in v10 by causing the legend to inherit the `Joined` option from the parent.
``` $Version ``` > > "10.2.0 for Mac OS X x86 (64-bit) (July 7, 2015)" > > > ``` dat = Transpose@{Range@40, RandomReal[{.8, 1.2}, 40]*Range@40}; Legended[ ListPlot[dat], Placed[ LineLegend[{Blue}, {Style["I want a line legend!!!", 14]}], {.3, .8}]] ``` [![enter image description here](https://i.stack.imgur.com/L1CKy.png)](https://i.stack.imgur.com/L1CKy.png)
59,898,911
I have installed net-snmp 5.8 on a Ubuntu 16.0.4 machine and then I have checked the correct installation: snmpget --version NET-SNMP version: 5.8 Next, I am trying to write and compile my first SNMP C program example. I have copied the one that is included as example on the tutorial from Ben Rockwood ("The Net-SNMP Programming Guide) and I have tried to compile it with the command: ``` gcc ‘net-snmp-config --cflags‘ ‘net-snmp-config --libs‘ \ > ‘net-snmp-config --external-libs‘ snmp_test.c -o snmp_test ``` As indicated in this tutorial. When do, I get the errors: gcc: error: unrecognized command line option ‘--cflags‘’ gcc: error: unrecognized command line option ‘--libs‘’ gcc: error: unrecognized command line option ‘--external-libs‘’ Then I have changed the gcc command to: gcc `net-snmp-config --cflags` `net-snmp-config --libs` \ > > `net-snmp-config --external-libs` snmp\_test.c -o snmp\_test > > > And get the error: bash: `net-snmp-config --external-libs`: ambiguous redirect What is wrong on the gcc call? Any comments or suggestions are welcome.
2020/01/24
[ "https://Stackoverflow.com/questions/59898911", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10528160/" ]
The only way (unfortunately) you can do this is iteratively; which means using an rCTE. **Assuming** that `Percentage` can't be a negative value: ``` CREATE TABLE dbo.Table1 (ID int, [Percentage] int, --Ideally you should store percentages as a decimal, that is what that are after all. E.g. 10% = 0.10. FKID int); CREATE TABLE dbo.Table2 (ID int, Amount decimal(5, 1)); GO INSERT INTO dbo.Table1 (ID, [Percentage], FKID) VALUES (1, 5, 1), (2, 10, 1), (3, 4, 1); GO INSERT INTO dbo.Table2 (ID, Amount) VALUES (1, 100); GO SELECT T2.ID AS ID2, T1.ID AS ID1, CONVERT(decimal(6, 2), T2.Amount * ((100 - T1.[Percentage]) / 100.0)) AS Amount FROM dbo.Table2 T2 JOIN dbo.Table1 T1 ON T2.ID = T1.ID WHERE T1.ID = 1; GO WITH rCTE AS (SELECT T2.ID AS ID2, T1.ID AS ID1, CONVERT(decimal(6, 2), T2.Amount * ((100 - T1.[Percentage]) / 100.0)) AS Amount FROM dbo.Table2 T2 JOIN dbo.Table1 T1 ON T2.ID = T1.ID WHERE T1.ID = 1 UNION ALL SELECT r.ID2, T1.ID, CONVERT(decimal(6, 2), r.Amount * ((100 - T1.[Percentage]) / 100.0)) FROM rCTE r JOIN dbo.Table1 T1 ON r.ID2 = T1.FKID AND r.ID1 + 1 = T1.ID) SELECT MIN(r.Amount) FROM rCTE r GROUP BY r.ID2; GO DROP TABLE dbo.Table1; DROP TABLE dbo.Table2; ```
If the goal is to merely calculate a variable for a given Table2.ID ? Then that method you used can work for it. But tables contain unordered sets. So you need to include an `ORDER BY` to respect the order that the percentages are subtracted. **Sample data:** > > > ``` > CREATE TABLE Table2 ( > ID INT IDENTITY(1,1) PRIMARY KEY, > Amount INT > ); > > INSERT INTO Table2 (Amount) VALUES > (100),(100) > ; > > CREATE TABLE Table1 ( > ID INT IDENTITY(1,1) PRIMARY KEY, > Percentage INT NOT NULL, > FKID INT NOT NULL, > FOREIGN KEY (FKID) REFERENCES Table2(ID) > ); > > INSERT INTO Table1 > (Percentage, FKID) VALUES > (5,1), (10,1), (4,1), > (30,2), (25,2), (20,2) > > ``` > > **T-Sql:** > > > ``` > DECLARE @Id INT = 1; > > DECLARE @qty FLOAT; > SELECT @qty = Amount > FROM Table2 > WHERE ID = @Id; > > SELECT > @qty = @qty-((@qty/100.0)*t1.Percentage) > FROM Table1 t1 > WHERE t1.FKID = @Id > ORDER BY t1.ID; > > SELECT CAST(@qty AS DECIMAL(16,2)) AS qty > > ``` > > > ``` > > | qty | > | :---- | > | 82.08 | > > ``` > > A test on *db<>fiddle [here](https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=c5a3a9931ac2b68454e102c4cca5ca33)*
59,898,911
I have installed net-snmp 5.8 on a Ubuntu 16.0.4 machine and then I have checked the correct installation: snmpget --version NET-SNMP version: 5.8 Next, I am trying to write and compile my first SNMP C program example. I have copied the one that is included as example on the tutorial from Ben Rockwood ("The Net-SNMP Programming Guide) and I have tried to compile it with the command: ``` gcc ‘net-snmp-config --cflags‘ ‘net-snmp-config --libs‘ \ > ‘net-snmp-config --external-libs‘ snmp_test.c -o snmp_test ``` As indicated in this tutorial. When do, I get the errors: gcc: error: unrecognized command line option ‘--cflags‘’ gcc: error: unrecognized command line option ‘--libs‘’ gcc: error: unrecognized command line option ‘--external-libs‘’ Then I have changed the gcc command to: gcc `net-snmp-config --cflags` `net-snmp-config --libs` \ > > `net-snmp-config --external-libs` snmp\_test.c -o snmp\_test > > > And get the error: bash: `net-snmp-config --external-libs`: ambiguous redirect What is wrong on the gcc call? Any comments or suggestions are welcome.
2020/01/24
[ "https://Stackoverflow.com/questions/59898911", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10528160/" ]
You're looking for the result of this expression since it doesn't matter the order of the multiplication. ``` 100 * (0.95 * 0.9 * 0.96) ``` You can emulate chaining the products using `LOG`, `SUM`, and `EXP` to get the desired result ```sql SELECT val.ID, EXP(SUM(LOG(0.01*(100-Percentage)))) * MAX(Amount) FROM percents INNER JOIN val ON percents.FKID = val.ID GROUP BY val.ID; ``` <http://sqlfiddle.com/#!18/60c27/1>
If the goal is to merely calculate a variable for a given Table2.ID ? Then that method you used can work for it. But tables contain unordered sets. So you need to include an `ORDER BY` to respect the order that the percentages are subtracted. **Sample data:** > > > ``` > CREATE TABLE Table2 ( > ID INT IDENTITY(1,1) PRIMARY KEY, > Amount INT > ); > > INSERT INTO Table2 (Amount) VALUES > (100),(100) > ; > > CREATE TABLE Table1 ( > ID INT IDENTITY(1,1) PRIMARY KEY, > Percentage INT NOT NULL, > FKID INT NOT NULL, > FOREIGN KEY (FKID) REFERENCES Table2(ID) > ); > > INSERT INTO Table1 > (Percentage, FKID) VALUES > (5,1), (10,1), (4,1), > (30,2), (25,2), (20,2) > > ``` > > **T-Sql:** > > > ``` > DECLARE @Id INT = 1; > > DECLARE @qty FLOAT; > SELECT @qty = Amount > FROM Table2 > WHERE ID = @Id; > > SELECT > @qty = @qty-((@qty/100.0)*t1.Percentage) > FROM Table1 t1 > WHERE t1.FKID = @Id > ORDER BY t1.ID; > > SELECT CAST(@qty AS DECIMAL(16,2)) AS qty > > ``` > > > ``` > > | qty | > | :---- | > | 82.08 | > > ``` > > A test on *db<>fiddle [here](https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=c5a3a9931ac2b68454e102c4cca5ca33)*
20,580,064
please help me some error is display for this line: ``` mediaElement1.MediaOpened += new RoutedEventHandler(mediaElement1.MediaOpened); ``` Error: > > Error 1 The event ‘System.Windows.Controls.MediaElement.MediaOpened’ can only appear on the left hand side of += or -= > > > Please help me how to solve the problem.
2013/12/14
[ "https://Stackoverflow.com/questions/20580064", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3101564/" ]
As the message says, you're placing `mediaElement1.MediaOpened` on the right-hand side: ``` mediaElement1.MediaOpened += new RoutedEventHandler(mediaElement1.MediaOpened); ^ //Can't place it here ``` You'll need to create the `RoutedEventHandler` in a different way.
With respect to events, such as MediaOpened, the += operator is used to add a delegate/method to take some action on said event. In this case you're interested in the MediaOpened event so you'll want something like: ``` mediaElement1.MediaOpened += new RoutedEventHandler(this.OnMediaOpened); private void OnMediaOpened(object sender, RoutedEventArgs e) { // TODO - Handle the MediaOpened event here } ```
20,580,064
please help me some error is display for this line: ``` mediaElement1.MediaOpened += new RoutedEventHandler(mediaElement1.MediaOpened); ``` Error: > > Error 1 The event ‘System.Windows.Controls.MediaElement.MediaOpened’ can only appear on the left hand side of += or -= > > > Please help me how to solve the problem.
2013/12/14
[ "https://Stackoverflow.com/questions/20580064", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3101564/" ]
As the message says, you're placing `mediaElement1.MediaOpened` on the right-hand side: ``` mediaElement1.MediaOpened += new RoutedEventHandler(mediaElement1.MediaOpened); ^ //Can't place it here ``` You'll need to create the `RoutedEventHandler` in a different way.
I am not sure what you are actually trying to do. if you wanna do some logic when mediaElement1.MediaOpened event occur, then you need to create a method and put your code to do the logic in that method. ``` private void mediaElement1_MediaOpened(object sender, RoutedEventArgs e) { //Put your logic here } ``` Then register above method to handle mediaElement1.MediaOpened event with one of the following code ``` //option 1: just like your existing code with correction mediaElement1.MediaOpened += new RoutedEventHandler(mediaElement1_MediaOpened); //option 2: brief version of option 1 mediaElement1.MediaOpened += mediaElement1_MediaOpened; //option 3: register in xaml instead of c# <MediaElement x:Name="mediaElement1" MediaOpened="mediaElement1_MediaOpened"/> ```
45,336,249
I have two very large tables (one with over 500 M records and the other with over 1B records) I need to update status of the record in table one if one of the fields in table two contains more than 4 Char(10) characters in a row. When I look for the records that meet that criteria it takes approximately 10 min - ``` SELECT B.ID as main_id FROM Table A, TABLE B WHERE A.CREATED_DATE > TRUNC(SYSDATE -1) AND A.STATUS_CODE = 'IN PROGRESS' AND A.ID = B.ID AND (REGEXP_COUNT(B.TEXT, CHR(10) || '{4},1,'mn')) > 0 ``` Now, I need to look up all of the records in table A and update status field to FAIL based on the query above. Basically I am suing above as a sub-query for the update. However, when I do that, my update statements run for a very long time where I would expect it to run slightly longer than 10 minutes (above query returns only 2 records back). Here is what I have --> ``` MERGE INTO TABLE A USING (SELECT B.ID as main_id FROM Table A, TABLE B WHERE A.CREATED_DATE > TRUNC(SYSDATE -1) AND A.STATUS_CODE = 'IN PROGRESS' AND A.ID = B.ID AND (REGEXP_COUNT(B.TEXT, CHR(10) || '{4},1,'mn')) > 0) CHECK_ERRORS ON (A.ID = CHECK_ERRORS.main_id) WHEN MATCHED THEN UPDATE SET A.STATUS_CODE = 'FAILED' ``` What am I doing wrong here? Thank you
2017/07/26
[ "https://Stackoverflow.com/questions/45336249", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8372238/" ]
What you are doing wrong is that you are unnecessarily joining the first table twice: once in the subquery (which already does the work needed in `MERGE`) and again in the `ON` clause of `MERGE`. The `MERGE` statement should be something like this: ``` merge into table_a a using table_b b on ( a.id = b.id ) when matched then update set a.status_code = 'FAILED' where a.created_date > trunc(sysdate - 1) and a.status_code = 'IN PROGRESS' and b.text like '%' || chr(10) || chr(10) || chr(10) || chr(10) || '%' ; ``` It will also help speed up the processing if you had indexes on the `id` columns in both tables, and perhaps also on `created_date`, assuming only a small fraction of rows fall within the last day or so.
Hmm. Wouldn't it be faster to use `B.TEXT LIKE '%'||CHR(10)||CHR(10)||CHR(10)||CHR(10)||'%'` instead of `REGEXP_COUNT`? Admittedly, I don't use MERGE very often, but if you're just doing updates, I would write the second statement like this: ``` UPDATE A SET A.STATUS_CODE = 'FAILED' WHERE A.CREATED_DATE > TRUNC(SYSDATE -1) AND A.STATUS_CODE = 'IN PROGRESS' AND A.ID IN (SELECT B.ID FROM B WHERE B.TEXT LIKE '%'||CHR(10)||CHR(10)||CHR(10)||CHR(10)||'%'); ``` (I'm assuming based on your code that you meant the Table 2 field contains 4+ CHR10 characters, not "more than 4")
97,240
I am trying to hide certain user names from the the lightdm login screen (Ubuntu 11.10) I have found a work round by messing with uid's. In getting this solution I have found in my /etc/passwd file a user name ending in $ sign,what does this mean?
2012/01/21
[ "https://askubuntu.com/questions/97240", "https://askubuntu.com", "https://askubuntu.com/users/42895/" ]
If you are running [Samba](http://www.samba.org/) in domain controller mode (NT4), usernames ending with a "$" usually mean a (Windows) machine account joined to the domain. Samba uses this to distinguish machine accounts from user accounts. <http://www.samba.org/samba/docs/using_samba/ch04.html#FNPTR-2>
Can you past an example ? My guess with your user name would be a typo. At any rate, to hide users in lightdm, edit `/etc/lightdm/users.conf` ``` # Graphical gksu gedit /etc/lightdm/users.conf # command line sudo -e /etc/lightdm/users.conf ``` To hide only some users add to the "hidden-users" line ``` hidden-users=nobody nobody4 noaccess user1 user2 ``` Users are separated by a space ;) To hide all users use ``` greeter-hide-users=true ``` As it turns out , there is a bug in lightdm such that it does not honor those settings in 11.10 or 12.04 See <https://bugs.launchpad.net/ubuntu/+source/accountsservice/+bug/857651> While you are there, add yourself to the "affects me too" You can , however, work around this by editing `/etc/lightdm/lightdm.conf` and adding the line (under [SeatDefaults] ) ``` [SeatDefaults] greeter-hide-users=true ```
54,812,273
Using ionic 3 on a desktop. I have a list of items. Each item can be edited and then the changes saved or cancelled. If I hit edit and the input box opens, I want to be able to close the edit/input box by hitting escape. I also have an alert controller to add an item to the list. I would like the alert controller to go away upon hitting escape. Neither of these functions work now, and I'm not sure how to add them. I've searched the ionic docs, but I guess I am not understanding them. Here is the code: settings.ts ``` itemTapped(item) { this.selectedItem = item; this.selectedItem.wasClicked = true; console.log(this.selectedItem); this.addTable = true; this.refreshRows(); } refreshRows() { this.editRowIndex = null; this.selectedItem.service.find() .subscribe(data => { this.rows = data; console.log("The data id is: " + data.id); }); } cancelTapped() { this.addTable = false; } addTapped(event, cell, rowIndex) { const prompt = this.alertCtrl.create({ title: "Add " + this.selectedItem.label.slice(0, this.selectedItem.label.length-this.selectedItem.trimSingle), cssClass: 'buttonCss', enableBackdropDismiss: false, inputs: [ { name: 'name', } ], buttons: [ { text: 'Cancel', cssClass: 'item-button button button-md button-outline button-outline-md' }, { text: 'Save', handler: data => { this.saveNewRow(data); }, cssClass: 'buttonColor item-button button button-md button-default button-default-md button-md-pm-yellow' }, ], }); prompt.present(); console.log("You clicked on a detail."); } saveNewRow(data) { this.selectedItem.service.findOne({order: "id DESC"}).subscribe(result => { console.log('The result is ', result); this.editRowId = result.id+1; this.editRowData = { id: this.editRowId, name: data.name }; console.log('editRowData is ', this.editRowData); this.selectedItem.service.create(this.editRowData).subscribe(result => { this.refreshRows(); }); }) } saveRow(name) { let newName = name.nativeElement.value; if (newName !== this.editRowData["name"]) { this.editRowData["name"] = newName; this.selectedItem.service.updateAttributes(this.editRowData["id"], this.editRowData).subscribe(result => { let rows = this.rows; this.editRowIndex = null; this.rows = [...this.rows]; }) } } editRow(rowIndex) { this.editRowData = this.rows[rowIndex]; this.editRowId = this.rows[rowIndex].id; this.editRowName = this.rows[rowIndex].name; this.editRowIndex = rowIndex; setTimeout(() => this.name.nativeElement.focus(), 50); } cancelEditRow(rowIndex) { this.rows[rowIndex].name = this.editRowName; this.editRowIndex = null; } deleteRow(rowIndex) { this.selectedItem.service.deleteById(this.rows[rowIndex].id) .subscribe(result => { this.refreshRows() }, error => { console.log(error); const noDelete = this.alertCtrl.create({ title: this.rows[rowIndex].name + ' is in use and cannot be deleted.', // subTitle: 'You cannot delete this ' + this.selectedItem.label.slice(0, this.selectedItem.label.length-this.selectedItem.trimSingle), buttons: [ { text: 'Dismiss', cssClass: 'item-button button button-md button-outline button-outline-md' } ] }); noDelete.present(); }); } } ``` Thanks!
2019/02/21
[ "https://Stackoverflow.com/questions/54812273", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7446623/" ]
If it's viable, you can set `enableBackdropDismiss` to `true`, that would solve your issue. But I guess you have set it for a reason ;) Otherwise, to make some changes to `JGFMK`'s answer, this is how you can do it, assign your alert to a variable, so that you can reference it in the `@HostListener` and there dismiss the alert, when user hits esc-key: ```ts import { AlertController, Alert } from 'ionic-angular'; // ... prompt: Alert; @HostListener('document:keydown.escape', ['$event']) onKeydownHandler(event: KeyboardEvent) { this.prompt.dismiss(); } addTapped() { this.prompt = this.alertCtrl.create({ ... }) this.prompt.present(); } ``` **[StackBlitz](https://stackblitz.com/edit/ionic-4rwwuc?file=pages%2Fhome%2Fhome.html)**
Let me know if this helps. ``` import { HostListener} from '@angular/core'; import { ViewController } from 'ionic-angular'; export class ModalPage { private exitData = {proceed:false}; constructor( private view:ViewController ) ... @HostListener('document:keydown.escape', ['$event']) onKeydownHandler(event: KeyboardEvent) { this.view.dismiss(this.exitData); } } ``` Courtesy of [here](https://stackoverflow.com/a/42349004/495157).
11,697,557
I have a section of code in my `$(document).ready(function() {}` that reads: `getInitial(len);` Where len is an integer. ``` function getInitial(number){ number--; if(number < 0) return var $items = $(balls()); $items.imagesLoaded(function(){ $container .masonry('reloadItems') .append( $items ).masonry( 'appended', $items, true ); }); getInitial(number); } ``` Notice the line that reads: `var $items = $balls(());` That is defined as: ``` function balls(){ $iterator -= 1; if($iterator < 0){ var $boxes = $( '<div class="box">No more games!</div>' ); $container.append( $boxes ).masonry( 'appended', $boxes, false ); return; } var imgPreload = new Image(); var ret; imgPreload.src = 'scripts/php/timthumb.php?src='+$test[$iterator][2]+'&q=100&w=300'; $(".imgHolder").append('<img src="'+imgPreload.src+'"/>'); //console.log(imgPreload); $(".imgHolder").imagesLoaded(function(){ ret = '<div class="box" style="width:18%;">' +'<p>'+$test[$iterator][1][2]['name']+'</p>' +'<img src="'+imgPreload.src+'"/>'//Replace this with the one below when timthumb is whitelisted +'<div id=boxBottom>'+Math.floor($test[$iterator][0]*100)+'%</div>' +'</div>'; }); console.log(ret); return ret; } ``` My question is how can I get `ret` from the imagesLoaded() method inside of the `balls()` function to return to the `$items` inside of `getInitial()`? I hope there's no more confusion.
2012/07/28
[ "https://Stackoverflow.com/questions/11697557", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1452624/" ]
Yes, set it in the loop: ``` $array[ $row['cat_title'] ][ $row['sub_cat_id'] ] = $row['sub_cat_title']; ``` But, `$array[$row['cat_title']]` might not be set yet, so you should add this check beforehand: ``` if( !isset( $array[$row['cat_title']])) { $array[$row['cat_title']] = array(); } ``` Your original code doesn't need this check since `$array[]` will not generate any notices/warnings, but when you try to set a specific key, that will generate a notice/warning if the variable isn't already declared as an array.
You could do something like this: ``` foreach($array as $key=>$val){ unset($array[$key]); $newKey = //New value $array[$newKey] = $val]; } ```
63,927,009
I am newbie to ruby. Below is my code where I am trying to find a value which has value true and put it into `values`. But getting error ``` possible_values = [ 'ABC', 'DEF', 'GHI', 'JKL', 'MNO', 'PQR' ] options = { "environment"=>"dev", "status"=>"valid", "abc"=>true, "def"=>true, "ghi"=>false, "jkl"=>false } options['values'] = [] possible_values.each do |val| options['values'] << val if options[val.downcase] options.delete("val") end puts "values: #{options['values'}" ``` Error: `can't convert String into Integer (TypeError)` Desired Output: ``` options = [ "environment"=>"dev", "status"=>"valid", "values"=>["ABC", "DEF"] ] ```
2020/09/16
[ "https://Stackoverflow.com/questions/63927009", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2175642/" ]
Three bugs: 1. Your `puts` line is missing a `]`: ```rb puts "values: #{options['values'}" # ^ should be here ``` 2. You want to remove the `options` key after processing it, but you're always removing `"val"` instead: ```rb options.delete("val") # ^ ^ extra quotes making this a "val" String ``` 3. Again, you want to remove the `options` key after processing. The `possible_values` are all uppercase, and won't match the corresponding keys in `options` for deletion without a `downcase`. Taking #2 and #3 together, what you want is: `options.delete(val.downcase)` After fixing all three of these, this is the contents of `options`: ```rb {"environment" => "dev", "status" => "valid", "values" => ["ABC", "DEF"]} ``` which seems to be what you wanted
I see you wish to mutate (modify) `options`, as opposed to returning a separate hash, leaving `options` unchanged. I would be inclined to write the code as follows, in part to facilitate the testing of `true_keys` and `options` (below), after `true_keys` has been computed. ``` true_keys = options.keys.each_with_object([]) do |k,arr| case options[k] when true arr << k.upcase options.delete(k) when false options.delete(k) end end #=> ["ABC", "DEF"] ``` We now have: ``` options #=> {"environment"=>"dev", "status"=>"valid"} ``` Notice that we cannot write ``` true_keys = options.each_key.each_with_object([]) do |k,arr|... ``` or ``` true_keys = options.each_with_object([]) do |(k,v),arr|... ``` because that would remove elements of `options` whilst interating over it, a no-no. That is not a problem when iterating over `options.keys`. One more step: ``` options.tap { |h| h['values'] = true_keys & possible_values } #=> {"environment"=>"dev", "status"=>"valid", "values"=>["ABC", "DEF"]} ``` See [Object#tap](https://ruby-doc.org/core-2.7.0/Object.html#method-i-tap). Just checking: ``` options #=> {"environment"=>"dev", "status"=>"valid", "values"=>["ABC", "DEF"]} ``` One could alternatively write ``` options.update('values'=>true_keys & possible_values) #=> {"environment"=>"dev", "status"=>"valid", "values"=>["ABC", "DEF"]} ``` See [Hash#update](https://ruby-doc.org/core-2.7.0/Hash.html#method-i-update) (a.k.a. `merge!`). --- If `options` and `possible_values` were large it would be sensible to convert `possible_values` to a set as an initial step, as set lookups are much faster than array lookups, the latter requiring a linear search. This only effects the `tap` (or `update`) operation. ``` require 'set' possible_values_set = possible_values.to_set #=> #<Set: {"ABC", "DEF", "GHI", "JKL", "MNO", "PQR"}> ``` Then with ``` true_keys #=> ["ABC", "DEF"] ``` the `tap` expression would become: ``` options.tap do |h| h['values'] = true_keys.select { |k| possible_values_set.include?(k) } end #=> {"environment"=>"dev", "status"=>"valid", "values"=>["ABC", "DEF"]} ```
17,574,013
I have define the following on my Model class:- ``` [DataType(DataType.MultilineText)] public string Description { get; set; } ``` On the view I have the following:- ``` <span class="f"> Description :- </span> @Html.EditorFor(model => model.Description) @Html.ValidationMessageFor(model => model.Description) ``` now the output will be a small text area, but it will not show all the text . so how I can control the size of the DataType.MultilineText ? **:::EDIT:::** I have added the following to the CSS file:- ``` .f { font-weight:bold; color:#000000; } .f textarea { width: 850px; height: 700px; } ``` And I have defined this :- ``` <div > <span class="f"> Description :- </span> @Html.TextArea("Description") @Html.ValidationMessageFor(model => model.Description) </div> ``` But nothing actually changed regarding the multi-line display.
2013/07/10
[ "https://Stackoverflow.com/questions/17574013", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1917176/" ]
This worked for me, with DataType set to MultilineText in the model: ``` [DataType(DataType.MultilineText)] public string Description { get; set; } ``` And in the View specifying the HTML attribute "rows": ``` @Html.EditorFor(model => model.Description, new { htmlAttributes = new { rows = "4" } }) ``` Generates HTML like that: ``` <textarea ... rows="4"></textarea> ``` A text area with 4 rows.
> > so how I can control the size of the DataType.MultilineText ? > > > You could define a class to the textarea: ``` @Html.TextArea("Description", new { @class = "mytextarea" }) ``` and then in your CSS file: ``` .mytextarea { width: 850px; height: 700px; } ```
20,757,615
I have a custom ValidationAttribute, it checks if another user exists already. To so it needs access to my data access layer, an instance injected into my controller by Unity How can I pass this (or anything for that matter) as a parameter into my custom validator? Is this possible? i.e where I'm creating Dal, that should be a paramter ``` public class EmailIsUnique : ValidationAttribute { private string _errorMessage = "An account with this {0} already exists"; protected override ValidationResult IsValid(object value, ValidationContext validationContext) { DataAccessHelper Dal = new DataAccessHelper(SharedResolver.AppSettingsHelper().DbConnectionString); //todo, this is way too slow bool isValid = true; if(value == null) { isValid = false; _errorMessage = "{0} Cannot be empty"; } else { string email = value.ToString(); if (Dal.User.FindByEmail(email) != null) { isValid = false; } } if (isValid) return ValidationResult.Success; else return new ValidationResult(String.Format(_errorMessage, validationContext.DisplayName)); } } ```
2013/12/24
[ "https://Stackoverflow.com/questions/20757615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/314963/" ]
You are probably looking for Property Injection. Have a look at [this](https://stackoverflow.com/questions/6121050/mvc-3-unity-2-inject-dependencies-into-a-filter) post. First solution is to create your custom filter provider that supports dependency injection. Second solution is to use Service Locator pattern and get instance of you service in attribute constructor.
yes.you can pass parameter which use in the Model class as below: ``` [EmailIsUnique()] public string Email {get; set;} ``` so this will automatically pass Email as a parameter and check the value.
20,757,615
I have a custom ValidationAttribute, it checks if another user exists already. To so it needs access to my data access layer, an instance injected into my controller by Unity How can I pass this (or anything for that matter) as a parameter into my custom validator? Is this possible? i.e where I'm creating Dal, that should be a paramter ``` public class EmailIsUnique : ValidationAttribute { private string _errorMessage = "An account with this {0} already exists"; protected override ValidationResult IsValid(object value, ValidationContext validationContext) { DataAccessHelper Dal = new DataAccessHelper(SharedResolver.AppSettingsHelper().DbConnectionString); //todo, this is way too slow bool isValid = true; if(value == null) { isValid = false; _errorMessage = "{0} Cannot be empty"; } else { string email = value.ToString(); if (Dal.User.FindByEmail(email) != null) { isValid = false; } } if (isValid) return ValidationResult.Success; else return new ValidationResult(String.Format(_errorMessage, validationContext.DisplayName)); } } ```
2013/12/24
[ "https://Stackoverflow.com/questions/20757615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/314963/" ]
I'm not too sure you'll be able to pass runtime parameters into your attribute. You could use `DependencyResolver.Current.GetService<DataAccessHelper>()` to resolve your dal (given that you've registered DataAccessHelper) You're probably more likely to have registered DataAccessHelper as IDataAccessHelper or something? in which case you'd call `GetService<IDataAccessHelper>` ``` public class EmailIsUnique : ValidationAttribute { private string _errorMessage = "An account with this {0} already exists"; protected override ValidationResult IsValid(object value, ValidationContext validationContext) { IDataAccessHelper Dal = DependencyResolver.Current.GetService<IDataAccessHelper>(); // too slow bool isValid = true; if(value == null) { isValid = false; _errorMessage = "{0} Cannot be empty"; } else { string email = value.ToString(); if (Dal.User.FindByEmail(email) != null) { isValid = false; } } if (isValid) return ValidationResult.Success; else return new ValidationResult(String.Format(_errorMessage, validationContext.DisplayName)); } } ``` or ``` public class EmailIsUnique : ValidationAttribute { [Dependency] public IDataAccessHelper DataAccess {get;set;} private string _errorMessage = "An account with this {0} already exists"; protected override ValidationResult IsValid(object value, ValidationContext validationContext) { bool isValid = true; if(value == null) { isValid = false; _errorMessage = "{0} Cannot be empty"; } else { string email = value.ToString(); if (DataAccess.User.FindByEmail(email) != null) { isValid = false; } } if (isValid) return ValidationResult.Success; else return new ValidationResult(String.Format(_errorMessage, validationContext.DisplayName)); } } ```
yes.you can pass parameter which use in the Model class as below: ``` [EmailIsUnique()] public string Email {get; set;} ``` so this will automatically pass Email as a parameter and check the value.
20,757,615
I have a custom ValidationAttribute, it checks if another user exists already. To so it needs access to my data access layer, an instance injected into my controller by Unity How can I pass this (or anything for that matter) as a parameter into my custom validator? Is this possible? i.e where I'm creating Dal, that should be a paramter ``` public class EmailIsUnique : ValidationAttribute { private string _errorMessage = "An account with this {0} already exists"; protected override ValidationResult IsValid(object value, ValidationContext validationContext) { DataAccessHelper Dal = new DataAccessHelper(SharedResolver.AppSettingsHelper().DbConnectionString); //todo, this is way too slow bool isValid = true; if(value == null) { isValid = false; _errorMessage = "{0} Cannot be empty"; } else { string email = value.ToString(); if (Dal.User.FindByEmail(email) != null) { isValid = false; } } if (isValid) return ValidationResult.Success; else return new ValidationResult(String.Format(_errorMessage, validationContext.DisplayName)); } } ```
2013/12/24
[ "https://Stackoverflow.com/questions/20757615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/314963/" ]
I'm not too sure you'll be able to pass runtime parameters into your attribute. You could use `DependencyResolver.Current.GetService<DataAccessHelper>()` to resolve your dal (given that you've registered DataAccessHelper) You're probably more likely to have registered DataAccessHelper as IDataAccessHelper or something? in which case you'd call `GetService<IDataAccessHelper>` ``` public class EmailIsUnique : ValidationAttribute { private string _errorMessage = "An account with this {0} already exists"; protected override ValidationResult IsValid(object value, ValidationContext validationContext) { IDataAccessHelper Dal = DependencyResolver.Current.GetService<IDataAccessHelper>(); // too slow bool isValid = true; if(value == null) { isValid = false; _errorMessage = "{0} Cannot be empty"; } else { string email = value.ToString(); if (Dal.User.FindByEmail(email) != null) { isValid = false; } } if (isValid) return ValidationResult.Success; else return new ValidationResult(String.Format(_errorMessage, validationContext.DisplayName)); } } ``` or ``` public class EmailIsUnique : ValidationAttribute { [Dependency] public IDataAccessHelper DataAccess {get;set;} private string _errorMessage = "An account with this {0} already exists"; protected override ValidationResult IsValid(object value, ValidationContext validationContext) { bool isValid = true; if(value == null) { isValid = false; _errorMessage = "{0} Cannot be empty"; } else { string email = value.ToString(); if (DataAccess.User.FindByEmail(email) != null) { isValid = false; } } if (isValid) return ValidationResult.Success; else return new ValidationResult(String.Format(_errorMessage, validationContext.DisplayName)); } } ```
You are probably looking for Property Injection. Have a look at [this](https://stackoverflow.com/questions/6121050/mvc-3-unity-2-inject-dependencies-into-a-filter) post. First solution is to create your custom filter provider that supports dependency injection. Second solution is to use Service Locator pattern and get instance of you service in attribute constructor.
55,120,635
I have declared a static path to the static files such as CSS and javascript files. where there is a single URL path the static files are retrieved successfully but when I add a subpath they are not accessible. Folders location ``` /static/css /static/js ``` in HTML ``` <link rel="stylesheet/less" href="css/progress.less" type="text/css"> ``` in server.js ``` app.use(express.static(__dirname + "")); app.use(express.static(__dirname + "/static")); app.use('/static', express.static('/static/')); app.use(express.static(__dirname)); ``` in a single path, they are accessible for example ``` localhost:4000/css/style.css ``` but in a url like this ``` localhost:4000/services/construction/css/style.css ``` This throw an error.
2019/03/12
[ "https://Stackoverflow.com/questions/55120635", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5199821/" ]
You can not have access to the auth user inside the boot method of AppServiceProvider this method is called before the authentication mechanism. What you can do is you can create a ViewComposer and pass variables to any views you want. First create a ServiceProvider lets say `ComposerServiceProvider` , you can use `php artisan make:provider ComposerServiceProvider` to generate one. \*dont forget to register the provider on your config/app.php file and use the below code ``` namespace App\Providers; use Illuminate\Support\ServiceProvider; use Illuminate\Contracts\View\Factory as ViewFactory; class ComposerServiceProvider extends ServiceProvider { public function boot(ViewFactory $view) { $view->composer('*', 'App\Http\ViewComposers\GlobalComposer'); } public function register() { // } } ``` Then create a GlobalComposer.php class file with below code ``` namespace App\Http\ViewComposers; use Illuminate\Support\Facades\Auth; use Illuminate\Contracts\View\View; class GlobalComposer { /** * Bind data to the view. * * @param View $view * @return void */ public function compose(View $view) { $view->with('user', Auth::user()); } } ``` Now the asterisk on the boot method of the service provider means "all views" meaning for all the views of the project the GlobalComposer will take action. You can replace the asterisk with whatever view you want, you can use an array of views also e.g. `['auth/login', 'auth/register']` Next on the GlobalComposer file inside the compose method you "compose" variables that you want to be passed on the views the Composer is binded to. Check the Laravel [doc](https://laravel.com/docs/5.8/views#view-composers) also
Based on the comments i guess that your problem can be solved simple by adding an authenticated new route in your `api.php` file. Try this approach: ``` Route::middleware('auth:api')->get('/webiste/user', function (Request $request) { return $request->user()->id; }); ```
594,931
I'm maintaining a data-warehousing system that involves a lot of dependent jobs (data import, transform, etc). I've been using Linux's `crontab` to manage them until the dependency between jobs get complicated. Basically I'm looking for some `cron` replacement that helps me with the following scenario: * Run job A at `00:05` (easy). Usually this is the import job. * Schedule job B, C, D to run after job A finishes. Job D only runs 30 mins after job A finishes (to distribute load). These are the transform jobs. * Job E run when all B, C, D finish. Usually this is the job that bring aggregated data to a web front-end database. All of these happen on the same node. I imagine it looks like a topology graph. ``` A--> B -------------->---> E \-> C -------------/ / \-> (delay 30mins) -> D ``` Are there such simple linux-based tools that support this? I've looked into [Airbnb's Chronos](http://nerds.airbnb.com/introducing-chronos/) but it seems overkill for my need. Edit: The above scenario is just a simplified version of what's happening. We have a lot more daily jobs and the dependency is a lot more complicated. So I'm actually looking for some "cron on steroid" than case-by-case bash scripts to cater each scenario.
2013/05/13
[ "https://superuser.com/questions/594931", "https://superuser.com", "https://superuser.com/users/38887/" ]
As Michael Kjörling suggested in the comments, you should be able to do this with a simple bash script. Something like this: ``` #!/usr/bin/env bash ## Log file to which the "echo" commands bellow will write logfile="/tmp/$$.log" ## Change "ls /etc >/dev/null " to reflect the actual ## jobs you want to run but keep the "&& echo job N finished" as is. jobA="ls /etc >/dev/null" jobB="ls /etc >/dev/null && echo 'job B finished' >> $logfile" jobC="ls /etc >/dev/null && echo 'job C finished' >> $logfile" jobD="ls /etc >/dev/null && echo 'job D finished' >> $logfile" jobE="ls /etc >/dev/null"; ## Run job A, launch jobs B and C as soon as A is finished ## and launch job D 30 minutes after A finishes. eval $jobA && (sleep 30 && eval $jobD) & eval $jobB & eval $jobC & ## Now, monitor the logfile and run job E when the rest have finished while true; do lines=`wc -l $logfile | cut -f 1 -d ' '`; echo "$logfile : $lines" ## The logfile will contain 4 lines if all jobs have finished if [ "$lines" -eq 3 ]; then ## Run job E eval $jobE ## Delete the logfile rm $logfile ## exit the script exit 0; fi ## Only check if the jobs are finished once a minute sleep 60; done ``` If you use `cron` to launch this script at 00:05 it should do what you want. The main trick here is the use of [subshels](http://linux.about.com/od/Bash_Scripting_Solutions/a/Subshells-In-Bash-Scripts.htm) `()` and `&&`. Subshels allow you to run multiple background jobs and `&&` to only run jobs once another job has exited successfully.
BMC Software makes a product called Control-M which would be a perfect fit for your description of the issue. However, it isn't free :( We use it to administer around 500 jobs in production, and somewhere close to 400 in test environments. You install clients on whatever machines you need, then set up jobs on the Control-M server to run on the clients. There are a whole lot of configurable parameters and scheduling criteria, all of which can be administered through a GUI or command line. The most fitting part to your problem is that it thrives on setting up input/output conditions for jobs so that you can have dependencies just by drag and dropping between jobs. We use it to set up workflow streams of 20+ jobs at a time.
594,931
I'm maintaining a data-warehousing system that involves a lot of dependent jobs (data import, transform, etc). I've been using Linux's `crontab` to manage them until the dependency between jobs get complicated. Basically I'm looking for some `cron` replacement that helps me with the following scenario: * Run job A at `00:05` (easy). Usually this is the import job. * Schedule job B, C, D to run after job A finishes. Job D only runs 30 mins after job A finishes (to distribute load). These are the transform jobs. * Job E run when all B, C, D finish. Usually this is the job that bring aggregated data to a web front-end database. All of these happen on the same node. I imagine it looks like a topology graph. ``` A--> B -------------->---> E \-> C -------------/ / \-> (delay 30mins) -> D ``` Are there such simple linux-based tools that support this? I've looked into [Airbnb's Chronos](http://nerds.airbnb.com/introducing-chronos/) but it seems overkill for my need. Edit: The above scenario is just a simplified version of what's happening. We have a lot more daily jobs and the dependency is a lot more complicated. So I'm actually looking for some "cron on steroid" than case-by-case bash scripts to cater each scenario.
2013/05/13
[ "https://superuser.com/questions/594931", "https://superuser.com", "https://superuser.com/users/38887/" ]
These look interesting: * <https://airflow.incubator.apache.org/> > > not so simple but powerful and supported by apache, configured by code, widely used now > > > * <https://www.digdag.io/> > > java airflow like, simpler to configure > > > * <https://github.com/thieman/dagobah> > > Simple DAG-based job scheduler in Python > > > * <https://github.com/spotify/luigi> (by spotify) > > Luigi is a Python module that helps you build complex pipelines of > batch jobs. > > > These are all python projects (expect for digdag) which aim at replacing cron with a nice GUI to see the dependencies graph. I used to use bash for this stuff, but it's getting ugly when you grow into complex systems.
BMC Software makes a product called Control-M which would be a perfect fit for your description of the issue. However, it isn't free :( We use it to administer around 500 jobs in production, and somewhere close to 400 in test environments. You install clients on whatever machines you need, then set up jobs on the Control-M server to run on the clients. There are a whole lot of configurable parameters and scheduling criteria, all of which can be administered through a GUI or command line. The most fitting part to your problem is that it thrives on setting up input/output conditions for jobs so that you can have dependencies just by drag and dropping between jobs. We use it to set up workflow streams of 20+ jobs at a time.
27,992,304
I'm new to Spring. The goal is to learn Spring, to use Spring as a production application as it is industry standard. The requirements of the app: Hibernate, Security, MVC, RESTful, DI, etc. The other Spring frameworks might be added in future. I'm reading "Spring in Action. Third Edition." by Craig Walls. He gave the examples how to use annotations, but anyway .xml is used. I'm wonder if I can write the application using only java classes to configure all modules in the application. I found Spring Boot gives ability to develop not using xml files. However I read the article <http://steveperkins.com/use-spring-boot-next-project/> and author said Boot is not ready to be used for production applications. As far as I understood Boot hides all config work from me. Also my concern is that in future java-developers who knows Spring won't be able to deal with Spring Boot and I wouldn't find proper engineers for the project. Based upon this I have the following questions: * Is it possible to avoid using xml in Spring or better to mix xml files and annotations? * Is it easy for Spring developers to work with Spring Boot? * Am I able to learn Spring using Spring Boot? * Is Spring Boot is mature enough to use it in production?
2015/01/16
[ "https://Stackoverflow.com/questions/27992304", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3025055/" ]
> > Is it possible to avoid using xml in Spring or better to mix xml files and annotations? > > > Yes, it is. Spring now promotes Java configuration, and it's perfectly doable (I'm doing it) and even easy to only use Java to configure your Spring app. Even without using Boot. > > Is it east for Spring developers to work with Spring Boot? > > > Why wouldn't it? It's well documented, and is based on Spring best practices. > > Am I able to learn Spring using Spring Boot? > > > How could I answer that. Try doing it, and you'll see if you're able or not. > > Is Spring Boot is mature enough to use it in production? > > > Yes, it is. The articleyou linked to is one year old. Spring developers have worked a lot on Boot since then. And Spring uses Boot internally to host their own spring.io web application. See <https://github.com/spring-io/sagan>
I don't know much about Spring Boot but I know pretty much about spring. First of all you can use both annotations and xml configuration file/s in the same project. That is the most common way as far as I know. There is also JavaConfig configuration option in which you don't use any xml files instead you use ordinary java class with @Configuration annotation. I didn't use and not saw much usage also.
27,992,304
I'm new to Spring. The goal is to learn Spring, to use Spring as a production application as it is industry standard. The requirements of the app: Hibernate, Security, MVC, RESTful, DI, etc. The other Spring frameworks might be added in future. I'm reading "Spring in Action. Third Edition." by Craig Walls. He gave the examples how to use annotations, but anyway .xml is used. I'm wonder if I can write the application using only java classes to configure all modules in the application. I found Spring Boot gives ability to develop not using xml files. However I read the article <http://steveperkins.com/use-spring-boot-next-project/> and author said Boot is not ready to be used for production applications. As far as I understood Boot hides all config work from me. Also my concern is that in future java-developers who knows Spring won't be able to deal with Spring Boot and I wouldn't find proper engineers for the project. Based upon this I have the following questions: * Is it possible to avoid using xml in Spring or better to mix xml files and annotations? * Is it easy for Spring developers to work with Spring Boot? * Am I able to learn Spring using Spring Boot? * Is Spring Boot is mature enough to use it in production?
2015/01/16
[ "https://Stackoverflow.com/questions/27992304", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3025055/" ]
> > Is it possible to avoid using xml in Spring or better to mix xml files and annotations? > > > Yes, it is. Spring now promotes Java configuration, and it's perfectly doable (I'm doing it) and even easy to only use Java to configure your Spring app. Even without using Boot. > > Is it east for Spring developers to work with Spring Boot? > > > Why wouldn't it? It's well documented, and is based on Spring best practices. > > Am I able to learn Spring using Spring Boot? > > > How could I answer that. Try doing it, and you'll see if you're able or not. > > Is Spring Boot is mature enough to use it in production? > > > Yes, it is. The articleyou linked to is one year old. Spring developers have worked a lot on Boot since then. And Spring uses Boot internally to host their own spring.io web application. See <https://github.com/spring-io/sagan>
You can make a spring webapp without any xml, although spring security was ugly to configure last time I looked at that. For a webapp you need to implement WebApplicationInitializer, create an application context and register your @Configuration file(s) with the context. Then you register the dispatcher servlet and you're all set!
27,992,304
I'm new to Spring. The goal is to learn Spring, to use Spring as a production application as it is industry standard. The requirements of the app: Hibernate, Security, MVC, RESTful, DI, etc. The other Spring frameworks might be added in future. I'm reading "Spring in Action. Third Edition." by Craig Walls. He gave the examples how to use annotations, but anyway .xml is used. I'm wonder if I can write the application using only java classes to configure all modules in the application. I found Spring Boot gives ability to develop not using xml files. However I read the article <http://steveperkins.com/use-spring-boot-next-project/> and author said Boot is not ready to be used for production applications. As far as I understood Boot hides all config work from me. Also my concern is that in future java-developers who knows Spring won't be able to deal with Spring Boot and I wouldn't find proper engineers for the project. Based upon this I have the following questions: * Is it possible to avoid using xml in Spring or better to mix xml files and annotations? * Is it easy for Spring developers to work with Spring Boot? * Am I able to learn Spring using Spring Boot? * Is Spring Boot is mature enough to use it in production?
2015/01/16
[ "https://Stackoverflow.com/questions/27992304", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3025055/" ]
> > Is it possible to avoid using xml in Spring or better to mix xml files and annotations? > > > Yes, it is. Spring now promotes Java configuration, and it's perfectly doable (I'm doing it) and even easy to only use Java to configure your Spring app. Even without using Boot. > > Is it east for Spring developers to work with Spring Boot? > > > Why wouldn't it? It's well documented, and is based on Spring best practices. > > Am I able to learn Spring using Spring Boot? > > > How could I answer that. Try doing it, and you'll see if you're able or not. > > Is Spring Boot is mature enough to use it in production? > > > Yes, it is. The articleyou linked to is one year old. Spring developers have worked a lot on Boot since then. And Spring uses Boot internally to host their own spring.io web application. See <https://github.com/spring-io/sagan>
JB Nizet answered 3 answers very clearly. Just an addition about production readiness from my side. We are currently using Spring Boot for an application which we intend to move to production. There has not been any issue till now in prototyping and testing phase. It is very convenient and avoids boilerplate and gives production ready, standalone jar file with embedded server. You can also chose to build war file if you prefer. "Am I able to learn Spring using Spring Boot?" As you mentioned that you are new to Spring, it would probably be easier for you to pick up Spring Boot quickly. To get started, if you are interested, following is the link to a webinar by Josh Long which gives you a really good insight of how easy it is to pick up Spring Boot: <https://www.youtube.com/watch?v=eCos5VTtZoI>
27,992,304
I'm new to Spring. The goal is to learn Spring, to use Spring as a production application as it is industry standard. The requirements of the app: Hibernate, Security, MVC, RESTful, DI, etc. The other Spring frameworks might be added in future. I'm reading "Spring in Action. Third Edition." by Craig Walls. He gave the examples how to use annotations, but anyway .xml is used. I'm wonder if I can write the application using only java classes to configure all modules in the application. I found Spring Boot gives ability to develop not using xml files. However I read the article <http://steveperkins.com/use-spring-boot-next-project/> and author said Boot is not ready to be used for production applications. As far as I understood Boot hides all config work from me. Also my concern is that in future java-developers who knows Spring won't be able to deal with Spring Boot and I wouldn't find proper engineers for the project. Based upon this I have the following questions: * Is it possible to avoid using xml in Spring or better to mix xml files and annotations? * Is it easy for Spring developers to work with Spring Boot? * Am I able to learn Spring using Spring Boot? * Is Spring Boot is mature enough to use it in production?
2015/01/16
[ "https://Stackoverflow.com/questions/27992304", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3025055/" ]
> > Is it possible to avoid using xml in Spring or better to mix xml files and annotations? > > > Yes, it is. Spring now promotes Java configuration, and it's perfectly doable (I'm doing it) and even easy to only use Java to configure your Spring app. Even without using Boot. > > Is it east for Spring developers to work with Spring Boot? > > > Why wouldn't it? It's well documented, and is based on Spring best practices. > > Am I able to learn Spring using Spring Boot? > > > How could I answer that. Try doing it, and you'll see if you're able or not. > > Is Spring Boot is mature enough to use it in production? > > > Yes, it is. The articleyou linked to is one year old. Spring developers have worked a lot on Boot since then. And Spring uses Boot internally to host their own spring.io web application. See <https://github.com/spring-io/sagan>
I was nearly in the same boat four months ago when I started working on my web app & chose Spring as the platform after evaluating many choices. I also started with Spring in Action but got frustrated when the examples provided by the author didn't work ([Spring basic MVC app not working](https://stackoverflow.com/questions/25611263/spring-basic-mvc-app-not-working/25631214)). Since I was just starting, I was looking for some very basic but working examples. But unfortunately, most of the examples which came along with Spring text books, didn't work straight out of the box. I would like to suggest few Spring resources which I found useful for starters: * <http://springbyexample.org/> * <http://www.petrikainulainen.net/tutorials/> * <http://www.mkyong.com/tutorials/spring-tutorials/> * [Pro Spring 4th Edition](http://www.apress.com/9781430261513) * Spring Documentation (must read, but take your time to understand the concepts) Now, to answer your questions, although a bit differently: > > * Is it possible to avoid using xml in Spring or better to mix xml files and annotations > > > Now a days, you would find Annotations a lot in Spring code available on net/SO along with XML configuration. However, you can certainly avoid XML if you wish. > > Is it easy for Spring developers to work with Spring Boot? > Am I able to learn Spring using Spring Boot? > Is Spring Boot is mature enough to use it in production? > > > My personal opinion would be to go with Spring Boot only if you believe it offers you certain advantages which are not possible to achieve otherwise. Remember, you may save time now but later on, it would be an additional dependency in your app and you may need to understand its architecture to debug it if things go wrong OR to enhance it as per your app requirements. Better to have minimal dependencies, my learning till now :)
27,992,304
I'm new to Spring. The goal is to learn Spring, to use Spring as a production application as it is industry standard. The requirements of the app: Hibernate, Security, MVC, RESTful, DI, etc. The other Spring frameworks might be added in future. I'm reading "Spring in Action. Third Edition." by Craig Walls. He gave the examples how to use annotations, but anyway .xml is used. I'm wonder if I can write the application using only java classes to configure all modules in the application. I found Spring Boot gives ability to develop not using xml files. However I read the article <http://steveperkins.com/use-spring-boot-next-project/> and author said Boot is not ready to be used for production applications. As far as I understood Boot hides all config work from me. Also my concern is that in future java-developers who knows Spring won't be able to deal with Spring Boot and I wouldn't find proper engineers for the project. Based upon this I have the following questions: * Is it possible to avoid using xml in Spring or better to mix xml files and annotations? * Is it easy for Spring developers to work with Spring Boot? * Am I able to learn Spring using Spring Boot? * Is Spring Boot is mature enough to use it in production?
2015/01/16
[ "https://Stackoverflow.com/questions/27992304", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3025055/" ]
JB Nizet answered 3 answers very clearly. Just an addition about production readiness from my side. We are currently using Spring Boot for an application which we intend to move to production. There has not been any issue till now in prototyping and testing phase. It is very convenient and avoids boilerplate and gives production ready, standalone jar file with embedded server. You can also chose to build war file if you prefer. "Am I able to learn Spring using Spring Boot?" As you mentioned that you are new to Spring, it would probably be easier for you to pick up Spring Boot quickly. To get started, if you are interested, following is the link to a webinar by Josh Long which gives you a really good insight of how easy it is to pick up Spring Boot: <https://www.youtube.com/watch?v=eCos5VTtZoI>
I don't know much about Spring Boot but I know pretty much about spring. First of all you can use both annotations and xml configuration file/s in the same project. That is the most common way as far as I know. There is also JavaConfig configuration option in which you don't use any xml files instead you use ordinary java class with @Configuration annotation. I didn't use and not saw much usage also.
27,992,304
I'm new to Spring. The goal is to learn Spring, to use Spring as a production application as it is industry standard. The requirements of the app: Hibernate, Security, MVC, RESTful, DI, etc. The other Spring frameworks might be added in future. I'm reading "Spring in Action. Third Edition." by Craig Walls. He gave the examples how to use annotations, but anyway .xml is used. I'm wonder if I can write the application using only java classes to configure all modules in the application. I found Spring Boot gives ability to develop not using xml files. However I read the article <http://steveperkins.com/use-spring-boot-next-project/> and author said Boot is not ready to be used for production applications. As far as I understood Boot hides all config work from me. Also my concern is that in future java-developers who knows Spring won't be able to deal with Spring Boot and I wouldn't find proper engineers for the project. Based upon this I have the following questions: * Is it possible to avoid using xml in Spring or better to mix xml files and annotations? * Is it easy for Spring developers to work with Spring Boot? * Am I able to learn Spring using Spring Boot? * Is Spring Boot is mature enough to use it in production?
2015/01/16
[ "https://Stackoverflow.com/questions/27992304", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3025055/" ]
JB Nizet answered 3 answers very clearly. Just an addition about production readiness from my side. We are currently using Spring Boot for an application which we intend to move to production. There has not been any issue till now in prototyping and testing phase. It is very convenient and avoids boilerplate and gives production ready, standalone jar file with embedded server. You can also chose to build war file if you prefer. "Am I able to learn Spring using Spring Boot?" As you mentioned that you are new to Spring, it would probably be easier for you to pick up Spring Boot quickly. To get started, if you are interested, following is the link to a webinar by Josh Long which gives you a really good insight of how easy it is to pick up Spring Boot: <https://www.youtube.com/watch?v=eCos5VTtZoI>
You can make a spring webapp without any xml, although spring security was ugly to configure last time I looked at that. For a webapp you need to implement WebApplicationInitializer, create an application context and register your @Configuration file(s) with the context. Then you register the dispatcher servlet and you're all set!
27,992,304
I'm new to Spring. The goal is to learn Spring, to use Spring as a production application as it is industry standard. The requirements of the app: Hibernate, Security, MVC, RESTful, DI, etc. The other Spring frameworks might be added in future. I'm reading "Spring in Action. Third Edition." by Craig Walls. He gave the examples how to use annotations, but anyway .xml is used. I'm wonder if I can write the application using only java classes to configure all modules in the application. I found Spring Boot gives ability to develop not using xml files. However I read the article <http://steveperkins.com/use-spring-boot-next-project/> and author said Boot is not ready to be used for production applications. As far as I understood Boot hides all config work from me. Also my concern is that in future java-developers who knows Spring won't be able to deal with Spring Boot and I wouldn't find proper engineers for the project. Based upon this I have the following questions: * Is it possible to avoid using xml in Spring or better to mix xml files and annotations? * Is it easy for Spring developers to work with Spring Boot? * Am I able to learn Spring using Spring Boot? * Is Spring Boot is mature enough to use it in production?
2015/01/16
[ "https://Stackoverflow.com/questions/27992304", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3025055/" ]
JB Nizet answered 3 answers very clearly. Just an addition about production readiness from my side. We are currently using Spring Boot for an application which we intend to move to production. There has not been any issue till now in prototyping and testing phase. It is very convenient and avoids boilerplate and gives production ready, standalone jar file with embedded server. You can also chose to build war file if you prefer. "Am I able to learn Spring using Spring Boot?" As you mentioned that you are new to Spring, it would probably be easier for you to pick up Spring Boot quickly. To get started, if you are interested, following is the link to a webinar by Josh Long which gives you a really good insight of how easy it is to pick up Spring Boot: <https://www.youtube.com/watch?v=eCos5VTtZoI>
I was nearly in the same boat four months ago when I started working on my web app & chose Spring as the platform after evaluating many choices. I also started with Spring in Action but got frustrated when the examples provided by the author didn't work ([Spring basic MVC app not working](https://stackoverflow.com/questions/25611263/spring-basic-mvc-app-not-working/25631214)). Since I was just starting, I was looking for some very basic but working examples. But unfortunately, most of the examples which came along with Spring text books, didn't work straight out of the box. I would like to suggest few Spring resources which I found useful for starters: * <http://springbyexample.org/> * <http://www.petrikainulainen.net/tutorials/> * <http://www.mkyong.com/tutorials/spring-tutorials/> * [Pro Spring 4th Edition](http://www.apress.com/9781430261513) * Spring Documentation (must read, but take your time to understand the concepts) Now, to answer your questions, although a bit differently: > > * Is it possible to avoid using xml in Spring or better to mix xml files and annotations > > > Now a days, you would find Annotations a lot in Spring code available on net/SO along with XML configuration. However, you can certainly avoid XML if you wish. > > Is it easy for Spring developers to work with Spring Boot? > Am I able to learn Spring using Spring Boot? > Is Spring Boot is mature enough to use it in production? > > > My personal opinion would be to go with Spring Boot only if you believe it offers you certain advantages which are not possible to achieve otherwise. Remember, you may save time now but later on, it would be an additional dependency in your app and you may need to understand its architecture to debug it if things go wrong OR to enhance it as per your app requirements. Better to have minimal dependencies, my learning till now :)
14,543,274
I'm trying to select values from a database, but I need to check another value in another database . I created this code, but only get 1 result and I don't know why: ``` SELECT `id` FROM `mc_region` WHERE `is_subregion` = 'false' AND lastseen < CURDATE() - INTERVAL 20 DAY AND (SELECT id_region FROM mc_region_flags WHERE flag <> 'expire' AND id_region = mc_region.id ) LIMIT 0, 30 ``` What I've made wrong? @Edit I think I know why this code is not working. At database mc\_region\_flags not all records from the primary database has flag. I would like to do the following: 1º Select all records on the first database, where is not subregion and lastseen is more than 20 day 2º Check if any result on the 1st database has flag 'expire', if yes, they are not included in the result. I cant do this in 1 only SQL Code? @Edit2 I created this code that simulate `FULL JOIN` but seems that `WHERE` is not work ``` SELECT * FROM mc_region AS r RIGHT OUTER JOIN mc_region_flags AS f ON r.id = f.id_region UNION ALL SELECT * from mc_region AS r LEFT OUTER JOIN mc_region_flags AS f ON r.id = f.id_region WHERE r.is_subregion = 'false' AND f.flag = 'exipre' AND r.lastseen < CURDATE() - INTERVAL 20 DAY ``` Problems WHERE not work 1. `f.flag` is not 'expire' 2. `f.lastseen` is not > 20 days ![results](https://i.stack.imgur.com/atj2Y.png)
2013/01/27
[ "https://Stackoverflow.com/questions/14543274", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1821304/" ]
If it's a globally defined function in some javascript that is loaded via an inline script tag (either locally defined or in an external JS file), you can just redefine it with your own version of that function. Whichever definition comes last will be the active one. So, it sounds like what you want to do is to provide your own definition right after the external JS file containing the target function. That way your definition will replace the original one. If you want to retain the original one, you can assign it to another variable name before replacing it. ``` // save original function reference (if desired) var originHello13 = hello13; // now define the new function which will replace the previous definition function hello13(x, y, z) { z = MyValueOveride... } ``` If the external javascript file is dynamically loaded, then things are a little more complicated because you will need to figure out how to know when the dynamically loaded external JS file has been loaded so you can then define your override. You'd have to show us more about how the external JS file is loaded for us to offer specifics on how to do that.
Create a closure that redefines the function, then call the old function whenever your new function is called: ``` hello13 = (function () { // Keep a reference to the old function var _hello13 = hello13; // return a new function, which will be stored in hello13 return function (x, y, z) { z = MyValueOverride; return _hello13(x, y, z); }; }()); ``` Here's the fiddle: <http://jsfiddle.net/hKavH/>
14,543,274
I'm trying to select values from a database, but I need to check another value in another database . I created this code, but only get 1 result and I don't know why: ``` SELECT `id` FROM `mc_region` WHERE `is_subregion` = 'false' AND lastseen < CURDATE() - INTERVAL 20 DAY AND (SELECT id_region FROM mc_region_flags WHERE flag <> 'expire' AND id_region = mc_region.id ) LIMIT 0, 30 ``` What I've made wrong? @Edit I think I know why this code is not working. At database mc\_region\_flags not all records from the primary database has flag. I would like to do the following: 1º Select all records on the first database, where is not subregion and lastseen is more than 20 day 2º Check if any result on the 1st database has flag 'expire', if yes, they are not included in the result. I cant do this in 1 only SQL Code? @Edit2 I created this code that simulate `FULL JOIN` but seems that `WHERE` is not work ``` SELECT * FROM mc_region AS r RIGHT OUTER JOIN mc_region_flags AS f ON r.id = f.id_region UNION ALL SELECT * from mc_region AS r LEFT OUTER JOIN mc_region_flags AS f ON r.id = f.id_region WHERE r.is_subregion = 'false' AND f.flag = 'exipre' AND r.lastseen < CURDATE() - INTERVAL 20 DAY ``` Problems WHERE not work 1. `f.flag` is not 'expire' 2. `f.lastseen` is not > 20 days ![results](https://i.stack.imgur.com/atj2Y.png)
2013/01/27
[ "https://Stackoverflow.com/questions/14543274", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1821304/" ]
If it's a globally defined function in some javascript that is loaded via an inline script tag (either locally defined or in an external JS file), you can just redefine it with your own version of that function. Whichever definition comes last will be the active one. So, it sounds like what you want to do is to provide your own definition right after the external JS file containing the target function. That way your definition will replace the original one. If you want to retain the original one, you can assign it to another variable name before replacing it. ``` // save original function reference (if desired) var originHello13 = hello13; // now define the new function which will replace the previous definition function hello13(x, y, z) { z = MyValueOveride... } ``` If the external javascript file is dynamically loaded, then things are a little more complicated because you will need to figure out how to know when the dynamically loaded external JS file has been loaded so you can then define your override. You'd have to show us more about how the external JS file is loaded for us to offer specifics on how to do that.
Redefine it. If you want to use the logic in the original function, store the reference to the original function and then redefine it and call the original from the new one: ``` var originalHello13 = hello13; hello13 = function( x, y, z ){ z = MyValueOverride. return originalHello13( x, y, z ); } ```
14,543,274
I'm trying to select values from a database, but I need to check another value in another database . I created this code, but only get 1 result and I don't know why: ``` SELECT `id` FROM `mc_region` WHERE `is_subregion` = 'false' AND lastseen < CURDATE() - INTERVAL 20 DAY AND (SELECT id_region FROM mc_region_flags WHERE flag <> 'expire' AND id_region = mc_region.id ) LIMIT 0, 30 ``` What I've made wrong? @Edit I think I know why this code is not working. At database mc\_region\_flags not all records from the primary database has flag. I would like to do the following: 1º Select all records on the first database, where is not subregion and lastseen is more than 20 day 2º Check if any result on the 1st database has flag 'expire', if yes, they are not included in the result. I cant do this in 1 only SQL Code? @Edit2 I created this code that simulate `FULL JOIN` but seems that `WHERE` is not work ``` SELECT * FROM mc_region AS r RIGHT OUTER JOIN mc_region_flags AS f ON r.id = f.id_region UNION ALL SELECT * from mc_region AS r LEFT OUTER JOIN mc_region_flags AS f ON r.id = f.id_region WHERE r.is_subregion = 'false' AND f.flag = 'exipre' AND r.lastseen < CURDATE() - INTERVAL 20 DAY ``` Problems WHERE not work 1. `f.flag` is not 'expire' 2. `f.lastseen` is not > 20 days ![results](https://i.stack.imgur.com/atj2Y.png)
2013/01/27
[ "https://Stackoverflow.com/questions/14543274", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1821304/" ]
Redefine it. If you want to use the logic in the original function, store the reference to the original function and then redefine it and call the original from the new one: ``` var originalHello13 = hello13; hello13 = function( x, y, z ){ z = MyValueOverride. return originalHello13( x, y, z ); } ```
Create a closure that redefines the function, then call the old function whenever your new function is called: ``` hello13 = (function () { // Keep a reference to the old function var _hello13 = hello13; // return a new function, which will be stored in hello13 return function (x, y, z) { z = MyValueOverride; return _hello13(x, y, z); }; }()); ``` Here's the fiddle: <http://jsfiddle.net/hKavH/>
73,689
I have a data set which looks something like this (not real data): ``` conc Resp 0 5 0.1 18 0.2 20 0.3 23 0.4 24 0.5 24.5 0 5 0.1 17 .. .. ``` which happens to fit perfectly to the Michaelis-Menten equation: > > Resp = max\_value \* conc / (conc\_value\_at\_half\_max + conc) > > > Even though it is something else entirely importantly, the response increases quickly with "conc" and then reaches a ceiling or max value of sorts. Anyway, I want to know how low I can go in "conc" before the value of "Resp" is not significantly lower than the max value. Using a simple ANOVA accomplices this nicely, but I was thinking: "should I not be exploiting the fact that the structure of the data is so nicely explained by a known equation?" Is there such a way? I am using minitab for this because it is easier, but would work in `R` all the time.
2013/10/24
[ "https://stats.stackexchange.com/questions/73689", "https://stats.stackexchange.com", "https://stats.stackexchange.com/users/31891/" ]
I think you should rethink the question. Why would it possibly matter to find the highest concentration where the response is far enough below the maximum plateau to give a P value less than some arbitrary threshold? If you added more concentrations, or collected replicate values, or obtained cleaner (smaller experimental error) data, then you'd reach a different conclusion about the largest concentration that gives a response "significantly" less than the plateau. So the answer to that question is partly determined by details of the experimental design that you can change. The answer tells you nothing fundamental about the system. As with most questions in statistics, I urge you to set aside the word "significant" and try to articulate the question you want answered in scientific terms.
You could model it using nonlinear least squares regression, then use the modeled values and SE of the fit to determine the conc level that is "different" than the max. Once you fit the model, you could brute force search progressively lower thresholds until you reach a conc where Resp differs by a pre-specified alpha value from the max value and the estimated error around that. So, fit a nls, then write a for loop to calculate the p values for, say, a t-test comparison, and search that for the critical conc value you're looking for.
20,417,228
I need to create a list of size N from already given list. ``` N = 3 a_list = [10,4,18,2,6,19,24,1,20] ``` The O/P should be: ``` [10,4,18] [4,18,2] [18,2,6] [2,6,19] [6,19,24] [19,24,1] [24,1,20] ``` It's like a window size of N=3 , which slides one step to its right. How will I do it?
2013/12/06
[ "https://Stackoverflow.com/questions/20417228", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1162512/" ]
A faster way: ``` >>> zip(a_list,a_list[1:],a_list[2:]) [(10, 4, 18), (4, 18, 2), (18, 2, 6), (2, 6, 19), (6, 19, 24), (19, 24, 1), (24, 1, 20)] ``` Comparison: ``` In [6]: %timeit [a_list[i:i+n] for i in xrange(len(a_list)-n+1)] 100000 loops, best of 3: 9.61 us per loop In [7]: %timeit zip(a_list,a_list[1:],a_list[2:]) 100000 loops, best of 3: 5.23 us per loop ``` Or more general: ``` >>> zip(*[a_list[i:] for i in range(3)]) #3 (or 2, 4, 5, etc)is the length of step ``` For larger `list`, probably you have to use `numpy` to get a faster solution than @Ashwini Chaudhary's (<http://www.rigtorp.se/2011/01/01/rolling-statistics-numpy.html>): ``` import numpy as np lista=np.array(lis) def rolling_window(a, window): shape = a.shape[:-1] + (a.shape[-1] - window + 1, window) strides = a.strides + (a.strides[-1],) return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides) %timeit [lis[i:i+n] for i in xrange(len(lis)-n+1)] %timeit rolling_window(lista, n) 1 loops, best of 3: 171 ms per loop 100000 loops, best of 3: 19.7 µs per loop ```
Use list comprehension and slicing: ``` >>> lis = [10,4,18,2,6,19,24,1,20] >>> n = 3 >>> [lis[i:i+n] for i in xrange(len(lis)-n+1)] [[10, 4, 18], [4, 18, 2], [18, 2, 6], [2, 6, 19], [6, 19, 24], [19, 24, 1], [24, 1, 20]] >>> n = 4 >>> [lis[i:i+n] for i in xrange(len(lis)-n+1)] [[10, 4, 18, 2], [4, 18, 2, 6], [18, 2, 6, 19], [2, 6, 19, 24], [6, 19, 24, 1], [19, 24, 1, 20]] ``` For a bigger list the `zip` based approach is actually slower: ``` In [27]: n = 100 In [28]: lis = [10,4,18,2,6,19,24,1,20]*10000 In [30]: %timeit zip(*[lis[i:] for i in xrange(n)]) 1 loops, best of 3: 593 ms per loop In [31]: %timeit [lis[i:i+n] for i in xrange(len(lis)-n+1)] 10 loops, best of 3: 114 ms per loop ```
20,417,228
I need to create a list of size N from already given list. ``` N = 3 a_list = [10,4,18,2,6,19,24,1,20] ``` The O/P should be: ``` [10,4,18] [4,18,2] [18,2,6] [2,6,19] [6,19,24] [19,24,1] [24,1,20] ``` It's like a window size of N=3 , which slides one step to its right. How will I do it?
2013/12/06
[ "https://Stackoverflow.com/questions/20417228", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1162512/" ]
Use list comprehension and slicing: ``` >>> lis = [10,4,18,2,6,19,24,1,20] >>> n = 3 >>> [lis[i:i+n] for i in xrange(len(lis)-n+1)] [[10, 4, 18], [4, 18, 2], [18, 2, 6], [2, 6, 19], [6, 19, 24], [19, 24, 1], [24, 1, 20]] >>> n = 4 >>> [lis[i:i+n] for i in xrange(len(lis)-n+1)] [[10, 4, 18, 2], [4, 18, 2, 6], [18, 2, 6, 19], [2, 6, 19, 24], [6, 19, 24, 1], [19, 24, 1, 20]] ``` For a bigger list the `zip` based approach is actually slower: ``` In [27]: n = 100 In [28]: lis = [10,4,18,2,6,19,24,1,20]*10000 In [30]: %timeit zip(*[lis[i:] for i in xrange(n)]) 1 loops, best of 3: 593 ms per loop In [31]: %timeit [lis[i:i+n] for i in xrange(len(lis)-n+1)] 10 loops, best of 3: 114 ms per loop ```
try this ``` >>> lis = [10,4,18,2,6,19,24,1,20] >>> n=3 >>> [lis[i:i+n] for i in range(len(lis))][:-2] ``` the output is ``` [[10, 4, 18], [4, 18, 2], [18, 2, 6], [2, 6, 19], [6, 19, 24], [19, 24, 1], [24, 1, 20]] ```
20,417,228
I need to create a list of size N from already given list. ``` N = 3 a_list = [10,4,18,2,6,19,24,1,20] ``` The O/P should be: ``` [10,4,18] [4,18,2] [18,2,6] [2,6,19] [6,19,24] [19,24,1] [24,1,20] ``` It's like a window size of N=3 , which slides one step to its right. How will I do it?
2013/12/06
[ "https://Stackoverflow.com/questions/20417228", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1162512/" ]
A faster way: ``` >>> zip(a_list,a_list[1:],a_list[2:]) [(10, 4, 18), (4, 18, 2), (18, 2, 6), (2, 6, 19), (6, 19, 24), (19, 24, 1), (24, 1, 20)] ``` Comparison: ``` In [6]: %timeit [a_list[i:i+n] for i in xrange(len(a_list)-n+1)] 100000 loops, best of 3: 9.61 us per loop In [7]: %timeit zip(a_list,a_list[1:],a_list[2:]) 100000 loops, best of 3: 5.23 us per loop ``` Or more general: ``` >>> zip(*[a_list[i:] for i in range(3)]) #3 (or 2, 4, 5, etc)is the length of step ``` For larger `list`, probably you have to use `numpy` to get a faster solution than @Ashwini Chaudhary's (<http://www.rigtorp.se/2011/01/01/rolling-statistics-numpy.html>): ``` import numpy as np lista=np.array(lis) def rolling_window(a, window): shape = a.shape[:-1] + (a.shape[-1] - window + 1, window) strides = a.strides + (a.strides[-1],) return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides) %timeit [lis[i:i+n] for i in xrange(len(lis)-n+1)] %timeit rolling_window(lista, n) 1 loops, best of 3: 171 ms per loop 100000 loops, best of 3: 19.7 µs per loop ```
try this ``` >>> lis = [10,4,18,2,6,19,24,1,20] >>> n=3 >>> [lis[i:i+n] for i in range(len(lis))][:-2] ``` the output is ``` [[10, 4, 18], [4, 18, 2], [18, 2, 6], [2, 6, 19], [6, 19, 24], [19, 24, 1], [24, 1, 20]] ```
20,835,808
I am using 3DESC to decrypt data but i am getting following exception ``` java.security.InvalidKeyException: Invalid key length: 16 bytes ``` My Code: ``` public static byte[] decrypt3DESCBC(byte[] keyBytes, byte[] ivBytes, byte[] dataBytes) { try { AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes); SecretKeySpec newKey = new SecretKeySpec(keyBytes, "DESede"); Cipher cipher = Cipher.getInstance("DESede/CBC/NoPadding"); cipher.init(Cipher.DECRYPT_MODE, newKey, ivSpec); // Causes Exception return cipher.doFinal(dataBytes); } catch (Exception e) { e.printStackTrace(); } return null; } ``` Printed all the byte array above used ``` keyBytes : FC15780BB4B0**********0876482C1B // Masked 10 Characters ivBytes : 0000000000000000 dataBytes : AF53C90F7FAD977E**********69DB5A2BF3080F9F07F4BFEA3EDB4DE96887BE7D40A5A590C0911A // Masked 10 Characters ```
2013/12/30
[ "https://Stackoverflow.com/questions/20835808", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1169180/" ]
DES-EDE cipher can be used with 3 different subkeys therefore the key size should be 24 bytes (3 times 8 bytes). If you want to use only 2 keys (i.e. in this mode first key == last key) then you just have to duplicate the first 8 bytes of the key array. ``` byte[] key; if (keyBytes.length == 16) { key = new byte[24]; System.arraycopy(keyBytes, 0, key, 0, 16); System.arraycopy(keyBytes, 0, key, 16, 8); } else { key = keyBytes; } ```
You are using an older Java version that does not handle 128 bit key lengths. In principle, 3DES always uses three keys - keys ABC - which are 64 bit each when we include the parity bits into the count (for a single DES encrypt with A, then decrypt with B, then encrypt again with C). 128 bit (dual) key however uses A = C. So to create a valid 24 byte key, you need to copy and concatenate the first 8 bytes to the tail of the array. Or you could upgrade to a newer JRE, or use a provider that does accept 16 byte 3DES keys. Note that 192 bit (168 bit effective) 3DES keys are quite a bit more secure than 128 (112 bit effective) bit keys; 128 bit 3DES is not accepted by NIST (which handles US government standardization of cryptography) anymore. You should try and switch to AES if possible; AES doesn't have these kind of shenanigans and is much more secure.
44,706,737
So I have a project I'm working on where I have a large excel spreadsheet and I want to search one of the columns/cells and if the cell contains a certain word then I want to add a tag in another column but the same row. So the cell would have a long description in it and if the description contained a keyword I'm looking for it would add a tag in another column in the same row. I would like to able to search for more than one keyword at a time. I've messed around with openpyxl for awhile but that hasn't really panned out. I am familiar with python, C, C++, and Java so if you could help me with any of those languages I would really appreciate it. Python is preferred.
2017/06/22
[ "https://Stackoverflow.com/questions/44706737", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8201484/" ]
It's actually vertically centered, because the bottom offset for letters such as **"j,q,g,p .."** - with a bottom part/descender. Just try to paste any text with those letters in "span" tag, like so: ``` <div> <span> <span>Eqpjg combinedqjpg</span> </span> </div> ``` I created this example for you <https://jsfiddle.net/vfusz07z/1/>. And vice versa if you have letters in the words/sentences that I mentioned above and at the same time you don't have capital letters there you'll see that text looks aligned to the bottom
You have no letters with descenders in your example. Try it with a word like "Tagcloud" or "Taj Mahal" - (letters g, j) then you'll see that it fills the whole height...
44,706,737
So I have a project I'm working on where I have a large excel spreadsheet and I want to search one of the columns/cells and if the cell contains a certain word then I want to add a tag in another column but the same row. So the cell would have a long description in it and if the description contained a keyword I'm looking for it would add a tag in another column in the same row. I would like to able to search for more than one keyword at a time. I've messed around with openpyxl for awhile but that hasn't really panned out. I am familiar with python, C, C++, and Java so if you could help me with any of those languages I would really appreciate it. Python is preferred.
2017/06/22
[ "https://Stackoverflow.com/questions/44706737", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8201484/" ]
It's actually vertically centered, because the bottom offset for letters such as **"j,q,g,p .."** - with a bottom part/descender. Just try to paste any text with those letters in "span" tag, like so: ``` <div> <span> <span>Eqpjg combinedqjpg</span> </span> </div> ``` I created this example for you <https://jsfiddle.net/vfusz07z/1/>. And vice versa if you have letters in the words/sentences that I mentioned above and at the same time you don't have capital letters there you'll see that text looks aligned to the bottom
Well it would appear that the font (Avenir Pro) just happens to be weirdly baselined.
44,706,737
So I have a project I'm working on where I have a large excel spreadsheet and I want to search one of the columns/cells and if the cell contains a certain word then I want to add a tag in another column but the same row. So the cell would have a long description in it and if the description contained a keyword I'm looking for it would add a tag in another column in the same row. I would like to able to search for more than one keyword at a time. I've messed around with openpyxl for awhile but that hasn't really panned out. I am familiar with python, C, C++, and Java so if you could help me with any of those languages I would really appreciate it. Python is preferred.
2017/06/22
[ "https://Stackoverflow.com/questions/44706737", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8201484/" ]
You have no letters with descenders in your example. Try it with a word like "Tagcloud" or "Taj Mahal" - (letters g, j) then you'll see that it fills the whole height...
Well it would appear that the font (Avenir Pro) just happens to be weirdly baselined.
25,074,075
For some functions in OpenGL, one must specify a byte offset, such as in `glVertexAttribPointer()`, for stride. At first I would have guessed that it would be a normal number value like an integer. But upon inspection, I realized that it needs to be casted to `void*` (more specifically `GLvoid*`). My question is: what is the intended meaning of `void*` and why must it be used for a byte offset?
2014/08/01
[ "https://Stackoverflow.com/questions/25074075", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1775989/" ]
glVertexAttribPointer() is an older function from before Vertex Buffer Objects. Before VBO's your vertex data would be stored in client side arrays and you would need to pass a pointer to the data to OpenGL before you could draw. When VBO's came along they repurposed this function by allowing the pointer to be used to pass an integer offset. e.g. `void* offset = (void*)offsetof(vertexStructName, vertexMemberName);`
It's called void pointer and it can point at any type, like char\* does - but it's slightly different. Firstly you have to remember that the pointer is just a number, an address to right location, nothing more. To use data pointed by void pointer you have to explicitly cast it to correct type, they cannot be dereferenced directly. They allow you to skip type checking and they should be avoided. Another difference I see is clarity of intentions. When you see char\* pointer you can't be sure it'll point at char/char array. It can be something else, it's highly situational: I saw cases when it's confusing, sometimes it's obvious; on the other hand void pointer intentions are clear: it can be really anything and you have to consider the context of application to find the type. Another thing is pointer arithmetics, AFAIR in case of void pointers it's not defined by standard. I guess void pointers in OpenGL are used to make API more general, giving more control to drivers (it makes changing types from floats to doubles easier, by settings). But that's only speculation, confirmation is needed.
25,074,075
For some functions in OpenGL, one must specify a byte offset, such as in `glVertexAttribPointer()`, for stride. At first I would have guessed that it would be a normal number value like an integer. But upon inspection, I realized that it needs to be casted to `void*` (more specifically `GLvoid*`). My question is: what is the intended meaning of `void*` and why must it be used for a byte offset?
2014/08/01
[ "https://Stackoverflow.com/questions/25074075", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1775989/" ]
Some OpenGL functions, such as [`glDrawElements`](https://www.opengl.org/sdk/docs/man/html/glDrawElements.xhtml) take a `GLvoid *` parameter that is context dependant. On old GL, pre Vertex Buffers, the programmer would pass an array of integer indexes directly to `glDrawElements`, like this: ``` const GLuint indexes[] = { ... }; glDrawElements(GL_TRIANGLES, numIndexes, GL_UNSIGNED_INT, indexes); ``` That was called the *immediate mode* drawing. When Vertex and Index Buffers were introduced, the OpenGL architecture board decided that they should reuse the existing interfaces, thus giving a new context dependant meaning to that last void pointer parameter of `glDrawElements`, `glVertexAttribPointer` and a few other similar functions. With Index Buffers, the rendering data is already on the GPU, so the void pointer param is meant to be an *offset* into the buffer. E.g.: The first index to render. Leading to a new usage of `glDrawElements`: ``` size_t firstIndex = ... size_t indexDataSize = sizeof(GLuint); glDrawElements(GL_TRIANGLES, numIndexes, GL_UNSIGNED_INT, reinterpret_cast<const GLvoid *>(firstIndex * indexDataSize)); ``` This applies to all the older functions that were repurposed on modern OpenGL, like `glDrawElementsInstanced`, `glDrawElementsBaseVertex`, `glDrawRangeElements` and others. Now in the specific case of [`glVertexAttribPointer`](http://www.opengl.org/wiki/GLAPI/glVertexAttribPointer): ``` void glVertexAttribPointer(GLuint index​, GLint size​, GLenum type​, GLboolean normalized​, GLsizei stride​, const GLvoid * pointer​); ``` The `const GLvoid * pointer​` parameter is an offset in bytes from the beginning of the vertex to the given element. Again, it was kept like this because the function existed before Vertex/Index Buffers and was repurposed to work with them, whereas in the immediate mode days, you would pass an array of vertexes as the 'pointer' parameter. So in the old days, `glVertexAttribPointer` would be used somewhat like: ``` const vec3 positions[] = { ... }; glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, positions); ``` And in modern GL, you would use: ``` struct Vert { vec3 position; vec3 normal; }; size_t offset; offset = offsetof(Vert, position); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, reinterpret_cast<const GLvoid *>(offset)); offset = offsetof(Vert, normal); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, reinterpret_cast<const GLvoid *>(offset)); ```
It's called void pointer and it can point at any type, like char\* does - but it's slightly different. Firstly you have to remember that the pointer is just a number, an address to right location, nothing more. To use data pointed by void pointer you have to explicitly cast it to correct type, they cannot be dereferenced directly. They allow you to skip type checking and they should be avoided. Another difference I see is clarity of intentions. When you see char\* pointer you can't be sure it'll point at char/char array. It can be something else, it's highly situational: I saw cases when it's confusing, sometimes it's obvious; on the other hand void pointer intentions are clear: it can be really anything and you have to consider the context of application to find the type. Another thing is pointer arithmetics, AFAIR in case of void pointers it's not defined by standard. I guess void pointers in OpenGL are used to make API more general, giving more control to drivers (it makes changing types from floats to doubles easier, by settings). But that's only speculation, confirmation is needed.
25,074,075
For some functions in OpenGL, one must specify a byte offset, such as in `glVertexAttribPointer()`, for stride. At first I would have guessed that it would be a normal number value like an integer. But upon inspection, I realized that it needs to be casted to `void*` (more specifically `GLvoid*`). My question is: what is the intended meaning of `void*` and why must it be used for a byte offset?
2014/08/01
[ "https://Stackoverflow.com/questions/25074075", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1775989/" ]
glVertexAttribPointer() is an older function from before Vertex Buffer Objects. Before VBO's your vertex data would be stored in client side arrays and you would need to pass a pointer to the data to OpenGL before you could draw. When VBO's came along they repurposed this function by allowing the pointer to be used to pass an integer offset. e.g. `void* offset = (void*)offsetof(vertexStructName, vertexMemberName);`
Some OpenGL functions, such as [`glDrawElements`](https://www.opengl.org/sdk/docs/man/html/glDrawElements.xhtml) take a `GLvoid *` parameter that is context dependant. On old GL, pre Vertex Buffers, the programmer would pass an array of integer indexes directly to `glDrawElements`, like this: ``` const GLuint indexes[] = { ... }; glDrawElements(GL_TRIANGLES, numIndexes, GL_UNSIGNED_INT, indexes); ``` That was called the *immediate mode* drawing. When Vertex and Index Buffers were introduced, the OpenGL architecture board decided that they should reuse the existing interfaces, thus giving a new context dependant meaning to that last void pointer parameter of `glDrawElements`, `glVertexAttribPointer` and a few other similar functions. With Index Buffers, the rendering data is already on the GPU, so the void pointer param is meant to be an *offset* into the buffer. E.g.: The first index to render. Leading to a new usage of `glDrawElements`: ``` size_t firstIndex = ... size_t indexDataSize = sizeof(GLuint); glDrawElements(GL_TRIANGLES, numIndexes, GL_UNSIGNED_INT, reinterpret_cast<const GLvoid *>(firstIndex * indexDataSize)); ``` This applies to all the older functions that were repurposed on modern OpenGL, like `glDrawElementsInstanced`, `glDrawElementsBaseVertex`, `glDrawRangeElements` and others. Now in the specific case of [`glVertexAttribPointer`](http://www.opengl.org/wiki/GLAPI/glVertexAttribPointer): ``` void glVertexAttribPointer(GLuint index​, GLint size​, GLenum type​, GLboolean normalized​, GLsizei stride​, const GLvoid * pointer​); ``` The `const GLvoid * pointer​` parameter is an offset in bytes from the beginning of the vertex to the given element. Again, it was kept like this because the function existed before Vertex/Index Buffers and was repurposed to work with them, whereas in the immediate mode days, you would pass an array of vertexes as the 'pointer' parameter. So in the old days, `glVertexAttribPointer` would be used somewhat like: ``` const vec3 positions[] = { ... }; glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, positions); ``` And in modern GL, you would use: ``` struct Vert { vec3 position; vec3 normal; }; size_t offset; offset = offsetof(Vert, position); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, reinterpret_cast<const GLvoid *>(offset)); offset = offsetof(Vert, normal); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, reinterpret_cast<const GLvoid *>(offset)); ```
21,354,416
I need to get rid of words that are duplicated within a column of spreadsheet cells. I can use Excel or OpenOffice as I have both. I want to get rid of the any duplicated words within a cell ... for instance ... happy, sad, fun, happy, silly, sad, jokey, - would become - happy, sad, fun, silly, jokey, (duplicate words removed.) I would need a step by step guide on how to create a macro and apply it to the column of offending cells! Thanks for any help!
2014/01/25
[ "https://Stackoverflow.com/questions/21354416", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3235839/" ]
You can have a RelativeLayout. Place the LinearLayout at the bottom. Place listview above LinearLayout. ``` <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" > <LinearLayout // this can be vartical or horizontal orientation depending on your need android:id="@+id/linearLayout1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" android:gravity="center" android:orientation="horizontal" > <EditText android:id="@+id/editText2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:ems="10" /> <Button android:id="@+id/button1" style="?android:attr/buttonStyleSmall" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="enviar" /> </LinearLayout> <ListView android:id="@+id/listView1" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_above="@+id/linearLayout1" android:layout_centerHorizontal="true" > </ListView> </RelativeLayout> ``` Or Using single RelativeLayout ``` <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" > <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_alignParentRight="true" android:text="Button" /> <EditText android:id="@+id/editText1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_alignParentLeft="true" android:ems="10" > <requestFocus /> </EditText> <ListView android:id="@+id/listView1" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_above="@+id/editText1" android:layout_alignEnd="@+id/button1" android:layout_alignParentRight="true" > </ListView> </RelativeLayout> ```
I would recommend using a relative layout that holds both the list view and your buttons. Set their layout weight attributes so that they take up the screen. Layout weight of 1 on one object and 7 on the other, for example, makes one take 7/8 of the screen while the other takes 1/8. If you need to be able to see more list view than that, put it in a scroll view.
152,196
There seems to have been some interest over the past year around COP within the .NET community (ala [Qi4j](http://www.qi4j.org/)). A few folks have rolled there own COP frameworks (*see links below*) and it would appear .NET 4.0's Dynamic Dispatch and MEF might have a potential role in any .NET COP framework. On one hand a lot of this would appear to hark back to ideas from System/38 days (*yes, I'm an old guy*), though on the other it would also seem to be a pretty good fit with Oslo (*Modeling and Repository*). Can anyone comment on the whether Microsoft is doing any work on COP? Some recent .NET COP framework efforts: Hendry Luk - [Roll Your Own COP](http://hendryluk.wordpress.com/2008/05/28/roll_your_own_cop_part_i_mixins/) Yves GoEleven.com - [Cop - Proof of concept](http://www.goeleven.com/blog/entryDetail.aspx?entry=147) Anders Norås - [Trick or Trait? Composite Oriented Programming with C#](http://andersnoras.com/blogs/anoras/archive/2008/08/21/trick-or-trait-composite-oriented-programming-with-c.aspx) Magnus Mårtensson - [Composite Oriented Programming spike on Unity Application Block](http://blog.noop.se/archive/2008/08/27/composite-oriented-programming-spike-on-unity-application-block.aspx)
2008/09/30
[ "https://Stackoverflow.com/questions/152196", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5946/" ]
Aku - There is considerable difference between the CAB / Composite WPF guidance and COP which is a fundamentally different approach to the expression of object behavior via the assembly of 'fragments' based on [Domain] context. The appearance of Mixins, Concerns, Constraints, and SideEffects in .NET 4.0 variously might point in that direction, but I guess I'm more specifically curious if Microsoft is by chance, or in any way, formally "doing COP" and in particular on top of the Oslo repository.
> > Can anyone comment on the whether > Microsoft is doing any work on COP? > > > Microsoft released [Composite Application Block](http://msdn.microsoft.com/en-us/library/aa480450.aspx) and [Composite WPF](http://msdn.microsoft.com/en-us/library/cc707819.aspx), They have DI FW (Unity). Now they are working on MEF. What should we comment here ?
152,196
There seems to have been some interest over the past year around COP within the .NET community (ala [Qi4j](http://www.qi4j.org/)). A few folks have rolled there own COP frameworks (*see links below*) and it would appear .NET 4.0's Dynamic Dispatch and MEF might have a potential role in any .NET COP framework. On one hand a lot of this would appear to hark back to ideas from System/38 days (*yes, I'm an old guy*), though on the other it would also seem to be a pretty good fit with Oslo (*Modeling and Repository*). Can anyone comment on the whether Microsoft is doing any work on COP? Some recent .NET COP framework efforts: Hendry Luk - [Roll Your Own COP](http://hendryluk.wordpress.com/2008/05/28/roll_your_own_cop_part_i_mixins/) Yves GoEleven.com - [Cop - Proof of concept](http://www.goeleven.com/blog/entryDetail.aspx?entry=147) Anders Norås - [Trick or Trait? Composite Oriented Programming with C#](http://andersnoras.com/blogs/anoras/archive/2008/08/21/trick-or-trait-composite-oriented-programming-with-c.aspx) Magnus Mårtensson - [Composite Oriented Programming spike on Unity Application Block](http://blog.noop.se/archive/2008/08/27/composite-oriented-programming-spike-on-unity-application-block.aspx)
2008/09/30
[ "https://Stackoverflow.com/questions/152196", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5946/" ]
> > Can anyone comment on the whether > Microsoft is doing any work on COP? > > > Microsoft released [Composite Application Block](http://msdn.microsoft.com/en-us/library/aa480450.aspx) and [Composite WPF](http://msdn.microsoft.com/en-us/library/cc707819.aspx), They have DI FW (Unity). Now they are working on MEF. What should we comment here ?
Check MEF <http://mef.codeplex.com>, currently shipped inside .NET 4, more in PDC session <http://microsoftpdc.com/Sessions/FT24>
152,196
There seems to have been some interest over the past year around COP within the .NET community (ala [Qi4j](http://www.qi4j.org/)). A few folks have rolled there own COP frameworks (*see links below*) and it would appear .NET 4.0's Dynamic Dispatch and MEF might have a potential role in any .NET COP framework. On one hand a lot of this would appear to hark back to ideas from System/38 days (*yes, I'm an old guy*), though on the other it would also seem to be a pretty good fit with Oslo (*Modeling and Repository*). Can anyone comment on the whether Microsoft is doing any work on COP? Some recent .NET COP framework efforts: Hendry Luk - [Roll Your Own COP](http://hendryluk.wordpress.com/2008/05/28/roll_your_own_cop_part_i_mixins/) Yves GoEleven.com - [Cop - Proof of concept](http://www.goeleven.com/blog/entryDetail.aspx?entry=147) Anders Norås - [Trick or Trait? Composite Oriented Programming with C#](http://andersnoras.com/blogs/anoras/archive/2008/08/21/trick-or-trait-composite-oriented-programming-with-c.aspx) Magnus Mårtensson - [Composite Oriented Programming spike on Unity Application Block](http://blog.noop.se/archive/2008/08/27/composite-oriented-programming-spike-on-unity-application-block.aspx)
2008/09/30
[ "https://Stackoverflow.com/questions/152196", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5946/" ]
Aku - There is considerable difference between the CAB / Composite WPF guidance and COP which is a fundamentally different approach to the expression of object behavior via the assembly of 'fragments' based on [Domain] context. The appearance of Mixins, Concerns, Constraints, and SideEffects in .NET 4.0 variously might point in that direction, but I guess I'm more specifically curious if Microsoft is by chance, or in any way, formally "doing COP" and in particular on top of the Oslo repository.
Check MEF <http://mef.codeplex.com>, currently shipped inside .NET 4, more in PDC session <http://microsoftpdc.com/Sessions/FT24>
67,725,991
I have a list of data frames, and I want to remove all the data frames that have no observations from the list. ``` df.list <- list(structure(list(Date = structure(c(1621814400, 1621900800), class = c("POSIXct", "POSIXt"), tzone = "UTC"), units = c(7,9), dollars = c(41.93, 53.91), margin = c(20.09, 25.83), margin_pct = c(0.479131,0.479131)), row.names = c(NA, -2L), class = c("tbl_df", "tbl","data.frame")), structure(list(Date = structure(c(1621641600,1621728000, 1621814400, 1621900800), class = c("POSIXct", "POSIXt"), tzone = "UTC"), units = c(2, 4, 28, 45), dollars = c(2.78,5.56, 37.32, 59.95), margin = c(2.23, 4.46, 29.6, 47.56), margin_pct = c(0.802158,0.802158, 0.79314, 0.793327)), row.names = c(NA, -4L), class = c("tbl_df","tbl", "data.frame")), structure(list(Date = structure(numeric(0), class = c("POSIXct","POSIXt"), tzone = "UTC"), units = numeric(0), dollars = numeric(0),margin = numeric(0), margin_pct = numeric(0)), row.names = integer(0), class = c("tbl_df","tbl", "data.frame")), structure(list(Date = structure(numeric(0), class = c("POSIXct","POSIXt"), tzone = "UTC"), units = numeric(0), dollars = numeric(0),margin = numeric(0), margin_pct = numeric(0)), row.names = integer(0), class = c("tbl_df","tbl", "data.frame"))) ``` ```
2021/05/27
[ "https://Stackoverflow.com/questions/67725991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6414727/" ]
Try this: ``` import collections for k, freq in collections.Counter(L).items(): print(f"{k} occurred {freq} times") ```
If you want to print these out as strings: ``` for i in set(L): print(f"{i} occurred {L.count(i)} times" ``` If you want to store these counts to use later in the code, use a dictionary: `d = {i: L.count(i) for i in set(L)`
50,757,796
I am reading Multiple JSON Files as such: ``` using (var fbd = new FolderBrowserDialog()) { DialogResult result = fbd.ShowDialog(); if (result == System.Windows.Forms.DialogResult.OK && !string.IsNullOrWhiteSpace(fbd.SelectedPath)) { IEnumerable<string> allJSONFiles = GetFileList("*.json", fbd.SelectedPath); txtOutput.Clear(); txtOutput.Text = "Number of files found: " + allJSONFiles.ToList().Count + "\n"; foreach (string filename in allJSONFiles) { txtOutput.Text += filename + "\n"; } } } ``` Now the JSON files more or less look like this, with multiple objects: ``` [{ "Domain": "example.com", "A": ["50.63.202.28"], "MX": ["0 example-com.mail.protection.outlook.com."], "NS": ["ns48.example.com.", "ns47.example.com."], "SOA": ["ns47.example.com. dns.jomax.net. 2017062304 28800 7200 604800 600"], "TXT": ["\"MS=ms94763887\"", "\"google-site-verification=example-f0KFEgl-HnJF4_Gk\"", "\"v=spf1 include:spf.protection.outlook.com -all\""], "Country": ["United States"], "Hostname": ["'ip-50-63-202-28.ip.secureserver.net'"], "SSL": ["None"], "WHOIS": [1096], "TTL": ["568"] }, { "Domain": "example.org", "A": ["50.63.202.59"], "MX": ["30 ALT2.ASPMX.L.GOOGLE.COM.", "20 ALT1.ASPMX.L.GOOGLE.COM.", "50 ASPMX3.GOOGLEMAIL.COM.", "10 ASPMX.L.GOOGLE.COM.", "40 ASPMX2.GOOGLEMAIL.COM."], "NS": ["ns13.example.com.", "ns14.example.com."], "SOA": ["ns13.example.com. dns.jomax.net. 2016081700 28800 7200 604800 600"], "Country": ["United States"], "Hostname": ["'ip-50-63-202-59.ip.secureserver.net'"], "SSL": ["None"], "WHOIS": [5844], "TTL": ["569"] } ] ``` All I want to do is to join these objects from the multiple files I am reading to create a single file as output. So assuming that there were 2 exactly same files as stated above, my output file would contain: ``` [{ "Domain": "example.com", "A": ["50.63.202.28"], "MX": ["0 example-com.mail.protection.outlook.com."], "NS": ["ns48.example.com.", "ns47.example.com."], "SOA": ["ns47.example.com. dns.jomax.net. 2017062304 28800 7200 604800 600"], "TXT": ["\"MS=ms94763887\"", "\"google-site-verification=example-f0KFEgl-HnJF4_Gk\"", "\"v=spf1 include:spf.protection.outlook.com -all\""], "Country": ["United States"], "Hostname": ["'ip-50-63-202-28.ip.secureserver.net'"], "SSL": ["None"], "WHOIS": [1096], "TTL": ["568"] }, { "Domain": "example.org", "A": ["50.63.202.59"], "MX": ["30 ALT2.ASPMX.L.GOOGLE.COM.", "20 ALT1.ASPMX.L.GOOGLE.COM.", "50 ASPMX3.GOOGLEMAIL.COM.", "10 ASPMX.L.GOOGLE.COM.", "40 ASPMX2.GOOGLEMAIL.COM."], "NS": ["ns13.example.com.", "ns14.example.com."], "SOA": ["ns13.example.com. dns.jomax.net. 2016081700 28800 7200 604800 600"], "Country": ["United States"], "Hostname": ["'ip-50-63-202-59.ip.secureserver.net'"], "SSL": ["None"], "WHOIS": [5844], "TTL": ["569"] }, { "Domain": "example.com", "A": ["50.63.202.28"], "MX": ["0 example-com.mail.protection.outlook.com."], "NS": ["ns48.example.com.", "ns47.example.com."], "SOA": ["ns47.example.com. dns.jomax.net. 2017062304 28800 7200 604800 600"], "TXT": ["\"MS=ms94763887\"", "\"google-site-verification=example-f0KFEgl-HnJF4_Gk\"", "\"v=spf1 include:spf.protection.outlook.com -all\""], "Country": ["United States"], "Hostname": ["'ip-50-63-202-28.ip.secureserver.net'"], "SSL": ["None"], "WHOIS": [1096], "TTL": ["568"] }, { "Domain": "example.org", "A": ["50.63.202.59"], "MX": ["30 ALT2.ASPMX.L.GOOGLE.COM.", "20 ALT1.ASPMX.L.GOOGLE.COM.", "50 ASPMX3.GOOGLEMAIL.COM.", "10 ASPMX.L.GOOGLE.COM.", "40 ASPMX2.GOOGLEMAIL.COM."], "NS": ["ns13.example.com.", "ns14.example.com."], "SOA": ["ns13.example.com. dns.jomax.net. 2016081700 28800 7200 604800 600"], "Country": ["United States"], "Hostname": ["'ip-50-63-202-59.ip.secureserver.net'"], "SSL": ["None"], "WHOIS": [5844], "TTL": ["569"] } ] ``` How do I achieve this without serializing (as the objects vary significantly and I want to retain the format somewhat) and merging? I tried [NewtonSoft's merge](https://www.newtonsoft.com/json/help/html/MergeJson.htm), but it seems too complicated for such simple operation. Is string manipulation my last option (somehow that doesn't feel correct, hence this question)? **Note:** While the example just shows 2 files, I will be merging atleast 100 files in a go.
2018/06/08
[ "https://Stackoverflow.com/questions/50757796", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1928597/" ]
We will need to have function which will clear brackets ``` private string RemoveBrackets(string content) { var openB = content.IndexOf("["); content = content.Substring(openB + 1, content.Length - openB - 1); var closeB = content.LastIndexOf("]"); content = content.Substring(0, closeB); return content; } ``` function to merge jsons ``` private string MergeJsons(string[] jsons) { var sb = new StringBuilder(); sb.AppendLine("["); for(var i=0; i<jsons.Length; i++) { var json = jsons[i]; var cleared = RemoveBrackets(json); sb.AppendLine(cleared); if (i != jsons.Length-1) sb.Append(","); } sb.AppendLine("]"); return sb.ToString(); } ``` sample data ``` string fileContent = @"[{ ""Domain"": ""example.com"", ""A"": [""50.63.202.28""], ""MX"": [""0 example-com.mail.protection.outlook.com.""], ""NS"": [""ns48.example.com."", ""ns47.example.com.""], ""SOA"": [""ns47.example.com. dns.jomax.net. 2017062304 28800 7200 604800 600""], ""TXT"": [""\""MS=ms94763887\"""", ""\""google-site-verification=example-f0KFEgl-HnJF4_Gk\"""", ""\""v=spf1 include:spf.protection.outlook.com -all\""""], ""Country"": [""United States""], ""Hostname"": [""'ip-50-63-202-28.ip.secureserver.net'""], ""SSL"": [""None""], ""WHOIS"": [1096], ""TTL"": [""568""] } ]"; ``` Example of usage ``` var files = Enumerable.Range(1, 3).Select(x=>fileContent).ToArray(); Console.WriteLine(MergeJsons(files)); ``` Results ``` [ { "Domain": "example.com", "A": ["50.63.202.28"], "MX": ["0 example-com.mail.protection.outlook.com."], "NS": ["ns48.example.com.", "ns47.example.com."], "SOA": ["ns47.example.com. dns.jomax.net. 2017062304 28800 7200 604800 600"], "TXT": ["\"MS=ms94763887\"", "\"google-site-verification=example-f0KFEgl-HnJF4_Gk\"", "\"v=spf1 include:spf.protection.outlook.com - all\""], "Country": ["United States"], "Hostname": ["'ip-50-63-202-28.ip.secureserver.net'"], "SSL": ["None"], "WHOIS": [1096], "TTL": ["568"] } ,{ "Domain": "example.com", "A": ["50.63.202.28"], "MX": ["0 example-com.mail.protection.outlook.com."], "NS": ["ns48.example.com.", "ns47.example.com."], "SOA": ["ns47.example.com. dns.jomax.net. 2017062304 28800 7200 604800 600"], "TXT": ["\"MS=ms94763887\"", "\"google-site-verification=example-f0KFEgl-HnJF4_Gk\"", "\"v=spf1 include:spf.protection.outlook.com - all\""], "Country": ["United States"], "Hostname": ["'ip-50-63-202-28.ip.secureserver.net'"], "SSL": ["None"], "WHOIS": [1096], "TTL": ["568"] } ,{ "Domain": "example.com", "A": ["50.63.202.28"], "MX": ["0 example-com.mail.protection.outlook.com."], "NS": ["ns48.example.com.", "ns47.example.com."], "SOA": ["ns47.example.com. dns.jomax.net. 2017062304 28800 7200 604800 600"], "TXT": ["\"MS=ms94763887\"", "\"google-site-verification=example-f0KFEgl-HnJF4_Gk\"", "\"v=spf1 include:spf.protection.outlook.com - all\""], "Country": ["United States"], "Hostname": ["'ip-50-63-202-28.ip.secureserver.net'"], "SSL": ["None"], "WHOIS": [1096], "TTL": ["568"] } ] ```
I'm not sure i understand what you mean, but seems that all the data you need is just into an "array-like" format, so using string manipulation you only need to do something like that: Read First file (usa a for with a counter that let you know what is the first file), replace last charcater with "," and add the whole 2nd file replacing first character with " " and last character with ",". Do the stuff of the 2nd file for all your files, when you finish replace last character with "]" and you've a single array of json stuff that can be read by a json serializer. The cose should be something like that (write at the moment on notepad, without visual studio opened, so it could contain some digit error): ``` string my_big_json = string.empty; for (int a = 0; a < allJSONFiles.Lenght; a++) { StreamReader sr = new StreamReader(allJSONFiles[a]); string temp_data = sr.ReadToEnd().TrimEnd().TrimStart(); sr.Close(); if(a = 0) { temp_data = temp_data.Substring(0,temp_data.Lenght -1) + ","; } else { temp_data = temp_data.Substring(1,temp_data.Lenght -1) + " "; if(a < allJSONFiles.LenghtallJSONFiles.Lenght -1) temp_data = temp_data.Substring(0,temp_data.Lenght -1) + ","; } my_big_json += temp_data; } ```
52,510,830
I need to use recursion but I can't seem to figure it out. I need to make a method to call that will convert a binary string into an int decimal form. I need to do this with recursion only. This means no global variables or loops. Here is what I have: ``` public class Practice { public static void main( String[] args ) { if( convert( "1010111" ) == 57) { System.out.println( "test worked: 57" ); } if( convert( "1110001" ) == 113) { System.out.println( "test worked: 113" ); } } public static int convert( String temp ) { Integer.parseInt(temp); if(Integer.parseInt(temp)>0) { return 0; } return temp/%100 + convert(temp*2) } } } ``` Output: > > test worked : 57 > > > test worked : 113 > > >
2018/09/26
[ "https://Stackoverflow.com/questions/52510830", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10387200/" ]
If the binary string is just one digit long the task is trivial. For strings of length `n > 1`, split into the first `n-1` digits and the last digit. Find the value of the first `n-1` digits via a recursive call and then multiply that result by two and add the last digit.
``` public static int convert( String s ) { int n = s.length(); if(n == 0) return 0; else return Character.getNumericValue(s.charAt(n-1)) + 2*convert(s.substring(0, n-1)); } ``` By the way, `1010111` is 87, not 57.
52,510,830
I need to use recursion but I can't seem to figure it out. I need to make a method to call that will convert a binary string into an int decimal form. I need to do this with recursion only. This means no global variables or loops. Here is what I have: ``` public class Practice { public static void main( String[] args ) { if( convert( "1010111" ) == 57) { System.out.println( "test worked: 57" ); } if( convert( "1110001" ) == 113) { System.out.println( "test worked: 113" ); } } public static int convert( String temp ) { Integer.parseInt(temp); if(Integer.parseInt(temp)>0) { return 0; } return temp/%100 + convert(temp*2) } } } ``` Output: > > test worked : 57 > > > test worked : 113 > > >
2018/09/26
[ "https://Stackoverflow.com/questions/52510830", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10387200/" ]
If you need to use recursion (as homework or exercise), here is the way you can consider: Pseudo code: ``` int convert(String input) { if input is empty { return 0; } else { int lastDigit = last digit of input String prefix = input excluding last digit int result = convert(prefix) * 2 + lastDigit } } ```
``` public static int convert( String s ) { int n = s.length(); if(n == 0) return 0; else return Character.getNumericValue(s.charAt(n-1)) + 2*convert(s.substring(0, n-1)); } ``` By the way, `1010111` is 87, not 57.
3,600,116
Let $\Omega$ be an open subset of $\mathbb{R^2}$ and $f$ a continuos function in $\Omega$. Is it true that, if $$\int\_{\Omega} f(x)g(x) dx = 0$$ $\forall g \in C\_c^{\infty}(\Omega) $ then $f=0$ in $\Omega$?
2020/03/29
[ "https://math.stackexchange.com/questions/3600116", "https://math.stackexchange.com", "https://math.stackexchange.com/users/749205/" ]
Suppose $f\neq 0$, i.e., there is $y\in \Omega $ s.t. $f(y)\neq 0$ (suppose WLOG that $f(y)>0$). By continuity, there is a ball $B(y,r)\subset \Omega $ s.t. $f(x)>0$ for all $x\in \overline{B(y,r)}$. Let $r'>r$ s.t. $B(y,r)\subset B(y,r')\subset \Omega $. Take $g\in \mathcal C^\infty $ s.t. $$g(x)=\begin{cases}1&x\in \overline{B(y,r)}\\ 0&x\in B(y,r')^c\end{cases}$$ and $0\leq g(x)\leq 1$ if $x\in B(y,r')\setminus \overline{B(y,r)}$. Such function exist. Then, $$\int\_\Omega fg\geq \int\_{B(y,r)}f>0,$$ which is a contradiction.
Under all these assumptions I would say that the answer is yes. Assume towards contradiction that $f(x)\not \equiv0$, then there exists $x\in \Omega $ such that $f(x\_0)\neq 0$, because $f$ is continuous. Assume without loss of generality that $f(x\_0)=\epsilon>0$. Then there exists $\delta>0$ such that $f(x)>\frac{\epsilon}{2}$ for all $\Vert x-x\_0\Vert<\delta$. There exists $h\_\delta\in C\_c^\infty$ satisfying that $h\_\delta \vert\_{B(x\_0,\delta/2)}=1$, $h\_\delta (x)=0$ when $\Vert x-x\_0\Vert \geq \delta$ and $\vert h\_\delta \vert\leq 1$. You would get that $\int f \cdot h\_\delta \geq \frac{\epsilon}{2}\cdot \vert B(x\_0,\delta/2)\vert>0$ and this is a contradiction. I can see that @Surb has already written an answer, but since it took me a while to write this, I'll leave it.
61,918,207
I got following migration in django: ``` # Generated by Django 2.2.12 on 2020-05-20 16:22 from django.db import migrations import re def numeric_version(version): digits = 4 pattern = r"(\d+).(\d+).(\d+)" major, minor, patch = tuple(map(int, re.findall(pattern, version)[0])) return patch + pow(10, digits) * minor + pow(10, 2 * digits) * major def insert_numeric_software_version(apps, scheme_editor): Device = apps.get_model("devices", "Device") for device in Device.objects.all(): if device.software_version is not None: device.numeric_software_version = numeric_version(device.software_version) class Migration(migrations.Migration): dependencies = [ ("devices", "0037_device_numeric_software_version"), ] operations = [insert_numeric_software_version] ``` It should fill the "numeric\_software\_version" field in the database with numeric fields. In the model this field is: ``` numeric_software_version = models.IntegerField(default=0) ``` When I run "`python manage.py migrate`" I got following error: ``` File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/usr/local/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 234, in handle fake_initial=fake_initial, File "/usr/local/lib/python3.6/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 "/usr/local/lib/python3.6/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 "/usr/local/lib/python3.6/site-packages/django/db/migrations/executor.py", line 245, in apply_migration state = migration.apply(state, schema_editor) File "/usr/local/lib/python3.6/site-packages/django/db/migrations/migration.py", line 114, in apply operation.state_forwards(self.app_label, project_state) AttributeError: 'function' object has no attribute 'state_forwards' ``` I don't know what I'm doing wrong.. I checked my numeric\_version number apart from the migration and that should work. Any tips?
2020/05/20
[ "https://Stackoverflow.com/questions/61918207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3608475/" ]
Looking at the [documentation](https://docs.djangoproject.com/en/3.0/ref/migration-operations/#runpython) i guess you should change: ``` operations = [insert_numeric_software_version] ``` to: ``` operations = [migrations.RunPython(insert_numeric_software_version)] ```
This error also occurs when declaring a second operation in the list instead of the tuple. eg mistakenly using this ``` class Migration(migrations.Migration): dependencies = [('app', '0001_initial'),] operations = [migrations.RunPython(load_fixture), clear_fixture_files] ``` Instead of ``` class Migration(migrations.Migration): dependencies = [('app', '0001_initial'),] operations = [migrations.RunPython(load_fixture, clear_fixture_files),] ```
28,767,287
I've tried generating multiple solutions with cplex using ``` option solver cplexamp; option cplex_options 'poolstub=solfile populate=1 poolintensity=4'; ... for {k in K_mach_RESOURCES} { solve SUB1[k]; for {l in 1..SUB1[k].npool}{ solution ("solfile" & l & ".sol"); display _varname, _var; } ``` Gives the error ``` Bad suffix .npool for SUB1 context: for {l in >>> 1..SUB1[k].npool} <<< { Possible suffix values for SUB1.suffix: astatus exitcode message relax result sstatus stage ``` The weird thing is that it's generating .sol files, but I don't know how to access the generated solutions! Possibly relevant info: there's multiple problems declared in the run file. Accessing Current.npool doesn't work either (in fact, it assumes Current is the latest DECLARED problem, not the latest SOLVED problem). Any ideas??
2015/02/27
[ "https://Stackoverflow.com/questions/28767287", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2391384/" ]
It seems as if the problem arose because the problem wasn't defined to be an INTEGER problem, but a LP-relaxation of an integer problem. For some reason, CPLEX doesn't seem to support the populate method for linear programs.
I think you forgot the "solve" command ampl: solve; and then you can display the results.
67,986,590
I always get this error when I start node. please reply to me where I am going wrong. **Error : creating application: failed to initialize ORM: initializeORM#NewORM: unable to init DB: unable to open ?application\_name=Chainlink+0.10.7+%7C+ORM+%7C+98d78e80-6fa0-4e2f-a9a4-c51199bf9d2a for gorm DB conn &{0 0xc0004a93e0 0 {0 0} [] map[] 0 0 0xc0005e29c0 false map[] map[] 0 0 0 0 0 0 0 0 0x59b0a0}: failed to connect to host=/var/run/postgresql user=root database=: server error (FATAL: unrecognized configuration parameter "?application\_name" (SQLSTATE 42704))** config : ``` LOG_LEVEL=debug ETH_CHAIN_ID=42 MIN_OUTGOING_CONFIRMATIONS=2 LINK_CONTRACT_ADDRESS=0xa36085F69e2889c224210F603D836748e7dC0088 CHAINLINK_TLS_PORT=0 SECURE_COOKIES=false FEATURE_EXTERNAL_INITIATORS=true ALLOW_ORIGINS=* ETH_URL=wss://kovan.infura.io/ws/v3/8e32345678ghjk456789cvbn4yu DATABASE_URL=postgresql://localhost:5432/kovan_demo?sslmode=disable DATABASE_TIMEOUT=0 FEATURE_FLUX_MONITOR=true MINIMUM_CONTRACT_PAYMENT=100000000000000000 CHAINLINK_DEV=true ```
2021/06/15
[ "https://Stackoverflow.com/questions/67986590", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14842966/" ]
The problem lies in the syntax of your configuration variable `DATABASE_URL` To connect to the database you need a specially created `USER` with a `PASSWORD`, which then locks this database by starting the chainlink node. The default `postgres` user will not work because it is used for administrative purposes. These credentials are then added to the environmental variable with this syntax: `DATABASE_URL=postgresql://$USERNAME:$PASSWORD@$SERVER:5432/$DATABASE` Because you have set "localhost" for the `postgresql server IP` in your environmental, I assume that your postgres is running on the same host as the Chainlink node. There are 2 different ways of establishing a connection: **1) You have both, the Chainlink node and the postgresql server inside of a docker container:** You need to point to the `container ID` or the `container name` of your postgresql server and create both containers in the same network. Here you can find the official documentation of docker: <https://docs.docker.com/network/bridge/> This means you have to bridge the containers in order to be able to communicate with each other, by creating a network with: `docker network create $NAME` Then you add the network flag to your Chainlink node container and the run command of your postgres-server container: `--network $NAME` After reinitialise all these containers, you are able to point to the **container name** instead of an IP. The syntax of your `DATABASE_URL` in your environmental looks now like this: `DATABASE_URL=postgresql://$USERNAME:$PASSWORD@$CONTAINER_NAME:$5432/$DATABASE` *Instead of reinitialising the containers, you can also connect a running docker container to a network/ user-defined bridge with:* `docker network connect $NETWORK_NAME $CONTAINER_NAME` **2) The postgresql server is as an application on your host and the chainlink node inside of a docker container:** To realise this you need to configure the chainlink node and the database in order to allow communication. **postgresql server**: you need to change the configuration file to allow communication of a specific Ip-range (by default the postgres Ip-range is just set for `localhost` ). Usually you find the config files in `/etc/postgresql/<version>/main` directory. 1. edit postgresql.conf to `listen_addresses = '*'` 2. edit pg\_hba.conf to `host all all 172.17.0.1/16 md5` This range of addresses belongs to Docker and includes the assigned IP of your chainlink container. **Chainlink node**: you need to add `--add-host=host:127.0.0.1` to your run command to enable the connection to the database and services on your host. Please ensure also that you disable ssl for testing purposes by adding `?ssl=disbable` to your `ETH_URL` configuration, because the Chainlink node will return an [ERROR] log if SSL is not configured on your Server (You are able to configure SSL later on your server, because this is an own topic you have to read about in the official documentation) **In production SSL (also when "just" encrypt your traffic internally) is highly recommended**, because it simply secures all your database communication and keeps the information inside of this database safe.
Make sure that these environment variables are also saved in your `.zprofile` or `.bash_profile` depending on what shell you are running. You can check if these files are present with this command in your home directory: `ls -al` If the there is no such file you can create one: `touch ~/.zprofile` Then write all the variables from your `.env` file prefixed with `export` After saving the variables, run the following command to enable the changes to take effect in the current terminal session: `source .zprofile` or `source .bash_profile` if you are running a bash shell. This will ensure that your chainlink node knows where to find the environment variable when booting the node: `chainlink node start`
20,815,470
I try to do a notepad in c#, I have some problems at delete function, I want to delete selected text... ``` private void deleteToolStripMenuItem_Click(object sender, EventArgs e) { int a; a = textBox1.SelectionLength; textBox1.Text.Remove(textBox1.SelectionStart,a); } ``` what is wrong?
2013/12/28
[ "https://Stackoverflow.com/questions/20815470", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3142035/" ]
`Remove` will return the truncated string, so you just need to reassign to the `TextBox`: ``` private void deleteToolStripMenuItem_Click(object sender, EventArgs e) { int a = textBox1.SelectionLength; textBox1.Text = textBox1.Text.Remove(textBox1.SelectionStart,a); } ```
Use SelectedText like this : ``` textbox1.SelectedText = ""; ```
3,398,555
I have a WCF webservice using the WebServiceHost class. new WebServiceHost(typeof(MyServiceClass)); If I use a blocking call like Thread.Sleep (just an example) in one of my webservice methods and i call this method the whole service is not usable while the blocking call is active. Is that normal behaviour or is there an error somewhere in my configuration or usage?
2010/08/03
[ "https://Stackoverflow.com/questions/3398555", "https://Stackoverflow.com", "https://Stackoverflow.com/users/409890/" ]
What's the [InstanceContextMode](http://msdn.microsoft.com/en-us/library/system.servicemodel.instancecontextmode.aspx) and [ConcurrencyMode](http://msdn.microsoft.com/en-us/library/system.servicemodel.concurrencymode.aspx) settings on your service? If it's set to Single then there's only one instance of your service and all the calls are queued so if you put the service thread to sleep it will block all subsequent calls. For example: ``` [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Single)] public class MyService : IMyService { } ```
Ok, I got it. If you start the service in a windows forms GUI thread you can add ``` UseSynchronizationContext = false ``` to the ServiceBehavior and the requests get handled in parallel. :)
9,035,548
I'm currently writing a REST service within a Symfony2 application. This is (roughly) how one of my controllers look like: ``` /** * @Route("/account", defaults={"_format" = "json"}) */ class AccountController extends APIController { /** * @Route("/") * @Method("get") */ public function listAction() { // process something here and return JSON-encoded response } } ``` This works all fine - i.e. if some problem pops up and I throw a `HTTPException`, the correct `error.json.twig` from Symfony2's TwigBundle is used and renders the HTTP error as JSON. However, this is not true for the violation of route requirements, of which `@Method("get")` is one. If I for example throw a `POST` or `PUT` against the above URL, I still get the correct HTTP status code back, but rendered with the wrong content-type (text/html instead of application/json). I'm very much interested to let the complete API return JSON responses and nothing else - the question is: How do I achieve that? Do I have to omit route requirements alltogether and check the requirements myself (and then eventually throw my own `HTTPException`s)?
2012/01/27
[ "https://Stackoverflow.com/questions/9035548", "https://Stackoverflow.com", "https://Stackoverflow.com/users/305532/" ]
A **Function declaration** *may/may* not not include the function arguments. While a **Function Prototype** *must* include the function arguments. From **[Wikipedia](http://en.wikipedia.org/wiki/Function_prototype)**: Consider the following function prototype: ``` int fac(int n); ``` This prototype specifies that in this program, there is a function named `fac` which takes a single integer argument `n` and returns an integer. Elsewhere in the program a function definition must be provided if one wishes to use this function. It's important to be aware that a declaration of a function does not need to include a prototype. The following is a prototype-less function declaration, which just declares the function name and its return type, but doesn't tell what parameter types the definition expects. ``` int fac(); ```
A prototype is a declaration, but a declaration not always is a prototype. If you don't specify the parameters, then that's only a declaration and not a prototype. That means the compiler won't reject a call to that function complaining it wasn't declared, but won't be able to check if the parameters passed are correct (as it would if you had a prototype).
9,035,548
I'm currently writing a REST service within a Symfony2 application. This is (roughly) how one of my controllers look like: ``` /** * @Route("/account", defaults={"_format" = "json"}) */ class AccountController extends APIController { /** * @Route("/") * @Method("get") */ public function listAction() { // process something here and return JSON-encoded response } } ``` This works all fine - i.e. if some problem pops up and I throw a `HTTPException`, the correct `error.json.twig` from Symfony2's TwigBundle is used and renders the HTTP error as JSON. However, this is not true for the violation of route requirements, of which `@Method("get")` is one. If I for example throw a `POST` or `PUT` against the above URL, I still get the correct HTTP status code back, but rendered with the wrong content-type (text/html instead of application/json). I'm very much interested to let the complete API return JSON responses and nothing else - the question is: How do I achieve that? Do I have to omit route requirements alltogether and check the requirements myself (and then eventually throw my own `HTTPException`s)?
2012/01/27
[ "https://Stackoverflow.com/questions/9035548", "https://Stackoverflow.com", "https://Stackoverflow.com/users/305532/" ]
A **Function declaration** *may/may* not not include the function arguments. While a **Function Prototype** *must* include the function arguments. From **[Wikipedia](http://en.wikipedia.org/wiki/Function_prototype)**: Consider the following function prototype: ``` int fac(int n); ``` This prototype specifies that in this program, there is a function named `fac` which takes a single integer argument `n` and returns an integer. Elsewhere in the program a function definition must be provided if one wishes to use this function. It's important to be aware that a declaration of a function does not need to include a prototype. The following is a prototype-less function declaration, which just declares the function name and its return type, but doesn't tell what parameter types the definition expects. ``` int fac(); ```
A function prototype is a function declaration that specifies the number and types of parameters. ``` T foo(); // non-prototype declaration T foo(int, char *); // prototype declaration T foo(int a, char *b); // prototype declaration ```
9,035,548
I'm currently writing a REST service within a Symfony2 application. This is (roughly) how one of my controllers look like: ``` /** * @Route("/account", defaults={"_format" = "json"}) */ class AccountController extends APIController { /** * @Route("/") * @Method("get") */ public function listAction() { // process something here and return JSON-encoded response } } ``` This works all fine - i.e. if some problem pops up and I throw a `HTTPException`, the correct `error.json.twig` from Symfony2's TwigBundle is used and renders the HTTP error as JSON. However, this is not true for the violation of route requirements, of which `@Method("get")` is one. If I for example throw a `POST` or `PUT` against the above URL, I still get the correct HTTP status code back, but rendered with the wrong content-type (text/html instead of application/json). I'm very much interested to let the complete API return JSON responses and nothing else - the question is: How do I achieve that? Do I have to omit route requirements alltogether and check the requirements myself (and then eventually throw my own `HTTPException`s)?
2012/01/27
[ "https://Stackoverflow.com/questions/9035548", "https://Stackoverflow.com", "https://Stackoverflow.com/users/305532/" ]
A **Function declaration** *may/may* not not include the function arguments. While a **Function Prototype** *must* include the function arguments. From **[Wikipedia](http://en.wikipedia.org/wiki/Function_prototype)**: Consider the following function prototype: ``` int fac(int n); ``` This prototype specifies that in this program, there is a function named `fac` which takes a single integer argument `n` and returns an integer. Elsewhere in the program a function definition must be provided if one wishes to use this function. It's important to be aware that a declaration of a function does not need to include a prototype. The following is a prototype-less function declaration, which just declares the function name and its return type, but doesn't tell what parameter types the definition expects. ``` int fac(); ```
The prototype tells the compiler hey there is a function that looks like this and this is its name `int getanint()`. When you use that function the compiler puts the code calls that function and leaves a place to insert the address to the code that defines what that function does. So in File Header A; ``` int getanint(); ``` IN main.c ``` int main(...) { getanint(); } ``` when you compile main.c it has no idea what getanint does or even where it is the created .o file is incomplete and is not enough to create an actually program. remember that the compiler operates on a single file that file can be very large because of the #include directives but they create a single file. When you complie A.cpp ``` int getanint() { return 4; } ``` You now have the code for getanint in an object file. To actually make a program you have to get main.o and A.o together and have the definitions of the functions inserted into the appropriate places. That is the job of the linker.