qid int64 1 74.7M | question stringlengths 15 58.3k | date stringlengths 10 10 | metadata list | response_j stringlengths 4 30.2k | response_k stringlengths 11 36.5k |
|---|---|---|---|---|---|
74,546,731 | So I'm trying to lexicographically sort this collection but with no success. The same unsorted collection is in the input and the output of the sort method.
```
class Person {
private String privateName;
private String lastName;
public Person(String privateName, String lastName) {
this.privateName = privateName;
this.lastName = lastName;
}
public String toString() {
return privateName + " " + lastName;
}
}
class Main {
public static void main(String[] args) {
Collection<Person> people = new ArrayList<>();
people.add(new Person("aaa", "hhh"));
people.add(new Person("aaa", "aaa"));
people.add(new Person("aaa", "uuu"));
Arrays.sort(people.toArray(), Comparator.comparing(Object::toString));
}
}
```
The order of the elements in the output collection:
"aaa hhh" -> "aaa aaa" -> "aaa uuu"
While I want it to be:
"aaa aaa" -> "aaa hhh" -> "aaa uuu"
Can somebody tell me why? | 2022/11/23 | [
"https://Stackoverflow.com/questions/74546731",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16076953/"
] | Your problem is that you are converting your Collection/ArrayList to an array and then sort that Array.
Sorting that Array will have no effect on the original ArrayList.
If you want to sort your List you first need to declare it as a List, because Collections themself have no predefined order and therefor no sort method for them exists, and then in a second step use the corresponding method to sort that list:
```
public static void main(final String[] args) {
final List<Person> people = new ArrayList<>();
people.add(new Person("aaa", "hhh"));
people.add(new Person("aaa", "aaa"));
people.add(new Person("aaa", "uuu"));
Collections.sort(people, Comparator.comparing(Person::toString));
System.out.println(people);
}
```
Will output
>
> [aaaaaa, aaahhh, aaauuu]
>
>
> | Plot twist
The following
```
public static void main(String[] args) {
Person[] peopleArray = {
new Person("aaa", "hhh"),
new Person("aaa", "aaa"),
new Person("aaa", "uuu")
};
Collection<Person> people = Arrays.asList(peopleArray);
Arrays.sort(peopleArray, Comparator.comparing(Object::toString));
System.out.println(people);
}
```
Will print you the `[aaa aaa, aaa hhh, aaa uuu]` which is what you expect.
If you don't sort it and remove the line `Arrays.sort(peopleArray, Comparator.comparing(Object::toString));` it will print you the `[aaa hhh, aaa aaa, aaa uuu]`.
Reason why this would work -> `Arrays.asList()` is backed directly by the array, so when you sort the array you see the same sorting in the collection .
`java.util.ArrayList()` on the other side is not backed directly by any array that stores the elements since the `ArrayList` supports dynamic list size. |
10,843,929 | Really stuck with this question in my homework assignment.
Everything works, but when there is a space (`' '`) in the `p`. I need to stop the process of creating `can`.
For example, if I submit:
```
rankedVote("21 4", [('AB', '132'), ('C D', ''), ('EFG', ''), ('HJ K', '2 1')])
```
I would like to have:
```
['C D', 'AB']
```
returned, rather than just `[]` like it is now.
Code as below:
```
def rankedVote(p,cs):
candsplit = zip(*cs)
cand = candsplit[0]
vote = list(p)
ppl = vote
can = list(p)
for i in range(len(vote)):
if ' ' in vote[i-1]:
return []
else:
vote[i] = int(vote[i])
can[vote[i]-1] = cand[i]
for i in range(len(vote)):
for j in range(len(vote)):
if i != j:
if vote[i] == vote[j]:
return []
return can
```
**EDIT:**
In the example:
```
rankedVote("21 4", [('AB', '132'), ('C D', ''), ('EFG', ''), ('HJ K', '2 1')])
```
This means that the 1st, `AB` becomes 2nd,
and the 2nd one `C D` becomes 1st,
and it should stop because 3rd does not exist.
Let's say that instead of `21 4`, it was `2143`.
It would mean that the 3rd one `EFG` would be 4th,
and the 4th `HJ K` would be 3rd. | 2012/06/01 | [
"https://Stackoverflow.com/questions/10843929",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/138737/"
] | Managed arrays are different than pointers. A managed array requires the size of the array, and if you're trying to marshal a struct, it requires a fixed size to marshal directly.
You can use the `SizeConst` parameter of the [`MarshalAs` attribute](http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshalasattribute.aspx) to set the size of data when it gets marshaled.
But I'm guessing that `x` and `y` are the dimensions of the image and that the size of `data` depends on those variables. The best solution here is to marshal it over as an `IntPtr` and access the data when you need it:
```
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public class IMAGE
{
public UInt32 x;
public UInt32 y;
private IntPtr data;
public byte[][] Data
{
get
{
byte[][] newData = new byte[y][];
for(int i = 0; i < y; i++)
{
newData[i] = new byte[x];
Marshal.Copy(new IntPtr(data.ToInt64() + (i * x)), newData[i], 0, x);
}
return newData;
}
set
{
for (int i = 0; i < value.Length; i++)
{
Marshal.Copy(value[i], 0, new IntPtr(data.ToInt64() + (i * x)), value[i].Length);
}
}
}
}
```
If you are allowed to use unsafe code, you can change the `IntPtr` to a `byte**` and work with it directly.
With the setter, you'll probably want to verify the dimensions of the value before you blindly write to unmanaged memory. | My guess is that it is:
```
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public class IMAGE
{
public UInt32 x;
public UInt32 y;
public ref IntPtr data;
};
```
A very handy reference is the p/invoke [cheatsheet](http://khason.net/blog/pinvoke-cheat-sheet/). |
57,846 | It is not possible to prove being a human!!!
There is no text to read.
Checked adblocker, nothing blocked.
Update:
To repro:
1. Open question
2. Enter 'abc'
3. Click 'Post answer'
4. Get the expected error that message is too short
5. Click 'Post answer' again
6. Presented with 'empty' CAPTCHA
Here is the HTML I receive:
```
<script type="text/javascript" src="http://api.recaptcha.net/challenge?k=6Ld...">
</script>
<noscript>
<iframe src="http://api.recaptcha.net/noscript?k=6Ldchg..." ...>
</iframe><br>
</br>
<textarea name="recaptcha_challenge_field" rows="3" cols="40"></textarea>
<input name="recaptcha_response_field" value="manual_challenge" type="hidden"/>
</noscript>
```
Also I cannot even open the [CAPTCHA url](http://api.recaptcha.net/challenge?k=6LdchgIAAAAAAJwGpIzRQSOFaO0pU6s44Xt8aTwc) directly. Just end up with a Google 404 error.
I find it surprising no-one else is getting this.
Another update:
Here is what Firebug gives me:
```
HTTP/1.1 302 Moved Temporarily
Via: 1.1 ZAISA01
Connection: Keep-Alive
Proxy-Connection: Keep-Alive
Content-Length: 154
Date: Fri, 23 Jul 2010 11:11:49 GMT
Location: http://www.google.com/recaptcha/api/challenge?k=6LdchgIAAAAAAJwGpIzRQSOFaO0pU6s44Xt8aTwc
Content-Type: text/html
Server: nginx
P3P: CP="NOI ADM DEV PSA PSD UNI COM NAV OUR STP"
```
Then it 404's on the Google url.
I will try it out from home tonite, seeing this is a work connection.
**Update:**
It works from home. I get a JSON reponse from the URL I provided earlier. I can only assume this is some proxy issue, as it used to work.
**Final update:**
We got a new proxy installation at work, and it started working magically even though all the rules were replicated...
At least it works now :)
 | 2010/07/21 | [
"https://meta.stackexchange.com/questions/57846",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/15541/"
] | Some general pointers to debug this:
1. Check the JavaScript console for errors.
2. Is scripting allowed?
3. Try again after a few minutes; maybe there was a problem with the captcha provider
4. Are you behind a proxy?
5. I guess the captcha is embedded using an `iframe` or something like that. Check the source code of the page for any oddities. | We can't reproduce this in any browser. |
7,027,196 | I want make an authentication system for my app along the lines of [SUAS](https://github.com/aht/suas), except instead of using SHA256 for hashing passwords I'd like to [use bcrypt](http://codahale.com/how-to-safely-store-a-password) or scrypt. Unfortunately both py-bcrypt and scrypt for python use native c, which is unsupported by GAE.
Any way around this? | 2011/08/11 | [
"https://Stackoverflow.com/questions/7027196",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/877300/"
] | Scrypt and BCrypt are both extremely processor-intensive (by design). Because of this, I very much doubt any pure-python implementation is going to be fast enough to be secure - that is, be able to hash using a sufficient number of rounds within a reasonable amount of time.
I can personally attest to this, I've tried writing a pure-python BCrypt, and it was *way* too slow to be useful. The docs for the pure-python bcrypt implementation mentioned in another answer note this exact flaw - to beware of using it for actual security, it's rounds must be set too low. The only time such implementations will be fast enough is under pypy, which is not the situation you're faced with.
---
What you want to go with is something based on an available hash primitive like SHA-2. That way the heavy calculation bit will still be able to be written in C, even under GAE. I'd recommend something based on PBKDF2 or SHA-512-Crypt (note: this is *not* just a plain sha512 hash). The security of the algorithms is just as good, but pure-python implementations will be much more efficient, since they can leverage `hashlib` to do the heavy lifting.
The [Passlib](http://packages.python.org/passlib) library might be useful in this case, it contains implementations of [PBKDF2](http://packages.python.org/passlib/lib/passlib.hash.pbkdf2_digest.html) and [SHA-512-Crypt](http://packages.python.org/passlib/lib/passlib.hash.sha512_crypt.html) in pure python. *(Disclaimer: I'm the author of that library)*. Another Python library with PBKDF2 support is [Cryptacular](http://pypi.python.org/pypi/cryptacular). | This [guy](http://groups.google.com/group/google-appengine-python/browse_thread/thread/36fe567ccece8e14) ported py-bcrypt to pure python so you can use it on GAE:
<https://github.com/erlichmen/py-bcrypt> |
10,953,401 | I was thinking to do this server side, but what i was wanting to do was disable the telerik control called the "Editor." Located at the site: [telerick editor control](http://demos.telerik.com/aspnet-ajax/editor/examples/overview/defaultcs.aspx).
My reasoning behind this was that I wanted to give a user the exact look and feel of the object while having everything disabled. I didnt want to use an image at all because it would be stretched, shrank, clicked, etc and wanted to maintain how the editor would look. I had an alternate option i COULD do but not only it would be ineffecient, but have holes to open up for injection.
Looking through the API for that i didnt see which way to accomplish that.
I was thinking to do jquery maybe on the client side to disable, but why do that when you can set the item itself be flagged as disabled and never be entirely sent to the client.
Thoughts? Ideas? How would you go about it? I didnt see methods or attributes that really led to what i was doing. | 2012/06/08 | [
"https://Stackoverflow.com/questions/10953401",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1404049/"
] | Create an xml file per each icon you wan to show in the action bar in the 'drawable' directory like the one below:
```
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:drawable="@drawable/menuitem_bk"/>
<item android:drawable="@drawable/icon_one"/>
</layer-list>
```
Drawable icon\_one is just the icon with a transparent background and 'menuitem\_bk' will be a drawable defined as follows:
```
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<size
android:height="36dp"
android:width="36dp" />
<solid android:color="@color/action_bar_items_bk_color" />
</shape>
```
You will have to create four of these, one in each drawable directory (xhdpi, hdpi, mdpi and ldpi). The size of the shape will be different according to the directory:
* xhdpi -> 48x48 hdpi -> 36x36 mdpi -> 24x24 ldpi -> 18x18
(Acording to this: <http://developer.android.com/guide/practices/ui_guidelines/icon_design_action_bar.html> )
And you got your ActionBar icons with background. | As a workaround you could always have different icons for your localization. There is nothing stopping you having:
```
/drawable-fr/
/drawable-us/
```
On the other hand if you believe it is something to do with the Theme you are inheriting you could look through the source code for the DarkActionBar and then extend this in styles.xml overriding the values you want to change (the color of).
<https://github.com/android/platform_frameworks_base/tree/master/core/res/res/values> |
15,942,952 | I have written an app that performs some lengthy operations, such as web requests, in a background thread. My problem is that after a while the automatic screen lock turns the screen off and my operations are aborted.
Is there a way to prevent the screen to be automatically turned off during these operations? Or is it in some way possible to keep running while screen is turned off?
I know there are ways to prevent the screen to turn off while debugging, but i need this behavior in the hands of the end user. Therefore I can not rely on some setting being set on the phone, but rather some programmatic solution. | 2013/04/11 | [
"https://Stackoverflow.com/questions/15942952",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/438906/"
] | The screen can be forced to stay on using the `UserIdleDetectionMode` property of the current `PhoneApplicationService`.
To disable automatic screen lock:
```
PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Disabled;
```
To enable it again:
```
PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Enabled;
```
More information can be found on [MSDN](http://msdn.microsoft.com/en-us/library/windowsphone/develop/microsoft.phone.shell.phoneapplicationservice.useridledetectionmode%28v=vs.105%29.aspx) | I know this question is about Windows Phone 8, but I had a hard time figuring out the way for Windows Phone 8.1 (Universal XAML Apps).
Use:
```
var displayRequest = new Windows.System.Display.DisplayRequest();
displayRequest.RequestActive();
```
>
> Apps that show video or run for extended periods without user input can request that the display remain on by calling DisplayRequest::RequestActive. When a display request is activated, the device's display remains on while the app is visible. When the user moves the app out of the foreground, the system deactivates the app's display requests and reactivates them when the app returns to the foreground.
>
>
>
See: <http://msdn.microsoft.com/en-us/library/windows/apps/br241816.aspx> |
317,167 | Let $f$ be continuous on $\mathbb{R}$ and $A$, a subset of the reals, be open. Prove that $f^{-1}(A) := \{x \in \mathbb{R}:f(x) \in A\}$ is open. | 2013/02/28 | [
"https://math.stackexchange.com/questions/317167",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/64416/"
] | Recall the definition of continuity:
**DEF** A function $f:A\to \Bbb R$ is continuous at $a\in A$ if for every $\epsilon >0$ there exists a $\delta >0$ such that $$|x-a|<\delta\implies |f(x)-f(a)|<\epsilon$$
Put this in terms of open balls:
**DEF** A function $f:A\to \Bbb R$ is continuous at $a\in A$ if for every ball $B(f(a);\epsilon)$ there exists a ball $B(a;\delta)$ such that $$x\in B(a;\delta)\implies f(x)\in B(f(a);\epsilon)$$
But since $f(x)\in B(f(a);\epsilon)$ means the same as $x\in f^{-1}(B(f(a);\epsilon))$ we can phrase our definition as
**DEF** A function $f:A\to \Bbb R$ is continuous at $a\in A$ if for every ball $B(f(a);\epsilon)$ there exists a ball $B(a;\delta)$ such that $$B(a;\delta)\subseteq f^{-1}(B(f(a);\epsilon))$$
---
Now we're ready to prove what you claim, plus it's converse.
**THM** A function $f:S\subseteq \Bbb R\to \Bbb R$ is continuous if and only if for every open set $A\in \Bbb R$, $f^{-1}(A)$ is open.
**PROOF** Suppose first that $f$ is continuous, and pick an open set $A$. We want to prove that $f^{-1}(A)$ is open, that is, for every $x\in f^{-1}(A)$ there exists an open ball $B(x;\delta)\subseteq f^{-1}(A)$. Pick $y\in A$. We can assume $y=f(x)$ for some $x\in f^{-1}(A)$. Since $A$ is open, there exists an open ball $B(f(x);\epsilon)\subseteq A$. Using continuity, can you show there exists an open ball $B(x;\delta)\subseteq f^{-1}(A)$?
Conversely, suppose that for every open $A$, $f^{-1}(A)$ is open. In particular, for every open ball $B(f(x),\epsilon)$, $f^{-1}(B(f(x),\epsilon))$ is open, so it contains an open ball for each of its points. What does this tell you about the continuity of$f$? | Let $a$ is a point of $f^{-1}(A)$. By def. of $f^{-1}(A)$, $f(a)$ is an element of $A$. Since $A$ is open, there exists $r>0$ such that $B(f(a),r)\subset A$. Because $f$ is continous, there exists $\delta>0$ such that
$$|x-a|<\delta \implies |f(x)-f(a)|<r$$
for all $x$.
If you show that $B(a,\delta)\subset f^{-1}(A)$, then proof is completed, and it is easy to prove. |
408,554 | I am currently using Monit to monitor Apache and restart it if its memory usage is too high. However, I'd also like to be able to monitor the individual apache2 subprocesses that are spawned, and kill any subprocess whose memory usage is too high over a period of a few minutes. How can I do that? | 2012/07/17 | [
"https://serverfault.com/questions/408554",
"https://serverfault.com",
"https://serverfault.com/users/103498/"
] | Monit's documentation suggests that you can natively monitor the total memory used by Apahce and its child processes, not any individual child process.
However, you can check the return status of a script using the `check program` test:
<http://mmonit.com/monit/documentation/monit.html#program_status_testing>
So, you can do something like this as a check script:
```
#/bin/bash
threshold=10000 # 10MB
for childmem in $(ps h orss p $(pgrep -P $(cat /var/run/httpd.pid)))
do
if [ $childmem -gt $threshold ]; then
exit 1
fi
done
exit 0
```
If that script is `/usr/local/bin/check_apache_children.sh`, then you can do something like:
```
check program myscript with path "/usr/local/bin/check_apache_children.sh"
if status != 0 then exec "/usr/local/bin/kill_apache_children.sh"
```
The kill script will presumably look like the check script, but with a kill on the PID instead of an exit.
The scripts are, of course, illustrative, and should be modified to your environment. | I accepted cjc's answer above, but wanted to post exactly how I used his suggestion to solve this problem. Note that you will need to use at least Monit 5.3 to use Monit's "check program". I am running Debian.
/usr/local/bin/monit\_check\_apache2\_children:
```
#!/usr/bin/env bash
log_file=/path/to/monit_check_apache2_children.log
mem_limit=6
kill_after_minutes=5
exit_code=0
date_nice=$(date +'%Y-%m-%d %H:%M:%S')
date_seconds=$(date +'%s')
apache_children=$(ps h -o pid,%mem p $(pgrep -P $(cat /var/run/apache2.pid)) | sed 's/^ *//' | tr ' ' ',' | sed 's/,,/,/g')
for apache_child in $apache_children; do
pid=`echo $apache_child | awk -F, '{ print $1 }'`
mem=`echo $apache_child | awk -F, '{ print $2 }'`
mem_rounded=`echo $apache_child | awk -F, '{ printf("%d\n", $2 + 0.5) }'`
if [ $mem_rounded -ge $mem_limit ]; then
log_entry_count=$(cat $log_file | grep -v 'KILLED' | grep " $pid; " | wc -l)
log_entry_time=$(cat $log_file | grep -v 'KILLED' | grep " $pid; " | tail -$kill_after_minutes | head -1 | awk '{ print $3 }')
if [ "$1" != "kill" ]; then
echo "$date_nice $date_seconds Process: $pid; Memory Usage: $mem" >> $log_file
fi
if [ $((date_seconds - log_entry_time)) -le $(((kill_after_minutes * 60) + 30)) ] && [ $log_entry_count -ge $kill_after_minutes ]; then
if [ "$1" = "kill" ]; then
kill -9 $pid
echo "$date_nice $date_seconds ***** KILLED APACHE2 PROCESS: $pid; MEMORY USAGE: $mem" >> $log_file
else
exit_code=1
fi
fi
fi
done
exit $exit_code
```
/etc/monitrc:
```
...
check program apache2_children
with path "/usr/local/bin/monit_check_apache2_children"
if status != 0 then exec "/usr/local/bin/monit_check_apache2_children kill"
...
``` |
202,758 | OK just before I start, I **do** know what does and doesn't constitute [valid housing](https://gaming.stackexchange.com/questions/22408/how-do-i-build-a-house-for-my-npcs) in Terraria. I'm also playing v1.2.4.1
What I'd like to know is does the "must have a door" requirement also mean "must be accessible", or can I create a walled-off cube with internal doors to satisfy the housing rules? i.e. are any of the houses A, B, C or D in the following diagram valid?

If I can, then I'm going to be making pressure-plate/activator automatic doors that don't get torn down in a blood moon. | 2015/01/23 | [
"https://gaming.stackexchange.com/questions/202758",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/77650/"
] | The structure does not have to be "accessible" with a door; as in you can create a switched active block entry way so that Blood Moon/Eclipse mobs can't get in. You can also create a double door entry way, where the outer door is the switched active blocks.
Another way, would be to place a platform, container or decoration against the door. This creates an "open from the inside only" door, that can't be opened inwards (the direction most mobs are headed to get inside your house). The exception to this is goblin armies, as they break the door instead of opening it. The "issue" is that YOU also can not open the door inwardly. You would have to face out and click to open the door.
In your diagram, the C/D version where there is a switched "ceiling" between the doors is a good way to do it. | I would say these are all valid if the requirements fit.
But you need to remember that the need to teleport into there houses wich means that you have to leave the place.
Second you need to think about monsters spawning in your house eg. Goblin Army.
third how will you talk with those npcs ? |
202,758 | OK just before I start, I **do** know what does and doesn't constitute [valid housing](https://gaming.stackexchange.com/questions/22408/how-do-i-build-a-house-for-my-npcs) in Terraria. I'm also playing v1.2.4.1
What I'd like to know is does the "must have a door" requirement also mean "must be accessible", or can I create a walled-off cube with internal doors to satisfy the housing rules? i.e. are any of the houses A, B, C or D in the following diagram valid?

If I can, then I'm going to be making pressure-plate/activator automatic doors that don't get torn down in a blood moon. | 2015/01/23 | [
"https://gaming.stackexchange.com/questions/202758",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/77650/"
] | Assuming that all of those have walls and a light source, those would count as valid housing. The requirement is that it has a door, not that the door go anywhere. Also notable is that [wooden platforms count as doors for the housing rule](http://terraria.gamepedia.com/Guide:Base_defense_and_precautions#Reminder), so you can actually just have a wooden platform separate the rooms from each other as well.
Here is an example of housing with internal doors:

>
> If I can, then I'm going to be making pressure-plate/activator automatic doors that don't get torn down in a blood moon.
>
>
>
This is actually a very common strategy to defend from a blood moon. As noted in the [Base Defense Guide](http://terraria.gamepedia.com/Guide:Base_defense_and_precautions) on the Wiki:
>
> By using actuators and Grey, Brown, Blue or Lihzahrd pressure plates, you can create a player only door that doesn't even require you to use your mouse. Setup the door as you would an active stone/actuator door and because Grey, Brown, Blue or Lihzahrd pressure plates can only be activated by the player no mobs are able to enter (nor escape).
>
>
>
You can also just place a torch or other item in front of the door so that it can only be opened when you are facing towards the outside. [From the wiki](http://terraria.gamepedia.com/Guide:Base_defense_and_precautions#Possible_Methods):
>
> Another way to prevent enemies breaking down your door is to place a non-solid object, such as a chest, wooden platform or other Furniture item, on the inside of the door. This will prevent enemies from opening it but will require the player to face away from the house to open the door.
>
>
> | I would say these are all valid if the requirements fit.
But you need to remember that the need to teleport into there houses wich means that you have to leave the place.
Second you need to think about monsters spawning in your house eg. Goblin Army.
third how will you talk with those npcs ? |
202,758 | OK just before I start, I **do** know what does and doesn't constitute [valid housing](https://gaming.stackexchange.com/questions/22408/how-do-i-build-a-house-for-my-npcs) in Terraria. I'm also playing v1.2.4.1
What I'd like to know is does the "must have a door" requirement also mean "must be accessible", or can I create a walled-off cube with internal doors to satisfy the housing rules? i.e. are any of the houses A, B, C or D in the following diagram valid?

If I can, then I'm going to be making pressure-plate/activator automatic doors that don't get torn down in a blood moon. | 2015/01/23 | [
"https://gaming.stackexchange.com/questions/202758",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/77650/"
] | Assuming that all of those have walls and a light source, those would count as valid housing. The requirement is that it has a door, not that the door go anywhere. Also notable is that [wooden platforms count as doors for the housing rule](http://terraria.gamepedia.com/Guide:Base_defense_and_precautions#Reminder), so you can actually just have a wooden platform separate the rooms from each other as well.
Here is an example of housing with internal doors:

>
> If I can, then I'm going to be making pressure-plate/activator automatic doors that don't get torn down in a blood moon.
>
>
>
This is actually a very common strategy to defend from a blood moon. As noted in the [Base Defense Guide](http://terraria.gamepedia.com/Guide:Base_defense_and_precautions) on the Wiki:
>
> By using actuators and Grey, Brown, Blue or Lihzahrd pressure plates, you can create a player only door that doesn't even require you to use your mouse. Setup the door as you would an active stone/actuator door and because Grey, Brown, Blue or Lihzahrd pressure plates can only be activated by the player no mobs are able to enter (nor escape).
>
>
>
You can also just place a torch or other item in front of the door so that it can only be opened when you are facing towards the outside. [From the wiki](http://terraria.gamepedia.com/Guide:Base_defense_and_precautions#Possible_Methods):
>
> Another way to prevent enemies breaking down your door is to place a non-solid object, such as a chest, wooden platform or other Furniture item, on the inside of the door. This will prevent enemies from opening it but will require the player to face away from the house to open the door.
>
>
> | The structure does not have to be "accessible" with a door; as in you can create a switched active block entry way so that Blood Moon/Eclipse mobs can't get in. You can also create a double door entry way, where the outer door is the switched active blocks.
Another way, would be to place a platform, container or decoration against the door. This creates an "open from the inside only" door, that can't be opened inwards (the direction most mobs are headed to get inside your house). The exception to this is goblin armies, as they break the door instead of opening it. The "issue" is that YOU also can not open the door inwardly. You would have to face out and click to open the door.
In your diagram, the C/D version where there is a switched "ceiling" between the doors is a good way to do it. |
434,429 | How much mass can you levitate with air? Take air hockey table for example, pressurised air is pushed through holes and they levitate a disk but how much mass is possible?
I think it would probably depend on three things; the mass of the disk, the surface area of the disk and the air pressure. (Possibly on the size and number of holes on the table as well) | 2018/10/14 | [
"https://physics.stackexchange.com/questions/434429",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/154711/"
] | This is a "how long is a piece of string" question - there isn't really any limit.
Four of [these devices](http://www.movetechuk.com/hovairairskates.html) can levitate 240 tons. Use more than four, and you can levitate "thousands of tons" according to the manufacturer's website. | The table can be modeled as a porous medium (using Darcy's law) with a constant air pressure reservoir beneath it. The flow interaction between the puck and the table can be modeled as a aerodynamic lubrication flow, involving the same viscous flow equations as for hydrodynamic lubrication, but with a compressible fluid. |
11,519,979 | I'm trying to make a custom list for inquiries, where users will fill in some information such as "Name", "Reason" etc. When they've finished filling in the information and added the item, the administrator will then go through the item, and fill in some new columns that the user hasn't been able to fill in.
I hope you understand me, otherwise you're more than welcome to ask questions! | 2012/07/17 | [
"https://Stackoverflow.com/questions/11519979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/744102/"
] | It is because `$pdo->errorInfo()` refers to the last statement that was successfully executed. Since `$sql->execute()` returns false, then it cannot refer to that statement (either to nothing or to the query before).
As to why `$sql->execute()` returns false, I don't know... either there is a problem with your `$params` array or with your database connection.
>
> PDO::errorCode — Fetch the SQLSTATE associated with the last operation on the database handle
>
>
>
Note: The PHP manual (<http://php.net/manual/en/pdo.errorinfo.php>) does not define exactly what "last operation on the database handle" means, but if there was an issue with binding parameters, that error would have occurred inside PDO and without any interaction with the database. It is safe to say that if `$pdo->execute()` returns `true`, that `$pdo->errorInfo()` is valid. If `$pdo->execute()` returns `false`, the behavior of `$pdo->errorInfo()` is not explicitly clear from the documentation. If I recall correctly from my experience, execute returns `true`, even if MySQL returned an error, returns `false` if no operation was done. Since the documentation is not specific, it might be db driver specific.
This answer reflects practical experience as of when it was written in September 2012. As a user has pointed out, the documentation does not explicitly reaffirm this interpretation. It also may only reflect the particular database driver implementation, but it should always be true that if `$pdo->execute()` returns `true`, that `$pdo->errorInfo()` is valid.
You might also want to set *PDO::ERRMODE\_EXCEPTION* in your connect sequence. Exception handling makes it unnecessary to check and query the error.
```
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
``` | I Faced the similar problem ,
This occurs manly due to **error in query**, try to **run your query in php-myadmin** or any other query runner and **confirm** that your **query is working** fine.
Even if our query syntax is correct other simple errors like leaving null or not mentioan a column that set as not null in table structure will cause this error.(This was the errror made by me)
As user1122069 explained the reason for $pdo->errorInfo() says nothing is wrong may be due to
>
> $pdo->errorInfo() refers to the last statement that was successfully
> executed.
> Since $sql->execute() returns false, then it cannot refer to
> that statement (either to nothing or to the query before)
>
>
>
Hopes this helps :) |
11,519,979 | I'm trying to make a custom list for inquiries, where users will fill in some information such as "Name", "Reason" etc. When they've finished filling in the information and added the item, the administrator will then go through the item, and fill in some new columns that the user hasn't been able to fill in.
I hope you understand me, otherwise you're more than welcome to ask questions! | 2012/07/17 | [
"https://Stackoverflow.com/questions/11519979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/744102/"
] | It is because `$pdo->errorInfo()` refers to the last statement that was successfully executed. Since `$sql->execute()` returns false, then it cannot refer to that statement (either to nothing or to the query before).
As to why `$sql->execute()` returns false, I don't know... either there is a problem with your `$params` array or with your database connection.
>
> PDO::errorCode — Fetch the SQLSTATE associated with the last operation on the database handle
>
>
>
Note: The PHP manual (<http://php.net/manual/en/pdo.errorinfo.php>) does not define exactly what "last operation on the database handle" means, but if there was an issue with binding parameters, that error would have occurred inside PDO and without any interaction with the database. It is safe to say that if `$pdo->execute()` returns `true`, that `$pdo->errorInfo()` is valid. If `$pdo->execute()` returns `false`, the behavior of `$pdo->errorInfo()` is not explicitly clear from the documentation. If I recall correctly from my experience, execute returns `true`, even if MySQL returned an error, returns `false` if no operation was done. Since the documentation is not specific, it might be db driver specific.
This answer reflects practical experience as of when it was written in September 2012. As a user has pointed out, the documentation does not explicitly reaffirm this interpretation. It also may only reflect the particular database driver implementation, but it should always be true that if `$pdo->execute()` returns `true`, that `$pdo->errorInfo()` is valid.
You might also want to set *PDO::ERRMODE\_EXCEPTION* in your connect sequence. Exception handling makes it unnecessary to check and query the error.
```
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
``` | I was getting this error at one time. I only got it on one server for all failures. A different server would report the error correctly for the same errors. That led me to believe it was a MySQL client configuration error. I never solved the specific error, but check your configurations. |
11,519,979 | I'm trying to make a custom list for inquiries, where users will fill in some information such as "Name", "Reason" etc. When they've finished filling in the information and added the item, the administrator will then go through the item, and fill in some new columns that the user hasn't been able to fill in.
I hope you understand me, otherwise you're more than welcome to ask questions! | 2012/07/17 | [
"https://Stackoverflow.com/questions/11519979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/744102/"
] | It is because `$pdo->errorInfo()` refers to the last statement that was successfully executed. Since `$sql->execute()` returns false, then it cannot refer to that statement (either to nothing or to the query before).
As to why `$sql->execute()` returns false, I don't know... either there is a problem with your `$params` array or with your database connection.
>
> PDO::errorCode — Fetch the SQLSTATE associated with the last operation on the database handle
>
>
>
Note: The PHP manual (<http://php.net/manual/en/pdo.errorinfo.php>) does not define exactly what "last operation on the database handle" means, but if there was an issue with binding parameters, that error would have occurred inside PDO and without any interaction with the database. It is safe to say that if `$pdo->execute()` returns `true`, that `$pdo->errorInfo()` is valid. If `$pdo->execute()` returns `false`, the behavior of `$pdo->errorInfo()` is not explicitly clear from the documentation. If I recall correctly from my experience, execute returns `true`, even if MySQL returned an error, returns `false` if no operation was done. Since the documentation is not specific, it might be db driver specific.
This answer reflects practical experience as of when it was written in September 2012. As a user has pointed out, the documentation does not explicitly reaffirm this interpretation. It also may only reflect the particular database driver implementation, but it should always be true that if `$pdo->execute()` returns `true`, that `$pdo->errorInfo()` is valid.
You might also want to set *PDO::ERRMODE\_EXCEPTION* in your connect sequence. Exception handling makes it unnecessary to check and query the error.
```
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
``` | Try to check $sql by print\_r() and copy your query then try resultant query in phpMyadmin. Hope will get the reason. There would be chance of irrelevant value. |
11,519,979 | I'm trying to make a custom list for inquiries, where users will fill in some information such as "Name", "Reason" etc. When they've finished filling in the information and added the item, the administrator will then go through the item, and fill in some new columns that the user hasn't been able to fill in.
I hope you understand me, otherwise you're more than welcome to ask questions! | 2012/07/17 | [
"https://Stackoverflow.com/questions/11519979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/744102/"
] | It is because `$pdo->errorInfo()` refers to the last statement that was successfully executed. Since `$sql->execute()` returns false, then it cannot refer to that statement (either to nothing or to the query before).
As to why `$sql->execute()` returns false, I don't know... either there is a problem with your `$params` array or with your database connection.
>
> PDO::errorCode — Fetch the SQLSTATE associated with the last operation on the database handle
>
>
>
Note: The PHP manual (<http://php.net/manual/en/pdo.errorinfo.php>) does not define exactly what "last operation on the database handle" means, but if there was an issue with binding parameters, that error would have occurred inside PDO and without any interaction with the database. It is safe to say that if `$pdo->execute()` returns `true`, that `$pdo->errorInfo()` is valid. If `$pdo->execute()` returns `false`, the behavior of `$pdo->errorInfo()` is not explicitly clear from the documentation. If I recall correctly from my experience, execute returns `true`, even if MySQL returned an error, returns `false` if no operation was done. Since the documentation is not specific, it might be db driver specific.
This answer reflects practical experience as of when it was written in September 2012. As a user has pointed out, the documentation does not explicitly reaffirm this interpretation. It also may only reflect the particular database driver implementation, but it should always be true that if `$pdo->execute()` returns `true`, that `$pdo->errorInfo()` is valid.
You might also want to set *PDO::ERRMODE\_EXCEPTION* in your connect sequence. Exception handling makes it unnecessary to check and query the error.
```
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
``` | From the php manual:
PDO::ERR\_NONE (string)
Corresponds to SQLSTATE '00000', meaning that the SQL statement was successfully issued with no errors or warnings. This constant is for your convenience when checking PDO::errorCode() or PDOStatement::errorCode() to determine if an error occurred. You will usually know if this is the case by examining the return code from the method that raised the error condition anyway.
So it sounds like it did insert the record. Check the last record id in your table... maybe you just missed it? |
11,519,979 | I'm trying to make a custom list for inquiries, where users will fill in some information such as "Name", "Reason" etc. When they've finished filling in the information and added the item, the administrator will then go through the item, and fill in some new columns that the user hasn't been able to fill in.
I hope you understand me, otherwise you're more than welcome to ask questions! | 2012/07/17 | [
"https://Stackoverflow.com/questions/11519979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/744102/"
] | I Faced the similar problem ,
This occurs manly due to **error in query**, try to **run your query in php-myadmin** or any other query runner and **confirm** that your **query is working** fine.
Even if our query syntax is correct other simple errors like leaving null or not mentioan a column that set as not null in table structure will cause this error.(This was the errror made by me)
As user1122069 explained the reason for $pdo->errorInfo() says nothing is wrong may be due to
>
> $pdo->errorInfo() refers to the last statement that was successfully
> executed.
> Since $sql->execute() returns false, then it cannot refer to
> that statement (either to nothing or to the query before)
>
>
>
Hopes this helps :) | I was getting this error at one time. I only got it on one server for all failures. A different server would report the error correctly for the same errors. That led me to believe it was a MySQL client configuration error. I never solved the specific error, but check your configurations. |
11,519,979 | I'm trying to make a custom list for inquiries, where users will fill in some information such as "Name", "Reason" etc. When they've finished filling in the information and added the item, the administrator will then go through the item, and fill in some new columns that the user hasn't been able to fill in.
I hope you understand me, otherwise you're more than welcome to ask questions! | 2012/07/17 | [
"https://Stackoverflow.com/questions/11519979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/744102/"
] | I Faced the similar problem ,
This occurs manly due to **error in query**, try to **run your query in php-myadmin** or any other query runner and **confirm** that your **query is working** fine.
Even if our query syntax is correct other simple errors like leaving null or not mentioan a column that set as not null in table structure will cause this error.(This was the errror made by me)
As user1122069 explained the reason for $pdo->errorInfo() says nothing is wrong may be due to
>
> $pdo->errorInfo() refers to the last statement that was successfully
> executed.
> Since $sql->execute() returns false, then it cannot refer to
> that statement (either to nothing or to the query before)
>
>
>
Hopes this helps :) | Try to check $sql by print\_r() and copy your query then try resultant query in phpMyadmin. Hope will get the reason. There would be chance of irrelevant value. |
11,519,979 | I'm trying to make a custom list for inquiries, where users will fill in some information such as "Name", "Reason" etc. When they've finished filling in the information and added the item, the administrator will then go through the item, and fill in some new columns that the user hasn't been able to fill in.
I hope you understand me, otherwise you're more than welcome to ask questions! | 2012/07/17 | [
"https://Stackoverflow.com/questions/11519979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/744102/"
] | I was getting this error at one time. I only got it on one server for all failures. A different server would report the error correctly for the same errors. That led me to believe it was a MySQL client configuration error. I never solved the specific error, but check your configurations. | Try to check $sql by print\_r() and copy your query then try resultant query in phpMyadmin. Hope will get the reason. There would be chance of irrelevant value. |
11,519,979 | I'm trying to make a custom list for inquiries, where users will fill in some information such as "Name", "Reason" etc. When they've finished filling in the information and added the item, the administrator will then go through the item, and fill in some new columns that the user hasn't been able to fill in.
I hope you understand me, otherwise you're more than welcome to ask questions! | 2012/07/17 | [
"https://Stackoverflow.com/questions/11519979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/744102/"
] | From the php manual:
PDO::ERR\_NONE (string)
Corresponds to SQLSTATE '00000', meaning that the SQL statement was successfully issued with no errors or warnings. This constant is for your convenience when checking PDO::errorCode() or PDOStatement::errorCode() to determine if an error occurred. You will usually know if this is the case by examining the return code from the method that raised the error condition anyway.
So it sounds like it did insert the record. Check the last record id in your table... maybe you just missed it? | I was getting this error at one time. I only got it on one server for all failures. A different server would report the error correctly for the same errors. That led me to believe it was a MySQL client configuration error. I never solved the specific error, but check your configurations. |
11,519,979 | I'm trying to make a custom list for inquiries, where users will fill in some information such as "Name", "Reason" etc. When they've finished filling in the information and added the item, the administrator will then go through the item, and fill in some new columns that the user hasn't been able to fill in.
I hope you understand me, otherwise you're more than welcome to ask questions! | 2012/07/17 | [
"https://Stackoverflow.com/questions/11519979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/744102/"
] | From the php manual:
PDO::ERR\_NONE (string)
Corresponds to SQLSTATE '00000', meaning that the SQL statement was successfully issued with no errors or warnings. This constant is for your convenience when checking PDO::errorCode() or PDOStatement::errorCode() to determine if an error occurred. You will usually know if this is the case by examining the return code from the method that raised the error condition anyway.
So it sounds like it did insert the record. Check the last record id in your table... maybe you just missed it? | Try to check $sql by print\_r() and copy your query then try resultant query in phpMyadmin. Hope will get the reason. There would be chance of irrelevant value. |
188,820 | I need to change the response of Search Rest API in Magento 2.
**Request**:`rest/V1/search?searchCriteria[requestName]=quick_search_container
&searchCriteria[filterGroups][0][filters][0][field]=search_term
&searchCriteria[filterGroups][0][filters][0][value]=t-shirt
&searchCriteria[filterGroups][1][filters][1][field]=sleeve_type
&searchCriteria[filterGroups][1][filters][1][value]=173
&searchCriteria[filterGroups][2][filters][2][field]=neck
&searchCriteria[filterGroups][2][filters][2][value]=105`
**Response**:
```
"items": [
{
"id": 154,
"custom_attributes": [
{
"attribute_code": "score",
"value": "45.5335884094238300"
}
]
}
]
```
need to add more product information like **product name, sku, type, images etc..**,
```
"items": [
{
"id": 154,
"sku": "sample001",
"name": "sample product 1",
"type": "configurable",
"image_url": "http://magentohost/pub/media/catalog/product/s/s/1.png",
"custom_attributes": [
{
"attribute_code": "score",
"value": "45.5335884094238300"
}
]
}
]
```
but response have id and score only. How to add product information to search api response? | 2017/08/11 | [
"https://magento.stackexchange.com/questions/188820",
"https://magento.stackexchange.com",
"https://magento.stackexchange.com/users/-1/"
] | The beautiful thing about Magento is that you can take reference from the its core code. For answering the question I will took the example of the product API call to filter product from the "color" attribute code.
`rest/all/V1/products-render-info?
searchCriteria[filterGroups][0][filters][0][field]=color&
searchCriteria[filterGroups][0][filters][0][value]=53&
searchCriteria[filterGroups][0][filters][0][conditionType]=eq&
searchCriteria[sortOrders][0][field]=size&
searchCriteria[sortOrders][0][direction]=asc&
storeId=1
¤cyCode=usd`
From your code I assume that this is custom search criteria. Try to build search criteria in this way and if you are using the Magento code this can be helpful to you. | According to this question [Magento2 Rest Api Search Criteria not working properly!](https://magento.stackexchange.com/questions/172767/magento2-rest-api-search-criteria-not-working-properly)
you can add a "fields" parameter...
Not used it, but from the answer I guess it works...
**EDIT:**
Actually, from what I can tell, "fields" is used for restricting the data returned, not adding more data. |
188,820 | I need to change the response of Search Rest API in Magento 2.
**Request**:`rest/V1/search?searchCriteria[requestName]=quick_search_container
&searchCriteria[filterGroups][0][filters][0][field]=search_term
&searchCriteria[filterGroups][0][filters][0][value]=t-shirt
&searchCriteria[filterGroups][1][filters][1][field]=sleeve_type
&searchCriteria[filterGroups][1][filters][1][value]=173
&searchCriteria[filterGroups][2][filters][2][field]=neck
&searchCriteria[filterGroups][2][filters][2][value]=105`
**Response**:
```
"items": [
{
"id": 154,
"custom_attributes": [
{
"attribute_code": "score",
"value": "45.5335884094238300"
}
]
}
]
```
need to add more product information like **product name, sku, type, images etc..**,
```
"items": [
{
"id": 154,
"sku": "sample001",
"name": "sample product 1",
"type": "configurable",
"image_url": "http://magentohost/pub/media/catalog/product/s/s/1.png",
"custom_attributes": [
{
"attribute_code": "score",
"value": "45.5335884094238300"
}
]
}
]
```
but response have id and score only. How to add product information to search api response? | 2017/08/11 | [
"https://magento.stackexchange.com/questions/188820",
"https://magento.stackexchange.com",
"https://magento.stackexchange.com/users/-1/"
] | For get the product information in the `Search API` you have to use `searchCriteria` with `filters` in request URL. Use below API Request URL.
**Request URL:**
```
http://localhost/magentosample230/rest/V1/products?searchCriteria[filter_groups][0][filters][0][field]=name&searchCriteria[filter_groups][0][filters][0][value]=%25Watch%25&searchCriteria[filter_groups][0][filters][0][condition_type]=like&searchCriteria[filter_groups][0][filters][1][field]=name&searchCriteria[filter_groups][0][filters][1][value]=%25Bag %25&searchCriteria[filter_groups][0][filters][1][condition_type]=like
```
**Response:**
```
{
"items": [
{
"id": 36,
"sku": "24-MG04",
"name": "Aim Analog Watch",
"attribute_set_id": 11,
"price": 45,
"status": 1,
"visibility": 4,
"type_id": "simple",
"created_at": "2019-08-30 07:14:59",
"updated_at": "2019-08-30 07:14:59",
"extension_attributes": {
"website_ids": [
1
],
"category_links": [
{
"position": 0,
"category_id": "3"
},
{
"position": 0,
"category_id": "6"
}
],
"stock_item": {
"item_id": 36,
"product_id": 36,
"stock_id": 1,
"qty": 100,
"is_in_stock": true,
"is_qty_decimal": false,
"show_default_notification_message": false,
"use_config_min_qty": true,
"min_qty": 0,
"use_config_min_sale_qty": 1,
"min_sale_qty": 1,
"use_config_max_sale_qty": true,
"max_sale_qty": 10000,
"use_config_backorders": true,
"backorders": 0,
"use_config_notify_stock_qty": true,
"notify_stock_qty": 1,
"use_config_qty_increments": true,
"qty_increments": 0,
"use_config_enable_qty_inc": true,
"enable_qty_increments": false,
"use_config_manage_stock": true,
"manage_stock": true,
"low_stock_date": null,
"is_decimal_divided": false,
"stock_status_changed_auto": 0
}
},
"product_links": [],
"options": [],
"media_gallery_entries": [
{
"id": 41,
"media_type": "image",
"label": "Image",
"position": 1,
"disabled": false,
"types": [
"image",
"small_image",
"thumbnail"
],
"file": "/m/g/mg04-bk-0.jpg"
}
],
"tier_prices": [],
"custom_attributes": [
{
"attribute_code": "image",
"value": "/m/g/mg04-bk-0.jpg"
},
{
"attribute_code": "small_image",
"value": "/m/g/mg04-bk-0.jpg"
},
{
"attribute_code": "thumbnail",
"value": "/m/g/mg04-bk-0.jpg"
},
{
"attribute_code": "options_container",
"value": "container2"
},
{
"attribute_code": "url_key",
"value": "aim-analog-watch"
},
{
"attribute_code": "required_options",
"value": "0"
},
{
"attribute_code": "has_options",
"value": "0"
},
{
"attribute_code": "tax_class_id",
"value": "2"
},
{
"attribute_code": "category_ids",
"value": [
"3",
"6"
]
},
{
"attribute_code": "description",
"value": "<p>Stay light-years ahead of the competition with our Aim Analog Watch. The flexible, rubberized strap is contoured to conform to the shape of your wrist for a comfortable all-day fit. The face features three illuminated hands, a digital read-out of the current time, and stopwatch functions.</p>\n<ul>\n<li>Japanese quartz movement.</li>\n<li>Strap fits 7\" to 8.0\".</li>\n</ul>"
},
{
"attribute_code": "activity",
"value": "9,17,5,11"
},
{
"attribute_code": "material",
"value": "44,45"
},
{
"attribute_code": "gender",
"value": "80"
},
{
"attribute_code": "category_gear",
"value": "86,87,90"
}
]
},
{
"id": 37,
"sku": "24-MG01",
"name": "Endurance Watch",
"attribute_set_id": 11,
"price": 49,
"status": 1,
"visibility": 4,
"type_id": "simple",
"created_at": "2019-08-30 07:14:59",
"updated_at": "2019-08-30 07:14:59",
"extension_attributes": {
"website_ids": [
1
],
"category_links": [
{
"position": 0,
"category_id": "3"
},
{
"position": 0,
"category_id": "6"
}
],
"stock_item": {
"item_id": 37,
"product_id": 37,
"stock_id": 1,
"qty": 100,
"is_in_stock": true,
"is_qty_decimal": false,
"show_default_notification_message": false,
"use_config_min_qty": true,
"min_qty": 0,
"use_config_min_sale_qty": 1,
"min_sale_qty": 1,
"use_config_max_sale_qty": true,
"max_sale_qty": 10000,
"use_config_backorders": true,
"backorders": 0,
"use_config_notify_stock_qty": true,
"notify_stock_qty": 1,
"use_config_qty_increments": true,
"qty_increments": 0,
"use_config_enable_qty_inc": true,
"enable_qty_increments": false,
"use_config_manage_stock": true,
"manage_stock": true,
"low_stock_date": null,
"is_decimal_divided": false,
"stock_status_changed_auto": 0
}
},
"product_links": [],
"options": [],
"media_gallery_entries": [
{
"id": 42,
"media_type": "image",
"label": "Image",
"position": 1,
"disabled": false,
"types": [
"image",
"small_image",
"thumbnail"
],
"file": "/m/g/mg01-bk-0.jpg"
}
],
"tier_prices": [],
"custom_attributes": [
{
"attribute_code": "image",
"value": "/m/g/mg01-bk-0.jpg"
},
{
"attribute_code": "small_image",
"value": "/m/g/mg01-bk-0.jpg"
},
{
"attribute_code": "thumbnail",
"value": "/m/g/mg01-bk-0.jpg"
},
{
"attribute_code": "options_container",
"value": "container2"
},
{
"attribute_code": "url_key",
"value": "endurance-watch"
},
{
"attribute_code": "required_options",
"value": "0"
},
{
"attribute_code": "has_options",
"value": "0"
},
{
"attribute_code": "tax_class_id",
"value": "2"
},
{
"attribute_code": "category_ids",
"value": [
"3",
"6"
]
},
{
"attribute_code": "description",
"value": "<p>It's easy to track and monitor your training progress with the Endurance Watch. You'll see standard info like time, date and day of the week, but it also functions for the serious high-mileage athete: lap counter, stopwatch, distance, heart rate, speed/pace, cadence and altitude.</p>\n<ul>\n<li>Digital display.</li>\n<li>LED backlight.</li>\n<li>Strap fits 7\" to 10\".</li>\n<li>1-year limited warranty.</li>\n<li>Comes with polished metal case.</li>\n</ul>"
},
{
"attribute_code": "activity",
"value": "9,16"
},
{
"attribute_code": "material",
"value": "43,45,48"
},
{
"attribute_code": "gender",
"value": "80"
},
{
"attribute_code": "category_gear",
"value": "86,87,90"
}
]
},
{
"id": 38,
"sku": "24-MG03",
"name": "Summit Watch",
"attribute_set_id": 11,
"price": 54,
"status": 1,
"visibility": 4,
"type_id": "simple",
"created_at": "2019-08-30 07:15:00",
"updated_at": "2019-08-30 07:15:00",
"extension_attributes": {
"website_ids": [
1
],
"category_links": [
{
"position": 0,
"category_id": "3"
},
{
"position": 0,
"category_id": "7"
},
{
"position": 0,
"category_id": "6"
},
{
"position": 0,
"category_id": "8"
}
],
"stock_item": {
"item_id": 38,
"product_id": 38,
"stock_id": 1,
"qty": 100,
"is_in_stock": true,
"is_qty_decimal": false,
"show_default_notification_message": false,
"use_config_min_qty": true,
"min_qty": 0,
"use_config_min_sale_qty": 1,
"min_sale_qty": 1,
"use_config_max_sale_qty": true,
"max_sale_qty": 10000,
"use_config_backorders": true,
"backorders": 0,
"use_config_notify_stock_qty": true,
"notify_stock_qty": 1,
"use_config_qty_increments": true,
"qty_increments": 0,
"use_config_enable_qty_inc": true,
"enable_qty_increments": false,
"use_config_manage_stock": true,
"manage_stock": true,
"low_stock_date": null,
"is_decimal_divided": false,
"stock_status_changed_auto": 0
}
},
"product_links": [],
"options": [],
"media_gallery_entries": [
{
"id": 43,
"media_type": "image",
"label": "Image",
"position": 1,
"disabled": false,
"types": [
"image",
"small_image",
"thumbnail"
],
"file": "/m/g/mg03-br-0.jpg"
}
],
"tier_prices": [],
"custom_attributes": [
{
"attribute_code": "image",
"value": "/m/g/mg03-br-0.jpg"
},
{
"attribute_code": "small_image",
"value": "/m/g/mg03-br-0.jpg"
},
{
"attribute_code": "thumbnail",
"value": "/m/g/mg03-br-0.jpg"
},
{
"attribute_code": "options_container",
"value": "container2"
},
{
"attribute_code": "url_key",
"value": "summit-watch"
},
{
"attribute_code": "required_options",
"value": "0"
},
{
"attribute_code": "has_options",
"value": "0"
},
{
"attribute_code": "tax_class_id",
"value": "2"
},
{
"attribute_code": "category_ids",
"value": [
"3",
"7",
"6",
"8"
]
},
{
"attribute_code": "description",
"value": "<p>Trek high and low in the attractive Summit Watch, which features a digital LED display with time and date, stopwatch, lap counter, and 3-second backlight. It can also calculate the number of steps taken and calories burned.</p>\n<ul>\n<li>Brushed metal case.</li>\n<li>Water resistant (100 meters).</li>\n<li>Buckle clasp.</li>\n<li>Strap fits 7\" - 10\".</li>\n<li>1-year limited warranty.</li>\n</ul>"
},
{
"attribute_code": "activity",
"value": "9,16,17,5,11"
},
{
"attribute_code": "material",
"value": "43,44,48"
},
{
"attribute_code": "gender",
"value": "80,81,84"
},
{
"attribute_code": "category_gear",
"value": "86,87,90"
},
{
"attribute_code": "new",
"value": "1"
}
]
},
{
"id": 39,
"sku": "24-MG05",
"name": "Cruise Dual Analog Watch",
"attribute_set_id": 11,
"price": 55,
"status": 1,
"visibility": 4,
"type_id": "simple",
"created_at": "2019-08-30 07:15:00",
"updated_at": "2019-08-30 07:15:00",
"extension_attributes": {
"website_ids": [
1
],
"category_links": [
{
"position": 0,
"category_id": "3"
},
{
"position": 0,
"category_id": "7"
},
{
"position": 0,
"category_id": "6"
},
{
"position": 0,
"category_id": "8"
}
],
"stock_item": {
"item_id": 39,
"product_id": 39,
"stock_id": 1,
"qty": 100,
"is_in_stock": true,
"is_qty_decimal": false,
"show_default_notification_message": false,
"use_config_min_qty": true,
"min_qty": 0,
"use_config_min_sale_qty": 1,
"min_sale_qty": 1,
"use_config_max_sale_qty": true,
"max_sale_qty": 10000,
"use_config_backorders": true,
"backorders": 0,
"use_config_notify_stock_qty": true,
"notify_stock_qty": 1,
"use_config_qty_increments": true,
"qty_increments": 0,
"use_config_enable_qty_inc": true,
"enable_qty_increments": false,
"use_config_manage_stock": true,
"manage_stock": true,
"low_stock_date": null,
"is_decimal_divided": false,
"stock_status_changed_auto": 0
}
},
"product_links": [],
"options": [],
"media_gallery_entries": [
{
"id": 44,
"media_type": "image",
"label": "Image",
"position": 1,
"disabled": false,
"types": [
"image",
"small_image",
"thumbnail"
],
"file": "/m/g/mg05-br-0.jpg"
}
],
"tier_prices": [],
"custom_attributes": [
{
"attribute_code": "image",
"value": "/m/g/mg05-br-0.jpg"
},
{
"attribute_code": "small_image",
"value": "/m/g/mg05-br-0.jpg"
},
{
"attribute_code": "thumbnail",
"value": "/m/g/mg05-br-0.jpg"
},
{
"attribute_code": "options_container",
"value": "container2"
},
{
"attribute_code": "url_key",
"value": "cruise-dual-analog-watch"
},
{
"attribute_code": "required_options",
"value": "0"
},
{
"attribute_code": "has_options",
"value": "0"
},
{
"attribute_code": "tax_class_id",
"value": "2"
},
{
"attribute_code": "category_ids",
"value": [
"3",
"7",
"6",
"8"
]
},
{
"attribute_code": "description",
"value": "<p>Whether you're traveling or wish you were, you'll never let time zones perplex you again with the Cruise Dual Analog Watch. The thick, adjustable band promises a comfortable, personalized fit to this classy, modern time piece.</p>\n<ul>\n<li>Two dials.</li>\n<li>Stainless steel case.</li>\n<li>Adjustable leather band.</li>\n</ul>"
},
{
"attribute_code": "activity",
"value": "9"
},
{
"attribute_code": "material",
"value": "35,44"
},
{
"attribute_code": "gender",
"value": "80"
},
{
"attribute_code": "category_gear",
"value": "86,88,90"
},
{
"attribute_code": "new",
"value": "1"
}
]
}
],
"search_criteria": {
"filter_groups": [
{
"filters": [
{
"field": "name",
"value": "%Watch%",
"condition_type": "like"
}
]
}
]
},
"total_count": 4
}
``` | According to this question [Magento2 Rest Api Search Criteria not working properly!](https://magento.stackexchange.com/questions/172767/magento2-rest-api-search-criteria-not-working-properly)
you can add a "fields" parameter...
Not used it, but from the answer I guess it works...
**EDIT:**
Actually, from what I can tell, "fields" is used for restricting the data returned, not adding more data. |
9,335,282 | I build up my datagrid with bindnig source:
```
SqlDataAdapter adapter = new SqlDataAdapter(Datenbank.cmd);
dataSet1.Tables.Clear();
adapter.Fill(dataSet1, "Table");
bs = new BindingSource();
bs.DataSource = dataSet1.Tables["Table"];
dataGridView1.DataSource = bs;
```
Now I sort grid
```
bs.Sort = "customer DESC";
```
Now I want to remove row 0
```
dataSet1.Tables[0].Rows.RemoveAt(0);
```
However, the row which was at position 0 before sorting will be deleted, not the row which now is on position 0
**//EDIT :** is there similar for `test.Tables[0].Rows.InsertAt(newRow, 0);` ? | 2012/02/17 | [
"https://Stackoverflow.com/questions/9335282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1032703/"
] | See the section called **State List** in this bit of documentation...[Drawable Resources](http://developer.android.com/guide/topics/resources/drawable-resource.html#StateList).
You can define two different `Button` xml files one for the transparent 'default' state and another with the button as Red for your 'pressed' state. You then define a `selector` which switches the drawable resources in the different states.
EDIT: As per devunwired's comment the Color State List resource is probably more suitable for just changing colours rather than the drawable itself. | I like the solution proposed by Konstantin Burov in the other issue: [Android customized button; changing text color](https://stackoverflow.com/questions/4692642/android-customized-button-changing-text-color)
You can actually manage more states than just pressed and normal. But it should solve the problem.
```
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Focused and not pressed -->
<item android:state_focused="true"
android:state_pressed="false"
android:color="#ffffff" />
<!-- Focused and pressed -->
<item android:state_focused="true"
android:state_pressed="true"
android:color="#000000" />
<!-- Unfocused and pressed -->
<item android:state_focused="false"
android:state_pressed="true"
android:color="#000000" />
<!-- Default color -->
<item android:color="#ffffff" />
</selector>
```
Then you can use that selector drawable in your button changing the text color attribute like below. Note that the selector in the example below is named "button\_text\_color"
>
> android:textColor="@drawable/button\_text\_color"
>
>
>
Using the same drawable approach you can also solve the background color of the button. Just remember that in the selector instead of using the "android:color" attribute you need to use the "android:drawable" attribute like below.
```
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Focused and not pressed -->
<item android:state_focused="true"
android:state_pressed="false"
android:drawable="#ffffff" />
<!-- Focused and pressed -->
<item android:state_focused="true"
android:state_pressed="true"
android:drawable="#000000" />
<!-- Unfocused and pressed -->
<item android:state_focused="false"
android:state_pressed="true"
android:drawable="#000000" />
<!-- Default color -->
<item android:drawable="#ffffff" />
</selector>
```
And then in the button itself do, note that this time the selector name is "button\_background"
>
> android:background="@drawable/button\_background"
>
>
> |
9,335,282 | I build up my datagrid with bindnig source:
```
SqlDataAdapter adapter = new SqlDataAdapter(Datenbank.cmd);
dataSet1.Tables.Clear();
adapter.Fill(dataSet1, "Table");
bs = new BindingSource();
bs.DataSource = dataSet1.Tables["Table"];
dataGridView1.DataSource = bs;
```
Now I sort grid
```
bs.Sort = "customer DESC";
```
Now I want to remove row 0
```
dataSet1.Tables[0].Rows.RemoveAt(0);
```
However, the row which was at position 0 before sorting will be deleted, not the row which now is on position 0
**//EDIT :** is there similar for `test.Tables[0].Rows.InsertAt(newRow, 0);` ? | 2012/02/17 | [
"https://Stackoverflow.com/questions/9335282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1032703/"
] | See the section called **State List** in this bit of documentation...[Drawable Resources](http://developer.android.com/guide/topics/resources/drawable-resource.html#StateList).
You can define two different `Button` xml files one for the transparent 'default' state and another with the button as Red for your 'pressed' state. You then define a `selector` which switches the drawable resources in the different states.
EDIT: As per devunwired's comment the Color State List resource is probably more suitable for just changing colours rather than the drawable itself. | ```
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_pressed="false"
android:color="#FFFFFF" />
<item
android:state_pressed="true"
android:color="#000000" />
</selector>
``` |
9,335,282 | I build up my datagrid with bindnig source:
```
SqlDataAdapter adapter = new SqlDataAdapter(Datenbank.cmd);
dataSet1.Tables.Clear();
adapter.Fill(dataSet1, "Table");
bs = new BindingSource();
bs.DataSource = dataSet1.Tables["Table"];
dataGridView1.DataSource = bs;
```
Now I sort grid
```
bs.Sort = "customer DESC";
```
Now I want to remove row 0
```
dataSet1.Tables[0].Rows.RemoveAt(0);
```
However, the row which was at position 0 before sorting will be deleted, not the row which now is on position 0
**//EDIT :** is there similar for `test.Tables[0].Rows.InsertAt(newRow, 0);` ? | 2012/02/17 | [
"https://Stackoverflow.com/questions/9335282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1032703/"
] | See the section called **State List** in this bit of documentation...[Drawable Resources](http://developer.android.com/guide/topics/resources/drawable-resource.html#StateList).
You can define two different `Button` xml files one for the transparent 'default' state and another with the button as Red for your 'pressed' state. You then define a `selector` which switches the drawable resources in the different states.
EDIT: As per devunwired's comment the Color State List resource is probably more suitable for just changing colours rather than the drawable itself. | You must set `@drawable` xml resource in `textColor` attributte
Here is example: [Android customized button; changing text color](https://stackoverflow.com/questions/4692642/android-customized-button-changing-text-color) |
9,335,282 | I build up my datagrid with bindnig source:
```
SqlDataAdapter adapter = new SqlDataAdapter(Datenbank.cmd);
dataSet1.Tables.Clear();
adapter.Fill(dataSet1, "Table");
bs = new BindingSource();
bs.DataSource = dataSet1.Tables["Table"];
dataGridView1.DataSource = bs;
```
Now I sort grid
```
bs.Sort = "customer DESC";
```
Now I want to remove row 0
```
dataSet1.Tables[0].Rows.RemoveAt(0);
```
However, the row which was at position 0 before sorting will be deleted, not the row which now is on position 0
**//EDIT :** is there similar for `test.Tables[0].Rows.InsertAt(newRow, 0);` ? | 2012/02/17 | [
"https://Stackoverflow.com/questions/9335282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1032703/"
] | Yes, you can do it like that:
layout/main\_layout.xml:
```xml
.....
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="bonjour !"
android:textColor="@color/button_text_color"
/>
.....
```
color/button\_text\_color.xml:
```xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="#c0c0c0" android:state_pressed="true"/>
<item android:color="#ffffff"/>
</selector>
``` | You must set `@drawable` xml resource in `textColor` attributte
Here is example: [Android customized button; changing text color](https://stackoverflow.com/questions/4692642/android-customized-button-changing-text-color) |
9,335,282 | I build up my datagrid with bindnig source:
```
SqlDataAdapter adapter = new SqlDataAdapter(Datenbank.cmd);
dataSet1.Tables.Clear();
adapter.Fill(dataSet1, "Table");
bs = new BindingSource();
bs.DataSource = dataSet1.Tables["Table"];
dataGridView1.DataSource = bs;
```
Now I sort grid
```
bs.Sort = "customer DESC";
```
Now I want to remove row 0
```
dataSet1.Tables[0].Rows.RemoveAt(0);
```
However, the row which was at position 0 before sorting will be deleted, not the row which now is on position 0
**//EDIT :** is there similar for `test.Tables[0].Rows.InsertAt(newRow, 0);` ? | 2012/02/17 | [
"https://Stackoverflow.com/questions/9335282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1032703/"
] | Yes, you can do it like that:
layout/main\_layout.xml:
```xml
.....
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="bonjour !"
android:textColor="@color/button_text_color"
/>
.....
```
color/button\_text\_color.xml:
```xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="#c0c0c0" android:state_pressed="true"/>
<item android:color="#ffffff"/>
</selector>
``` | I like the solution proposed by Konstantin Burov in the other issue: [Android customized button; changing text color](https://stackoverflow.com/questions/4692642/android-customized-button-changing-text-color)
You can actually manage more states than just pressed and normal. But it should solve the problem.
```
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Focused and not pressed -->
<item android:state_focused="true"
android:state_pressed="false"
android:color="#ffffff" />
<!-- Focused and pressed -->
<item android:state_focused="true"
android:state_pressed="true"
android:color="#000000" />
<!-- Unfocused and pressed -->
<item android:state_focused="false"
android:state_pressed="true"
android:color="#000000" />
<!-- Default color -->
<item android:color="#ffffff" />
</selector>
```
Then you can use that selector drawable in your button changing the text color attribute like below. Note that the selector in the example below is named "button\_text\_color"
>
> android:textColor="@drawable/button\_text\_color"
>
>
>
Using the same drawable approach you can also solve the background color of the button. Just remember that in the selector instead of using the "android:color" attribute you need to use the "android:drawable" attribute like below.
```
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Focused and not pressed -->
<item android:state_focused="true"
android:state_pressed="false"
android:drawable="#ffffff" />
<!-- Focused and pressed -->
<item android:state_focused="true"
android:state_pressed="true"
android:drawable="#000000" />
<!-- Unfocused and pressed -->
<item android:state_focused="false"
android:state_pressed="true"
android:drawable="#000000" />
<!-- Default color -->
<item android:drawable="#ffffff" />
</selector>
```
And then in the button itself do, note that this time the selector name is "button\_background"
>
> android:background="@drawable/button\_background"
>
>
> |
9,335,282 | I build up my datagrid with bindnig source:
```
SqlDataAdapter adapter = new SqlDataAdapter(Datenbank.cmd);
dataSet1.Tables.Clear();
adapter.Fill(dataSet1, "Table");
bs = new BindingSource();
bs.DataSource = dataSet1.Tables["Table"];
dataGridView1.DataSource = bs;
```
Now I sort grid
```
bs.Sort = "customer DESC";
```
Now I want to remove row 0
```
dataSet1.Tables[0].Rows.RemoveAt(0);
```
However, the row which was at position 0 before sorting will be deleted, not the row which now is on position 0
**//EDIT :** is there similar for `test.Tables[0].Rows.InsertAt(newRow, 0);` ? | 2012/02/17 | [
"https://Stackoverflow.com/questions/9335282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1032703/"
] | I like the solution proposed by Konstantin Burov in the other issue: [Android customized button; changing text color](https://stackoverflow.com/questions/4692642/android-customized-button-changing-text-color)
You can actually manage more states than just pressed and normal. But it should solve the problem.
```
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Focused and not pressed -->
<item android:state_focused="true"
android:state_pressed="false"
android:color="#ffffff" />
<!-- Focused and pressed -->
<item android:state_focused="true"
android:state_pressed="true"
android:color="#000000" />
<!-- Unfocused and pressed -->
<item android:state_focused="false"
android:state_pressed="true"
android:color="#000000" />
<!-- Default color -->
<item android:color="#ffffff" />
</selector>
```
Then you can use that selector drawable in your button changing the text color attribute like below. Note that the selector in the example below is named "button\_text\_color"
>
> android:textColor="@drawable/button\_text\_color"
>
>
>
Using the same drawable approach you can also solve the background color of the button. Just remember that in the selector instead of using the "android:color" attribute you need to use the "android:drawable" attribute like below.
```
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Focused and not pressed -->
<item android:state_focused="true"
android:state_pressed="false"
android:drawable="#ffffff" />
<!-- Focused and pressed -->
<item android:state_focused="true"
android:state_pressed="true"
android:drawable="#000000" />
<!-- Unfocused and pressed -->
<item android:state_focused="false"
android:state_pressed="true"
android:drawable="#000000" />
<!-- Default color -->
<item android:drawable="#ffffff" />
</selector>
```
And then in the button itself do, note that this time the selector name is "button\_background"
>
> android:background="@drawable/button\_background"
>
>
> | You have to do it in your code. Try this:
```
mBtn = ((Button) findViewById( R.id.button1 ));
mBtn.setOnClickListener( new OnClickListener() {
@Override
public void onClick(View v) {
mBtn.setTextColor( Color.RED );
}
});
```
Declare:
```
private Button mBtn;
``` |
9,335,282 | I build up my datagrid with bindnig source:
```
SqlDataAdapter adapter = new SqlDataAdapter(Datenbank.cmd);
dataSet1.Tables.Clear();
adapter.Fill(dataSet1, "Table");
bs = new BindingSource();
bs.DataSource = dataSet1.Tables["Table"];
dataGridView1.DataSource = bs;
```
Now I sort grid
```
bs.Sort = "customer DESC";
```
Now I want to remove row 0
```
dataSet1.Tables[0].Rows.RemoveAt(0);
```
However, the row which was at position 0 before sorting will be deleted, not the row which now is on position 0
**//EDIT :** is there similar for `test.Tables[0].Rows.InsertAt(newRow, 0);` ? | 2012/02/17 | [
"https://Stackoverflow.com/questions/9335282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1032703/"
] | Yes, you can do it like that:
layout/main\_layout.xml:
```xml
.....
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="bonjour !"
android:textColor="@color/button_text_color"
/>
.....
```
color/button\_text\_color.xml:
```xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="#c0c0c0" android:state_pressed="true"/>
<item android:color="#ffffff"/>
</selector>
``` | See the section called **State List** in this bit of documentation...[Drawable Resources](http://developer.android.com/guide/topics/resources/drawable-resource.html#StateList).
You can define two different `Button` xml files one for the transparent 'default' state and another with the button as Red for your 'pressed' state. You then define a `selector` which switches the drawable resources in the different states.
EDIT: As per devunwired's comment the Color State List resource is probably more suitable for just changing colours rather than the drawable itself. |
9,335,282 | I build up my datagrid with bindnig source:
```
SqlDataAdapter adapter = new SqlDataAdapter(Datenbank.cmd);
dataSet1.Tables.Clear();
adapter.Fill(dataSet1, "Table");
bs = new BindingSource();
bs.DataSource = dataSet1.Tables["Table"];
dataGridView1.DataSource = bs;
```
Now I sort grid
```
bs.Sort = "customer DESC";
```
Now I want to remove row 0
```
dataSet1.Tables[0].Rows.RemoveAt(0);
```
However, the row which was at position 0 before sorting will be deleted, not the row which now is on position 0
**//EDIT :** is there similar for `test.Tables[0].Rows.InsertAt(newRow, 0);` ? | 2012/02/17 | [
"https://Stackoverflow.com/questions/9335282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1032703/"
] | Yes, you can do it like that:
layout/main\_layout.xml:
```xml
.....
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="bonjour !"
android:textColor="@color/button_text_color"
/>
.....
```
color/button\_text\_color.xml:
```xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="#c0c0c0" android:state_pressed="true"/>
<item android:color="#ffffff"/>
</selector>
``` | You have to do it in your code. Try this:
```
mBtn = ((Button) findViewById( R.id.button1 ));
mBtn.setOnClickListener( new OnClickListener() {
@Override
public void onClick(View v) {
mBtn.setTextColor( Color.RED );
}
});
```
Declare:
```
private Button mBtn;
``` |
9,335,282 | I build up my datagrid with bindnig source:
```
SqlDataAdapter adapter = new SqlDataAdapter(Datenbank.cmd);
dataSet1.Tables.Clear();
adapter.Fill(dataSet1, "Table");
bs = new BindingSource();
bs.DataSource = dataSet1.Tables["Table"];
dataGridView1.DataSource = bs;
```
Now I sort grid
```
bs.Sort = "customer DESC";
```
Now I want to remove row 0
```
dataSet1.Tables[0].Rows.RemoveAt(0);
```
However, the row which was at position 0 before sorting will be deleted, not the row which now is on position 0
**//EDIT :** is there similar for `test.Tables[0].Rows.InsertAt(newRow, 0);` ? | 2012/02/17 | [
"https://Stackoverflow.com/questions/9335282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1032703/"
] | I like the solution proposed by Konstantin Burov in the other issue: [Android customized button; changing text color](https://stackoverflow.com/questions/4692642/android-customized-button-changing-text-color)
You can actually manage more states than just pressed and normal. But it should solve the problem.
```
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Focused and not pressed -->
<item android:state_focused="true"
android:state_pressed="false"
android:color="#ffffff" />
<!-- Focused and pressed -->
<item android:state_focused="true"
android:state_pressed="true"
android:color="#000000" />
<!-- Unfocused and pressed -->
<item android:state_focused="false"
android:state_pressed="true"
android:color="#000000" />
<!-- Default color -->
<item android:color="#ffffff" />
</selector>
```
Then you can use that selector drawable in your button changing the text color attribute like below. Note that the selector in the example below is named "button\_text\_color"
>
> android:textColor="@drawable/button\_text\_color"
>
>
>
Using the same drawable approach you can also solve the background color of the button. Just remember that in the selector instead of using the "android:color" attribute you need to use the "android:drawable" attribute like below.
```
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Focused and not pressed -->
<item android:state_focused="true"
android:state_pressed="false"
android:drawable="#ffffff" />
<!-- Focused and pressed -->
<item android:state_focused="true"
android:state_pressed="true"
android:drawable="#000000" />
<!-- Unfocused and pressed -->
<item android:state_focused="false"
android:state_pressed="true"
android:drawable="#000000" />
<!-- Default color -->
<item android:drawable="#ffffff" />
</selector>
```
And then in the button itself do, note that this time the selector name is "button\_background"
>
> android:background="@drawable/button\_background"
>
>
> | ```
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_pressed="false"
android:color="#FFFFFF" />
<item
android:state_pressed="true"
android:color="#000000" />
</selector>
``` |
9,335,282 | I build up my datagrid with bindnig source:
```
SqlDataAdapter adapter = new SqlDataAdapter(Datenbank.cmd);
dataSet1.Tables.Clear();
adapter.Fill(dataSet1, "Table");
bs = new BindingSource();
bs.DataSource = dataSet1.Tables["Table"];
dataGridView1.DataSource = bs;
```
Now I sort grid
```
bs.Sort = "customer DESC";
```
Now I want to remove row 0
```
dataSet1.Tables[0].Rows.RemoveAt(0);
```
However, the row which was at position 0 before sorting will be deleted, not the row which now is on position 0
**//EDIT :** is there similar for `test.Tables[0].Rows.InsertAt(newRow, 0);` ? | 2012/02/17 | [
"https://Stackoverflow.com/questions/9335282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1032703/"
] | You have to do it in your code. Try this:
```
mBtn = ((Button) findViewById( R.id.button1 ));
mBtn.setOnClickListener( new OnClickListener() {
@Override
public void onClick(View v) {
mBtn.setTextColor( Color.RED );
}
});
```
Declare:
```
private Button mBtn;
``` | ```
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_pressed="false"
android:color="#FFFFFF" />
<item
android:state_pressed="true"
android:color="#000000" />
</selector>
``` |
72,662,360 | So I'm super new to react. I have some code where I use fetch to get data from an API (that I created, structured like {'userData': {'overall': {'rank': '10', 'level': '99', 'xp': '200000000'}}}) and I display it on screen. It was working fine for hours and now all of a sudden without touching any code, it's broken. it will display the data just fine if i make an API request and then refresh the page. but then when I refresh the page again it tells me "Uncaught TypeError: Cannot read properties of undefined (reading 'overall')"
I don't know what I'm doing wrong and I'm wondering if someone can help me because I don't know how it became undefined, it was reading it just fine and then on refresh it changes to undefined. here's my code for the component
```
function Activities() {
let name = "three-dawg";
function fetchPlayerData(name){
fetch(URL)
.then(response => response.json())
.then(data => setPlayerData(data));
};
function refreshPage() {
window.location.reload(false)
}
const [playerData, setPlayerData] = useState([]);
useEffect(() => {fetchPlayerData(name)}, [name]);
return (
<div>
Hello {playerData._id}
<button onClick={() => {
fetchPlayerData(name)
refreshPage()
}}>load player</button>
<ul>
<li>{playerData.userData.overall.rank}</li>
</ul>
</div>
);
}
``` | 2022/06/17 | [
"https://Stackoverflow.com/questions/72662360",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16367560/"
] | You need to first redirect to your application path in `CLI`
```
cd app_name
```
Try again `flutterfire` configure command after that. | You must make sure that in your pubspec.yaml the following lines are on the start of dependencies place, ex:
```
dependencies:
flutter:
sdk: flutter
``` |
72,662,360 | So I'm super new to react. I have some code where I use fetch to get data from an API (that I created, structured like {'userData': {'overall': {'rank': '10', 'level': '99', 'xp': '200000000'}}}) and I display it on screen. It was working fine for hours and now all of a sudden without touching any code, it's broken. it will display the data just fine if i make an API request and then refresh the page. but then when I refresh the page again it tells me "Uncaught TypeError: Cannot read properties of undefined (reading 'overall')"
I don't know what I'm doing wrong and I'm wondering if someone can help me because I don't know how it became undefined, it was reading it just fine and then on refresh it changes to undefined. here's my code for the component
```
function Activities() {
let name = "three-dawg";
function fetchPlayerData(name){
fetch(URL)
.then(response => response.json())
.then(data => setPlayerData(data));
};
function refreshPage() {
window.location.reload(false)
}
const [playerData, setPlayerData] = useState([]);
useEffect(() => {fetchPlayerData(name)}, [name]);
return (
<div>
Hello {playerData._id}
<button onClick={() => {
fetchPlayerData(name)
refreshPage()
}}>load player</button>
<ul>
<li>{playerData.userData.overall.rank}</li>
</ul>
</div>
);
}
``` | 2022/06/17 | [
"https://Stackoverflow.com/questions/72662360",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16367560/"
] | You need to first redirect to your application path in `CLI`
```
cd app_name
```
Try again `flutterfire` configure command after that. | Make sure your pubspec.yaml file is well defined and correct.
In my case, I had erased after dependencies
```
flutter:
sdk: flutter
...
```
The correct format may be in flutter 3.3.0 [Flutter and the pubspec file](https://docs.flutter.dev/development/tools/pubspec)
```
name: myapp
version: 1.0.0+1
publish_to: none
description: A new Flutter project.
environment:
sdk: '>=2.18.0 <3.0.0'
dependencies:
cupertino_icons:
flutter:
sdk: flutter
dev_dependencies:
flutter_test:
sdk: flutter
flutter:
assets:
- assets/
uses-material-design: true
``` |
24,054,662 | Developing dictionary application for Android. There is a database in XML file. It is quite large(72MB) to parse with DOM parser. Trying to parse it with JDOM parser:
```
List<org.jdom2.Element> list = null;
try {
File db = new File(UnZip.DATABASE_PATH);
InputStream stream = new FileInputStream(db);
SAXBuilder builder = new SAXBuilder();
//HERE CODE IS GETTING STUCK
Document document = (Document) builder.build(stream);
org.jdom2.Element rootNode = document.getRootElement();
list = rootNode.getChildren(ENTRY_TAG);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JDOMException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (Element node : list) {
Log.d(LOG_TAG, node.getChildText(ENT_SEQ));
Log.d(LOG_TAG, node.getChildText(REB));
}
```
This code is giving OutOfMemory error:
>
> 06-05 12:45:58.788: E/AndroidRuntime(10068): FATAL EXCEPTION: main
> 06-05 12:45:58.788: E/AndroidRuntime(10068):
> java.lang.OutOfMemoryError: [memory exhausted] 06-05 12:45:58.788:
> E/AndroidRuntime(10068): at dalvik.system.NativeStart.main(Native
> Method)
>
>
>
I assume that code is getting stuck here:
```
Document document = (Document) builder.build(stream);
```
How to avoid this error and find needed entry from whole XML file(170000 entries)? | 2014/06/05 | [
"https://Stackoverflow.com/questions/24054662",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2752399/"
] | JDOM, like DOM, XOM, and all other in-memory-xml-model libraries will represent the entire XML document in memory. If you consider that most XML documents are singe-byte-encoded (UTF-8 or ASCII) and that is then converted to 2-byte chars in Java/Android, it is normal for in-memory XML representations to take about twice as much memory as the raw XML document.
Compared to others, JDOM is pretty respectful of memory usage (I am the maintainer, I am biased, but I have also tried really, really hard on the memory management side).
You could try using [the SlimJDOMFactory](http://jdom.org/docs/apidocs/org/jdom2/SlimJDOMFactory.html) as part of your document build, but that will not save you as much as you will need.
The same problem exists for all in-memory XML models, and (for different document sizes) on all platforms and system configurations.
The solutions are:
* find out [how much memory you re allowed](http://developer.android.com/training/articles/memory.html)
* don't have such big documents. A 72Meg document on Android seems .... redundant.
* to not parse the entire document at once, and to use streaming systems for parsing (SAX, etc)
* off-load the processing to a server app.
* others. | Use the [XmlPullParser](http://developer.android.com/reference/org/xmlpull/v1/XmlPullParser.html) class, as DarkDarker suggested. Use either the setInput() that takes a Reader or the one that takes an InputStream and an encoding name (probably "UTF-8"). Then you can just use the parser to move through the document one element at a time, building your list as you go.
All DOM approaches (including JDOM, dom4j, and others) are memory hogs since they build the entire document representation in memory. The actual memory usage is typically at least 4x the byte size of the document, between the overhead of strings (two bytes per character) and the overhead of objects for every component of the document. |
65,064,403 | I have been trying to have my Python scripts operational on my Synology server. So far, I managed to install necessary libraries such as requests, bs4 and cython. That works. But I am stuck with numpy and pandas, which return the following error output.
It is not pip-related (which is suggested in another question on Stackoverflow), as I already use the most recent version.
Can anyone help me out?
Edit: Python 3.8 installed
```
ERROR: Command errored out with exit status 1:
command: /var/packages/py3k/target/usr/local/bin/python3 /var/packages/py3k/target/usr/local/lib/python3.8/site-packages/pip install --ignore-installed --no-user --prefix /tmp/pip-build-env-cbb90c2z/overlay --no-warn-script
-location --no-binary :none: --only-binary :none: -i https://pypi.org/simple -- setuptools wheel 'Cython>=0.29.21,<3' 'numpy==1.15.4; python_version=='"'"'3.6'"'"' and platform_system!='"'"'AIX'"'"'' 'numpy==1.15.4; python_ver
sion=='"'"'3.7'"'"' and platform_system!='"'"'AIX'"'"'' 'numpy==1.17.3; python_version=='"'"'3.8'"'"' and platform_system!='"'"'AIX'"'"'' 'numpy==1.16.0; python_version=='"'"'3.6'"'"' and platform_system=='"'"'AIX'"'"'' 'numpy
==1.16.0; python_version=='"'"'3.7'"'"' and platform_system=='"'"'AIX'"'"'' 'numpy==1.17.3; python_version=='"'"'3.8'"'"' and platform_system=='"'"'AIX'"'"'' 'numpy; python_version>='"'"'3.9'"'"''
cwd: None
Complete output (87 lines):
Ignoring numpy: markers 'python_version == "3.6" and platform_system != "AIX"' don't match your environment
Ignoring numpy: markers 'python_version == "3.7" and platform_system != "AIX"' don't match your environment
Ignoring numpy: markers 'python_version == "3.6" and platform_system == "AIX"' don't match your environment
Ignoring numpy: markers 'python_version == "3.7" and platform_system == "AIX"' don't match your environment
Ignoring numpy: markers 'python_version == "3.8" and platform_system == "AIX"' don't match your environment
Ignoring numpy: markers 'python_version >= "3.9"' don't match your environment
Collecting setuptools
Using cached setuptools-50.3.2-py3-none-any.whl (785 kB)
Collecting wheel
Using cached wheel-0.35.1-py2.py3-none-any.whl (33 kB)
Collecting Cython<3,>=0.29.21
Using cached Cython-0.29.21-py2.py3-none-any.whl (974 kB)
Collecting numpy==1.17.3
Using cached numpy-1.17.3.zip (6.4 MB)
Building wheels for collected packages: numpy
Building wheel for numpy (setup.py): started
Building wheel for numpy (setup.py): finished with status 'error'
ERROR: Command errored out with exit status 1:
command: /var/packages/py3k/target/usr/local/bin/python3 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-ltbznc4c/numpy/setup.py'"'"'; __file__='"'"'/tmp/pip-install-ltbznc4c/numpy/setup.py'"'
"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-caq_alpn
cwd: /tmp/pip-install-ltbznc4c/numpy/
Complete output (14 lines):
Running from numpy source directory.
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/tmp/pip-install-ltbznc4c/numpy/setup.py", line 443, in <module>
setup_package()
File "/tmp/pip-install-ltbznc4c/numpy/setup.py", line 422, in setup_package
from numpy.distutils.core import setup
File "/tmp/pip-install-ltbznc4c/numpy/numpy/distutils/core.py", line 26, in <module>
from numpy.distutils.command import config, config_compiler, \
File "/tmp/pip-install-ltbznc4c/numpy/numpy/distutils/command/config.py", line 20, in <module>
from numpy.distutils.mingw32ccompiler import generate_manifest
File "/tmp/pip-install-ltbznc4c/numpy/numpy/distutils/mingw32ccompiler.py", line 31, in <module>
import distutils.cygwinccompiler
ModuleNotFoundError: No module named 'distutils.cygwinccompiler'
----------------------------------------
ERROR: Failed building wheel for numpy
Running setup.py clean for numpy
ERROR: Command errored out with exit status 1:
command: /var/packages/py3k/target/usr/local/bin/python3 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-ltbznc4c/numpy/setup.py'"'"'; __file__='"'"'/tmp/pip-install-ltbznc4c/numpy/setup.py'"'
"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' clean --all
cwd: /tmp/pip-install-ltbznc4c/numpy
Complete output (10 lines):
Running from numpy source directory.
`setup.py clean` is not supported, use one of the following instead:
- `git clean -xdf` (cleans all files)
- `git clean -Xdf` (cleans all versioned files, doesn't touch
files that aren't checked into the git repo)
Add `--force` to your command to use it anyway if you must (unsupported).
----------------------------------------
ERROR: Failed cleaning build dir for numpy
Failed to build numpy
Installing collected packages: setuptools, wheel, Cython, numpy
Running setup.py install for numpy: started
Running setup.py install for numpy: finished with status 'error'
ERROR: Command errored out with exit status 1:
command: /var/packages/py3k/target/usr/local/bin/python3 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-ltbznc4c/numpy/setup.py'"'"'; __file__='"'"'/tmp/pip-install-ltbznc4c/numpy/setup.py'
"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /tmp/pip-record-l0tp9bsn/install-record.txt
--single-version-externally-managed --prefix /tmp/pip-build-env-cbb90c2z/overlay --compile --install-headers /tmp/pip-build-env-cbb90c2z/overlay/include/python3.8/numpy
cwd: /tmp/pip-install-ltbznc4c/numpy/
Complete output (23 lines):
Running from numpy source directory.
Note: if you need reliable uninstall behavior, then install
with pip instead of using `setup.py install`:
- `pip install .` (from a git repo or downloaded source
release)
- `pip install numpy` (last NumPy release on PyPi)
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/tmp/pip-install-ltbznc4c/numpy/setup.py", line 443, in <module>
setup_package()
File "/tmp/pip-install-ltbznc4c/numpy/setup.py", line 422, in setup_package
from numpy.distutils.core import setup
File "/tmp/pip-install-ltbznc4c/numpy/numpy/distutils/core.py", line 26, in <module>
from numpy.distutils.command import config, config_compiler, \
File "/tmp/pip-install-ltbznc4c/numpy/numpy/distutils/command/config.py", line 20, in <module>
from numpy.distutils.mingw32ccompiler import generate_manifest
File "/tmp/pip-install-ltbznc4c/numpy/numpy/distutils/mingw32ccompiler.py", line 31, in <module>
import distutils.cygwinccompiler
ModuleNotFoundError: No module named 'distutils.cygwinccompiler'
----------------------------------------
ERROR: Command errored out with exit status 1: /var/packages/py3k/target/usr/local/bin/python3 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-ltbznc4c/numpy/setup.py'"'"'; __file__='"'"'/tmp/pip
-install-ltbznc4c/numpy/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /tmp/pip-r
ecord-l0tp9bsn/install-record.txt --single-version-externally-managed --prefix /tmp/pip-build-env-cbb90c2z/overlay --compile --install-headers /tmp/pip-build-env-cbb90c2z/overlay/include/python3.8/numpy Check the logs for full
command output.
----------------------------------------
ERROR: Command errored out with exit status 1: /var/packages/py3k/target/usr/local/bin/python3 /var/packages/py3k/target/usr/local/lib/python3.8/site-packages/pip install --ignore-installed --no-user --prefix /tmp/pip-build-en
v-cbb90c2z/overlay --no-warn-script-location --no-binary :none: --only-binary :none: -i https://pypi.org/simple -- setuptools wheel 'Cython>=0.29.21,<3' 'numpy==1.15.4; python_version=='"'"'3.6'"'"' and platform_system!='"'"'A
IX'"'"'' 'numpy==1.15.4; python_version=='"'"'3.7'"'"' and platform_system!='"'"'AIX'"'"'' 'numpy==1.17.3; python_version=='"'"'3.8'"'"' and platform_system!='"'"'AIX'"'"'' 'numpy==1.16.0; python_version=='"'"'3.6'"'"' and pla
tform_system=='"'"'AIX'"'"'' 'numpy==1.16.0; python_version=='"'"'3.7'"'"' and platform_system=='"'"'AIX'"'"'' 'numpy==1.17.3; python_version=='"'"'3.8'"'"' and platform_system=='"'"'AIX'"'"'' 'numpy; python_version>='"'"'3.9'
"'"'' Check the logs for full command output.
``` | 2020/11/29 | [
"https://Stackoverflow.com/questions/65064403",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14133202/"
] | I assume the logic you want is more like this:
```c
if((strcmp(usernameServer, username) == 0) && (strcmp(passwordServer, password) == 0))
```
So testing if user AND password are both equal to the value you compare them to. | Comparing strings with `strcmp()`:
>
> This function starts comparing the first character of each string. If they are equal to each other, it continues with the following pairs until the characters differ or until a terminating null-character is reached.
>
>
>
Returns:
* <0 the first character that does not match has a lower value in ptr1 than in ptr2
* 0 the contents of both strings are equal
* >0 the first character that does not match has a greater value in ptr1 than in ptr2
---
So in order to see if the strings match you would check if the return value is 0:
```
if(strcmp(usernameServer, username) == 0 && strcmp(passwordServer, password) == 0)
```
[cpp reference - strcmp](http://www.cplusplus.com/reference/cstring/strcmp/) |
71,637,734 | I was trying to solve a variance problem, but after the for loop **I can't the sum** values to finally dived by the numbers of items in the list.
```
lista = [1.86, 1.97, 2.05, 1.91, 1.80, 1.78]
n = len(lista) #NUMBERS OF DATA IN THE LIST
MA = sum(lista)/n #ARITHMETIC MEAN
for x in lista:
y = pow(x - MA, 2) #SUBTRACTION OF ALL DATA BY THE MA, RAISED TO THE POWER OF 2
print(y)
print(sum(y)/n) # AND THAT IS IT, I CAN'T FINISH
```
I‘m trying to do this work for days and I didn't discovery yet. Is it possible to finish or should I just quit it because there are better ways to solve it?
The result of the variance must be: 0.008891666666666652
PS: I don't want to have to install other programs or libs like pandas or numpy | 2022/03/27 | [
"https://Stackoverflow.com/questions/71637734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18594968/"
] | You are just updating the value of y each time you run the loop so y will be a single element after it reached end of loop.
What you are printing is :
```
sum(pow(1.78 - MA, 2)/2)
```
So either you store each value of y inside function in a array of simply do a thing
```
y=0
y = pow(x-ma, 2)
y += y
``` | I did it again and found the result, thanks Deepak Singh for your help, the asnwer is:
```
lista = [1.86, 1.97, 2.05, 1.91, 1.80, 1.78]
n = len(lista)
MA = sum(lista)/n
y = 0
for x in lista:
subts = pow(x - MA, 2)
y = (y + subts)
print("Varience:", y/n)
``` |
38,750,651 | This is my `CustomObdRowAdapter.java`
I added a "Select All" row at the top, when the user chooses it, all items in current listView should be checked, but how should I implement it in my customized row adapter?
```
private class ViewHolder{
CheckBox name;
}
@Override
public View getView(final int position, View convertView, final ViewGroup parent) {
ViewHolder holder = null;
LayoutInflater settingInflater = LayoutInflater.from(getContext());
if (convertView == null) {
convertView = settingInflater.inflate(R.layout.custom_row, parent, false);
holder = new ViewHolder();
holder.name = (CheckBox) convertView.findViewById(R.id.checkBox1);
convertView.setTag(holder);
}else{
holder = (ViewHolder)convertView.getTag();
}
holder.name.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
RowCheckbox rowCommandCheckbox = (RowCheckbox) cb.getTag();
if (cb.getText() == ifAllSelectStr){
if (cb.isChecked()){
// Select all items in this listView
}else{
// Unselect all items in this listView
}
}
``` | 2016/08/03 | [
"https://Stackoverflow.com/questions/38750651",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6094757/"
] | ```
// select all
for (int i = 0; i < adapter.getCount(); i++) {
list.setItemChecked(i, true);
}
// unselect all
for (int i = 0; i < adapter.getCount(); i++) {
list.setItemChecked(i, false);
}
```
you may need to call this from outside the adapter
```
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
``` | ```
boolean isAllTrue=false;
@Override
public View getView(final int position, View convertView, final ViewGroup parent) {
ViewHolder holder = null;
LayoutInflater settingInflater = LayoutInflater.from(getContext());
if (convertView == null) {
convertView = settingInflater.inflate(R.layout.custom_row, parent, false);
holder = new ViewHolder();
holder.name = (CheckBox) convertView.findViewById(R.id.checkBox1);
}
else{
holder = (ViewHolder)convertView.getTag();
}
holder.name.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
RowCheckbox rowCommandCheckbox = (RowCheckbox) cb.getTag();
if (cb.getText() == ifAllSelectStr){
if (cb.isChecked()){
isAllTrue=true;
// Select all items in this listView
}else{
isAllTrue=false;
// Unselect all items in this listView
}
notifyDataSetChanged();
}
}
```
convertView.setTag(holder);//always put this setting tag outside of if else //of tag
holder.name.setChecked(isAllTrue);
}//end of getView Function
In above code their are two things first is to change setting tag of viewholder to view and place it at the end of function before returning convertView and second create boolean for allTrue checked and when all item selected click listner call then notify adopter to redraw. |
66,010,937 | I'm getting different `sysdate` results depending on the node. But how to figure out which are the problematic nodes? | 2021/02/02 | [
"https://Stackoverflow.com/questions/66010937",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15124130/"
] | Assuming you are able to connect via sqlplus or another tool and assuming you are using TNS names.....
If the assumptions above are correct your TNS names will look somthing like the below
```
(DESCRIPTION=
(ADDRESS_LIST=
(ADDRESS=(PROTOCOL=tcp)(HOST=sales1-server)(PORT=1521))
(ADDRESS=(PROTOCOL=tcp)(HOST=sales2-server)(PORT=1521)))
(CONNECT_DATA=(SERVICE_NAME=sales.us.example.com)))
```
You can then simply remove all nodes except 1 (backing up file first of course) then connect to via SQLPULS or your tool of choice and do..
```
select sysdate from dual;
```
Rinse and repeat for each of the nodes in the TNSNames original file, until you find which are the problematic nodes, although I am unsure of any reason that different nodes would give a different sysdate. | This query tells you which node your session is using:
```
select * from v$instance;
```
You can use the undocumented `GV$` table function to run a query against all RAC instances to find out which ones have a bad clock. The function is a bit tricky because the cursor gets parsed on your instance but executed on all the instances. It's not always clear exactly where the code is running, and you may have to create a PL/SQL function to ensure that the code is truly executing on the remote instance.
```
create or replace function get_sysdate return date is
begin
return sysdate;
end;
/
select * from
table(gv$(cursor(
select instance_name, get_sysdate from v$instance
)));
```
Unfortunately I am not able to fully test the above code since I don't have access to change the time on any RAC clusters. But I've used similar code in the past. |
43,365,549 | Currently, I have URL like
>
> **/recipes-detail/?recipe=(Slug of recipe)**
>
>
>
How Can I change this to
>
> **/recipes-detail/(Slug of recipe)**
>
>
>
Currently, I am fetching the recipe custom plugin. | 2017/04/12 | [
"https://Stackoverflow.com/questions/43365549",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7562694/"
] | Change Permalink Settings to Post name | You can add to the .htaccess file a rewrite mode
```
RewriteRule ^recipes-detail/[a-z0-9]+(?:-[a-z0-9]+)*$/ ./recipes-detail/?recipe=$1
```
Now if you use this address yourwebsite.com/recipes-detail/cake-of-chocolate will work exactly as you will be doing yourwebsite.com/recipes-detail/?recipe=cake-of-chocolate
So you can now build your urls with the friendly option. |
33,126,644 | I am running a Java test program to establish a connection to OrientDB and keep getting these exceptions when I run the code from within IntelliJ IDEA or OpenFire (xmpp server):
>
> java.lang.NoSuchMethodError:
> com.googlecode.concurrentlinkedhashmap.ConcurrentLinkedHashMap$Builder.maximumWeightedCapacity(J)Lcom/googlecode/concurrentlinkedhashmap/ConcurrentLinkedHashMap$Builder;
> at
> com.orientechnologies.orient.core.db.record.ridbag.sbtree.OSBTreeCollectionManagerAbstract.(OSBTreeCollectionManagerAbstract.java:43)
> at
> com.orientechnologies.orient.core.db.record.ridbag.sbtree.OSBTreeCollectionManagerAbstract.(OSBTreeCollectionManagerAbstract.java:48)
> at
> com.orientechnologies.orient.client.remote.OSBTreeCollectionManagerRemote.(OSBTreeCollectionManagerRemote.java:58)
> at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native
> Method) at
> sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
> at
> sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
> at java.lang.reflect.Constructor.newInstance(Constructor.java:526) at
> java.lang.Class.newInstance(Class.java:379) at
> com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx$2.call(ODatabaseDocumentTx.java:2863)
> at
> com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx$2.call(ODatabaseDocumentTx.java:2854)
> at
> com.orientechnologies.common.concur.resource.OSharedContainerImpl.getResource(OSharedContainerImpl.java:64)
> at
> com.orientechnologies.orient.core.storage.OStorageAbstract.getResource(OStorageAbstract.java:143)
> at
> com.orientechnologies.orient.client.remote.OStorageRemoteThread.getResource(OStorageRemoteThread.java:658)
> at
> com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx.initAtFirstOpen(ODatabaseDocumentTx.java:2853)
> at
> com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx.open(ODatabaseDocumentTx.java:260)
> at
> com.orientechnologies.orient.jdbc.OrientJdbcConnection.(OrientJdbcConnection.java:63)
> at
> com.orientechnologies.orient.jdbc.OrientJdbcDriver.connect(OrientJdbcDriver.java:52)
> at java.sql.DriverManager.getConnection(DriverManager.java:571) at
> java.sql.DriverManager.getConnection(DriverManager.java:187) at
> com.momentum.orientdb.core.JdbcConnectionManager.getConnection(JdbcConnectionManager.java:87)
> at
> com.momentum.orientdb.core.JdbcConnectionManager.getConnection(JdbcConnectionManager.java:56)
> at
> com.momentum.orientdb.core.JdbcConnectionManager$getConnection.call(Unknown
> Source) at
> org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:42)
> at
> org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:108)
> at
> org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:112)
> at
> com.momentum.orientdb.core.test.JdbcConnectionManagerTest.testGetConnection(JdbcConnectionManagerTest.groovy:26)
> at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
> sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
> at
> sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
> at
> org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:84)
> at org.junit.runner.JUnitCore.run(JUnitCore.java:160) at
> com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:78)
> at
> com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:212)
> at
> com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:68)
> at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
> sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
> at
> com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
>
>
>
**Any idea why? How can I fix it?**
**UPDATE 1**
It seems to me that it has to do with this library (from Google): **concurrentlinkedhashmap-lru-1.4.1.jar**.
But I searched the development computer's file system and found only the above mentioned version (1.4.1).
**UPDATE 2 - Solution**
After searching thoroughly I found that I had different version of **concurrentlinkedhashmap-lru-xxxx.jar** on my development machine's file system and somehow I "managed" to put two different versions in the build.
Meanwhile, I still get the same exceptions when using my library (which I've already tested) in order to establish a connection to OrientDb from within OpenFire since OpenFire uses another version of concurrentlinkedhashmap then the one being used by OrientDb (concurrentlinkedhashmap-lru-1.4.1.jar). | 2015/10/14 | [
"https://Stackoverflow.com/questions/33126644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1837865/"
] | `NoSuchMethodError` happens because at runtime, Java tried to call a method on an object, and found it didn't exist, in particular:
```
com.googlecode.concurrentlinkedhashmap.ConcurrentLinkedHashMap$Builder.maximumWeightedCapacity(J)Lcom/googlecode/concurrentlinkedhashmap/ConcurrentLinkedHashMap$Builder;
```
Of course, you'd expect the code wouldn't compile if that was the case, so this almost always means you've built against a different version of the class than the one provided at runtime - it's usually a versioning issue.
So, you should figure out which library you're getting `ConcurrentLinkedHashMap` from, and compare this with the version being used at runtime (how are you deploying this? Is it running straight from IntelliJ?). You're likely to find that they have different versions, and you'll need to alter your version to match. | Please go to the below link and download the JAR file,
<http://mvnrepository.com/artifact/com.googlecode.concurrentlinkedhashmap/concurrentlinkedhashmap-lru/1.4.2>
The problem is with the version which you are trying, the correct version is 1.4.2. |
6,679,625 | I'm working with a bunch of Python programmers who use vim and they make Python using TABs for indent. I use Emacs with python-mode which translates the tab key to 4 spaces (like it should, but never mind). Since I don't want to cause trouble I want to add something to my .emacs file (or whatever) to make indents using real TABS instead of translating them to spaces. How?
I'm sorry if this is answered somewhere else: I didn't find it. | 2011/07/13 | [
"https://Stackoverflow.com/questions/6679625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/100981/"
] | You can define Python-specific settings in your `~/.emacs` with `python-mode-hook`. In order to use tabs for indentation, you could use:
```
(add-hook 'python-mode-hook
(lambda () (setq indent-tabs-mode t)))
```
Since `python.el` indents only 4 columns, by default, the above will use tabs when the indent is a multiple of 8 and tabs followed by spaces for other indents.
If you need to use a single tab for every indent level, you'll also need to set `python-indent` to 8. Then you can set `tab-width` to whatever width you want to see the tabs displayed as.
```
(add-hook 'python-mode-hook
(lambda ()
(setq indent-tabs-mode t)
(setq python-indent 8)
(setq tab-width 4)))
``` | probably need to do this in python mode:
```
(setq indent-tabs-mode t)
``` |
6,679,625 | I'm working with a bunch of Python programmers who use vim and they make Python using TABs for indent. I use Emacs with python-mode which translates the tab key to 4 spaces (like it should, but never mind). Since I don't want to cause trouble I want to add something to my .emacs file (or whatever) to make indents using real TABS instead of translating them to spaces. How?
I'm sorry if this is answered somewhere else: I didn't find it. | 2011/07/13 | [
"https://Stackoverflow.com/questions/6679625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/100981/"
] | probably need to do this in python mode:
```
(setq indent-tabs-mode t)
``` | As the commenters to the post correctly said, using tabs for indentation is a bad idea, and using a non-standard tab width is even worse. Nonetheless, sometimes you have no choice if you want to collaborate.
Depending on exactly how your colleagues have vim configured, you may need to *both* turn on `indent-tabs-mode` and set `tab-width` to 4.
A convenient way to do this, that won't mess up your other work, is to use [file local variables](http://www.gnu.org/software/libtool/manual/emacs/Specifying-File-Variables.html#Specifying-File-Variables). At the end of each offending file, put this:
```
# Local Variables:
# indent-tabs-mode: 1
# tab-width: 4
# End:
```
(You'll have to tell Emacs that `indent-tabs-mode` is a safe local variable.) |
6,679,625 | I'm working with a bunch of Python programmers who use vim and they make Python using TABs for indent. I use Emacs with python-mode which translates the tab key to 4 spaces (like it should, but never mind). Since I don't want to cause trouble I want to add something to my .emacs file (or whatever) to make indents using real TABS instead of translating them to spaces. How?
I'm sorry if this is answered somewhere else: I didn't find it. | 2011/07/13 | [
"https://Stackoverflow.com/questions/6679625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/100981/"
] | You can define Python-specific settings in your `~/.emacs` with `python-mode-hook`. In order to use tabs for indentation, you could use:
```
(add-hook 'python-mode-hook
(lambda () (setq indent-tabs-mode t)))
```
Since `python.el` indents only 4 columns, by default, the above will use tabs when the indent is a multiple of 8 and tabs followed by spaces for other indents.
If you need to use a single tab for every indent level, you'll also need to set `python-indent` to 8. Then you can set `tab-width` to whatever width you want to see the tabs displayed as.
```
(add-hook 'python-mode-hook
(lambda ()
(setq indent-tabs-mode t)
(setq python-indent 8)
(setq tab-width 4)))
``` | As the commenters to the post correctly said, using tabs for indentation is a bad idea, and using a non-standard tab width is even worse. Nonetheless, sometimes you have no choice if you want to collaborate.
Depending on exactly how your colleagues have vim configured, you may need to *both* turn on `indent-tabs-mode` and set `tab-width` to 4.
A convenient way to do this, that won't mess up your other work, is to use [file local variables](http://www.gnu.org/software/libtool/manual/emacs/Specifying-File-Variables.html#Specifying-File-Variables). At the end of each offending file, put this:
```
# Local Variables:
# indent-tabs-mode: 1
# tab-width: 4
# End:
```
(You'll have to tell Emacs that `indent-tabs-mode` is a safe local variable.) |
167,600 | I recall this old sci fi movie where a android is looking for its' "father", it will self destruct if not found in 7 days. The father knows how to defuse the H-bomb in it. Then it goes on to save humanity | 2017/08/20 | [
"https://scifi.stackexchange.com/questions/167600",
"https://scifi.stackexchange.com",
"https://scifi.stackexchange.com/users/76426/"
] | Probable duplicate of this question; [Film about alien/android that molds facial features](https://scifi.stackexchange.com/questions/116042/film-about-alien-android-that-molds-facial-features/116050#116050).
The Questor Tapes, created by Gene Rodenberry. Robert Foxworth stars as the android, who needs to find his father/creator, who can defuse his nuclear generator before it overloads and explodes.He becomes the current guardian of humanity
[](https://i.stack.imgur.com/SPjYh.jpg) | On the off chance you're confused about details (or someone else is looking for a film about an android looking for their creator while they have a bomb in them), I'm going to propose *[Eve of Destruction](https://en.wikipedia.org/wiki/Eve_of_Destruction_(film))*, a 1991 film about a gynoid named EVE VIII designed for military operations and looking identical to her creator, Dr. Eve Simmons. EVE is damaged during a bank robbery, which triggers embedded memories from her creator, and a desire to seek out Dr. Simmons's father, who was abusive to her as a child. EVE indeed does have a nuclear bomb in her, which must be disarmed, triggered to go off within 24 hours after she gets into a car crash.
Areas where it doesn't match up are a later time frame, possibly a different gender for the android, and that the father and creator are different people. Also, EVE doesn't go to save humanity, but defeating her does save a significant part of the population around her.
Trailer
------- |
45,816 | What does the expression/idiom "feather your nest" mean?
I see a lot of references to it but I can't seem to figure out its meaning. | 2011/10/21 | [
"https://english.stackexchange.com/questions/45816",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/4479/"
] | I found this from googling, so its validity may be questionable, but it came up fairly often.
It seems that both underdog and top dog originated from dog fighting which went on in the 19th century. The losing dog ended up on the bottom, or **under** the winner, who was on **top**.
My reference is [The Times of India](http://articles.timesofindia.indiatimes.com/2004-07-17/open-space/27159778_1_origin-word-top-dog). | *Underdog*
----------
The "under dog" was the dog who lost a fight (as opposed to the winning "top dog"), and *underdog* has become idiomatic for the inferior person or party, or the one fighting a larger adversary.
The OED says it originates in the US and their earliest citation is the British *Daily Telegraph* of 1887:
>
> There is an indefinable expression in his face and figure of having been vanquished, of having succumbed, of having been ‘under-dog’ as the saying is.
>
>
>
I found an earlier citation from *[The Popular Science Monthly](http://books.google.fi/books?id=FSIDAAAAMBAJ&pg=PA761&lpg=PA761&dq=underdog%20OR%20%22under%20dog%22%20OR%20%22under-dog%22&source=bl&ots=agYnTeviMi&sig=dbB0BJWYAUT0MXLJuWoLok0luJk&hl=en&sa=X&ei=YtI_UOH-MIjh4QSPxYDoAg&redir_esc=y#v=onepage&q=%22under%20dog%22&f=false)* of April 1882, in an article called "Has Science Yet Found a New Basis for Morality?" by Professor Goldwin Smith and quoting Dr. Van Buren Denslow:
>
> But, if the **under dog** in the social fight runs away with a bone in violation of superior force, the top dog runs after him bellowing, "Thou shalt not steal," and all the other **top dogs** unite in bellowing, "This is divine law, and not dog law"; the verdict of the **top dog**, so far as law, religion, and other forms of brute force are concerned, settles the question.
>
>
>
And on the next page, Smith summarises:
>
> It appears that between one state and the other there may be an interval in which the question will be not between the moral and the immoral, but between the **top and the under dog**.
>
>
>
---
*Top dog*
---------
The "top dog" was similarly the dog that won the fight, and now figuratively refers to a winner or the best person, party or thing.
The earliest OED citation is from a 1900 edition of *The Speaker: A Review of Politics*:
>
> The most popular argument in favour of the war is that it will make the individual Briton top dog in South Africa.
>
>
>
Again, the above *Popular Science Monthly* antedates this, as does another I found in [*The Spy of the Rebellion*](http://books.google.fi/books?id=3VLkkzpB_J4C&pg=PA305&lpg=PA305&dq=%22top%20dog%22&source=bl&ots=x7hAqJDTcl&sig=SVJAG221a7RsnsslB8VxF0QWJUY&hl=en&sa=X&ei=x9c_UJOeJeip4gTMyICwBQ&redir_esc=y#v=onepage&q=%22top%20dog%22%20&f=false) (1883) by Allan Pinkerton:
>
> "Fo' de Lawd, gemmen, I'se hopin an' prayin' de No'thun folks will be de **top dog** in dis wrastle, an' ef eber dis niggah hes a chance to gib yu'uns a a helpin' han', yu' kin bet a hoss agin' a coon-skin he'll do it; but I hope an' trus my missus not be boddered."
>
>
>
---
Variation: *upper dog*
----------------------
The OED's first citation for the rare variation *upper dog* is from 1903 by G. Bowles in Hansard's *Parliamentary Debates*:
>
> If it came to a question of force, we should always be the ‘upper dog’ in Persia.
>
>
>
I found an earlier example in the April 1881 [*Popular Science Monthly*](http://books.google.fi/books?id=DCIDAAAAMBAJ&pg=PA775&lpg=PA775&dq=%22upper%20dog%22&source=bl&ots=CLdLWrrtUK&sig=DDoj3qZqFRET2bs6sWInqNrqCks&hl=en&sa=X&ei=wNk_UKyiDo-K4gTM94DgDw&redir_esc=y#v=onepage&q=%22upper%20dog%22&f=false) in "Some Notes on a Doctor's Liability" by Oliver E. Lyman:
>
> Quackery was again the **upper dog**. But the struggle was not over. Although on top, the other dog had a vicious grip upon him. The empiric was still unable to recover compensation from delinquent patients.
>
>
> |
45,816 | What does the expression/idiom "feather your nest" mean?
I see a lot of references to it but I can't seem to figure out its meaning. | 2011/10/21 | [
"https://english.stackexchange.com/questions/45816",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/4479/"
] | I found this from googling, so its validity may be questionable, but it came up fairly often.
It seems that both underdog and top dog originated from dog fighting which went on in the 19th century. The losing dog ended up on the bottom, or **under** the winner, who was on **top**.
My reference is [The Times of India](http://articles.timesofindia.indiatimes.com/2004-07-17/open-space/27159778_1_origin-word-top-dog). | The terms from my search, seem to come from the blood-sport of bear baiting in 16th Century England. The underdog would go for the bears middle section, most likely losing meanwhile the top-dog would go for the bear's jugular and be less at risk of being killed if the unconscious bear awoke and began reacting to the dogs.
Book:[1](http://books.google.com/books?id=secyAwAAQBAJ&pg=PA38&lpg=PA38&dq=underdog+bear+baiting&source=bl&ots=-WrZeQke9U&sig=VQNQ4JKJJL6vZZq7FcxzorLo_Cw&hl=en&sa=X&ei=O15pU7K-A6G_8QG-mYGgBQ&ved=0CE4Q6AEwAw#v=onepage&q=underdog%20bear%20baiting&f=false)
Website:[2](http://www.madrigal.com.au/2013/08/26/supporting-the-underdog-explanation/) |
45,816 | What does the expression/idiom "feather your nest" mean?
I see a lot of references to it but I can't seem to figure out its meaning. | 2011/10/21 | [
"https://english.stackexchange.com/questions/45816",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/4479/"
] | I found this from googling, so its validity may be questionable, but it came up fairly often.
It seems that both underdog and top dog originated from dog fighting which went on in the 19th century. The losing dog ended up on the bottom, or **under** the winner, who was on **top**.
My reference is [The Times of India](http://articles.timesofindia.indiatimes.com/2004-07-17/open-space/27159778_1_origin-word-top-dog). | Does it come from pioneer days of sawing trees by hand? Top dog was the one on top, and clean, underdog was the one in the pit below the felled tree sawing away getting covered in sawdust. |
45,816 | What does the expression/idiom "feather your nest" mean?
I see a lot of references to it but I can't seem to figure out its meaning. | 2011/10/21 | [
"https://english.stackexchange.com/questions/45816",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/4479/"
] | *Underdog*
----------
The "under dog" was the dog who lost a fight (as opposed to the winning "top dog"), and *underdog* has become idiomatic for the inferior person or party, or the one fighting a larger adversary.
The OED says it originates in the US and their earliest citation is the British *Daily Telegraph* of 1887:
>
> There is an indefinable expression in his face and figure of having been vanquished, of having succumbed, of having been ‘under-dog’ as the saying is.
>
>
>
I found an earlier citation from *[The Popular Science Monthly](http://books.google.fi/books?id=FSIDAAAAMBAJ&pg=PA761&lpg=PA761&dq=underdog%20OR%20%22under%20dog%22%20OR%20%22under-dog%22&source=bl&ots=agYnTeviMi&sig=dbB0BJWYAUT0MXLJuWoLok0luJk&hl=en&sa=X&ei=YtI_UOH-MIjh4QSPxYDoAg&redir_esc=y#v=onepage&q=%22under%20dog%22&f=false)* of April 1882, in an article called "Has Science Yet Found a New Basis for Morality?" by Professor Goldwin Smith and quoting Dr. Van Buren Denslow:
>
> But, if the **under dog** in the social fight runs away with a bone in violation of superior force, the top dog runs after him bellowing, "Thou shalt not steal," and all the other **top dogs** unite in bellowing, "This is divine law, and not dog law"; the verdict of the **top dog**, so far as law, religion, and other forms of brute force are concerned, settles the question.
>
>
>
And on the next page, Smith summarises:
>
> It appears that between one state and the other there may be an interval in which the question will be not between the moral and the immoral, but between the **top and the under dog**.
>
>
>
---
*Top dog*
---------
The "top dog" was similarly the dog that won the fight, and now figuratively refers to a winner or the best person, party or thing.
The earliest OED citation is from a 1900 edition of *The Speaker: A Review of Politics*:
>
> The most popular argument in favour of the war is that it will make the individual Briton top dog in South Africa.
>
>
>
Again, the above *Popular Science Monthly* antedates this, as does another I found in [*The Spy of the Rebellion*](http://books.google.fi/books?id=3VLkkzpB_J4C&pg=PA305&lpg=PA305&dq=%22top%20dog%22&source=bl&ots=x7hAqJDTcl&sig=SVJAG221a7RsnsslB8VxF0QWJUY&hl=en&sa=X&ei=x9c_UJOeJeip4gTMyICwBQ&redir_esc=y#v=onepage&q=%22top%20dog%22%20&f=false) (1883) by Allan Pinkerton:
>
> "Fo' de Lawd, gemmen, I'se hopin an' prayin' de No'thun folks will be de **top dog** in dis wrastle, an' ef eber dis niggah hes a chance to gib yu'uns a a helpin' han', yu' kin bet a hoss agin' a coon-skin he'll do it; but I hope an' trus my missus not be boddered."
>
>
>
---
Variation: *upper dog*
----------------------
The OED's first citation for the rare variation *upper dog* is from 1903 by G. Bowles in Hansard's *Parliamentary Debates*:
>
> If it came to a question of force, we should always be the ‘upper dog’ in Persia.
>
>
>
I found an earlier example in the April 1881 [*Popular Science Monthly*](http://books.google.fi/books?id=DCIDAAAAMBAJ&pg=PA775&lpg=PA775&dq=%22upper%20dog%22&source=bl&ots=CLdLWrrtUK&sig=DDoj3qZqFRET2bs6sWInqNrqCks&hl=en&sa=X&ei=wNk_UKyiDo-K4gTM94DgDw&redir_esc=y#v=onepage&q=%22upper%20dog%22&f=false) in "Some Notes on a Doctor's Liability" by Oliver E. Lyman:
>
> Quackery was again the **upper dog**. But the struggle was not over. Although on top, the other dog had a vicious grip upon him. The empiric was still unable to recover compensation from delinquent patients.
>
>
> | The terms from my search, seem to come from the blood-sport of bear baiting in 16th Century England. The underdog would go for the bears middle section, most likely losing meanwhile the top-dog would go for the bear's jugular and be less at risk of being killed if the unconscious bear awoke and began reacting to the dogs.
Book:[1](http://books.google.com/books?id=secyAwAAQBAJ&pg=PA38&lpg=PA38&dq=underdog+bear+baiting&source=bl&ots=-WrZeQke9U&sig=VQNQ4JKJJL6vZZq7FcxzorLo_Cw&hl=en&sa=X&ei=O15pU7K-A6G_8QG-mYGgBQ&ved=0CE4Q6AEwAw#v=onepage&q=underdog%20bear%20baiting&f=false)
Website:[2](http://www.madrigal.com.au/2013/08/26/supporting-the-underdog-explanation/) |
45,816 | What does the expression/idiom "feather your nest" mean?
I see a lot of references to it but I can't seem to figure out its meaning. | 2011/10/21 | [
"https://english.stackexchange.com/questions/45816",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/4479/"
] | *Underdog*
----------
The "under dog" was the dog who lost a fight (as opposed to the winning "top dog"), and *underdog* has become idiomatic for the inferior person or party, or the one fighting a larger adversary.
The OED says it originates in the US and their earliest citation is the British *Daily Telegraph* of 1887:
>
> There is an indefinable expression in his face and figure of having been vanquished, of having succumbed, of having been ‘under-dog’ as the saying is.
>
>
>
I found an earlier citation from *[The Popular Science Monthly](http://books.google.fi/books?id=FSIDAAAAMBAJ&pg=PA761&lpg=PA761&dq=underdog%20OR%20%22under%20dog%22%20OR%20%22under-dog%22&source=bl&ots=agYnTeviMi&sig=dbB0BJWYAUT0MXLJuWoLok0luJk&hl=en&sa=X&ei=YtI_UOH-MIjh4QSPxYDoAg&redir_esc=y#v=onepage&q=%22under%20dog%22&f=false)* of April 1882, in an article called "Has Science Yet Found a New Basis for Morality?" by Professor Goldwin Smith and quoting Dr. Van Buren Denslow:
>
> But, if the **under dog** in the social fight runs away with a bone in violation of superior force, the top dog runs after him bellowing, "Thou shalt not steal," and all the other **top dogs** unite in bellowing, "This is divine law, and not dog law"; the verdict of the **top dog**, so far as law, religion, and other forms of brute force are concerned, settles the question.
>
>
>
And on the next page, Smith summarises:
>
> It appears that between one state and the other there may be an interval in which the question will be not between the moral and the immoral, but between the **top and the under dog**.
>
>
>
---
*Top dog*
---------
The "top dog" was similarly the dog that won the fight, and now figuratively refers to a winner or the best person, party or thing.
The earliest OED citation is from a 1900 edition of *The Speaker: A Review of Politics*:
>
> The most popular argument in favour of the war is that it will make the individual Briton top dog in South Africa.
>
>
>
Again, the above *Popular Science Monthly* antedates this, as does another I found in [*The Spy of the Rebellion*](http://books.google.fi/books?id=3VLkkzpB_J4C&pg=PA305&lpg=PA305&dq=%22top%20dog%22&source=bl&ots=x7hAqJDTcl&sig=SVJAG221a7RsnsslB8VxF0QWJUY&hl=en&sa=X&ei=x9c_UJOeJeip4gTMyICwBQ&redir_esc=y#v=onepage&q=%22top%20dog%22%20&f=false) (1883) by Allan Pinkerton:
>
> "Fo' de Lawd, gemmen, I'se hopin an' prayin' de No'thun folks will be de **top dog** in dis wrastle, an' ef eber dis niggah hes a chance to gib yu'uns a a helpin' han', yu' kin bet a hoss agin' a coon-skin he'll do it; but I hope an' trus my missus not be boddered."
>
>
>
---
Variation: *upper dog*
----------------------
The OED's first citation for the rare variation *upper dog* is from 1903 by G. Bowles in Hansard's *Parliamentary Debates*:
>
> If it came to a question of force, we should always be the ‘upper dog’ in Persia.
>
>
>
I found an earlier example in the April 1881 [*Popular Science Monthly*](http://books.google.fi/books?id=DCIDAAAAMBAJ&pg=PA775&lpg=PA775&dq=%22upper%20dog%22&source=bl&ots=CLdLWrrtUK&sig=DDoj3qZqFRET2bs6sWInqNrqCks&hl=en&sa=X&ei=wNk_UKyiDo-K4gTM94DgDw&redir_esc=y#v=onepage&q=%22upper%20dog%22&f=false) in "Some Notes on a Doctor's Liability" by Oliver E. Lyman:
>
> Quackery was again the **upper dog**. But the struggle was not over. Although on top, the other dog had a vicious grip upon him. The empiric was still unable to recover compensation from delinquent patients.
>
>
> | Does it come from pioneer days of sawing trees by hand? Top dog was the one on top, and clean, underdog was the one in the pit below the felled tree sawing away getting covered in sawdust. |
45,816 | What does the expression/idiom "feather your nest" mean?
I see a lot of references to it but I can't seem to figure out its meaning. | 2011/10/21 | [
"https://english.stackexchange.com/questions/45816",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/4479/"
] | The terms from my search, seem to come from the blood-sport of bear baiting in 16th Century England. The underdog would go for the bears middle section, most likely losing meanwhile the top-dog would go for the bear's jugular and be less at risk of being killed if the unconscious bear awoke and began reacting to the dogs.
Book:[1](http://books.google.com/books?id=secyAwAAQBAJ&pg=PA38&lpg=PA38&dq=underdog+bear+baiting&source=bl&ots=-WrZeQke9U&sig=VQNQ4JKJJL6vZZq7FcxzorLo_Cw&hl=en&sa=X&ei=O15pU7K-A6G_8QG-mYGgBQ&ved=0CE4Q6AEwAw#v=onepage&q=underdog%20bear%20baiting&f=false)
Website:[2](http://www.madrigal.com.au/2013/08/26/supporting-the-underdog-explanation/) | Does it come from pioneer days of sawing trees by hand? Top dog was the one on top, and clean, underdog was the one in the pit below the felled tree sawing away getting covered in sawdust. |
5,012,734 | i have a problem while uploading and resizing images in a loop.
can anyone please provide me the working sample of code of codeigniter for uploading and resizing at the same time in a loop.
I want to upload and resize images uploaded from the form. There will be more than 1 images so i have to upload them in loop.
My code first uploads the image then resizes it. 1ts images is uploaded and resized correctly but during 2nd loop the image is uploaded but not resized. It throws this error:
>
> Your server does not support the GD
> function required to process this type
> of image.
>
>
>
I have tried the clear function too
```
$this->image_lib->clear();
```
can anyone please help | 2011/02/16 | [
"https://Stackoverflow.com/questions/5012734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/318220/"
] | I had the same problem but this seemed to work:
```
// Do upload
if (! $this->upload->do_upload($image_name)) {
// return errors
return array('errors' => $this->upload->display_errors());
}
$data = $this->upload->data();
$config_manip = array(
'image_library' => 'gd2',
'source_image' => "./assets/uploads/{$data['file_name']}",
'new_image' => "./assets/uploads/thumbs/{$data['file_name']}",
'create_thumb' => true,
'thumb_marker' => '',
'maintain_ratio' => true,
'width' => 140,
'height' => 140
);
// Create thumbnail
$this->load->library('image_lib');
$this->image_lib->resize();
$this->image_lib->clear();
$this->image_lib->initialize($config_manip);
if ( ! $this->image_lib->resize()){
return array('errors' => $this->image_lib->display_errors());
}
```
Notice the Create Thumbnail goes:
Load Library,
Resize Image,
CLEAR,
Initialize Config
I was putting the clear after the initialize which was causing the same error you're getting. | Your error message suggest that it's not the loop that is the problem, but rather that the 2nd file is of a different filetype than the 1st. And that the underlying server don't have the needed libraries (http://www.libgd.org/Main\_Page) installed to handle that file type. |
5,012,734 | i have a problem while uploading and resizing images in a loop.
can anyone please provide me the working sample of code of codeigniter for uploading and resizing at the same time in a loop.
I want to upload and resize images uploaded from the form. There will be more than 1 images so i have to upload them in loop.
My code first uploads the image then resizes it. 1ts images is uploaded and resized correctly but during 2nd loop the image is uploaded but not resized. It throws this error:
>
> Your server does not support the GD
> function required to process this type
> of image.
>
>
>
I have tried the clear function too
```
$this->image_lib->clear();
```
can anyone please help | 2011/02/16 | [
"https://Stackoverflow.com/questions/5012734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/318220/"
] | Dont load image\_lib multiple times. Add image\_lib in autoload libs and change
```
$this->load->library('image_lib', $config);
```
to
```
$this->image_lib->initialize($config);
``` | Your error message suggest that it's not the loop that is the problem, but rather that the 2nd file is of a different filetype than the 1st. And that the underlying server don't have the needed libraries (http://www.libgd.org/Main\_Page) installed to handle that file type. |
5,012,734 | i have a problem while uploading and resizing images in a loop.
can anyone please provide me the working sample of code of codeigniter for uploading and resizing at the same time in a loop.
I want to upload and resize images uploaded from the form. There will be more than 1 images so i have to upload them in loop.
My code first uploads the image then resizes it. 1ts images is uploaded and resized correctly but during 2nd loop the image is uploaded but not resized. It throws this error:
>
> Your server does not support the GD
> function required to process this type
> of image.
>
>
>
I have tried the clear function too
```
$this->image_lib->clear();
```
can anyone please help | 2011/02/16 | [
"https://Stackoverflow.com/questions/5012734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/318220/"
] | Here is a working code from my image gallery controller. This function uploads a batch of images, resizes them and saves them to database.
```
public function create_photo_batch() {
$this->load->library('image_lib');
$this->load->library('upload');
// Get albums list for dropdown
$this->data['albums'] = $this->gallery_m->get_albums_list();
if(isset($_FILES['images']) && $_FILES['images']['size'] > 0) {
$album_id = $this->input->post('albumid');
$images = array();
$ret = array();
// Upload
$files = $_FILES['images'];
foreach ($files['name'] as $key => $image) {
$_FILES['images[]']['name']= $files['name'][$key];
$_FILES['images[]']['type']= $files['type'][$key];
$_FILES['images[]']['tmp_name']= $files['tmp_name'][$key];
$_FILES['images[]']['error']= $files['error'][$key];
$_FILES['images[]']['size']= $files['size'][$key];
$upload_config = array(
'allowed_types' => 'jpg|jpeg|gif|png',
'upload_path' => realpath(APPPATH . "../uploads/gallery"),
'max_size' => 5000,
'remove_spaces' => TRUE,
'file_name' => md5(time())
);
$this->upload->initialize($upload_config);
if ($this->upload->do_upload('images[]')) {
$image_data = $this->upload->data();
$images[] = $image_data['file_name'];
} else {
$this->session->set_flashdata('error', $this->upload->display_errors() );
redirect('admin/gallery/create_photo_batch');
}
}
// Resize
foreach ($images as $image) {
$resize_config = array(
'source_image' => realpath(APPPATH . '../uploads/gallery') .'/'. $image,
'new_image' => realpath(APPPATH . '../uploads/gallery/thumbs'),
'maintain_ratio' => TRUE,
'width' => 500,
'height' => 500
);
$this->image_lib->initialize($resize_config);
if ( ! $this->image_lib->resize() ) {
echo $this->image_lib->display_errors();
die;
}
$this->image_lib->clear();
}
// Save to db
foreach ($images as $image) {
$ret[] = array(
'AlbumID' => (int) $album_id,
'Url' => $image,
'IsActive' => 1
);
}
$this->gallery_m->save_images($ret);
redirect('admin/gallery/album/'.$album_id);
}
//Load view
$this->data['subview'] = 'admin/gallery/photo_upload_batch_view';
$this->load->view('admin/_layout_main', $this->data);
```
} | Your error message suggest that it's not the loop that is the problem, but rather that the 2nd file is of a different filetype than the 1st. And that the underlying server don't have the needed libraries (http://www.libgd.org/Main\_Page) installed to handle that file type. |
5,012,734 | i have a problem while uploading and resizing images in a loop.
can anyone please provide me the working sample of code of codeigniter for uploading and resizing at the same time in a loop.
I want to upload and resize images uploaded from the form. There will be more than 1 images so i have to upload them in loop.
My code first uploads the image then resizes it. 1ts images is uploaded and resized correctly but during 2nd loop the image is uploaded but not resized. It throws this error:
>
> Your server does not support the GD
> function required to process this type
> of image.
>
>
>
I have tried the clear function too
```
$this->image_lib->clear();
```
can anyone please help | 2011/02/16 | [
"https://Stackoverflow.com/questions/5012734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/318220/"
] | Dont load image\_lib multiple times. Add image\_lib in autoload libs and change
```
$this->load->library('image_lib', $config);
```
to
```
$this->image_lib->initialize($config);
``` | I had the same problem but this seemed to work:
```
// Do upload
if (! $this->upload->do_upload($image_name)) {
// return errors
return array('errors' => $this->upload->display_errors());
}
$data = $this->upload->data();
$config_manip = array(
'image_library' => 'gd2',
'source_image' => "./assets/uploads/{$data['file_name']}",
'new_image' => "./assets/uploads/thumbs/{$data['file_name']}",
'create_thumb' => true,
'thumb_marker' => '',
'maintain_ratio' => true,
'width' => 140,
'height' => 140
);
// Create thumbnail
$this->load->library('image_lib');
$this->image_lib->resize();
$this->image_lib->clear();
$this->image_lib->initialize($config_manip);
if ( ! $this->image_lib->resize()){
return array('errors' => $this->image_lib->display_errors());
}
```
Notice the Create Thumbnail goes:
Load Library,
Resize Image,
CLEAR,
Initialize Config
I was putting the clear after the initialize which was causing the same error you're getting. |
5,012,734 | i have a problem while uploading and resizing images in a loop.
can anyone please provide me the working sample of code of codeigniter for uploading and resizing at the same time in a loop.
I want to upload and resize images uploaded from the form. There will be more than 1 images so i have to upload them in loop.
My code first uploads the image then resizes it. 1ts images is uploaded and resized correctly but during 2nd loop the image is uploaded but not resized. It throws this error:
>
> Your server does not support the GD
> function required to process this type
> of image.
>
>
>
I have tried the clear function too
```
$this->image_lib->clear();
```
can anyone please help | 2011/02/16 | [
"https://Stackoverflow.com/questions/5012734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/318220/"
] | I had the same problem but this seemed to work:
```
// Do upload
if (! $this->upload->do_upload($image_name)) {
// return errors
return array('errors' => $this->upload->display_errors());
}
$data = $this->upload->data();
$config_manip = array(
'image_library' => 'gd2',
'source_image' => "./assets/uploads/{$data['file_name']}",
'new_image' => "./assets/uploads/thumbs/{$data['file_name']}",
'create_thumb' => true,
'thumb_marker' => '',
'maintain_ratio' => true,
'width' => 140,
'height' => 140
);
// Create thumbnail
$this->load->library('image_lib');
$this->image_lib->resize();
$this->image_lib->clear();
$this->image_lib->initialize($config_manip);
if ( ! $this->image_lib->resize()){
return array('errors' => $this->image_lib->display_errors());
}
```
Notice the Create Thumbnail goes:
Load Library,
Resize Image,
CLEAR,
Initialize Config
I was putting the clear after the initialize which was causing the same error you're getting. | Here is a working code from my image gallery controller. This function uploads a batch of images, resizes them and saves them to database.
```
public function create_photo_batch() {
$this->load->library('image_lib');
$this->load->library('upload');
// Get albums list for dropdown
$this->data['albums'] = $this->gallery_m->get_albums_list();
if(isset($_FILES['images']) && $_FILES['images']['size'] > 0) {
$album_id = $this->input->post('albumid');
$images = array();
$ret = array();
// Upload
$files = $_FILES['images'];
foreach ($files['name'] as $key => $image) {
$_FILES['images[]']['name']= $files['name'][$key];
$_FILES['images[]']['type']= $files['type'][$key];
$_FILES['images[]']['tmp_name']= $files['tmp_name'][$key];
$_FILES['images[]']['error']= $files['error'][$key];
$_FILES['images[]']['size']= $files['size'][$key];
$upload_config = array(
'allowed_types' => 'jpg|jpeg|gif|png',
'upload_path' => realpath(APPPATH . "../uploads/gallery"),
'max_size' => 5000,
'remove_spaces' => TRUE,
'file_name' => md5(time())
);
$this->upload->initialize($upload_config);
if ($this->upload->do_upload('images[]')) {
$image_data = $this->upload->data();
$images[] = $image_data['file_name'];
} else {
$this->session->set_flashdata('error', $this->upload->display_errors() );
redirect('admin/gallery/create_photo_batch');
}
}
// Resize
foreach ($images as $image) {
$resize_config = array(
'source_image' => realpath(APPPATH . '../uploads/gallery') .'/'. $image,
'new_image' => realpath(APPPATH . '../uploads/gallery/thumbs'),
'maintain_ratio' => TRUE,
'width' => 500,
'height' => 500
);
$this->image_lib->initialize($resize_config);
if ( ! $this->image_lib->resize() ) {
echo $this->image_lib->display_errors();
die;
}
$this->image_lib->clear();
}
// Save to db
foreach ($images as $image) {
$ret[] = array(
'AlbumID' => (int) $album_id,
'Url' => $image,
'IsActive' => 1
);
}
$this->gallery_m->save_images($ret);
redirect('admin/gallery/album/'.$album_id);
}
//Load view
$this->data['subview'] = 'admin/gallery/photo_upload_batch_view';
$this->load->view('admin/_layout_main', $this->data);
```
} |
5,012,734 | i have a problem while uploading and resizing images in a loop.
can anyone please provide me the working sample of code of codeigniter for uploading and resizing at the same time in a loop.
I want to upload and resize images uploaded from the form. There will be more than 1 images so i have to upload them in loop.
My code first uploads the image then resizes it. 1ts images is uploaded and resized correctly but during 2nd loop the image is uploaded but not resized. It throws this error:
>
> Your server does not support the GD
> function required to process this type
> of image.
>
>
>
I have tried the clear function too
```
$this->image_lib->clear();
```
can anyone please help | 2011/02/16 | [
"https://Stackoverflow.com/questions/5012734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/318220/"
] | I had the same problem but this seemed to work:
```
// Do upload
if (! $this->upload->do_upload($image_name)) {
// return errors
return array('errors' => $this->upload->display_errors());
}
$data = $this->upload->data();
$config_manip = array(
'image_library' => 'gd2',
'source_image' => "./assets/uploads/{$data['file_name']}",
'new_image' => "./assets/uploads/thumbs/{$data['file_name']}",
'create_thumb' => true,
'thumb_marker' => '',
'maintain_ratio' => true,
'width' => 140,
'height' => 140
);
// Create thumbnail
$this->load->library('image_lib');
$this->image_lib->resize();
$this->image_lib->clear();
$this->image_lib->initialize($config_manip);
if ( ! $this->image_lib->resize()){
return array('errors' => $this->image_lib->display_errors());
}
```
Notice the Create Thumbnail goes:
Load Library,
Resize Image,
CLEAR,
Initialize Config
I was putting the clear after the initialize which was causing the same error you're getting. | ```
$config['image_library'] = 'gd2';
$config['source_image'] = './assets/upload_images/A.jpg';
$config['create_thumb'] = FALSE;
$config['maintain_ratio'] = TRUE;
$config['width'] = 1600;
$config['height'] = 900;
$config['new_image'] = './assets/upload_images/'.$randy;
$this->load->library('image_lib', $config);
$this->image_lib->initialize($config);
$this->image_lib->resize();
$this->image_lib->clear();
```
I had same problem but solved these by this code. |
5,012,734 | i have a problem while uploading and resizing images in a loop.
can anyone please provide me the working sample of code of codeigniter for uploading and resizing at the same time in a loop.
I want to upload and resize images uploaded from the form. There will be more than 1 images so i have to upload them in loop.
My code first uploads the image then resizes it. 1ts images is uploaded and resized correctly but during 2nd loop the image is uploaded but not resized. It throws this error:
>
> Your server does not support the GD
> function required to process this type
> of image.
>
>
>
I have tried the clear function too
```
$this->image_lib->clear();
```
can anyone please help | 2011/02/16 | [
"https://Stackoverflow.com/questions/5012734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/318220/"
] | Dont load image\_lib multiple times. Add image\_lib in autoload libs and change
```
$this->load->library('image_lib', $config);
```
to
```
$this->image_lib->initialize($config);
``` | Here is a working code from my image gallery controller. This function uploads a batch of images, resizes them and saves them to database.
```
public function create_photo_batch() {
$this->load->library('image_lib');
$this->load->library('upload');
// Get albums list for dropdown
$this->data['albums'] = $this->gallery_m->get_albums_list();
if(isset($_FILES['images']) && $_FILES['images']['size'] > 0) {
$album_id = $this->input->post('albumid');
$images = array();
$ret = array();
// Upload
$files = $_FILES['images'];
foreach ($files['name'] as $key => $image) {
$_FILES['images[]']['name']= $files['name'][$key];
$_FILES['images[]']['type']= $files['type'][$key];
$_FILES['images[]']['tmp_name']= $files['tmp_name'][$key];
$_FILES['images[]']['error']= $files['error'][$key];
$_FILES['images[]']['size']= $files['size'][$key];
$upload_config = array(
'allowed_types' => 'jpg|jpeg|gif|png',
'upload_path' => realpath(APPPATH . "../uploads/gallery"),
'max_size' => 5000,
'remove_spaces' => TRUE,
'file_name' => md5(time())
);
$this->upload->initialize($upload_config);
if ($this->upload->do_upload('images[]')) {
$image_data = $this->upload->data();
$images[] = $image_data['file_name'];
} else {
$this->session->set_flashdata('error', $this->upload->display_errors() );
redirect('admin/gallery/create_photo_batch');
}
}
// Resize
foreach ($images as $image) {
$resize_config = array(
'source_image' => realpath(APPPATH . '../uploads/gallery') .'/'. $image,
'new_image' => realpath(APPPATH . '../uploads/gallery/thumbs'),
'maintain_ratio' => TRUE,
'width' => 500,
'height' => 500
);
$this->image_lib->initialize($resize_config);
if ( ! $this->image_lib->resize() ) {
echo $this->image_lib->display_errors();
die;
}
$this->image_lib->clear();
}
// Save to db
foreach ($images as $image) {
$ret[] = array(
'AlbumID' => (int) $album_id,
'Url' => $image,
'IsActive' => 1
);
}
$this->gallery_m->save_images($ret);
redirect('admin/gallery/album/'.$album_id);
}
//Load view
$this->data['subview'] = 'admin/gallery/photo_upload_batch_view';
$this->load->view('admin/_layout_main', $this->data);
```
} |
5,012,734 | i have a problem while uploading and resizing images in a loop.
can anyone please provide me the working sample of code of codeigniter for uploading and resizing at the same time in a loop.
I want to upload and resize images uploaded from the form. There will be more than 1 images so i have to upload them in loop.
My code first uploads the image then resizes it. 1ts images is uploaded and resized correctly but during 2nd loop the image is uploaded but not resized. It throws this error:
>
> Your server does not support the GD
> function required to process this type
> of image.
>
>
>
I have tried the clear function too
```
$this->image_lib->clear();
```
can anyone please help | 2011/02/16 | [
"https://Stackoverflow.com/questions/5012734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/318220/"
] | Dont load image\_lib multiple times. Add image\_lib in autoload libs and change
```
$this->load->library('image_lib', $config);
```
to
```
$this->image_lib->initialize($config);
``` | ```
$config['image_library'] = 'gd2';
$config['source_image'] = './assets/upload_images/A.jpg';
$config['create_thumb'] = FALSE;
$config['maintain_ratio'] = TRUE;
$config['width'] = 1600;
$config['height'] = 900;
$config['new_image'] = './assets/upload_images/'.$randy;
$this->load->library('image_lib', $config);
$this->image_lib->initialize($config);
$this->image_lib->resize();
$this->image_lib->clear();
```
I had same problem but solved these by this code. |
5,012,734 | i have a problem while uploading and resizing images in a loop.
can anyone please provide me the working sample of code of codeigniter for uploading and resizing at the same time in a loop.
I want to upload and resize images uploaded from the form. There will be more than 1 images so i have to upload them in loop.
My code first uploads the image then resizes it. 1ts images is uploaded and resized correctly but during 2nd loop the image is uploaded but not resized. It throws this error:
>
> Your server does not support the GD
> function required to process this type
> of image.
>
>
>
I have tried the clear function too
```
$this->image_lib->clear();
```
can anyone please help | 2011/02/16 | [
"https://Stackoverflow.com/questions/5012734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/318220/"
] | Here is a working code from my image gallery controller. This function uploads a batch of images, resizes them and saves them to database.
```
public function create_photo_batch() {
$this->load->library('image_lib');
$this->load->library('upload');
// Get albums list for dropdown
$this->data['albums'] = $this->gallery_m->get_albums_list();
if(isset($_FILES['images']) && $_FILES['images']['size'] > 0) {
$album_id = $this->input->post('albumid');
$images = array();
$ret = array();
// Upload
$files = $_FILES['images'];
foreach ($files['name'] as $key => $image) {
$_FILES['images[]']['name']= $files['name'][$key];
$_FILES['images[]']['type']= $files['type'][$key];
$_FILES['images[]']['tmp_name']= $files['tmp_name'][$key];
$_FILES['images[]']['error']= $files['error'][$key];
$_FILES['images[]']['size']= $files['size'][$key];
$upload_config = array(
'allowed_types' => 'jpg|jpeg|gif|png',
'upload_path' => realpath(APPPATH . "../uploads/gallery"),
'max_size' => 5000,
'remove_spaces' => TRUE,
'file_name' => md5(time())
);
$this->upload->initialize($upload_config);
if ($this->upload->do_upload('images[]')) {
$image_data = $this->upload->data();
$images[] = $image_data['file_name'];
} else {
$this->session->set_flashdata('error', $this->upload->display_errors() );
redirect('admin/gallery/create_photo_batch');
}
}
// Resize
foreach ($images as $image) {
$resize_config = array(
'source_image' => realpath(APPPATH . '../uploads/gallery') .'/'. $image,
'new_image' => realpath(APPPATH . '../uploads/gallery/thumbs'),
'maintain_ratio' => TRUE,
'width' => 500,
'height' => 500
);
$this->image_lib->initialize($resize_config);
if ( ! $this->image_lib->resize() ) {
echo $this->image_lib->display_errors();
die;
}
$this->image_lib->clear();
}
// Save to db
foreach ($images as $image) {
$ret[] = array(
'AlbumID' => (int) $album_id,
'Url' => $image,
'IsActive' => 1
);
}
$this->gallery_m->save_images($ret);
redirect('admin/gallery/album/'.$album_id);
}
//Load view
$this->data['subview'] = 'admin/gallery/photo_upload_batch_view';
$this->load->view('admin/_layout_main', $this->data);
```
} | ```
$config['image_library'] = 'gd2';
$config['source_image'] = './assets/upload_images/A.jpg';
$config['create_thumb'] = FALSE;
$config['maintain_ratio'] = TRUE;
$config['width'] = 1600;
$config['height'] = 900;
$config['new_image'] = './assets/upload_images/'.$randy;
$this->load->library('image_lib', $config);
$this->image_lib->initialize($config);
$this->image_lib->resize();
$this->image_lib->clear();
```
I had same problem but solved these by this code. |
60,464,009 | Say I insert three rows in cassandra in below order one by one
`ID,firstname, lastname, websitename
1:fname1, lname1, site1
2:fname2, lname2, site2
3:fname3, lname3, site3`
The column store stores columns together, like this:
`1:fname1,2:fname2,3:fname3
1:lname1,2:lname2,3:lname3
1:site1,2:site2,3:site3`
Does it mean when I insert the first row i.e `1:fname1, lname1, site1`, it will each column in separate disk block for all three columns so that
during firstname column has to be read in some query. all related column data is on single block ?
Will it not make write slow as it cassandra has to store the data in 3 blocks instead of one to ensure column data is tored together ? | 2020/02/29 | [
"https://Stackoverflow.com/questions/60464009",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3222249/"
] | Cassandra isn't a classical column store. It stores all inserted/updated data together, organized first by partition key, and then inside partition by clustering columns/primary keys. Data could be in different SSTables when you update them at different time point, but the compaction process will eventually try to merge them together.
If you're interested, you can use `sstabledump` against data files and see how data is stored. There is also a [very good blog post from The Last Pickle about storage engine in the Cassandra 3.0](https://thelastpickle.com/blog/2016/03/04/introductiont-to-the-apache-cassandra-3-storage-engine.html) (it's different from previous versions). | Cassandra is basically a column-family database or row partitioned database along with column information not column based/columnar/column oriented database. When insert/fetch we need to mention partition(aka row key , aka primary key) column information. We can add any column at any point of time.
Column-family stores, like Cassandra, is great if you have high throughput writes and want to be able to linearly scale horizontally.
The term "column-family" comes from the original storage engine that was a key/value store, where the value was a "family" of column/value tuples. There was no hard limit on the number of columns that each key could have. |
60,464,009 | Say I insert three rows in cassandra in below order one by one
`ID,firstname, lastname, websitename
1:fname1, lname1, site1
2:fname2, lname2, site2
3:fname3, lname3, site3`
The column store stores columns together, like this:
`1:fname1,2:fname2,3:fname3
1:lname1,2:lname2,3:lname3
1:site1,2:site2,3:site3`
Does it mean when I insert the first row i.e `1:fname1, lname1, site1`, it will each column in separate disk block for all three columns so that
during firstname column has to be read in some query. all related column data is on single block ?
Will it not make write slow as it cassandra has to store the data in 3 blocks instead of one to ensure column data is tored together ? | 2020/02/29 | [
"https://Stackoverflow.com/questions/60464009",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3222249/"
] | Cassandra is not a *column-oriented* database, it is a *partition-row* store, this means that the data in your example will be stored like this:
```
"YourTable" : {
row1 : { "ID":1, "firstname":"fname1", "lastname":"lname1", "websitename":"site1", "timestamp":1582988571},
row2 : { "ID":2, "firstname":"fname2", "lastname":"lname2", "websitename":"site2", "timestamp":1582989563}
row3 : { "ID":3, "firstname":"fname3", "lastname":"lname3", "websitename":"site3", "timestamp":1582989572}
...
}
```
The data is grouped and searched based on the primary key (which is the partition key and could include one or several clustering keys).
Some things to consider:
* Cassandra is an append-only store, this means that when you try to update or delete a record, internally it will create a new record with the new value and a different timestamp; for the delete operation it will add a meta-data called "tombstone" that identifies the records that will be removed
* Adding or removing nodes to the cluster will trigger a rearrangement of the tokens distribution, this means that the instance or server where a record can be located or maintained may change | Cassandra is basically a column-family database or row partitioned database along with column information not column based/columnar/column oriented database. When insert/fetch we need to mention partition(aka row key , aka primary key) column information. We can add any column at any point of time.
Column-family stores, like Cassandra, is great if you have high throughput writes and want to be able to linearly scale horizontally.
The term "column-family" comes from the original storage engine that was a key/value store, where the value was a "family" of column/value tuples. There was no hard limit on the number of columns that each key could have. |
43,962,188 | [![]]]](https://i.stack.imgur.com/BYLKP.png)](https://i.stack.imgur.com/BYLKP.png)
How do I remove the blue border around my circular button when I click it. | 2017/05/14 | [
"https://Stackoverflow.com/questions/43962188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5204814/"
] | In this example I have changed the `border-color` from blue to `transparent` and added `outline:none;` on `:focus` (could also add not enabled)
Hope this helps
```css
button {width:50px;
height:50px;
background-image:url("http://www.rachelgallen.com/images/purpleflowers.jpg");
background-size:70% 70%;
background-repeat:no-repeat;
background-position:center center;
border-width:3px;
border-style: solid;
border-color:#000099;
}
button:focus{
border-color:transparent!important;
outline:none;
}
```
```html
<button>
</button>
``` | Use `outline` Property :
```
selector {
outline:none;
}
```
**Example :**
```css
.btn {
outline: none;
}
```
```html
<button class="btn">Click Me!</button>
``` |
56,945,392 | We have an Object key to a map - `Map<Student,List<Subject>>:`
```
class Student {
String admitDate; //20190702
String name;
.....
}
```
At a particular trigger, we would like to sort the map based on the admitdate(in Date) of the Student - and remove the earliest admit/s.
The equals and hashcode of Student have a different comparison - so it cannot be a generic sort.
We are on Java 8.
What would be the least code way to achieve this? | 2019/07/09 | [
"https://Stackoverflow.com/questions/56945392",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1483620/"
] | This error is because to interger value. integer cannot store null value if not set as null yes in database meaning if not set null mysql will check that need to be insert value but null value is not a interger type. | As xenon states, the default expectation is that you will either define integer fields as nullable within your database, or provide a valid numeric value upon saving.
However, it is possible to override this behavior if you disable 'strict' mode in your database configuration file.
/config/database.php
```
'mysql' => [
...
'strict' => false,
...
],
``` |
27,414 | In English there is no general rule about where to place adverbs. One could say, "Do you see Tom often?" just as easily as "Do you often see Tom?"
Is the same true in French, or is there a preference to where you place adverbs in questions? That is to say, are both of these sentences equally correct?
>
> Vois-tu **parfois** Nicole?
>
>
> Vois-tu Nicole **parfois**?
>
>
> | 2017/10/04 | [
"https://french.stackexchange.com/questions/27414",
"https://french.stackexchange.com",
"https://french.stackexchange.com/users/14833/"
] | That would be:
>
> *Vois-tu parfois Nicole?*
>
>
>
but the literary *vois-tu* is seldom used in spoken French. More usual usual ways would be:
>
> *Est-ce que tu vois parfois Nicole ?*
>
>
>
or
>
> *Est-ce que ça t'arrive (parfois) de voir Nicole ?*
>
>
>
You might put the adverb at the end but generally to give a clarification after a short pause. A comma would show it:
>
> *Est-ce que tu vois Nicole, parfois ?*
>
>
> *Vois-tu Nicole, parfois ?*
>
>
>
Note that "often" is better translated by *souvent* or *fréquemment* while *parfois* is "sometimes", "at times".
>
> Vois-tu souvent Nicole ? (formal, literary)
>
>
> Tu vois souvent Nicole ? (usual spoken French)
>
>
> Est-ce que tu vois souvent Nicole ? (ditto)
>
>
> Est-ce que tu vois Nicole souvent ? (equivalent to the former, *souvent* can be placed in both positions here).
>
>
> Est-ce que ça t'arrive souvent de voir Nicole ? (spoken French)
>
>
> Vois-tu Nicole ? Souvent ? (formal, literary)
>
>
> | "vois-tu" is really too literary (though being the most correct form). Most French would say "tu vois" instead. "Vois-tu" is found only in books.
For the rest, I really agree with the previous response by jiliagre. |
38,863 | I have [multiple IP addresses](https://serverfault.com/questions/868/multiple-ip-addresses-per-nic) configured to a NIC in Windows 2003/2008 Servers.
This is done to get unique internal IPs to IIS websites, and there is a static NAT from each of these internal website addresses to corresponding public addresses. Each internal IP has a unique public IP.
Windows cmd and other applications use primary IP as a source IP by default.
But now I have a problem in that I would need to **initiate HTTP/HTTPS requests** from one of the secondary addresses to an external website that has allowed incoming traffic from only this secondary address.
Is it possible to assign source IPs to windows applications in a less intrusive way than setting the secondary IP as a primary IP in Windows, or switching public addresses in the NAT configuration? I don't want to hassle with NAT or IP settings in a production server with remote connections only.
What I'm looking for is an easier way to test this external url than developing and deploying a web application running on the site with this secondary IP assigned. | 2009/07/10 | [
"https://serverfault.com/questions/38863",
"https://serverfault.com",
"https://serverfault.com/users/1387/"
] | The short answer is no, unless the application specifically supports it. Otherwise it's up to the IP stack to determine how things get sent out so doing something like putting a weight on one interface is what you have to do.
A workaround for a browser would be to install a local proxy. [**WebScarab**](http://www.owasp.org/index.php/Category:OWASP_WebScarab_Project) will allow you to do this, if you don't mind installing it on a server. You can set up a local proxy bound to a specific IP and then set your browser to use the local proxy. Thus the request will be sent to the remote server using the IP that the proxy is bound to.
If you use an internal proxy follow [**this guide**](http://www.owasp.org/index.php/Chaining_WebScarab_onto_another_proxy) to chain WebScarab to that proxy. | You can't do it from the web browser, but you can add a default route for a particular IP/subnet that uses the secondary IP.
I know how to do this on Linux; no idea about windows, but I assume it will just be some call to "route add something" |
56,922,293 | I have a string `str1 = " 2*PI"` where PI is a global string `PI = "1*pi"`
If I perform `eval(str1)` it tries to evaluate `1.*pi1.*pi`. How do I get it evaluate it as `2*(1*pi)` i.e 2 pi? | 2019/07/07 | [
"https://Stackoverflow.com/questions/56922293",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5281266/"
] | `eval(str1)` returns `1.*pi1.*pi` because `eval(str1)` evaluates to `2*"1*pi"` and multiplication between a string and an integer results in a repetition of the string.
Format the string directly into `str1` instead.
```
from math import pi
PI = "1*pi"
str1 = f"2*({PI})" # or for versions < Python-3.6: "2*({})".format(PI)
print(str1) # '2*(1*pi)'
print(eval(str1)) # 6.283185307179586
```
---
If you're not in control of `PI`, you can evaluate `PI` first, then format it into the expression.
```
eval(f"2*({eval(PI)})") # or equivalently eval("2*({})".format(eval(PI)))
```
If you're not in control of `str1` either, you can replace all `PI` tokens with its literal string value: `1*pi`.
```
eval(str1.replace('PI', PI))
```
But this doesn't handle edge cases such as `2*PIE` (if they ever appear). A more robust solution would be use a regex and surround `PI` with `\b` characters to match a full token.
```
import re
eval(re.sub(r'\bPI\b', PI, str1))
```
This appropriately excludes strings such as `2*PIZZA` or `2*API`. | Thanks evaluating first seems to have solved the problem.
So I now have
```
from math import pi
PI = eval("1*pi")
str1 = "2*PI"
eval(str1)
```
Which avoided any need for a replace |
56,922,293 | I have a string `str1 = " 2*PI"` where PI is a global string `PI = "1*pi"`
If I perform `eval(str1)` it tries to evaluate `1.*pi1.*pi`. How do I get it evaluate it as `2*(1*pi)` i.e 2 pi? | 2019/07/07 | [
"https://Stackoverflow.com/questions/56922293",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5281266/"
] | what if you evaluated - eval() - the PI string first and the inserted the evaluated in to str1 as a str through the str() command and then evaluated str1
```
from math import *
PI = "1*pi"
str1 = "2*PI"
PI = str(eval(PI)) # Turns our PI string into a number
str1 = str1.replace("PI",PI) # Sets our PI number in
print(eval(str1)) # Calculates it one last time
```
**OUTPUT**
```
6.283185307179586
``` | Thanks evaluating first seems to have solved the problem.
So I now have
```
from math import pi
PI = eval("1*pi")
str1 = "2*PI"
eval(str1)
```
Which avoided any need for a replace |
16,284,590 | I need to have endResult to be in descending order by ID and am not sure how that works with c# Linq. Any help would be great.
```
private void textBox6_Leave(object sender, EventArgs e)
{
DataClasses3DataContext db = new DataClasses3DataContext();
int matchedAdd = (from c in db.GetTable<prop>()
where c.streetNum.Contains(textBox1.Text) && c.Direction.Contains(textBox2.Text) && c.street.Contains(textBox4.Text) && c.SUFF.Contains(textBox6.Text)
select c.ID).Single();
var before = (from c in db.GetTable<prop>()
where c.ID < matchedAdd
orderby c.PARCEL descending
select c).Take(6);
var after = (from c in db.GetTable<prop>()
where c.ID > matchedAdd
orderby c.PARCEL
select c).Take(6);
var endResult = after.Concat(before);
dgvBRT.DataSource = endResult;
}
``` | 2013/04/29 | [
"https://Stackoverflow.com/questions/16284590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/630737/"
] | ```
dgvBRT.DataSource = endResult.OrderByDescending(x => x.ID);
```
...there's not much else to say. | This may helps:
```
after.Concat(befor).OrderByDescending(i => i.ID);
``` |
7,926 | How can i efficiently use my dual monitor setup along with the same keyboard and mouse with dual machines, (Home Gaming pc and work laptop)
sometimes i need to work from home using my work laptop, but i don't want to disconnect all the Hdmi cables and connect new mouse or keyboard from my existing PC setup
i am thinking about plugging my laptop with usb 3.0 Docking station with multiple display outputs
current setup:
1. LG 34" Ultrawide with 2x thunderbolt, 2x hdmi, 1x Displayport (Display port is used by PC)
2. Acer 24" monitor with 1 HDMI, 1 DVI, 1 VGA (HDMI used by PC)
3. [Logitech M720 wireless Mouse](https://www.logitech.com/en-us/product/m720-triathlon) (Bluetooth can pair up to 3 devices, easy to switch)
Need suggestion for [wireless multi-computer keyboard](http://rads.stackoverflow.com/amzn/click/B01N5EVQ4Q)(mechanical gaming keyboard would be ideal) and good usb3.0 Docking station | 2017/08/15 | [
"https://hardwarerecs.stackexchange.com/questions/7926",
"https://hardwarerecs.stackexchange.com",
"https://hardwarerecs.stackexchange.com/users/6808/"
] | It so happens that there is a software only way to do this.
I was watching LinusTechTips and they were advertising this software on their end of video sponsor.
The software is called [Synergy](https://symless.com/synergy).
It actually works by creating some sort of local network and communicating over your own computers, making the experience very, very fast. The benefits of this over a hardware KVM switch is that this is software (not hardware duh ;)) and it is priced as low as $19, depending on the option you pick.
[The $19 option](https://symless.com/synergy/pricing) would be perfectly suitable for your needs, other options are encryption over the network, and unless your network is already insecure, you dont really need it.
As per a concern below, it runs on both wireless and wired connections!
Hope this is a suitable suggestion for you. | I'm having trouble finding anything that actually has all of the ports and connectors that (I think) you'll need, but I can explain how I would go about this. If you can get me specifics on what display outputs are available on your PC and laptop, as well as your monitor resolution and refresh rate, I'll take some time to find you the exact equipment.
---
What you want is a KVM switch, a mechanism designed to use one keyboard, mouse, and monitor (in your case two monitors) as a workstation that can dynamically swap between two computers. I recommend this over a standard dock for ease of use, flexible configurations, and preservation of desk surface real estate.
You've basically got two approaches. One is expensive and the other is somewhat convoluted.
<https://www.startech.com/Server-Management/KVM-Switches/>
That site is a good place to start, they make high end switches and they're just about the only company I can find that even does digital video formats or dual monitor outputs in any significant capacity. Almost everything else I've been able to pull up has been either analog (VGA) or DVI with maybe a few DVI-Dual Links in there. The downside of this approach is that you're probably going to drop $200+ on this solution.
The other method you could use would be to downgrade your cable connections to DVI (or whatever you can find that is compatible) and get two cheap units that handle single monitor outputs. This is still likely to run you $60+. There's also a concern about what resolution and refresh rate you're running at, as each type of cable has a ceiling on how much data it can transfer and thus what resolutions and frame rates it is capable of transmitting. I haven't found any single monitor HDMI or DisplayPort boxes that were cheap enough to consider over the StarTech products linked above, but you may have more luck. I searched Amazon, Newegg, and PCPartPicker if you were curious. Office Depot or Office Max might be worth a try.
PLEASE KEEP IN MIND: Most of these KVM switches do not come with extra cables, so plan your layout and figure out the types and lengths of cables you will need beforehand and order them alongside your KVM solution. This will save you headaches and irritation and time waiting for shipping.
Again, if you want to reply with those related specs that I mentioned above, I can find some time before Friday to help you hunt down specific hardware.
---
Keyboards are really up to you. If you don't mind a 60% board I can recommend an Anne Pro, I have one for work and love it; however, I haven't used it for gaming since it has a tiny layout and red switches. I can confirm though that it has built-in bluetooth (comes with dongle for non-BT devices) and hotkey device swapping for up to four connected devices, so it would fit your requirements there. Bonus points for being under $100 and having quality RGB because colors are fun. If that doesn't catch your eye, I know that Filco also has some good offerings, and CODE keyboards are always worth a look as well.
The subreddit for mechanical keyboards has this wiki page listing wireless options:
<https://www.reddit.com/r/MechanicalKeyboards/wiki/wireless-mechanical_keyboards>
You could also search around on that forum to see what other people have used and what they liked/disliked, it's an active community with a good amount of content. |
68,440,085 | Here's what Im trying to do.. The images I save on the database are going to the correct path. But they don't show up in the site.
```
@blogs.route("/post/new", methods=['GET', 'POST'])
def new_post():
if ('user' in session and session['user'] == params["username"]):
form = PostForm()
if form.validate_on_submit():
pic = save_picture(request.files['pic'])
post = Post(title=form.title.data,
content=form.content.data, img=pic)
db.session.add(post)
db.session.commit()
flash('Your post has been created!', 'success')
image_file = url_for('static', filename = 'profile_pics/' + pic)
return render_template('post.html',image_file=image_file)
return render_template('create_post.html', title='New Post',
form=form)
return "please login to the dashboard first. Dont try to enter without logging in!"
```
The HTML side
```
<img src="{{image_file}}" alt="error">
``` | 2021/07/19 | [
"https://Stackoverflow.com/questions/68440085",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14292889/"
] | **Found a fix!!**
I figured out that one can use the set keyword from python as a variable to store the post.img in it and then refer it inside the source.
```
{% set img_name = 'profile_pics/' + post.img %}
<img src="{{url_for('static', filename = img_name)}}" alt="error">
``` | This would be the route function:
```py
image_file = url_for('static', filename='profile_pics/' + post.img)
return render_template('template.html', image_file=image_file)
```
and this is what it looks like in the template:
```html
<img src="{{ image_file }}">
```
The issue is probably that You are not really able to have nested variables inside html especially because jinja probably interpreted that as a literal string |
4,615,213 | I have a DOS batch file to run on a daily basis.
Something similar like -
```
@ECHO ON
SET COMMON_LIB=commons-io-1.3.1.jar;
SET AR_CLASS_PATH=%CLASSPATH%%COMMON_LIB%
java -cp %AR_CLASS_PATH% -Xms128m -Xmx256m FileCreating
PAUSE
```
When I run the batch file directly, i.e. double cliking on the .bat file, it runs fine, the command window opens up and executes all the required commands( note the `PAUSE` ).
But when I schedule a daily task, I see the status as Running. Also, when I right click on the task, it gives me an option to end the task(when status is `Running` ) but I cant see the command window and so I cant make out if it has been processed or the error it has generated.
And so, cant understand if the error is in classpath or my java code or somewhere else.
The environment is Windows Server 2003 R2 EE, SP2. The user has Admin priviledges.
I checked but there is no file of Schedlgu.txt in `WINDOWS\Tasks` dir.
One thing I noticed was the `CLASSPATH` value had no reference to the jdk/bin, can that be a issue?
Please advise.
**EDIT**
Just to simplify things, I commented the `java` command for the bat file to do almost nothing then set some variables and then pause to keep the window open. Still no success. | 2011/01/06 | [
"https://Stackoverflow.com/questions/4615213",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/538058/"
] | you can only set the name anchor in the url basically yourpage.com/#/someurl/
it's not possible to change the whole url without reloading the whole page.
To set the name anchor you need to do this:
```
location.hash='#/my/name/anchor/path';
```
If you want to use it like that (to point to your page with name anchor) you'll need to define some kind of check to load proper content with `ver_pregunta` function, basically take the location.hash e.g. if your url = `www.someurl.com/#myid` you can run:
```
if(location.hash!=""){
ver_pregunta(location.hash.substring(1));
}
```
or better set a list of allowed ids:
```
var mypaths={"myid1":1,"myid2":1,"myid3":1}
```
and compare it with `location.hash`:
```
if(location.hash!="")
var lh=location.hash.substring(1);
if(mypaths[lh]==1)ver_pregunta(lh);
}
```
For title use:
```
$('title').text('new title');
```
For description:
```
$('meta[http-equiv="description"]').attr('content','new description');
```
If you want to do it for SEO reasons it won't work, Google bots don't use JS, they'll pick up only static HTML
Cheers
G. | ```
window.location = "#newurl";
document.title = 'new title';
$('meta[name=description]').attr("content", "new description")
``` |
4,615,213 | I have a DOS batch file to run on a daily basis.
Something similar like -
```
@ECHO ON
SET COMMON_LIB=commons-io-1.3.1.jar;
SET AR_CLASS_PATH=%CLASSPATH%%COMMON_LIB%
java -cp %AR_CLASS_PATH% -Xms128m -Xmx256m FileCreating
PAUSE
```
When I run the batch file directly, i.e. double cliking on the .bat file, it runs fine, the command window opens up and executes all the required commands( note the `PAUSE` ).
But when I schedule a daily task, I see the status as Running. Also, when I right click on the task, it gives me an option to end the task(when status is `Running` ) but I cant see the command window and so I cant make out if it has been processed or the error it has generated.
And so, cant understand if the error is in classpath or my java code or somewhere else.
The environment is Windows Server 2003 R2 EE, SP2. The user has Admin priviledges.
I checked but there is no file of Schedlgu.txt in `WINDOWS\Tasks` dir.
One thing I noticed was the `CLASSPATH` value had no reference to the jdk/bin, can that be a issue?
Please advise.
**EDIT**
Just to simplify things, I commented the `java` command for the bat file to do almost nothing then set some variables and then pause to keep the window open. Still no success. | 2011/01/06 | [
"https://Stackoverflow.com/questions/4615213",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/538058/"
] | you can only set the name anchor in the url basically yourpage.com/#/someurl/
it's not possible to change the whole url without reloading the whole page.
To set the name anchor you need to do this:
```
location.hash='#/my/name/anchor/path';
```
If you want to use it like that (to point to your page with name anchor) you'll need to define some kind of check to load proper content with `ver_pregunta` function, basically take the location.hash e.g. if your url = `www.someurl.com/#myid` you can run:
```
if(location.hash!=""){
ver_pregunta(location.hash.substring(1));
}
```
or better set a list of allowed ids:
```
var mypaths={"myid1":1,"myid2":1,"myid3":1}
```
and compare it with `location.hash`:
```
if(location.hash!="")
var lh=location.hash.substring(1);
if(mypaths[lh]==1)ver_pregunta(lh);
}
```
For title use:
```
$('title').text('new title');
```
For description:
```
$('meta[http-equiv="description"]').attr('content','new description');
```
If you want to do it for SEO reasons it won't work, Google bots don't use JS, they'll pick up only static HTML
Cheers
G. | Use javascript's native window function.
```
window.location.replace('http://www.google.com/')
``` |
18,526,131 | I'm trying to launch `service` and then open `socket` to have connection with server.
On button click I create new `Thread` and then start service.
```
Thread t = new Thread(){
public void run(){
mIntent= new Intent(MainActivity.this, ConnectonService.class);
mIntent.putExtra("KEY1", "Value used by the service");
context.startService(mIntent);
}
};
t.start();
```
Then on `service`, I try to open `socket` and have connection with server
```
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//TODO do something useful
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
Scanner scanner = new Scanner(socket.getInputStream());
message = scanner.nextLine();
} catch (IOException e) {
e.printStackTrace();
}
return Service.START_NOT_STICKY;
}
```
But when I call it, I have **error**
```
08-30 08:56:49.268: E/AndroidRuntime(3751): java.lang.RuntimeException: Unable to start service com.example.testofconnection.ConnectonService@40ef02a8 with Intent { cmp=com.example.testofconnection/.ConnectonService (has extras) }: android.os.NetworkOnMainThreadException*
```
I think problem is that `service` is on `main thread`, but I can't find how should I start service on new (independend) thread to keep `connection alive`? | 2013/08/30 | [
"https://Stackoverflow.com/questions/18526131",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1262436/"
] | You can use IntentService for this. Just launch it normally with an Intent from the main thread. `onHandleIntent()` method gets executed in background thread. Put your socket-code in there. Here is an example code.
```
public class MyIntentService extends IntentService {
public MyIntentService() {
super("MyIntentService");
}
@Override
protected void onHandleIntent(Intent intent) {
// this method is called in background thread
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
```
In your activity you start the service as following.
```
startService(new Intent(this, MyIntentService.class));
```
If you need a long-lasting service, you can create a normal service and start a thread there. Here is an example. Make sure you launch it as "foreground" service. This will allow service to run longer without been killed by Android.
```
public class MyAsyncService extends Service {
private AtomicBoolean working = new AtomicBoolean(true)
private Runnable runnable = new Runnable() {
@Override
public void run() {
while(working.get()) {
// put your socket-code here
...
}
}
}
@Override
public void onCreate() {
// start new thread and you your work there
new Thread(runnable).start();
// prepare a notification for user and start service foreground
Notification notification = ...
// this will ensure your service won't be killed by Android
startForeground(R.id.notification, notification);
}
@Override
public onDestroy() {
working.set(false)
}
}
``` | Move this code to your thread:
```
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
Scanner scanner = new Scanner(socket.getInputStream());
message = scanner.nextLine();
} catch (IOException e) {
e.printStackTrace();
}
```
Just as an example (I'm not sure it this fits to your task):
```
Thread t = new Thread(){
public void run(){
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
Scanner scanner = new Scanner(socket.getInputStream());
message = scanner.nextLine();
} catch (IOException e) {
e.printStackTrace();
}
mIntent= new Intent(MainActivity.this, ConnectonService.class);
mIntent.putExtra("KEY1", "Value used by the service");
context.startService(mIntent);
}
};
t.start();
```
You should know that a service is running on the UI thread, so you got this error. Check [this nice site](http://techtej.blogspot.com.es/2011/03/android-thread-constructspart-4.html) for more information about various threading approaches in Android. |
1,487,587 | My home network uses a `192.168.1.0/24` subnet, and when I `ping 192.168.1.137` I get a response saying the host is unavailable (as expected because I don't have any machines using that address)
However, when I `ping 10.10.10.140` it:
1. gets a response, and
2. goes on forever.
I thought `10.0.0.0/8` were all reserved addresses and that any sort of traffic going to those addresses was dropped. What am I pinging when I ping `10.10.10.140`? Is it [IANA](https://en.wikipedia.org/wiki/Internet_Assigned_Numbers_Authority) servers? | 2019/09/30 | [
"https://superuser.com/questions/1487587",
"https://superuser.com",
"https://superuser.com/users/486488/"
] | >
> I thought 10.0.0.0/8 were all reserved addresses and that any sort of traffic going to those addresses was dropped.
>
>
>
No. It's true that it's a special range, but it's reserved for *exactly the same purpose* as 192.168.0.0/16 – it is a private address block for LAN usage. (There is also a third block, 172.16.0.0/12. See the [IANA registry](https://www.iana.org/assignments/iana-ipv4-special-registry/iana-ipv4-special-registry.xhtml).)
All three private blocks act as normal unicast addresses and are routable locally, including between each other – they're just not routable across the global Internet. (What's actually dropped is traffic and route announcements *between ISPs.*)
So most likely you're pinging some host in your ISP's network, where they've decided to use 10.0.0.0/8. It could be a device on their internal network, or a 'management' VLAN on your router itself, or anything. | You potentially could have a device on the network using that IP address that you are not aware of. The 10/8 range is not routable over the internet. I would take a look at your routes and see where its going. |
1,487,587 | My home network uses a `192.168.1.0/24` subnet, and when I `ping 192.168.1.137` I get a response saying the host is unavailable (as expected because I don't have any machines using that address)
However, when I `ping 10.10.10.140` it:
1. gets a response, and
2. goes on forever.
I thought `10.0.0.0/8` were all reserved addresses and that any sort of traffic going to those addresses was dropped. What am I pinging when I ping `10.10.10.140`? Is it [IANA](https://en.wikipedia.org/wiki/Internet_Assigned_Numbers_Authority) servers? | 2019/09/30 | [
"https://superuser.com/questions/1487587",
"https://superuser.com",
"https://superuser.com/users/486488/"
] | These are three most likely possibilities:
1. Your ISP assigns its clients the `10.0.0.0/8` addresses. Your home router isn't advanced enough (nor needs to be) to limit routing private blocks upwards.
2. You have an additional routing device between your router and ISP, like a cable modem, which communicates with your router over `10.0.0.0/8`.
3. You host or access `10.0.0.0/8` network directly at your computer (i.e., a virtual machine network or some VPN).
The most important question is: why do you ping `10.10.10.140` specifically? Also, trying to access popular management services (HTTP, HTTPS, SSH, and Telnet) might reveal device identity and purpose. | You potentially could have a device on the network using that IP address that you are not aware of. The 10/8 range is not routable over the internet. I would take a look at your routes and see where its going. |
1,487,587 | My home network uses a `192.168.1.0/24` subnet, and when I `ping 192.168.1.137` I get a response saying the host is unavailable (as expected because I don't have any machines using that address)
However, when I `ping 10.10.10.140` it:
1. gets a response, and
2. goes on forever.
I thought `10.0.0.0/8` were all reserved addresses and that any sort of traffic going to those addresses was dropped. What am I pinging when I ping `10.10.10.140`? Is it [IANA](https://en.wikipedia.org/wiki/Internet_Assigned_Numbers_Authority) servers? | 2019/09/30 | [
"https://superuser.com/questions/1487587",
"https://superuser.com",
"https://superuser.com/users/486488/"
] | >
> I thought 10.0.0.0/8 were all reserved addresses and that any sort of traffic going to those addresses was dropped.
>
>
>
No. It's true that it's a special range, but it's reserved for *exactly the same purpose* as 192.168.0.0/16 – it is a private address block for LAN usage. (There is also a third block, 172.16.0.0/12. See the [IANA registry](https://www.iana.org/assignments/iana-ipv4-special-registry/iana-ipv4-special-registry.xhtml).)
All three private blocks act as normal unicast addresses and are routable locally, including between each other – they're just not routable across the global Internet. (What's actually dropped is traffic and route announcements *between ISPs.*)
So most likely you're pinging some host in your ISP's network, where they've decided to use 10.0.0.0/8. It could be a device on their internal network, or a 'management' VLAN on your router itself, or anything. | These are three most likely possibilities:
1. Your ISP assigns its clients the `10.0.0.0/8` addresses. Your home router isn't advanced enough (nor needs to be) to limit routing private blocks upwards.
2. You have an additional routing device between your router and ISP, like a cable modem, which communicates with your router over `10.0.0.0/8`.
3. You host or access `10.0.0.0/8` network directly at your computer (i.e., a virtual machine network or some VPN).
The most important question is: why do you ping `10.10.10.140` specifically? Also, trying to access popular management services (HTTP, HTTPS, SSH, and Telnet) might reveal device identity and purpose. |
10,895,951 | I have created binary file using C codings. This is the structure of that binary file.
```
struct emp
{
int eid,eage;
char name[20],city[20];
}record;
```
Using this 'C' Structure i created a binary file called "table1.txt"
Now i want to show the contents of the file in a web page using php. How can i do this ?
```
<html>
<head>
<title>binary file</title></head>
<body style="background-color:yellow">
<?
$fp = fopen("table1.txt", "rb");
$read = fread($fp, 4);
$n = unpack("i", $read);
$data1 = fread($fp, 8);
$nn = unpack("i",$data1);
echo $number[1];
?>
</body>
</html>
```
I have used the above code. But i can only read the first field of the file only. My first Record field is Employee id its values is '0'. The page displays only 0. | 2012/06/05 | [
"https://Stackoverflow.com/questions/10895951",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1437138/"
] | \_POST is an associative array (a superglobal)
You can access its content using the regular array syntax
```
$_POST['unu']
```
instead of
```
$_POST('unu')
``` | ```
if(isset($_POST['unu']))
```
Use square brackets |
10,895,951 | I have created binary file using C codings. This is the structure of that binary file.
```
struct emp
{
int eid,eage;
char name[20],city[20];
}record;
```
Using this 'C' Structure i created a binary file called "table1.txt"
Now i want to show the contents of the file in a web page using php. How can i do this ?
```
<html>
<head>
<title>binary file</title></head>
<body style="background-color:yellow">
<?
$fp = fopen("table1.txt", "rb");
$read = fread($fp, 4);
$n = unpack("i", $read);
$data1 = fread($fp, 8);
$nn = unpack("i",$data1);
echo $number[1];
?>
</body>
</html>
```
I have used the above code. But i can only read the first field of the file only. My first Record field is Employee id its values is '0'. The page displays only 0. | 2012/06/05 | [
"https://Stackoverflow.com/questions/10895951",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1437138/"
] | \_POST is an associative array (a superglobal)
You can access its content using the regular array syntax
```
$_POST['unu']
```
instead of
```
$_POST('unu')
``` | post values are stored as array
to acces them you need to write as
```
if(isset($_POST['unu'])){
echo "<tr>";
echo "<td>a mers</td>";
echo "</tr>";
}
``` |
65,673,101 | ```
var usedNumbers = []
var counter = 0
while(counter < 9){
var math = Math.floor(Math.random() * 9)
if(math != usedNumbers){
usedNumbers[counter] = math
counter++
}
}
console.log(usedNumbers)
```
i am really bad at explaining and really new to coding but i will do my best
i want my piece of code to create a random number, check if that number is used before and then put it in the array so i can use it later.
but for some reason the if statement is always true so it doesnt check for duplicates
if someone can explain what i did wrong and how to fix it that would be great | 2021/01/11 | [
"https://Stackoverflow.com/questions/65673101",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12660373/"
] | You could take a [`Set`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) and check only the `size` of it.
```js
const numbers = new Set;
while (numbers.size < 9) numbers.add(Math.floor(Math.random() * 9));
console.log(...numbers);
``` | You can use the array method [.includes](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes)
```js
var usedNumbers = []
var counter = 0
while(counter < 9){
var math = Math.floor(Math.random() * 9)
if(!usedNumbers.includes(math)){
usedNumbers[counter] = math
counter++
}
}
console.log(usedNumbers.sort())
``` |
65,673,101 | ```
var usedNumbers = []
var counter = 0
while(counter < 9){
var math = Math.floor(Math.random() * 9)
if(math != usedNumbers){
usedNumbers[counter] = math
counter++
}
}
console.log(usedNumbers)
```
i am really bad at explaining and really new to coding but i will do my best
i want my piece of code to create a random number, check if that number is used before and then put it in the array so i can use it later.
but for some reason the if statement is always true so it doesnt check for duplicates
if someone can explain what i did wrong and how to fix it that would be great | 2021/01/11 | [
"https://Stackoverflow.com/questions/65673101",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12660373/"
] | You can use the array method [.includes](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes)
```js
var usedNumbers = []
var counter = 0
while(counter < 9){
var math = Math.floor(Math.random() * 9)
if(!usedNumbers.includes(math)){
usedNumbers[counter] = math
counter++
}
}
console.log(usedNumbers.sort())
``` | Here is a functional and recursive way of doing it.
```
const saveNums = (currentNum, size, result) => {
if (result.length >= size) {
return result;
}
const newResult = result.includes(currentNum) ? result : [...result, currentNum];
return saveNums(Math.floor(Math.random() * size), size, newResult);
};
console.log(saveNums(Math.floor(Math.random() * 9), 9, []));
``` |
65,673,101 | ```
var usedNumbers = []
var counter = 0
while(counter < 9){
var math = Math.floor(Math.random() * 9)
if(math != usedNumbers){
usedNumbers[counter] = math
counter++
}
}
console.log(usedNumbers)
```
i am really bad at explaining and really new to coding but i will do my best
i want my piece of code to create a random number, check if that number is used before and then put it in the array so i can use it later.
but for some reason the if statement is always true so it doesnt check for duplicates
if someone can explain what i did wrong and how to fix it that would be great | 2021/01/11 | [
"https://Stackoverflow.com/questions/65673101",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12660373/"
] | You could take a [`Set`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) and check only the `size` of it.
```js
const numbers = new Set;
while (numbers.size < 9) numbers.add(Math.floor(Math.random() * 9));
console.log(...numbers);
``` | Here is a functional and recursive way of doing it.
```
const saveNums = (currentNum, size, result) => {
if (result.length >= size) {
return result;
}
const newResult = result.includes(currentNum) ? result : [...result, currentNum];
return saveNums(Math.floor(Math.random() * size), size, newResult);
};
console.log(saveNums(Math.floor(Math.random() * 9), 9, []));
``` |
18,750,850 | I need to input a string, if the string is just a whole string and not with spaces, the codes is fine, if the input is a string with spaces, the string only copys the first set of strings and not the whole strings? I'm an noob, please help.
```
#include <stdio.h>
#include <string.h>
int main() {
char again = 0;
do {
char str[60], s[60];
int i, j = 0;
printf("Enter any string->");
scanf("%s", str);
printf("The string is->%s", str);
for (i = 0; i <= strlen(str); i++) {
if (str[i] == 'a' || str[i] == 'e' || str[i] == 'i' ||
str[i] == 'o' || str[i] == 'u' || str[i] == 'A' ||
str[i] == 'E' || str[i] == 'I' || str[i] == 'O' ||
str[i] == 'U') {
str[i] = ' ';
} else {
s[j++] = str[i];
}
}
s[j] = '\0';
printf("\nThe string without vowel is->%s", s);
NSLog(@"Do you want to enter another string to be edit? (y/n) ");
scanf("%s", &again);
} while (again != 'n');
}
``` | 2013/09/11 | [
"https://Stackoverflow.com/questions/18750850",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2770315/"
] | Your code stops reading at a space because **that's how `scanf` works** with the `%s` format. It reads a sequence of non-whitespace characters.
If you're really using C++, then you'd be wise to switch to `std::string` and `std::getline`, which will read all input up to the end of the line. Your code doesn't appear to use any C++ features, though, so maybe you're really using C. In that case, consider `fgets` instead. It will read the whole line, too (up to a specified size, which generally corresponds to the size of your buffer). | You are allocating an array of 60 chars long (str). You can't expect to read a lot into it. Here are a few tips:
* Don't use such buffers, they are dangerous. The C++ library provides you [std::string](http://en.cppreference.com/w/cpp/string/basic_string).
* Never omit the curly braces `{}`.
* There are an easier way to check for chars than this horribly long if. Hint: [std::string::find\_first\_of](http://en.cppreference.com/w/cpp/string/basic_string/find_first_of) |
18,750,850 | I need to input a string, if the string is just a whole string and not with spaces, the codes is fine, if the input is a string with spaces, the string only copys the first set of strings and not the whole strings? I'm an noob, please help.
```
#include <stdio.h>
#include <string.h>
int main() {
char again = 0;
do {
char str[60], s[60];
int i, j = 0;
printf("Enter any string->");
scanf("%s", str);
printf("The string is->%s", str);
for (i = 0; i <= strlen(str); i++) {
if (str[i] == 'a' || str[i] == 'e' || str[i] == 'i' ||
str[i] == 'o' || str[i] == 'u' || str[i] == 'A' ||
str[i] == 'E' || str[i] == 'I' || str[i] == 'O' ||
str[i] == 'U') {
str[i] = ' ';
} else {
s[j++] = str[i];
}
}
s[j] = '\0';
printf("\nThe string without vowel is->%s", s);
NSLog(@"Do you want to enter another string to be edit? (y/n) ");
scanf("%s", &again);
} while (again != 'n');
}
``` | 2013/09/11 | [
"https://Stackoverflow.com/questions/18750850",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2770315/"
] | Your code stops reading at a space because **that's how `scanf` works** with the `%s` format. It reads a sequence of non-whitespace characters.
If you're really using C++, then you'd be wise to switch to `std::string` and `std::getline`, which will read all input up to the end of the line. Your code doesn't appear to use any C++ features, though, so maybe you're really using C. In that case, consider `fgets` instead. It will read the whole line, too (up to a specified size, which generally corresponds to the size of your buffer). | This code is a mess.
* C++ features like `std::string` are not used at all.
* You're mixing `printf/scanf` and `NSLog` for no reason.
* Modifying `str` in the `if` branch makes no sense, as it won't be read later.
* You probably want to use `i < strlen(str)` instead of `<=`, or you'll copy that terminating zero character twice.
* Your `scanf("%s", &again);` specifies to read a string, but you only have memory for a character, thus you probably end up writing into some random memory position.
While some of these points are more severe than others, I suggest fixing those issues and see what happens. If you experience unexpected output, then please do give your example input and output as well. |
9,712,606 | All,
I'm creating a side menu from a user defined menu in wordpress. I'm getting the menu options from the following code (since I know the menu id the user wants to display on the side):
```
$menu_items = wp_get_nav_menu_items($menu_id);
$menu_items = (array)$menu_items;
$output = '<div id="menu_options">';
$output .= '<ol class="tabs">';
foreach($menu_items as $menu){
$output .= '<li><a href="'.$menu->title.'" class="menu_page_id" id="'.$menu->ID.'">'.$menu->title.'</a></li>';
}
$output .= '</ol>';
$output .= '</div>';
$output .= '<div id="menu_content">This is content</div>';
$output .= '<input type="hidden" value="'.$menu_id.'" id="menu_id">';
return $output;
```
When a user clicks on one of the tabs I invoke an AJAX call to try and get the page content with the following code:
```
$('.menu_page_id').click(function(){
event.preventDefault();
page_id = $(this).attr("id");
menu_id = $('#menu_id').val();
action = "get_page_content";
$.post(ajaxurl, { page_id: page_id, menu_id: menu_id, action: action }, function(results) {
results = results.substring(0, results.length - 1);
$("#menu_content").hide();
$("#menu_content").html(results).fadeIn();
});
});
```
This calls the following function to return the content of the clicked page:
```
function get_page_content(){
$page_id = mysql_real_escape_string($_POST['page_id']);
$menu_id = mysql_real_escape_string($_POST['menu_id']);
$menu_items = wp_get_nav_menu_items($menu_id);
$menu_items = (array)$menu_items;
foreach($menu_items as $menu){
if($menu->ID == $page_id){
echo $menu->post_content;
}
}
}
add_action('wp_ajax_get_page_content', 'get_page_content');
add_action('wp_ajax_nopriv_get_page_content', 'get_page_content');
```
This all works good and it returns the page content except it just dumps the results out and actually doesn't display what I want with the shortcodes etc. Say I have the following on the page in Wordpress:
```
[frame_left]<img src="http://www.website.com/wp-content/uploads/2011/10/pic.jpg" alt="" width="300" height="240" />[/frame_left]
<h2 style="margin: 25px 0 0 0;">Person</h2>
<span class="small"><em>Title</em></span>
<p style="text-align: justify;">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris lacinia justo quis neque dapibus porta...</p>
[button link="http://www.google.com" text="Read More"]
[clear]
```
The following is what actually gets returned from my AJAX request:
```
[frame_left][/frame_left] Title Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris lacinia justo quis neque dapibus porta...[button link="http://www.google.com" text="Read More"] [clear]
```
Is there a way to actually return a page's content through Wordpress and have it display the shortcodes, html etc correctly??
Thanks for any help you can shed on this situation!! | 2012/03/15 | [
"https://Stackoverflow.com/questions/9712606",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1048676/"
] | See my answer for the **Android Studio environment**, [Mac and “PANIC: Missing emulator engine program for 'arm' CPU.”](https://stackoverflow.com/a/52161215/8034839).
To solve this problem, you need to specify the `-kernel` path manually. i.e.
```
$ ~/Library/Android/sdk/emulator/emulator @Galaxy_Nexus_Jelly_Bean_API_16 -kernel ~/Library/Android/sdk/system-images/android-16/default/armeabi-v7a/kernel-qemu
```
Remember to change the emulator name `Galaxy_Nexus_Jelly_Bean_API_16` to your own emulator name.
Below command is to check the emulators available for command line.
```
$ ~/Library/Android/sdk/emulator/emulator -list-avds
```
And also, ensure that your **emulator path** is correct, i.e. the one located at `~/Library/Android/sdk/emulator/`. | Just wanted to share my experience on this problem. Consulting each of the answers here, it didn't match my situation. Having a system image for Android API 22 causes this error and the weird thing is that all of the environment variables pointing to the correct directories. It doesn't make sense.
@BuvinJ answer had shed some light into the problem. I did check on the path describe on his answer and yes my copy of system image resides under the subfolder default when I look on the user directory (on Windows).
The weird thing is, there is also an android-sdk folder in the ANDROID\_SDK\_ROOT so I thought maybe Eclipse is looking there. Digging through the subfolders I figured out that the directory looks like this:
```
android-sdk-windows\system-images\android-22\google_apis\armeabi-v7a
```
This directory resides on the ANDROID\_SDK\_ROOT. There is also another one residing at the user directory user/XXXX/android-sdk/.
Eclipse is expecting it here:
```
android-sdk-windows\system-images\android-22\default\armeabi-v7a
```
Just changed the directory as such and it works now. |
9,712,606 | All,
I'm creating a side menu from a user defined menu in wordpress. I'm getting the menu options from the following code (since I know the menu id the user wants to display on the side):
```
$menu_items = wp_get_nav_menu_items($menu_id);
$menu_items = (array)$menu_items;
$output = '<div id="menu_options">';
$output .= '<ol class="tabs">';
foreach($menu_items as $menu){
$output .= '<li><a href="'.$menu->title.'" class="menu_page_id" id="'.$menu->ID.'">'.$menu->title.'</a></li>';
}
$output .= '</ol>';
$output .= '</div>';
$output .= '<div id="menu_content">This is content</div>';
$output .= '<input type="hidden" value="'.$menu_id.'" id="menu_id">';
return $output;
```
When a user clicks on one of the tabs I invoke an AJAX call to try and get the page content with the following code:
```
$('.menu_page_id').click(function(){
event.preventDefault();
page_id = $(this).attr("id");
menu_id = $('#menu_id').val();
action = "get_page_content";
$.post(ajaxurl, { page_id: page_id, menu_id: menu_id, action: action }, function(results) {
results = results.substring(0, results.length - 1);
$("#menu_content").hide();
$("#menu_content").html(results).fadeIn();
});
});
```
This calls the following function to return the content of the clicked page:
```
function get_page_content(){
$page_id = mysql_real_escape_string($_POST['page_id']);
$menu_id = mysql_real_escape_string($_POST['menu_id']);
$menu_items = wp_get_nav_menu_items($menu_id);
$menu_items = (array)$menu_items;
foreach($menu_items as $menu){
if($menu->ID == $page_id){
echo $menu->post_content;
}
}
}
add_action('wp_ajax_get_page_content', 'get_page_content');
add_action('wp_ajax_nopriv_get_page_content', 'get_page_content');
```
This all works good and it returns the page content except it just dumps the results out and actually doesn't display what I want with the shortcodes etc. Say I have the following on the page in Wordpress:
```
[frame_left]<img src="http://www.website.com/wp-content/uploads/2011/10/pic.jpg" alt="" width="300" height="240" />[/frame_left]
<h2 style="margin: 25px 0 0 0;">Person</h2>
<span class="small"><em>Title</em></span>
<p style="text-align: justify;">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris lacinia justo quis neque dapibus porta...</p>
[button link="http://www.google.com" text="Read More"]
[clear]
```
The following is what actually gets returned from my AJAX request:
```
[frame_left][/frame_left] Title Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris lacinia justo quis neque dapibus porta...[button link="http://www.google.com" text="Read More"] [clear]
```
Is there a way to actually return a page's content through Wordpress and have it display the shortcodes, html etc correctly??
Thanks for any help you can shed on this situation!! | 2012/03/15 | [
"https://Stackoverflow.com/questions/9712606",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1048676/"
] | I had the same problem. In my case it turned out I had installed another version of the sdk alongside the version provided by Android Studio. Changing my ANDROID\_SDK\_ROOT environment variable to the original value fixed it for me. | I installed Android SDK manager and Android SDK yestoday, and I get this error too when I tried to run the Android emulator immediately. But, right now this error disappear, I think restarting your system when the SDK has installed may solve this problem. |
9,712,606 | All,
I'm creating a side menu from a user defined menu in wordpress. I'm getting the menu options from the following code (since I know the menu id the user wants to display on the side):
```
$menu_items = wp_get_nav_menu_items($menu_id);
$menu_items = (array)$menu_items;
$output = '<div id="menu_options">';
$output .= '<ol class="tabs">';
foreach($menu_items as $menu){
$output .= '<li><a href="'.$menu->title.'" class="menu_page_id" id="'.$menu->ID.'">'.$menu->title.'</a></li>';
}
$output .= '</ol>';
$output .= '</div>';
$output .= '<div id="menu_content">This is content</div>';
$output .= '<input type="hidden" value="'.$menu_id.'" id="menu_id">';
return $output;
```
When a user clicks on one of the tabs I invoke an AJAX call to try and get the page content with the following code:
```
$('.menu_page_id').click(function(){
event.preventDefault();
page_id = $(this).attr("id");
menu_id = $('#menu_id').val();
action = "get_page_content";
$.post(ajaxurl, { page_id: page_id, menu_id: menu_id, action: action }, function(results) {
results = results.substring(0, results.length - 1);
$("#menu_content").hide();
$("#menu_content").html(results).fadeIn();
});
});
```
This calls the following function to return the content of the clicked page:
```
function get_page_content(){
$page_id = mysql_real_escape_string($_POST['page_id']);
$menu_id = mysql_real_escape_string($_POST['menu_id']);
$menu_items = wp_get_nav_menu_items($menu_id);
$menu_items = (array)$menu_items;
foreach($menu_items as $menu){
if($menu->ID == $page_id){
echo $menu->post_content;
}
}
}
add_action('wp_ajax_get_page_content', 'get_page_content');
add_action('wp_ajax_nopriv_get_page_content', 'get_page_content');
```
This all works good and it returns the page content except it just dumps the results out and actually doesn't display what I want with the shortcodes etc. Say I have the following on the page in Wordpress:
```
[frame_left]<img src="http://www.website.com/wp-content/uploads/2011/10/pic.jpg" alt="" width="300" height="240" />[/frame_left]
<h2 style="margin: 25px 0 0 0;">Person</h2>
<span class="small"><em>Title</em></span>
<p style="text-align: justify;">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris lacinia justo quis neque dapibus porta...</p>
[button link="http://www.google.com" text="Read More"]
[clear]
```
The following is what actually gets returned from my AJAX request:
```
[frame_left][/frame_left] Title Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris lacinia justo quis neque dapibus porta...[button link="http://www.google.com" text="Read More"] [clear]
```
Is there a way to actually return a page's content through Wordpress and have it display the shortcodes, html etc correctly??
Thanks for any help you can shed on this situation!! | 2012/03/15 | [
"https://Stackoverflow.com/questions/9712606",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1048676/"
] | Another reason you can get this error is that Eclipse can't find the correct file.
Check out where Eclipse is looking for your SDK files. You can do this on the command line. Below is an example for the windows command prompt for an avd I created and named 'SonyTabletS':
```none
c:\Program Files (x86)\Android\android-sdk\tools> emulator @SonyTabletS -verbose
```
The first line returned shows where eclipse is looking for the SDK files and will look something like:
```none
emulator: found ANDROID_SDK_ROOT: C:\Program Files (x86)\Android\android-sdk
```
Make sure that location is correct.
In my case, `ANDROID_SDK_ROOT` was initially set incorrectly to my home directory. This is because I set it that way by blindly following the Sony Tablet S SDK install instructions and adding an `ANDROID_SDK_ROOT` environment variable with the incorrect path. | Update the following commands in command prompt in windows:
1. `android update sdk --no-ui --all`
It update your SDK packages and it takes 3 minutes.
2. `android update sdk --no-ui --filter platform-tools,tools`
It updates the platform tools and its packages.
3. `android update sdk --no-ui --all --filter extra-android-m2repository`
Those who are working with maven project update this to support with latest support design library which will include extra maven android maven Repository.
1. In the command prompt it asks you for Y/N. Click on the Y then it proceeds with the installation.
2. It updates all Kernel-qemu files and qt5.dll commands. so that the Emulator works fine without any issues. |
9,712,606 | All,
I'm creating a side menu from a user defined menu in wordpress. I'm getting the menu options from the following code (since I know the menu id the user wants to display on the side):
```
$menu_items = wp_get_nav_menu_items($menu_id);
$menu_items = (array)$menu_items;
$output = '<div id="menu_options">';
$output .= '<ol class="tabs">';
foreach($menu_items as $menu){
$output .= '<li><a href="'.$menu->title.'" class="menu_page_id" id="'.$menu->ID.'">'.$menu->title.'</a></li>';
}
$output .= '</ol>';
$output .= '</div>';
$output .= '<div id="menu_content">This is content</div>';
$output .= '<input type="hidden" value="'.$menu_id.'" id="menu_id">';
return $output;
```
When a user clicks on one of the tabs I invoke an AJAX call to try and get the page content with the following code:
```
$('.menu_page_id').click(function(){
event.preventDefault();
page_id = $(this).attr("id");
menu_id = $('#menu_id').val();
action = "get_page_content";
$.post(ajaxurl, { page_id: page_id, menu_id: menu_id, action: action }, function(results) {
results = results.substring(0, results.length - 1);
$("#menu_content").hide();
$("#menu_content").html(results).fadeIn();
});
});
```
This calls the following function to return the content of the clicked page:
```
function get_page_content(){
$page_id = mysql_real_escape_string($_POST['page_id']);
$menu_id = mysql_real_escape_string($_POST['menu_id']);
$menu_items = wp_get_nav_menu_items($menu_id);
$menu_items = (array)$menu_items;
foreach($menu_items as $menu){
if($menu->ID == $page_id){
echo $menu->post_content;
}
}
}
add_action('wp_ajax_get_page_content', 'get_page_content');
add_action('wp_ajax_nopriv_get_page_content', 'get_page_content');
```
This all works good and it returns the page content except it just dumps the results out and actually doesn't display what I want with the shortcodes etc. Say I have the following on the page in Wordpress:
```
[frame_left]<img src="http://www.website.com/wp-content/uploads/2011/10/pic.jpg" alt="" width="300" height="240" />[/frame_left]
<h2 style="margin: 25px 0 0 0;">Person</h2>
<span class="small"><em>Title</em></span>
<p style="text-align: justify;">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris lacinia justo quis neque dapibus porta...</p>
[button link="http://www.google.com" text="Read More"]
[clear]
```
The following is what actually gets returned from my AJAX request:
```
[frame_left][/frame_left] Title Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris lacinia justo quis neque dapibus porta...[button link="http://www.google.com" text="Read More"] [clear]
```
Is there a way to actually return a page's content through Wordpress and have it display the shortcodes, html etc correctly??
Thanks for any help you can shed on this situation!! | 2012/03/15 | [
"https://Stackoverflow.com/questions/9712606",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1048676/"
] | I updated my android SDK to the latest version (API 19). When I tried to run the emulator with phonegap 3, the build was successful but it ran the same issue.
In the AVD manager there was an existent device, nevertheless, its parameters were all unknown. Surely this occurs because I uninstalled the old sdk version (API 17) that returns a second error while attempting to remove the device. With the message: "device is already running"
To solve the issue, I went to the AVD's location in ~/.android/avd/ and removed manually the device directory.avd and device.ini file. Finally, in the the device manager I created a new AVD provided by the newest API.
This allowed phonegap to build and run the emulator succesfully
I hope this helps
Good day | For me Updating the **SDK Tools** fixed the errors.
[](https://i.stack.imgur.com/zDrol.png) |
9,712,606 | All,
I'm creating a side menu from a user defined menu in wordpress. I'm getting the menu options from the following code (since I know the menu id the user wants to display on the side):
```
$menu_items = wp_get_nav_menu_items($menu_id);
$menu_items = (array)$menu_items;
$output = '<div id="menu_options">';
$output .= '<ol class="tabs">';
foreach($menu_items as $menu){
$output .= '<li><a href="'.$menu->title.'" class="menu_page_id" id="'.$menu->ID.'">'.$menu->title.'</a></li>';
}
$output .= '</ol>';
$output .= '</div>';
$output .= '<div id="menu_content">This is content</div>';
$output .= '<input type="hidden" value="'.$menu_id.'" id="menu_id">';
return $output;
```
When a user clicks on one of the tabs I invoke an AJAX call to try and get the page content with the following code:
```
$('.menu_page_id').click(function(){
event.preventDefault();
page_id = $(this).attr("id");
menu_id = $('#menu_id').val();
action = "get_page_content";
$.post(ajaxurl, { page_id: page_id, menu_id: menu_id, action: action }, function(results) {
results = results.substring(0, results.length - 1);
$("#menu_content").hide();
$("#menu_content").html(results).fadeIn();
});
});
```
This calls the following function to return the content of the clicked page:
```
function get_page_content(){
$page_id = mysql_real_escape_string($_POST['page_id']);
$menu_id = mysql_real_escape_string($_POST['menu_id']);
$menu_items = wp_get_nav_menu_items($menu_id);
$menu_items = (array)$menu_items;
foreach($menu_items as $menu){
if($menu->ID == $page_id){
echo $menu->post_content;
}
}
}
add_action('wp_ajax_get_page_content', 'get_page_content');
add_action('wp_ajax_nopriv_get_page_content', 'get_page_content');
```
This all works good and it returns the page content except it just dumps the results out and actually doesn't display what I want with the shortcodes etc. Say I have the following on the page in Wordpress:
```
[frame_left]<img src="http://www.website.com/wp-content/uploads/2011/10/pic.jpg" alt="" width="300" height="240" />[/frame_left]
<h2 style="margin: 25px 0 0 0;">Person</h2>
<span class="small"><em>Title</em></span>
<p style="text-align: justify;">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris lacinia justo quis neque dapibus porta...</p>
[button link="http://www.google.com" text="Read More"]
[clear]
```
The following is what actually gets returned from my AJAX request:
```
[frame_left][/frame_left] Title Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris lacinia justo quis neque dapibus porta...[button link="http://www.google.com" text="Read More"] [clear]
```
Is there a way to actually return a page's content through Wordpress and have it display the shortcodes, html etc correctly??
Thanks for any help you can shed on this situation!! | 2012/03/15 | [
"https://Stackoverflow.com/questions/9712606",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1048676/"
] | Here's my story. Under 'Actions' on the AVD manager, I viewed the details for the AVD which wasn't working. Scrolling down, I found the line:
```
image.sysdir.1: add-ons\addon-google_apis-google-16\images\armeabi-v7a\
```
I then navigated to this file at:
```
C:\Users\XXXX\AppData\Local\Android\sdk\add-ons\addon-google_apis-google-16\images\armeabi-v7a
```
I found there was no kernel file. However, I did find a kernel file at:
```
C:\Users\XXXX\AppData\Local\Android\sdk\system-images\android-16\default\armeabi-v7a
```
So I copied it and pasted back into:
```
C:\Users\XXXX\AppData\Local\Android\sdk\add-ons\addon-google_apis-google-16\images\armeabi-v7a
```
The AVD then worked. | Open AVD Manager in Administrator mode
Select VM and click edit, click OK
Start VM.
**Editor's note**: By administrator mode, he meant Right-click > Run as administrator on windows platforms . |
9,712,606 | All,
I'm creating a side menu from a user defined menu in wordpress. I'm getting the menu options from the following code (since I know the menu id the user wants to display on the side):
```
$menu_items = wp_get_nav_menu_items($menu_id);
$menu_items = (array)$menu_items;
$output = '<div id="menu_options">';
$output .= '<ol class="tabs">';
foreach($menu_items as $menu){
$output .= '<li><a href="'.$menu->title.'" class="menu_page_id" id="'.$menu->ID.'">'.$menu->title.'</a></li>';
}
$output .= '</ol>';
$output .= '</div>';
$output .= '<div id="menu_content">This is content</div>';
$output .= '<input type="hidden" value="'.$menu_id.'" id="menu_id">';
return $output;
```
When a user clicks on one of the tabs I invoke an AJAX call to try and get the page content with the following code:
```
$('.menu_page_id').click(function(){
event.preventDefault();
page_id = $(this).attr("id");
menu_id = $('#menu_id').val();
action = "get_page_content";
$.post(ajaxurl, { page_id: page_id, menu_id: menu_id, action: action }, function(results) {
results = results.substring(0, results.length - 1);
$("#menu_content").hide();
$("#menu_content").html(results).fadeIn();
});
});
```
This calls the following function to return the content of the clicked page:
```
function get_page_content(){
$page_id = mysql_real_escape_string($_POST['page_id']);
$menu_id = mysql_real_escape_string($_POST['menu_id']);
$menu_items = wp_get_nav_menu_items($menu_id);
$menu_items = (array)$menu_items;
foreach($menu_items as $menu){
if($menu->ID == $page_id){
echo $menu->post_content;
}
}
}
add_action('wp_ajax_get_page_content', 'get_page_content');
add_action('wp_ajax_nopriv_get_page_content', 'get_page_content');
```
This all works good and it returns the page content except it just dumps the results out and actually doesn't display what I want with the shortcodes etc. Say I have the following on the page in Wordpress:
```
[frame_left]<img src="http://www.website.com/wp-content/uploads/2011/10/pic.jpg" alt="" width="300" height="240" />[/frame_left]
<h2 style="margin: 25px 0 0 0;">Person</h2>
<span class="small"><em>Title</em></span>
<p style="text-align: justify;">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris lacinia justo quis neque dapibus porta...</p>
[button link="http://www.google.com" text="Read More"]
[clear]
```
The following is what actually gets returned from my AJAX request:
```
[frame_left][/frame_left] Title Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris lacinia justo quis neque dapibus porta...[button link="http://www.google.com" text="Read More"] [clear]
```
Is there a way to actually return a page's content through Wordpress and have it display the shortcodes, html etc correctly??
Thanks for any help you can shed on this situation!! | 2012/03/15 | [
"https://Stackoverflow.com/questions/9712606",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1048676/"
] | My story, Eclipse wanted a file called "`kernel-ranchu`" in the system image folder ( `/path/to/android-sdk-macosx/system-images/android-25/google_apis/arm64-v8a` ).
>
> emulator: ERROR: This AVD's configuration is missing a kernel file!
> Please ensure the file "kernel-ranchu" is in the same location as your
> system image.
>
>
> emulator: ERROR: ANDROID\_SDK\_ROOT is undefined
>
>
>
In that system image folder there was a file called "`kernel-qemu`". I just renamed it as "`kernel-ranchu`" and it worked... | Following the accepted answer by ChrLipp using Android Studio 1.2.2 in Ubuntu 14.04:
* Install "ARM EABI v7a System Image" package from Android SDK manager.
* Delete the non functional Virtual Device.
* Add a new device with Application Binary Interface(ABI) as armeabi-v7a.
* Boot into the new device.
This worked for me. Try rebooting your system if it is not working for you. |
9,712,606 | All,
I'm creating a side menu from a user defined menu in wordpress. I'm getting the menu options from the following code (since I know the menu id the user wants to display on the side):
```
$menu_items = wp_get_nav_menu_items($menu_id);
$menu_items = (array)$menu_items;
$output = '<div id="menu_options">';
$output .= '<ol class="tabs">';
foreach($menu_items as $menu){
$output .= '<li><a href="'.$menu->title.'" class="menu_page_id" id="'.$menu->ID.'">'.$menu->title.'</a></li>';
}
$output .= '</ol>';
$output .= '</div>';
$output .= '<div id="menu_content">This is content</div>';
$output .= '<input type="hidden" value="'.$menu_id.'" id="menu_id">';
return $output;
```
When a user clicks on one of the tabs I invoke an AJAX call to try and get the page content with the following code:
```
$('.menu_page_id').click(function(){
event.preventDefault();
page_id = $(this).attr("id");
menu_id = $('#menu_id').val();
action = "get_page_content";
$.post(ajaxurl, { page_id: page_id, menu_id: menu_id, action: action }, function(results) {
results = results.substring(0, results.length - 1);
$("#menu_content").hide();
$("#menu_content").html(results).fadeIn();
});
});
```
This calls the following function to return the content of the clicked page:
```
function get_page_content(){
$page_id = mysql_real_escape_string($_POST['page_id']);
$menu_id = mysql_real_escape_string($_POST['menu_id']);
$menu_items = wp_get_nav_menu_items($menu_id);
$menu_items = (array)$menu_items;
foreach($menu_items as $menu){
if($menu->ID == $page_id){
echo $menu->post_content;
}
}
}
add_action('wp_ajax_get_page_content', 'get_page_content');
add_action('wp_ajax_nopriv_get_page_content', 'get_page_content');
```
This all works good and it returns the page content except it just dumps the results out and actually doesn't display what I want with the shortcodes etc. Say I have the following on the page in Wordpress:
```
[frame_left]<img src="http://www.website.com/wp-content/uploads/2011/10/pic.jpg" alt="" width="300" height="240" />[/frame_left]
<h2 style="margin: 25px 0 0 0;">Person</h2>
<span class="small"><em>Title</em></span>
<p style="text-align: justify;">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris lacinia justo quis neque dapibus porta...</p>
[button link="http://www.google.com" text="Read More"]
[clear]
```
The following is what actually gets returned from my AJAX request:
```
[frame_left][/frame_left] Title Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris lacinia justo quis neque dapibus porta...[button link="http://www.google.com" text="Read More"] [clear]
```
Is there a way to actually return a page's content through Wordpress and have it display the shortcodes, html etc correctly??
Thanks for any help you can shed on this situation!! | 2012/03/15 | [
"https://Stackoverflow.com/questions/9712606",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1048676/"
] | The "ARM EABI v7a System Image" must be available. Install it via the Android SDK manager:

Another hint (see [here](https://plus.google.com/u/0/108967384991768947849/posts/DSi3oAuNnS7)) - with
* Android SDK Tools rev 17 or higher
* Android 4.0.3 (API Level 15)
* using SDK rev 3 and System Image rev 2 (or higher)
you are able to turn on GPU emulation to get a faster emulator:

**Note :** As per you786 comment if you have previously created emulator then you need to recreate it, otherwise this will not work.
**Alternative 1**
Intel provides the "[Intel hardware accelerated execution manager](http://software.intel.com/en-us/articles/intel-hardware-accelerated-execution-manager/)", which is a VM based emulator for executing X86 images and which is also served by the Android SDK Manager. See a tutorial for the Intel emulator here: [HAXM Speeds Up the Android Emulator](http://www.developer.com/ws/android/development-tools/haxm-speeds-up-the-android-emulator.html). Roman Nurik posts [here](https://plus.google.com/u/0/+RomanNurik/posts/iU5caAe7C6f) that the Intel emulator with Android 4.3 is "blazing fast".
**Alternative 2**
In the comments of the post above you can find a reference to [Genymotion](http://www.genymotion.com/) which claims to be the "fastest Android emulator for app testing and presentation". Genymotion runs on VirtualBox. See also their site on [Google+](https://plus.google.com/111561249038747241670/posts), this [post](http://cyrilmottier.com/2013/06/27/a-productive-android-development-environment/) from Cyril Mottier and this guide on [reddit](https://www.reddit.com/r/bravefrontier/comments/2jzo6y/guide_using_genymotion_the_correct_way_without/).
**Alternative 3**
In XDA-Forums I read about [MEmu - Most Powerful Android Emulator for PC, Better Than Bluestacks](http://forum.xda-developers.com/android/apps-games/memu-powerful-android-emulator-to-play-t3157906). You can find the emulator [here](http://www.xyaz.cn/en/). This brings me to ...
**Alternative 4**
... this XDA-Forum entry: [How to use THE FAST! BlueStack as your alternate Android development emulator](http://forum.xda-developers.com/showthread.php?t=1303563). You can find the emulator [here](http://www.bluestacks.com/). | My story, Eclipse wanted a file called "`kernel-ranchu`" in the system image folder ( `/path/to/android-sdk-macosx/system-images/android-25/google_apis/arm64-v8a` ).
>
> emulator: ERROR: This AVD's configuration is missing a kernel file!
> Please ensure the file "kernel-ranchu" is in the same location as your
> system image.
>
>
> emulator: ERROR: ANDROID\_SDK\_ROOT is undefined
>
>
>
In that system image folder there was a file called "`kernel-qemu`". I just renamed it as "`kernel-ranchu`" and it worked... |
9,712,606 | All,
I'm creating a side menu from a user defined menu in wordpress. I'm getting the menu options from the following code (since I know the menu id the user wants to display on the side):
```
$menu_items = wp_get_nav_menu_items($menu_id);
$menu_items = (array)$menu_items;
$output = '<div id="menu_options">';
$output .= '<ol class="tabs">';
foreach($menu_items as $menu){
$output .= '<li><a href="'.$menu->title.'" class="menu_page_id" id="'.$menu->ID.'">'.$menu->title.'</a></li>';
}
$output .= '</ol>';
$output .= '</div>';
$output .= '<div id="menu_content">This is content</div>';
$output .= '<input type="hidden" value="'.$menu_id.'" id="menu_id">';
return $output;
```
When a user clicks on one of the tabs I invoke an AJAX call to try and get the page content with the following code:
```
$('.menu_page_id').click(function(){
event.preventDefault();
page_id = $(this).attr("id");
menu_id = $('#menu_id').val();
action = "get_page_content";
$.post(ajaxurl, { page_id: page_id, menu_id: menu_id, action: action }, function(results) {
results = results.substring(0, results.length - 1);
$("#menu_content").hide();
$("#menu_content").html(results).fadeIn();
});
});
```
This calls the following function to return the content of the clicked page:
```
function get_page_content(){
$page_id = mysql_real_escape_string($_POST['page_id']);
$menu_id = mysql_real_escape_string($_POST['menu_id']);
$menu_items = wp_get_nav_menu_items($menu_id);
$menu_items = (array)$menu_items;
foreach($menu_items as $menu){
if($menu->ID == $page_id){
echo $menu->post_content;
}
}
}
add_action('wp_ajax_get_page_content', 'get_page_content');
add_action('wp_ajax_nopriv_get_page_content', 'get_page_content');
```
This all works good and it returns the page content except it just dumps the results out and actually doesn't display what I want with the shortcodes etc. Say I have the following on the page in Wordpress:
```
[frame_left]<img src="http://www.website.com/wp-content/uploads/2011/10/pic.jpg" alt="" width="300" height="240" />[/frame_left]
<h2 style="margin: 25px 0 0 0;">Person</h2>
<span class="small"><em>Title</em></span>
<p style="text-align: justify;">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris lacinia justo quis neque dapibus porta...</p>
[button link="http://www.google.com" text="Read More"]
[clear]
```
The following is what actually gets returned from my AJAX request:
```
[frame_left][/frame_left] Title Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris lacinia justo quis neque dapibus porta...[button link="http://www.google.com" text="Read More"] [clear]
```
Is there a way to actually return a page's content through Wordpress and have it display the shortcodes, html etc correctly??
Thanks for any help you can shed on this situation!! | 2012/03/15 | [
"https://Stackoverflow.com/questions/9712606",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1048676/"
] | My story, Eclipse wanted a file called "`kernel-ranchu`" in the system image folder ( `/path/to/android-sdk-macosx/system-images/android-25/google_apis/arm64-v8a` ).
>
> emulator: ERROR: This AVD's configuration is missing a kernel file!
> Please ensure the file "kernel-ranchu" is in the same location as your
> system image.
>
>
> emulator: ERROR: ANDROID\_SDK\_ROOT is undefined
>
>
>
In that system image folder there was a file called "`kernel-qemu`". I just renamed it as "`kernel-ranchu`" and it worked... | For me Updating the **SDK Tools** fixed the errors.
[](https://i.stack.imgur.com/zDrol.png) |
9,712,606 | All,
I'm creating a side menu from a user defined menu in wordpress. I'm getting the menu options from the following code (since I know the menu id the user wants to display on the side):
```
$menu_items = wp_get_nav_menu_items($menu_id);
$menu_items = (array)$menu_items;
$output = '<div id="menu_options">';
$output .= '<ol class="tabs">';
foreach($menu_items as $menu){
$output .= '<li><a href="'.$menu->title.'" class="menu_page_id" id="'.$menu->ID.'">'.$menu->title.'</a></li>';
}
$output .= '</ol>';
$output .= '</div>';
$output .= '<div id="menu_content">This is content</div>';
$output .= '<input type="hidden" value="'.$menu_id.'" id="menu_id">';
return $output;
```
When a user clicks on one of the tabs I invoke an AJAX call to try and get the page content with the following code:
```
$('.menu_page_id').click(function(){
event.preventDefault();
page_id = $(this).attr("id");
menu_id = $('#menu_id').val();
action = "get_page_content";
$.post(ajaxurl, { page_id: page_id, menu_id: menu_id, action: action }, function(results) {
results = results.substring(0, results.length - 1);
$("#menu_content").hide();
$("#menu_content").html(results).fadeIn();
});
});
```
This calls the following function to return the content of the clicked page:
```
function get_page_content(){
$page_id = mysql_real_escape_string($_POST['page_id']);
$menu_id = mysql_real_escape_string($_POST['menu_id']);
$menu_items = wp_get_nav_menu_items($menu_id);
$menu_items = (array)$menu_items;
foreach($menu_items as $menu){
if($menu->ID == $page_id){
echo $menu->post_content;
}
}
}
add_action('wp_ajax_get_page_content', 'get_page_content');
add_action('wp_ajax_nopriv_get_page_content', 'get_page_content');
```
This all works good and it returns the page content except it just dumps the results out and actually doesn't display what I want with the shortcodes etc. Say I have the following on the page in Wordpress:
```
[frame_left]<img src="http://www.website.com/wp-content/uploads/2011/10/pic.jpg" alt="" width="300" height="240" />[/frame_left]
<h2 style="margin: 25px 0 0 0;">Person</h2>
<span class="small"><em>Title</em></span>
<p style="text-align: justify;">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris lacinia justo quis neque dapibus porta...</p>
[button link="http://www.google.com" text="Read More"]
[clear]
```
The following is what actually gets returned from my AJAX request:
```
[frame_left][/frame_left] Title Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris lacinia justo quis neque dapibus porta...[button link="http://www.google.com" text="Read More"] [clear]
```
Is there a way to actually return a page's content through Wordpress and have it display the shortcodes, html etc correctly??
Thanks for any help you can shed on this situation!! | 2012/03/15 | [
"https://Stackoverflow.com/questions/9712606",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1048676/"
] | Open AVD Manager in Administrator mode
Select VM and click edit, click OK
Start VM.
**Editor's note**: By administrator mode, he meant Right-click > Run as administrator on windows platforms . | Just wanted to share my experience on this problem. Consulting each of the answers here, it didn't match my situation. Having a system image for Android API 22 causes this error and the weird thing is that all of the environment variables pointing to the correct directories. It doesn't make sense.
@BuvinJ answer had shed some light into the problem. I did check on the path describe on his answer and yes my copy of system image resides under the subfolder default when I look on the user directory (on Windows).
The weird thing is, there is also an android-sdk folder in the ANDROID\_SDK\_ROOT so I thought maybe Eclipse is looking there. Digging through the subfolders I figured out that the directory looks like this:
```
android-sdk-windows\system-images\android-22\google_apis\armeabi-v7a
```
This directory resides on the ANDROID\_SDK\_ROOT. There is also another one residing at the user directory user/XXXX/android-sdk/.
Eclipse is expecting it here:
```
android-sdk-windows\system-images\android-22\default\armeabi-v7a
```
Just changed the directory as such and it works now. |
9,712,606 | All,
I'm creating a side menu from a user defined menu in wordpress. I'm getting the menu options from the following code (since I know the menu id the user wants to display on the side):
```
$menu_items = wp_get_nav_menu_items($menu_id);
$menu_items = (array)$menu_items;
$output = '<div id="menu_options">';
$output .= '<ol class="tabs">';
foreach($menu_items as $menu){
$output .= '<li><a href="'.$menu->title.'" class="menu_page_id" id="'.$menu->ID.'">'.$menu->title.'</a></li>';
}
$output .= '</ol>';
$output .= '</div>';
$output .= '<div id="menu_content">This is content</div>';
$output .= '<input type="hidden" value="'.$menu_id.'" id="menu_id">';
return $output;
```
When a user clicks on one of the tabs I invoke an AJAX call to try and get the page content with the following code:
```
$('.menu_page_id').click(function(){
event.preventDefault();
page_id = $(this).attr("id");
menu_id = $('#menu_id').val();
action = "get_page_content";
$.post(ajaxurl, { page_id: page_id, menu_id: menu_id, action: action }, function(results) {
results = results.substring(0, results.length - 1);
$("#menu_content").hide();
$("#menu_content").html(results).fadeIn();
});
});
```
This calls the following function to return the content of the clicked page:
```
function get_page_content(){
$page_id = mysql_real_escape_string($_POST['page_id']);
$menu_id = mysql_real_escape_string($_POST['menu_id']);
$menu_items = wp_get_nav_menu_items($menu_id);
$menu_items = (array)$menu_items;
foreach($menu_items as $menu){
if($menu->ID == $page_id){
echo $menu->post_content;
}
}
}
add_action('wp_ajax_get_page_content', 'get_page_content');
add_action('wp_ajax_nopriv_get_page_content', 'get_page_content');
```
This all works good and it returns the page content except it just dumps the results out and actually doesn't display what I want with the shortcodes etc. Say I have the following on the page in Wordpress:
```
[frame_left]<img src="http://www.website.com/wp-content/uploads/2011/10/pic.jpg" alt="" width="300" height="240" />[/frame_left]
<h2 style="margin: 25px 0 0 0;">Person</h2>
<span class="small"><em>Title</em></span>
<p style="text-align: justify;">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris lacinia justo quis neque dapibus porta...</p>
[button link="http://www.google.com" text="Read More"]
[clear]
```
The following is what actually gets returned from my AJAX request:
```
[frame_left][/frame_left] Title Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris lacinia justo quis neque dapibus porta...[button link="http://www.google.com" text="Read More"] [clear]
```
Is there a way to actually return a page's content through Wordpress and have it display the shortcodes, html etc correctly??
Thanks for any help you can shed on this situation!! | 2012/03/15 | [
"https://Stackoverflow.com/questions/9712606",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1048676/"
] | If you know the kernel file is installed on your machine, then problem is getting emulator.exe to find it.
My fix was based on the post by user2789389. I could launch the AVD from the AVD Manager, but not from the command line. So, using AVD Manager, I selected the avd I wanted to run and clicked "Details". That showed me the path to the avd definition file. Within a folder of the same name, next to this .avd file, I found a config.ini file. In the ini, I found the following line:
```
image.sysdir.1=system-images\android-19\default\armeabi-v7a\
```
I looked in the folder C:\Users\XXXX\android-sdks\system-images\android-19, and found that the image.sysdir.1 path was invalid. I had to remove the "default" sub folder, thus changing it to the following:
```
image.sysdir.1=system-images\android-19\armeabi-v7a\
```
I saved the ini and tried again to launch the AVD. That fixed the problem! | I tried what ChrLipp suggested, but that wasn't the problem, as the image was already installed. What I did was run:
```
android avd
```
to start the emulator manually. Then I stopped the emulator, and form that point on the
```
cca emulate android
```
app started working, without the "missing a kernel file" error. |
22,768,353 | So I'm new to powershell. I've built a few scripts for fun but got stuck on one that I don't seem to be able to figure out. I'm trying to automate the clicking of the "Continue" button but don't know what to do. I have tried everything I can think of. Any ideas?
```
$username='username'
$password='password'
$ie = New-Object -ComObject 'internetExplorer.Application'
$ie.Visible= $true
$ie.Navigate("https://www.ksl.com/public/member/signin?login_forward=%2F")
while ($ie.Busy -eq $true){Start-Sleep -seconds 1;}
$usernamefield = $ie.Document.getElementByID('memberemail')
$usernamefield.value = $username
$passwordfield = $ie.Document.getElementByID('memberpassword')
$passwordfield.value = $password
$Link=$ie.Document.getElementsByTagName("input") | where-object {$_.type -eq "continue"}
$Link.click()
``` | 2014/03/31 | [
"https://Stackoverflow.com/questions/22768353",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3482032/"
] | The problem is that the object's Type is Image, not continue. The ClassName is continue. Try this line in that code and see if that works for you:
```
$Link=$ie.Document.getElementsByTagName("input") | where-object {$_.className -eq "continue"}
``` | Try
```
$ie.Document.getElementByID('dado_form_3').submit()
``` |
2,553,922 | This is what i want to do:
```
$line = 'blabla translate("test") blabla';
$line = preg_replace("/(.*?)translate\((.*?)\)(.*?)/","$1".translate("$2")."$3",$line);
```
So the result should be that translate("test") is replaced with the translation of "test".
The problem is that translate("$2") passes the string "$2" to the translate function. So translate() tries to translate "$2" instead of "test".
Is there some way to pass the value of the match to a function before replacing? | 2010/03/31 | [
"https://Stackoverflow.com/questions/2553922",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/136391/"
] | preg\_replace\_callback is your friend
```
function translate($m) {
$x = process $m[1];
return $x;
}
$line = preg_replace_callback("/translate\((.*?)\)/", 'translate', $line);
``` | You can use the preg\_replace\_callback function as:
```
$line = 'blabla translate("test") blabla';
$line = preg_replace_callback("/(.*?)translate\((.*?)\)(.*?)/",fun,$line);
function fun($matches) {
return $matches[1].translate($matches[2]).$matches[3];
}
``` |
68,046,767 | I'm new in python, please have a look on the code below
```
n = 5
m = 5
mat = [[0]*m]*n
print(mat)
i = 0
while(i < m):
mat[0][i] = i
i += 1
print(mat)
```
This code gives output like -
```
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
[[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]
```
In normal C program, this should give final output as-
```
[[0, 1, 2, 3, 4], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
```
And I want this output, but i cant get this, in loop I'm just accessing **0th row by mat[0][i]** but python changes all the rows. How am I supposed to get this output? And even if there is something I'm doing wrong then how during traversal it prints correct matrix? Please explain me how accessing the matrix differs in python? | 2021/06/19 | [
"https://Stackoverflow.com/questions/68046767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13275764/"
] | I have used SafetyNet API for accessing device's runtime env. I have kept signing certificate of app on server to verify its sha256 against what we get in the SafetyNet response. Below are the steps you can refer if applies to you too.
1. Get SHA256 fingerprint of signing X509Certificate
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] der = cert.getEncoded();
md.update(der);
byte[] **sha256** = md.digest();
2. Encode sha256 to base64 string
String **checksum** = Base64.getEncoder().encodeToString(**sha256**)
3. Match **checksum** with **apkCertificateDigestSha256** of SafetyNet response | I think this can help you
1.Find AttestationStatement file in GG example. and add this function:
```
public String bytesToHex(byte[] bytes) {
StringBuffer result = new StringBuffer();
for (byte b : bytes) result.append(Integer.toString((b & 0xff) + 0x100, 16).substring(1));
return result.toString();
}
```
2.Find getApkCertificateDigestSha256 function and edit like this:
```
public byte[][] getApkCertificateDigestSha256() {
byte[][] certs = new byte[apkCertificateDigestSha256.length][];
for (int i = 0; i < apkCertificateDigestSha256.length; i++) {
certs[i] = Base64.decodeBase64(apkCertificateDigestSha256[i]);
System.out.println(bytesToHex(certs[i]));
}
return certs;
}
```
3.Find process() function in OnlineVerrify and add like this:
```
if (stmt.getApkPackageName() != null && stmt.getApkDigestSha256() != null) {
System.out.println("APK package name: " + stmt.getApkPackageName());
System.out.println("APK digest SHA256: " + Arrays.toString(stmt.getApkDigestSha256()));
System.out.println("APK certificate digest SHA256: " +
Arrays.deepToString(stmt.getApkCertificateDigestSha256()));
}
```
4. Now, run and you'll see the SHA-256 and let compare.
Not: there is no ":" charactor bettwen sha-256 generated cause i'm lazy. ^^. |
68,046,767 | I'm new in python, please have a look on the code below
```
n = 5
m = 5
mat = [[0]*m]*n
print(mat)
i = 0
while(i < m):
mat[0][i] = i
i += 1
print(mat)
```
This code gives output like -
```
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
[[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]
```
In normal C program, this should give final output as-
```
[[0, 1, 2, 3, 4], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
```
And I want this output, but i cant get this, in loop I'm just accessing **0th row by mat[0][i]** but python changes all the rows. How am I supposed to get this output? And even if there is something I'm doing wrong then how during traversal it prints correct matrix? Please explain me how accessing the matrix differs in python? | 2021/06/19 | [
"https://Stackoverflow.com/questions/68046767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13275764/"
] | I have used SafetyNet API for accessing device's runtime env. I have kept signing certificate of app on server to verify its sha256 against what we get in the SafetyNet response. Below are the steps you can refer if applies to you too.
1. Get SHA256 fingerprint of signing X509Certificate
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] der = cert.getEncoded();
md.update(der);
byte[] **sha256** = md.digest();
2. Encode sha256 to base64 string
String **checksum** = Base64.getEncoder().encodeToString(**sha256**)
3. Match **checksum** with **apkCertificateDigestSha256** of SafetyNet response | Check the code here as reference on how to do the validations: <https://github.com/Gralls/SafetyNetSample/blob/master/Server/src/main/java/pl/patryk/springer/safetynet/Main.kt>
I just found it while searching for the same thing, and all credit goes to the person that owns the repo. |
68,046,767 | I'm new in python, please have a look on the code below
```
n = 5
m = 5
mat = [[0]*m]*n
print(mat)
i = 0
while(i < m):
mat[0][i] = i
i += 1
print(mat)
```
This code gives output like -
```
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
[[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]
```
In normal C program, this should give final output as-
```
[[0, 1, 2, 3, 4], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
```
And I want this output, but i cant get this, in loop I'm just accessing **0th row by mat[0][i]** but python changes all the rows. How am I supposed to get this output? And even if there is something I'm doing wrong then how during traversal it prints correct matrix? Please explain me how accessing the matrix differs in python? | 2021/06/19 | [
"https://Stackoverflow.com/questions/68046767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13275764/"
] | I have used SafetyNet API for accessing device's runtime env. I have kept signing certificate of app on server to verify its sha256 against what we get in the SafetyNet response. Below are the steps you can refer if applies to you too.
1. Get SHA256 fingerprint of signing X509Certificate
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] der = cert.getEncoded();
md.update(der);
byte[] **sha256** = md.digest();
2. Encode sha256 to base64 string
String **checksum** = Base64.getEncoder().encodeToString(**sha256**)
3. Match **checksum** with **apkCertificateDigestSha256** of SafetyNet response | ```
public class Starter {
static String keystore_location = "C:\\Users\\<your_user>\\.android\\debug.keystore";
private static final char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray();
public static String bytesToHex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = HEX_ARRAY[v >>> 4];
hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];
}
return new String(hexChars);
}
public static void main(String[] args) {
try {
File file = new File(keystore_location);
InputStream is = new FileInputStream(file);
KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
String password = "android"; // This is the default password
keystore.load(is, password.toCharArray());
Enumeration<String> enumeration = keystore.aliases();
while(enumeration.hasMoreElements()) {
String alias = enumeration.nextElement();
System.out.println("alias name: " + alias);
Certificate certificate = keystore.getCertificate(alias);
System.out.println(certificate.toString());
System.out.println(certificate.getEncoded());
final MessageDigest md = MessageDigest.getInstance("SHA-1");
final MessageDigest md2 = MessageDigest.getInstance("SHA-256");
final byte[] der = certificate.getEncoded();
md.update(der);
md2.update(der);
final byte[] digest = md.digest();
final byte[] digest2 = md2.digest();
System.out.println(bytesToHex(digest));
System.out.println(bytesToHex(digest2));
byte[] encoded = Base64.getEncoder().encode(digest2);
System.out.println(encoded);
String checksum = Base64.getEncoder().encodeToString(digest2);
System.out.println(checksum); // This should match apkCertificateDigestSha256
}
} catch (java.security.cert.CertificateException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.