qid int64 10 74.7M | question stringlengths 15 26.2k | date stringlengths 10 10 | metadata list | response_j stringlengths 27 28.1k | response_k stringlengths 23 26.8k |
|---|---|---|---|---|---|
31,289,037 | I am getting this error on two different Macs (iMac and Mac Book pro). No idea why people can't reproduce it but I need some help.

I am running **Xcode 7 beta 2** (23 June '15) on a Mac running **OS X Yosemite 10.10.4**.
Can't even compile and run my project..
I created a single view application project from the create menu, and that's it.
EDIT:
I tried to delete and re-add the storyboard file (also the Main.storyboard cannote be opened) and I still get the same message. This is the crash report:
```
Process: com.apple.CoreSimulator.CoreSimulatorService [2316]
Path: /Applications/Xcode-beta.app/Contents/Developer/Library/PrivateFrameworks/CoreSimulator.framework/Versions/A/XPCServices/com.apple.CoreSimulator.CoreSimulatorService.xpc/Contents/MacOS/com.apple.CoreSimulator.CoreSimulatorService
Identifier: com.apple.CoreSimulator.CoreSimulatorService
Version: ???
Code Type: X86-64 (Native)
Parent Process: ??? [1]
Responsible: com.apple.CoreSimulator.CoreSimulatorService [2316]
User ID: 489132888
Date/Time: 2015-07-08 11:47:46.022 +0100
OS Version: Mac OS X 10.10.4 (14E11f)
Report Version: 11
Anonymous UUID: --value--
Time Awake Since Boot: 7500 seconds
Crashed Thread: 0
Exception Type: EXC_BREAKPOINT (SIGTRAP)
Exception Codes: 0x0000000000000002, 0x0000000000000000
Application Specific Information:
dyld: launch, loading dependent libraries
Dyld Error Message:
Library not loaded: /usr/lib/libwep
Referenced from: /Applications/Xcode-beta.app/Contents/Developer/Library/PrivateFrameworks/CoreSimulator.framework/Versions/A/XPCServices/com.apple.CoreSimulator.CoreSimulatorService.xpc/Contents/MacOS/com.apple.CoreSimulator.CoreSimulatorService
Reason: no suitable image found. Did find:
/usr/lib/libwep: mmap() error 1 at address=0x105FB8000, size=0x00003000 segment=__TEXT in Segment::map() mapping /usr/lib/libwep
/usr/lib/libwep: mmap() error 1 at address=0x105FBF000, size=0x00003000 segment=__TEXT in Segment::map() mapping /usr/lib/libwep
Binary Images:
0x7fff6a06c000 - 0x7fff6a0a2837 dyld (353.2.1) <72A99D0F-0B56-3938-ABC5-67A0F33757C4> /usr/lib/dyld
0x7fff843dd000 - 0x7fff8470efff com.apple.Foundation (6.9 - 1153.20) <F0FF3A5D-C5B7-34A1-9319-DE1EF928E58E> /System/Library/Frameworks/Foundation.framework/Versions/C/Foundation
0x7fff89079000 - 0x7fff89411ff7 com.apple.CoreFoundation (6.9 - 1153.18) <5C0892B8-9691-341F-9279-CA3A74D59AA0> /System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation
0x7fff8944a000 - 0x7fff8944bff3 libSystem.B.dylib (1213) <17F6DDBE-8FDC-3DD5-8562-76618A81CFE6> /usr/lib/libSystem.B.dylib
0x7fff8d2f1000 - 0x7fff8d4eb46f libobjc.A.dylib (647) <759E155D-BC42-3D4E-869B-6F57D477177C> /usr/lib/libobjc.A.dylib
``` | 2015/07/08 | [
"https://Stackoverflow.com/questions/31289037",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/382788/"
] | This worked for me on El Capitan.
Go to
>
> /Library/Developer/CoreSimulator/Profiles/Runtimes
>
>
>
and remove the profiles in there.
Restart Xcode and it should work!
---
For Yosemite users try the following:
* Open up terminal
>
> cd Library
>
>
> cd Developer
>
>
> cd Devices
>
>
> rm -rf \*
>
>
>
Also, you can always type **ls** to list the files and directories. There may be another folder such as Profiles on your machine. Not sure since I only did this on my Yosemite machine that wasn't having issues.
Restart Xcode, clean, build etc.
Use sudo if there are any permission issues. | 1. Clean Project
2. Clean derived data
Wait for reindexing files |
12,424,469 | In the following code:
```
class A
{
A() {}
friend class B;
};
class B
{
public:
void foo() {A* p=new A;};
};
int main()
{
B b;
b.foo();
A* p = new A;
return 0;
}
```
The function `foo()` passes compilation, however the line `A* p = new A;` does not. How can this be? `new` is a global operator, thus it cannot call the private constructor, so why doesn't the compiler complain about `foo()` as well? | 2012/09/14 | [
"https://Stackoverflow.com/questions/12424469",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1622810/"
] | The operator new function does not call constructors. It just allocates the needed storage.
The constructor is called afterwards by compiler magic and is considered to be done by `foo` and `main` respectively. | A new-expression does two things:
* calls some overload of `operator new` to acquire some memory;
* constructs an object in that memory.
The construction happens in the context of the new-expression, not the call to `operator new`. Therefore, the constructor must be accessible in that context; so in your example, it is accessible in `B::foo` but not in `main`. |
577,623 | I'm currnetly trying to retrieve files from my AWS EC2 Linux server to my Windows 7 PC using `scp`
I'm a bit of a Linux newbie and from the server I'm currently trying things like:
```
scp transferMe.tar Username@publicIP/lanIP/C:/
```
But it doesn't seem to be going very well, I've also tried things like `tcp` comands, filezilla, and winSCP to retrieve these files, but they also hit stumbling blocks that I won't go into here.
I think that the way I'm trying to use the `scp` command is invalid. How should I structure the command? | 2013/04/03 | [
"https://superuser.com/questions/577623",
"https://superuser.com",
"https://superuser.com/users/213888/"
] | You have a couple of problems here. The first, as laurent pointed out is that `scp` does not work out of the box with Windows. You need to use specific software, for example [pscp](http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html) from the putty tools. Once you have installed it, you can run this command from the Windows command line:
```
pscp user@linux.server.com:/home/user/transferMe.tar C:\
```
The second problem is that even if you had an ssh server on your windows machine, copying from the server to the local computer would not have worked the way you are attempting it. You probably don't have access to your private IP from outside your home network, you need to configure your router to [forward](http://en.wikipedia.org/wiki/Port_forwarding) port 22 to the private IP of your computer. The details on how to do that depend on your router. So, even if you were trying to copy to another Linux machine, it would not have worked. You cannot use IPs like folder names, `public_ip/private_ip` is a reasonable assumption, but that's not how it works unfortunately. | As far as I know, scp doesn't work with windows. You need to use [winscp](http://winscp.net/eng/index.php) ([introduction to winscp](http://winscp.net/eng/docs/introduction)) or use [cygwin](http://www.cygwin.com/).
Is your local machine accessible from internet (public IP on the machine or port forwarding on the router conected to internet)? If not, it would be better to transfer the files using your local machine to issue the command as the ec2 machine is probably reachable from internet. |
4,622,808 | I have the below message (slightly changed):
>
> "Enter the competition by January 30, 2011 and you could win up to
> $$$$ — including amazing summer trips!"
>
>
>
I currently have:
```
<p style="font-size:14px; color:#538b01; font-weight:bold; font-style:italic;">
```
formatting the text string, but want to change the color of "January 30, 2011" to #FF0000 and "summer" to #0000A0.
How do I do this strictly with HTML or inline CSS? | 2011/01/07 | [
"https://Stackoverflow.com/questions/4622808",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/566463/"
] | You could use the HTML5 Tag `<mark>`:
```html
<p>Enter the competition by
<mark class="red">January 30, 2011</mark> and you could win up to $$$$ — including amazing
<mark class="blue">summer</mark> trips!</p>
```
And use this in the CSS:
```css
p {
font-size:14px;
color:#538b01;
font-weight:bold;
font-style:italic;
}
mark.red {
color:#ff0000;
background: none;
}
mark.blue {
color:#0000A0;
background: none;
}
```
The tag `<mark>` has a default background color... at least in Chrome. | ```
<p style="font-size:14px; color:#538b01; font-weight:bold; font-style:italic;">
Enter the competition by <span style="color:#FF0000">January 30, 2011</span> and you could win up to $$$$ — including amazing <span style="color:#0000A0">summer</span> trips!
</p>
```
The span elements are inline an thus don't break the flow of the paragraph, only style in between the tags. |
81,749 | I downloaded the Android app for my phone and set it up to move my pictures from the phone into UbuntuOne. When I go to the UbuntuOne web site the folder shows up and I can view the pictures after I download them.
But when I open the UbuntuOne folder on my laptop, the folder with the pictures from my phone isn't listed. How can I get the picture folder to show up in the UbuntuOne folder on my laptop? I was hoping this would be an easy way to get photos from phone to computer. | 2011/11/22 | [
"https://askubuntu.com/questions/81749",
"https://askubuntu.com",
"https://askubuntu.com/users/34924/"
] | When you're performing a normal search with Nautilus, it will search within the current folder and all subfolder for files with the search pattern in their names. You can limit the type of files you want by clicking on the '+' button once the search is started and adding a rule on the file type.
That's pretty much all you can do, I think. For advanced search, advanced users use the command line program `find` and other users don't have any solutions. | I discovered just by chance that, unlike what is stated in another answer, and despite what is *not* documented in Help (!!!), a space character in the search string does does not act as a wildcard but as an AND condition.
Example: "screen .png -4" will find filenames that contains all of the 3 "sceen", ".png" and "-4" strings.
I'm highly surprised that the Helps are (generally) so imprecise and that no Nautilus search special strings are used, and inserted by the "+" icon, to add special search conditions such as the much needed "not in subfolders" option. |
31,695 | I have seen in some screen-shots (can't remember where on the web) that the terminal can display the `[username@machine /]$` in bold letters. I'm looking forward to getting this too because I always find myself scrolling through long outputs to find out with difficulty the first line after my command.
How can I make the user name etc. bold or coloured? | 2012/02/14 | [
"https://unix.stackexchange.com/questions/31695",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/7892/"
] | You should be able to do this by setting the `PS1` prompt variable in your `~/.bashrc` file like this:
```
PS1='[\u@\h \w]\$ '
```
To make it colored (and possibly bold - this depends on whether your terminal emulator has enabled it) you need to add escape color codes:
```
PS1='\[\e[1;91m\][\u@\h \w]\$\[\e[0m\] '
```
Here, everything not being escaped between the `1;91m` and `0m` parts will be colored in the `1;91` color (bold red). Put these escape codes around different parts of the prompt to use different colors, but remember to reset the colors with `0m` or else you will have colored terminal output as well. Remember to source the file afterwards to update the current shell: `source ~/.bashrc` | This is the default prompt that you get in cygwin bash shell:
```
PS1='\[\e]0;\w\a\]\n\[\e[32m\]\u@\h \[\e[33m\]\w\[\e[0m\]\n\$ '
```

```
\[\e]0;\w\a\] = Set the Window title to your current working directory
\n = new line
\[\e[32m\] = Set text color to green
\u@\h = display username@hostname
\[\e[33m\] = Set text color to yellow
\w = display working directory
\[\e[0m\] = Reset text color to default
\n = new line
\$ = display $ prompt
```
References:
* See `man bash` and check the `PROMPTING` section.
* See [ANSI escape code - Wikipedia](http://en.wikipedia.org/wiki/ANSI_escape_code). |
35,118,148 | My Cron Setup is:
```
0 * * * * ruby /directory/to/ruby/file.rb
```
And I get this error:
```
/usr/lib64/ruby/1.9.3/rubygems/custom_require.rb:36:in `require': cannot load such file -- mechanize (LoadError)
from /usr/lib64/ruby/1.9.3/rubygems/custom_require.rb:36:in `require'
from /home4/ofixcom1/rails_apps/products.rb:3:in `<main>'
```
When I run that script on SSH it runs without a problem, but when I cron setup it gives me this error. I have read a lot of solutions. Even with RVM and I tried them almost all.
A previous cron with ruby was running smoothly I dont know why it is not working with mine.
I forgot to mention, on the JustHost help they have this link with examples for other codes:
[Cron Setup](https://my.justhost.com/cgi/help/168) | 2016/01/31 | [
"https://Stackoverflow.com/questions/35118148",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/789884/"
] | The key part of the error is the duplicated path:
`/Users/KerimCaglar/KerimCaglar/.ssh/id_rsa (Errno::ENOENT)`
Notice how the username is mentioned twice. I have found this to be caused by:
1. Specifying too much path in the Vagrantfile, e.g.
config.vm.provision "file", source: "**KerimCaglar**/.ssh/id\_rsa", destination: ".ssh/rd\_rsa"
2. You're invoking `vagrant up` from a subdirectory - `cd ..; vagrant up` will fix it. | If you've got Git installed, all you have to do is simply go generate your ssh key through the GUI. Help -> Show Key
 |
7,926,868 | I got the following code to generate a DLL :
```
public class QtObject : DependencyObject
{
public int speedSimu
{
get { return (int)GetValue(speedSimuProperty); }
set { SetValue(speedSimuProperty, value); }
}
public static readonly DependencyProperty speedSimuProperty =
DependencyProperty.Register("speedSimu", typeof(int), typeof(QtObject), new PropertyMetadata(0));
public int rpmSimu
{
get { return (int)GetValue(rpmSimuProperty); }
set { SetValue(rpmSimuProperty, value); }
}
public static readonly DependencyProperty rpmSimuProperty =
DependencyProperty.Register("rpmSimu", typeof(int), typeof(QtObject), new PropertyMetadata(0));
public int nbSimu;
}
public class Timer : DependencyObject
{
public string description
{
get { return (string)GetValue(descriptionProperty); }
set { SetValue(descriptionProperty, value); }
}
public static readonly DependencyProperty descriptionProperty =
DependencyProperty.Register("description", typeof(string), typeof(Timer), new PropertyMetadata("This is a time"));
public bool isActive
{
get { return (bool)GetValue(isActiveProperty); }
set { SetValue(isActiveProperty, value); }
}
public static readonly DependencyProperty isActiveProperty =
DependencyProperty.Register("isActive", typeof(bool), typeof(Timer), new PropertyMetadata(true));
}
public class AnotherClass
{
//blaaa
}
```
I now would like to ONLY get DependencyObject/Properties. (ie without property "nbSimu" and without object "AnotherClass")
Here is the code I have :
```
var library = Assembly.LoadFrom(libraryPath);
IEnumerable<Type> types = library.GetTypes();
var libs = types.Where(t => true);
foreach (Type type in libs)
{
foreach (PropertyInfo property in type.GetProperties())
{
//TODO
}
}
```
On the 3rd line I tried :
```
var libs = types.Where(t => t.BaseType == typeof(DependencyObject));
```
It doesn't say any error, but doesn't filter anything...
And about filtering the DependencyProperties, I just got no idead about how to do it...
Thanks in advance for any help on it, on both problems. | 2011/10/28 | [
"https://Stackoverflow.com/questions/7926868",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/946425/"
] | The ultimate goal of thread pools and Fork/Join are alike: Both want to utilize the available CPU power the best they can for maximum throughput. Maximum throughput means that as many tasks as possible should be completed in a long period of time. What is needed to do that? (For the following we will assume that there is no shortage of calculation tasks: There is always enough to do for 100% CPU utilisation. Additionally I use "CPU" equivalently for cores or virtual cores in case of hyper-threading).
1. At least there need to be as many threads running as there are CPUs available, because running less threads will leave a core unused.
2. At maximum there must be as many threads running as there are CPUs available, because running more threads will create additional load for the Scheduler who assigns CPUs to the different threads which causes some CPU time to go to the scheduler rather than our computational task.
Thus we figured out that for maximum throughput we need to have the exact same number of threads than CPUs. In Oracle's blurring example you can both take a fixed size thread pool with the number of threads equal to the number of available CPUs or use a thread pool. It won't make a difference, you are right!
**So when will you get into trouble with a thread pools? That is if a thread blocks**, because your thread is waiting for another task to complete. Assume the following example:
```java
class AbcAlgorithm implements Runnable {
public void run() {
Future<StepAResult> aFuture = threadPool.submit(new ATask());
StepBResult bResult = stepB();
StepAResult aResult = aFuture.get();
stepC(aResult, bResult);
}
}
```
What we see here is an algorithm that consists of three steps A, B and C. A and B can be performed independently of each other, but step C needs the result of step A AND B. What this algorithm does is submit task A to the threadpool and perform task b directly. After that the thread will wait for task A to be done as well and continue with step C. If A and B are completed at the same time, then everything is fine. But what if A takes longer than B? That may be because the nature of task A dictates it, but it may also be the case because there is not
thread for task A available in the beginning and task A needs to wait. (If there is only a single CPU available and thus your threadpool has only a single thread this will even cause a deadlock, but for now that is besides the point). The point is that the thread that just executed task B **blocks the whole thread**. Since we have the same number of threads as CPUs and one thread is blocked that means that **one CPU is idle**.
Fork/Join solves this problem: In the fork/join framework you'd write the same algorithm as follows:
```java
class AbcAlgorithm implements Runnable {
public void run() {
ATask aTask = new ATask());
aTask.fork();
StepBResult bResult = stepB();
StepAResult aResult = aTask.join();
stepC(aResult, bResult);
}
}
```
Looks the same, does it not? However the clue is that `aTask.join` **will not block**. Instead here is where **work-stealing** comes into play: The thread will look around for other tasks that have been forked in the past and will continue with those. First it checks whether the tasks it has forked itself have started processing. So if A has not been started by another thread yet, it will do A next, otherwise it will check the queue of other threads and steal their work. Once this other task of another thread has completed it will check whether A is completed now. If it is the above algorithm can call `stepC`. Otherwise it will look for yet another task to steal. Thus **fork/join pools can achieve 100% CPU utilisation, even in the face of blocking actions**.
However there is a trap: Work-stealing is only possible for the `join` call of `ForkJoinTask`s. It cannot be done for external blocking actions like waiting for another thread or waiting for an I/O action. So what about that, waiting for I/O to complete is a common task? In this case if we could add an additional thread to Fork/Join pool that will be stopped again as soon as the blocking action has completed will be the second best thing to do. And the `ForkJoinPool` can actually do just that if we are using `ManagedBlocker`s.
Fibonacci
=========
In the [JavaDoc for RecursiveTask](http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/RecursiveTask.html) is an example for calculating Fibonacci numbers using Fork/Join. For a classic recursive solution see:
```java
public static int fib(int n) {
if (n <= 1) {
return n;
}
return fib(n - 1) + fib(n - 2);
}
```
As is explained int the JavaDocs this is a pretty dump way to calculate fibonacci numbers, as this algorithm has O(2^n) complexity while simpler ways are possible. However this algorithm is very simple and easy to understand, so we stick with it. Let's assume we want to speed this up with Fork/Join. A naive implementation would look like this:
```java
class Fibonacci extends RecursiveTask<Long> {
private final long n;
Fibonacci(long n) {
this.n = n;
}
public Long compute() {
if (n <= 1) {
return n;
}
Fibonacci f1 = new Fibonacci(n - 1);
f1.fork();
Fibonacci f2 = new Fibonacci(n - 2);
return f2.compute() + f1.join();
}
}
```
The steps that this Task is split into are way too short and thus this will perform horribly, but you can see how the framework generally works very well: The two summands can be calculated independently, but then we need both of them to build the final result. So one half is done in an other thread. Have fun doing the same with thread pools without getting a deadlock (possible, but not nearly as simple).
Just for completeness: If you'd actually want to calculate Fibonacci numbers using this recursive approach here is an optimized version:
```java
class FibonacciBigSubtasks extends RecursiveTask<Long> {
private final long n;
FibonacciBigSubtasks(long n) {
this.n = n;
}
public Long compute() {
return fib(n);
}
private long fib(long n) {
if (n <= 1) {
return 1;
}
if (n > 10 && getSurplusQueuedTaskCount() < 2) {
final FibonacciBigSubtasks f1 = new FibonacciBigSubtasks(n - 1);
final FibonacciBigSubtasks f2 = new FibonacciBigSubtasks(n - 2);
f1.fork();
return f2.compute() + f1.join();
} else {
return fib(n - 1) + fib(n - 2);
}
}
}
```
This keeps the subtasks much smaller because they are only split when `n > 10 && getSurplusQueuedTaskCount() < 2` is true, which means that there are significantly more than 100 method calls to do (`n > 10`) and there are not very man tasks already waiting (`getSurplusQueuedTaskCount() < 2`).
On my computer (4 core (8 when counting Hyper-threading), Intel(R) Core(TM) i7-2720QM CPU @ 2.20GHz) the `fib(50)` takes 64 seconds with the classic approach and just 18 seconds with the Fork/Join approach which is quite a noticeable gain, although not as much as theoretically possible.
Summary
=======
* Yes, in your example Fork/Join has no advantage over classic thread pools.
* Fork/Join can drastically improve performance when blocking is involved
* Fork/Join circumvents some deadlock problems | Fork/join is different from a thread pool because it implements work stealing. From [Fork/Join](http://download.oracle.com/javase/tutorial/essential/concurrency/forkjoin.html)
>
> As with any ExecutorService, the fork/join framework distributes tasks
> to worker threads in a thread pool. The fork/join framework is
> distinct because it uses a work-stealing algorithm. Worker threads
> that run out of things to do can steal tasks from other threads that
> are still busy.
>
>
>
Say you have two threads, and 4 tasks a, b, c, d which take 1, 1, 5 and 6 seconds respectively. Initially, a and b are assigned to thread 1 and c and d to thread 2. In a thread pool, this would take 11 seconds. With fork/join, thread 1 finishes and can steal work from thread 2, so task d would end up being executed by thread 1. Thread 1 executes a, b and d, thread 2 just c. Overall time: 8 seconds, not 11.
EDIT: As Joonas points out, tasks are not necessarily pre-allocated to a thread. The idea of fork/join is that a thread can choose to split a task into multiple sub-pieces. So to restate the above:
We have two tasks (ab) and (cd) which take 2 and 11 seconds respectively. Thread 1 starts to execute ab and split it into two sub-tasks a & b. Similarly with thread 2, it splits into two sub-tasks c & d. When thread 1 has finished a & b, it can steal d from thread 2. |
60,233,448 | I have a schema where users have tags associated with them:
```
user_id: int4 tags: text[]
------------- ------------
1 [ 'apple', 'carrot', 'jelly' ]
2 [ 'jelly', 'zebra' ]
```
I am looking to create query that returns the list of all tags along with their associated counts. Example:
```
tag: text count: int4
--------- -----------
'apple' 1
'carrot' 1
'jelly' 2
'zebra' 1
```
Triggers seem to be the ideal way to do this, since the application is read-heavy and write-light.
However, I am having difficulty implementing this. The trigger itself seems simple enough I think:
```
CREATE TRIGGER tags_count_update
AFTER UPDATE OF tags ON person
FOR EACH ROW
EXECUTE PROCEDURE trigger_update_tags_count();
```
The `trigger_update_tags_count` is the part I'm having trouble with, because it seems to be a highly complex operation. For example, if the tag doesn't already exist in the `tags` table then it should be inserted with a count of 1.
Also, I believe you need to do some sort of diff operation, because if someone's tags are updated from `[ 'apple', 'carrot', 'jelly' ]` to `[ 'apple', 'dogs' ]` then `apple`'s count doesn't change, `carrot` and `jelly` is decremented by 1, and `dogs` is created with its count set to 1. This is compounded with the fact that tags are arrays. I currently have something like this:
```
CREATE OR REPLACE FUNCTION public.trigger_update_tags_count()
RETURNS trigger
LANGUAGE plpgsql
AS $function$
BEGIN
INSERT INTO tags (tag, count) VALUES (new.tag, 1)
ON CONFLICT (tag) DO UPDATE
SET count = CASE WHEN (tag.new AND NOT tag.old) THEN count + 1
WHEN (tag.old AND NOT tag.new) THEN count - 1
ELSE count
END
RETURN NEW;
END;
$function$;
```
Which is slightly pseudocode because I'm not sure how to integrate the fact that I'm dealing with text arrays, nor how to handle the diffing case. | 2020/02/14 | [
"https://Stackoverflow.com/questions/60233448",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/962155/"
] | You have nothing called `tag` in the data; it is `tags`. So you need to `UNNEST()` and to handle both old and new tags. I'm thinking something like:
```
INSERT INTO tags (tag, count)
SELECT COALESCE(ntag, otag),
(ntag IS NOT NULL)::int - (otag IS NOT NULL)::int
FROM UNNEST(new.tags) ntag FULL JOIN
UNNEST(old.tags) otag
ON ntag = otag
ON CONFLICT (tag) DO UPDATE
SET count = count + (excluded.ntag IS NOT NULL)::int - (excluded.otag IS NOT NULL)::int
``` | I was facing a similar problem so tried it by creating some dummy tables code as follows
```
CREATE TABLE public.test_tags(
tags_names text[],
id integer)
CREATE TABLE public.tag_counter(
tag_name text,
tag_count integer,
CONSTRAINT tag_counter_tag_name_key UNIQUE (tag_name))
create or replace function test_count() returns trigger as $func$
begin
INSERT INTO tag_counter(tag_name)
SELECT UNNEST(new.tags_names) ntag
except
select UNNEST(old.tags_names)
ON CONFLICT (tag_name) DO UPDATE
SET tag_count = tag_counter.tag_count + 1;
INSERT INTO tag_counter(tag_name)
SELECT UNNEST(old.tags_names) otag
except
select UNNEST(new.tags_names)
ON CONFLICT (tag_name) DO UPDATE
SET tag_count = tag_counter.tag_count - 1;
return new;
END;
$func$
LANGUAGE plpgsql;
create trigger test_update after update on test_tags for each row execute procedure test_count()
```
It's working fine but doesn't think its production-ready if possible can you share your code |
96,861 | I'm currently in my early days of learning about aviation, and have just started learning how to use a VFR chart. One thing that I have noticed is that the class D airspaces generally have frequencies to contact the controller for that airspace. Outside of CAS however, there is nothing. Do you just tune the FIS frequency? I understand that the airspace isn't really controlled, but can you still ask for Traffic Service etc? | 2023/01/11 | [
"https://aviation.stackexchange.com/questions/96861",
"https://aviation.stackexchange.com",
"https://aviation.stackexchange.com/users/67148/"
] | You want [CAP 774: UK Flight Information Services](https://publicapps.caa.co.uk/docs/33/CAP774_UK%20FIS_Edition%204.pdf). That document lists the air traffic services provided to aircraft in class G in the UK.
The services listed are:
Basic Service:
>
> A Basic Service is an ATS provided for the purpose of giving advice
> and information useful for the safe and efficient conduct of flights.
> This may include weather information, changes of serviceability of
> facilities, conditions at aerodromes, general airspace activity
> information, and any other information likely to affect safety. The
> avoidance of other traffic is solely the pilot’s responsibility.
>
>
>
Traffic Service:
>
> A Traffic Service is a surveillance based ATS, where in addition to
> the provisions of a Basic Service, the controller provides specific
> surveillance- derived traffic information to assist the pilot in
> avoiding other traffic. Controllers may provide headings and/or levels
> for the purposes of positioning and/or sequencing; however, the
> controller is not required to achieve deconfliction minima, and the
> pilot remains responsible for collision avoidance.
>
>
>
Deconfliction Service:
>
> A Deconfliction Service is a surveillance based ATS where, in addition
> to the provisions of a Basic Service, the controller provides specific
> surveillance- derived traffic information and issues headings and/or
> levels aimed at achieving planned deconfliction minima, or for
> positioning and/ or sequencing. However, the avoidance of other
> traffic is ultimately the pilot’s responsibility.
>
>
>
Procedural Service:
>
> A Procedural Service is an ATS where, in addition to the provisions of
> a Basic Service, the controller provides restrictions, instructions,
> and approach clearances, which if complied with, shall achieve
> deconfliction minima against other aircraft participating in the
> Procedural Service. Neither traffic information nor deconfliction
> advice can be passed with respect to unknown traffic
>
>
>
These aren't always available and you don't have to use them. A Basic Service will let an ATS provider know you are there & I've had warnings about unusual activity (police helos, helimeds or fast jets letting down in class G) but I pretty much expect to be ignored. Traffic services are great but are often withdrawn at busy times (when you most need them) due to controller overload!
Even if I'm not recieving a service, I'll usually listen in to the local frequencies just for situational awareness. Also, if you're passing close to an ATZ, it's good practice to let them know where you are and where you're going. | Class G is uncontrolled free airspace. You don’t have to talk to anyone if you don’t want to.
If there is a nearby radar facility then you could call them and ask for a service if you like but it’s not mandatory.
In my opinion the ability to just go flying without talking to anyone or filing anything is one of the advantages of the way UK airspace is organised. |
109,185 | American citizens can apply for a [passport card](https://travel.state.gov/content/travel/en/passports/apply-renew-passport/card.html) at the same time they apply for a passport book. There’s even a small discount when you do so.
I’ve heard, however, it’s better to apply for them separately because if you apply at the same time, both the book and the card will have the same number and if you lose one of them, the other becomes invalid when you report the loss. For example, this comment in this article below:
>
> One important trick... do not get your card at the same time as the passport book. If you do that they will both have the same number and if one is lost or stolen, the other immediately becomes invalid. If you get the card separately it will have its own distinct number and will remain valid even if your passport book is stolen. Comment on thread in [Elliot.org](http://www.elliott.org/case-dismissed-2/no-baby-cant-fly-mexico-without-a-passport/)
>
>
>
Is this really the case? This seems really another reason not to get the card — or at least not to get the card at the same time. | 2018/02/02 | [
"https://travel.stackexchange.com/questions/109185",
"https://travel.stackexchange.com",
"https://travel.stackexchange.com/users/17153/"
] | It’s wrong.
They have completely different numbers, and are unrelated; the pattern is also different.
Note that the ‘overlap’ technique for usage works very limited only, as the passport card is not valid for entry into the US except on the land borders. So if you are flying, you need a passport, or a Global Entry card (and they typically ask for a passport there too, but it should work without one). | I am not from the US but from a country (the Netherlands) where the citizens can get an ID card as well as a passport.
I have always applied at different dates, due to practical reasons, but would not want to apply for the two at the same time as for me the fact they have different expiry dates is very important.
When traveling within the region where the ID card is valid for border crossings, I am never without a valid document even when I fail to replace a document.
(Besides, due to the local laws, I should always carry on or the other when out of the house, having both I can take my passport when my ID card has to be renewed or is in the process of doing so.)
I think these points should work in the USA for the passport card (as long as the end date of validity is based on the date it is applied for and not on the date your passport expires) and the passport booklet. |
20,321 | How can I prevent someone from modifying the contents of an email they received and then forwarding it to others? Some employees cheat managers by changing the content of emails and forwarding the modified email to them. I need a policy that prevents this backdoor. | 2012/09/18 | [
"https://security.stackexchange.com/questions/20321",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/13196/"
] | Email is an insecure communication channel. The "to" and "from" headers can be set to anything. Anything can be written into the body of an email message. This includes changing the quote text.
The first issue of manipulating "to" and "from" headers can be prevented in a closed environment such as company internal mail. The company mail server can verify that the "from" header matches the account used to send the email. And it can verify that the visible "to" header matches the real recipient.
But there is no easy and reliable way to prevent manipulation of quoted text.
You could use [GPG](http://en.wikipedia.org/wiki/GNU_Privacy_Guard) / [PGP](http://en.wikipedia.org/wiki/Pretty_Good_Privacy) or [s/mime](http://en.wikipedia.org/wiki/S/MIME) signatures. But rolling out a public/private key infrastructure is usually not worth the costs.
Summary
-------
There is no simple technical solution. Use a social or legal approach ("Cheating a manager" sounds serious enough to warrant a talk with the human resources department). | Besides the very valid answer of having managers sign communications, referencing sources would be the other appropriate way of handling things. If there's a debate about the content of an email, the sent messages archive is the better reference for each party. If you have an email archiving system, then the server's copy of the message would be best.
At that point, we're back to the human element. If you forge an email and the server shows that you wrote something which wasn't really sent then you can forget about having a job.
One last comment on signing: a caveat with signing is that you'll run into issues where the message is signed, then altered, then sent. If the receiver doesn't verify every signature, then nothing would really be "valid." |
57,969,617 | I need some help I want to show my reactive tabPanel in a popup with the `shinyBS` package.
Everything seems to work well except the creation of popup.
I am inspired by :
1) [R Shiny - add tabPanel to tabsetPanel dynamically (with the use of renderUI)](https://stackoverflow.com/questions/19470426/r-shiny-add-tabpanel-to-tabsetpanel-dynamically-with-the-use-of-renderui?noredirect=1&lq=1)
2)[Show dataTableOutput in modal in shiny app](https://stackoverflow.com/questions/43748316/show-datatableoutput-in-modal-in-shiny-app)
My code :
```
library(shiny)
library(DT) # need datatables package
library(shinyBS)
ui <- shinyUI(fluidPage(
titlePanel("Example"),
sidebarLayout(
sidebarPanel(
selectInput("decision", label = "Choose your specie",
choices = iris$Species,
selected = "mtcars", multiple = TRUE)
),
mainPanel(
uiOutput('mytabs')
)
)
))
server <- shinyServer(function(input, output, session) {
output$mytabs <- renderUI({
nTabs = length(input$decision)
# create tabPanel with datatable in it
myTabs = lapply(seq_len(nTabs), function(i) {
tabPanel(paste0("dataset_", input$decision[i]),
tableOutput(paste0("datatable_",i))
)
})
do.call(tabsetPanel, myTabs)
})
# create datatables in popup ?
bsModal(
id = "modalExample",
"yb",
observe(
lapply(seq_len(length(input$decision)), function(i) {
output[[paste0("datatable_",i)]] <- renderTable({
as.data.frame(iris[iris$Species == input$decision[i], ])
})
})
)
)
})
shinyApp(ui, server)
```
Thanks in advance for any help ! | 2019/09/17 | [
"https://Stackoverflow.com/questions/57969617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3530895/"
] | `bsModal` is an UI element, so you need to put it into you UI. Within this modal you want to show the `tabPanels` (rendered via `uiOutput`), so all you need to do is to place your `bsModal` into the UI, and within this `bsModal` you have your `uiOutput`. All what is left is to add an `actionButton` which shows the modal.
```
library(shiny)
library(shinyBS)
ui <- shinyUI(fluidPage(
titlePanel("Example"),
sidebarLayout(
sidebarPanel(
selectInput("decision", label = "Choose your species",
choices = unique(iris$Species),
selected = unique(iris$Species), multiple = TRUE),
actionButton("show", "Show")
),
mainPanel(
bsModal("modalExample",
"myTitle",
"show",
uiOutput('mytabs')
)
)
)
))
server <- shinyServer(function(input, output, session) {
output$mytabs <- renderUI({
nTabs <- length(input$decision)
# create tabPanel with datatable in it
myTabs <- lapply(seq_len(nTabs), function(i) {
tabPanel(paste0("dataset_", input$decision[i]),
tableOutput(paste0("datatable_",i))
)
})
do.call(tabsetPanel, myTabs)
})
# create datatables in popup ?
observe(
lapply(seq_len(length(input$decision)), function(i) {
output[[paste0("datatable_",i)]] <- renderTable({
as.data.frame(iris[iris$Species == input$decision[i], ])
})
})
)
})
shinyApp(ui, server)
``` | It's not clear to me what you want to do (maybe @thothal has the right answer). What about this app ?
```
library(shiny)
library(DT) # need datatables package
library(shinyBS)
ui <- shinyUI(fluidPage(
titlePanel("Example"),
sidebarLayout(
sidebarPanel(
selectInput("decision", label = "Choose your specie",
choices = iris$Species,
selected = "mtcars", multiple = TRUE),
actionButton("trigger_modal", "View modal")
),
mainPanel(
uiOutput("modal")
# uiOutput('mytabs')
)
)
))
server <- shinyServer(function(input, output, session) {
# output$mytabs <- renderUI({
# nTabs = length(input$decision)
# # create tabPanel with datatable in it
# myTabs = lapply(seq_len(nTabs), function(i) {
# tabPanel(paste0("dataset_", input$decision[i]),
# tableOutput(paste0("datatable_",i))
# )
# })
#
# do.call(tabsetPanel, myTabs)
# })
# create datatables in popup ?
observe(
lapply(seq_len(length(input$decision)), function(i) {
output[[paste0("datatable_",i)]] <- renderTable({
as.data.frame(iris[iris$Species == input$decision[i], ])
})
})
)
output$modal <- renderUI({
bsModal(
id = "modalExample",
"yb",
trigger = "trigger_modal",
do.call(tagList, lapply(seq_along(input$decision), function(i){
tableOutput(paste0("datatable_",i))
}))
)
})
})
shinyApp(ui, server)
``` |
46,742,333 | I don't think my question duplicate with [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call)
In orther language(C#) i see, a variable declare
in a function or loop, When you out of function or loop they can't access variable has been declare in other function, but in javascript can.
```
$(document).ready(function () {
Text();
Tex2();
});
function Text() {
for (xxi = 0; xxi < 10; xxi++) {
console.log(xxi);
iix = 99;
}
console.log(xxi + iix);
Tex2();
}
function Tex2() {
console.log("What the hel:" + (xxi + iix));
}
```
The result is:
[](https://i.stack.imgur.com/FzCEN.png)
Is there anyone can explain detail for me? thanks. | 2017/10/14 | [
"https://Stackoverflow.com/questions/46742333",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8063048/"
] | You are declaring them as global variables without using `var` keyword. Use the `var` keyword to scope them to their intended scope or use `"use strict"` on top of javascript file. You can also use `let` keyword to scope them to their very local scope.
1. Variables declared not using [var and let keywords](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let%60) have global scope.
2. Variables declared using var keyword are treated by javascript as first statement inside their closed scope or function. So, it defines a variable globally, or locally to an entire function regardless of block scope.
3. let keyword allows to declare variables limited in scope to the block, statement, or expression on which it is used.
>
> I have created 3 snippets below. one with `let` keyword, one with `var` keyword, and one with `use strict` keyword over your code. Run to see changing behavior of same code piece.
>
>
>
**SNIPPETS BELOW**
>
> `let` keyword snippet. Run to see that variable is not available outside block scope even.
>
>
>
> ```js
> //let keyword snippet. See variable is not available outside block scope even.
>
> $(document).ready(function () {
> Text();
> Tex2();
> });
> function Text() {
> for (let xxi = 0; xxi < 10; xxi++) {
> console.log(xxi);
> let iix = 99;
> }
> var xyz;
> try
> {
> xyz = xxi + iix;
> }
> catch (e){
> xyz = e;
> }
> console.log(xyz);
> Tex2();
> }
> function Tex2() {
> var abc;
> try
> {
> abc = (xxi + iix);
> }
> catch (e){
> abc = e;
> }
> console.log("What the hel:" + abc);
> }
> ```
>
>
> ```html
> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
> ```
>
>
>
> `var` keyword snippet. Run to see that variable is not available outside function scope.
>
>
>
> ```js
> //var keyword snippet. See variable is not available outside function scope.
>
> $(document).ready(function () {
> Text();
> Tex2();
> });
> function Text() {
> for (var xxi = 0; xxi < 10; xxi++) {
> console.log(xxi);
> var iix = 99;
> }
> var xyz;
> try
> {
> xyz = xxi + iix;
> }
> catch (e){
> xyz = e;
> }
> console.log(xyz);
> Tex2();
> }
> function Tex2() {
> var abc;
> try
> {
> abc = (xxi + iix);
> }
> catch (e){
> abc = e;
> }
> console.log("What the hel:" + abc);
> }
> ```
>
>
> ```html
> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
> ```
>
>
>
>
>
>
>
>
> `use strict` keyword snippet. Run to see that it will not run at all. This is your code with use strict.
>
>
>
```js
//Your snippet with "use strict". Will not work at all.
"use strict"
$(document).ready(function () {
Text();
Tex2();
});
function Text() {
for (xxi = 0; xxi < 10; xxi++) {
console.log(xxi);
iix = 99;
}
console.log(xxi + iix);
Tex2();
}
function Tex2() {
console.log("What the hel:" + (xxi + iix));
}
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
``` | Any variable which is not declared inside a function, is treated as a window variable:
```
for (xxi = 0; xxi < 10; xxi++) {
console.log(xxi); // this variable
iix = 99; // this variable
}
```
If you had done this, javascript won't read the variable outside the scope:
```
for (var xxi = 0; xxi < 10; xxi++) {
console.log(xxi);
var iix = 99;
}
```
Explained (Let's understand using declarations instead of looking for errors):
```
var xxi = "one"; //global variable
var iix = "two"; //global variable
globalVar = "three"; // window variable i.e. window.globalVar
var getValues = function () {
var xxi; //local variable for the scope
var iix; //local variable for the scope
for (xxi = 0; xxi < 10; xxi++) {
console.log(xxi); // takes the local variable
iix = 99; //local change of value
}
globalVar = 100; //change of value to window variable accessible inside
};
getValues();
var seeValues = function () {
console.log(xxi); //"one" //Displays the value of global because the local variable of getValues() is not accessible outside
console.log(iix); //"two" //Same as above
console.log(globalVar); //100 and not "three" //Displays the altered window variable
};
seeValues();
```
See this link for detailed information: <http://www.dotnettricks.com/learn/javascript/understanding-local-and-global-variables-in-javascript> and [What's the difference between a global var and a window.variable in javascript?](https://stackoverflow.com/questions/6349232/whats-the-difference-between-a-global-var-and-a-window-variable-in-javascript) |
17,464,658 | I need calculate and set the height for some div (initial settings). When the height of the browser window is changed --> change the height for div.
How will be better to rewrite this code (I want do initial settings once and change it when window resize):
```
$(document).ready(function () {
var height = document.documentElement.clientHeight - 500;
if (height < 135) {
height = 135;
}
document.getElementById('left_space').style.height = height + 'px';
$(window).resize(function () {
var height = document.documentElement.clientHeight - 500;
if (height < 135)
{
height = 135;
}
document.getElementById('left_space').style.height = height + 'px';
});
});
``` | 2013/07/04 | [
"https://Stackoverflow.com/questions/17464658",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2299110/"
] | is that what you are looking for?
[api.jquery.com](http://api.jquery.com/resize/)
```
jQuery(document).ready(function () {
$(window).resize(function() {
var height = document.documentElement.clientHeight - 500;
if (height < 135) {
height = 135;
}
document.getElementById('left_space').style.height = height + 'px';
jQuery(window).resize(function () {
var height = document.documentElement.clientHeight - 500;
if (height < 135)
{
height = 135;
}
document.getElementById('left_space').style.height = height + 'px';
});
});
});
``` | I think jQuery(window).resize one would be good |
74,832 | I am trying to prove that there exists logspace deterministic Turing machine that check if exists path between first row and last row in grid graph. Grid graph is matrix of $0s$ and $1s$, the undirected edge exists between two $0s$ or $1s$ - one the left, right, up, down. Path can contains only $0s$ or only $1s$.
For example in following graph there exists such path:
```
0 0 1 0
0 0 1 1
0 0 0 1
0 0 0 1
```
For following there is no such path
```
0 0 0 0
1 1 1 1
0 0 0 0
1 1 1 1
```
How to prove it ? | 2017/05/02 | [
"https://cs.stackexchange.com/questions/74832",
"https://cs.stackexchange.com",
"https://cs.stackexchange.com/users/-1/"
] | I can't post a comment, which would be more appropriate:
Reingold's result gives a logspace algorithm, but reachability on undirected grid graphs was show to be in $L$ by Blum and Kozen about 30 years prior:
M. Blum and D. Kozen. [On the power of the compass (or,
why mazes are easier to search than graphs).](https://www.clear.rice.edu/comp651/papers/2015-01-Spring/04567972.pdf) In IEEE Symposium
on Foundations of Computer Science (FOCS), pages
132–142, 1978. | Your problem is an instance of [USTCON](https://en.wikipedia.org/wiki/SL_(complexity)), which is known to be solvable in log space, thanks to a result of Omer Reingold:
[Undirected connectivity in log-space](https://pdfs.semanticscholar.org/4b07/94ae3788df1851bdc4c7024764b99cd27f46.pdf). Omer Reingold. Journal of the ACM, vol 55 no 4, Sept 2008.
Thus, that paper describes how to build a logspace deterministic Turing machine that does what you want. |
1,980,012 | Since boost is forbidden in a company I work for I need to implement its functionality in pure C++. I've looked into boost sources but they seem to be too complex to understand, at least for me. I know there is something called `static_assert()` in the C++0x standart, but I'd like not to use any C++0x features. | 2009/12/30 | [
"https://Stackoverflow.com/questions/1980012",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/82625/"
] | One other trick (which can be used in C) is to try to build an array with a negative size if the assert fail:
```
#define ASSERT(cond) int foo[(cond) ? 1 : -1]
```
as a bonus, you may use a typedef instead of an object, so that it is usable in more contexts and doesn't takes place when it succeed:
```
#define ASSERT(cond) typedef int foo[(cond) ? 1 : -1]
```
finally, build a name with less chance of name clash (and reusable at least in different lines):
```
#define CAT_(a, b) a ## b
#define CAT(a, b) CAT_(a, b)
#define ASSERT(cond) typedef int CAT(AsSeRt, __LINE__)[(cond) ? 1 : -1]
``` | I am using the following header file, with code ripped from someone else...
```
#ifndef STATIC_ASSERT__H
#define STATIC_ASSERT__H
/* ripped from http://www.pixelbeat.org/programming/gcc/static_assert.html */
#define ASSERT_CONCAT_(a, b) a##b
#define ASSERT_CONCAT(a, b) ASSERT_CONCAT_(a, b)
/* These can't be used after statements in c89. */
#ifdef __COUNTER__
/* microsoft */
#define STATIC_ASSERT(e) enum { ASSERT_CONCAT(static_assert_, __COUNTER__) = 1/(!!(e)) }
#else
/* This can't be used twice on the same line so ensure if using in headers
* that the headers are not included twice (by wrapping in #ifndef...#endif)
* Note it doesn't cause an issue when used on same line of separate modules
* compiled with gcc -combine -fwhole-program. */
#define STATIC_ASSERT(e) enum { ASSERT_CONCAT(assert_line_, __LINE__) = 1/(!!(e)) }
#endif
/* http://msdn.microsoft.com/en-us/library/ms679289(VS.85).aspx */
#ifndef C_ASSERT
#define C_ASSERT(e) STATIC_ASSERT(e)
#endif
#endif
``` |
155,437 | How to get the placeholder image URL on my template file of product listing page? | 2017/01/19 | [
"https://magento.stackexchange.com/questions/155437",
"https://magento.stackexchange.com",
"https://magento.stackexchange.com/users/6123/"
] | ```
use \Magento\Store\Model\StoreManager $storeManager
$this->storeManager = $storeManager;
$path =
catalog/placeholder/thumbnail_placeholder OR
catalog/placeholder/swatch_image_placeholder OR
catalog/placeholder/small_image_placeholder OR
catalog/placeholder/image_placeholder OR
public function getConfig($config_path)
{
return $this->storeManager->getStore()->getConfig($config_path);
}
$mediaUrl = $this ->storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA );
<img src = $mediaUrl.'catalog/product/placeholder/'.$this->getConfig($path) />
```
On Magento 2.2:
* Get Helper in Block (phtml)
`$imageHelper = $this->helper(\Magento\Catalog\Helper\Image::class);`
* Get Helper Global
`$imageHelper = \Magento\Framework\App\ObjectManager::getInstance()->get(\Magento\Catalog\Helper\Image::class);`
* Get Placeholder Image Url. User as parameter: 'image', 'smal\_image', 'swatch\_image' or 'thumbnail'.
`$placeholderImageUrl = $imageHelper->getDefaultPlaceholderUrl('image');` | If you're trying to get it in any template file. You'll need Magento's image helper. `\Magento\Catalog\Helper\Image::class`
You can get an instance like this at the top of any .phtml file
```
$imageHelper = \Magento\Framework\App\ObjectManager::getInstance()->get(\Magento\Catalog\Helper\Image::class);
```
and get the path to the placeholder image url like this
```
$imageHelper->getDefaultPlaceholderUrl('small_image')
$imageHelper->getDefaultPlaceholderUrl('image')
``` |
1,662,600 | When I type this into the Visual Studio 2008 immediate window:
`? .9 - .8999999999999995`
It gives me this as the answer:
`0.00000000000000055511151231257827`
The documentation says that a double has 15-16 digits of precision, but it's giving me a result with 32 digits of precision. Where is all that extra precision coming from? | 2009/11/02 | [
"https://Stackoverflow.com/questions/1662600",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4228/"
] | You should read: [What Every Computer Scientist Should
Know About Floating-Point Arithmetic](http://www.google.com/url?sa=t&source=web&ct=res&cd=2&ved=0CBMQFjAB&url=http%3A%2F%2Fdlc.sun.com%2Fpdf%2F800-7895%2F800-7895.pdf&ei=pRjvSpucFNDKlAe5z7H_BA&usg=AFQjCNFqeDj_vhcrQrnZ_zytDsczXO85fw&sig2=LQ1EROQQV6k7cX90ufFyMg).
Basically it comes down to Floating Point numbers being stored with finite precision. You have to do your comparison with some delta.
```
if(.9 - .8999999999999995 <= 0.0001)
//close enough to be equal
``` | I think its because in the binary system, 5 is periodic as it is not dividable by 2. And then what Mark Rushakoff said applies. |
7,002,137 | I have tried to create a custom NumberPicker which works in most of the cases pretty well. The only problem is the layout which is created dynamically. The layout consists of
* two buttons ("+" at the top and "-" at the bottom in portrait mode)
* one edit
In the constructor ("NumberPicker extends LinearLayout") I add the three components by using addView() to the layout.
In case of viewing this layout in landscape mode I would like the buttons "+" and "-" not to be at the top and the bottom, but on the right and on the left, because otherwise the size of the NumberPicker is too large.
By using the event onConfigurationChanged I check if the user has changed the screen orientation and set the orientation of the LinearLayout to horizontal and vertical. The problem is that the "+"- and "-"-Buttons are on wrong positions. It should look this way (e.g. in landscape):
"-" | edit | "+"
But it looks this way:
"+" | edit | "-"
How can I solve this problem? I would like to have the buttons in the right order. Could I solve the problem by using XMLs?
Thank you. | 2011/08/09 | [
"https://Stackoverflow.com/questions/7002137",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/871517/"
] | I would think just making an extension method would be a clear way of doing it:
```
public static bool CannotBeCastAs<T>(this object actual)
where T: class
{
return (actual as T == null);
}
```
You then simply make a check like so:
```
if(myObject.CannotBeCastAs<SomeClass>())
{
}
``` | I would be of the opinion that braced functionality should always match whatever brace pattern is in use in your application. For instance, in the case of iteration or conditional blocks, if you use:
```
If (foo != bar)
{
//Do Something
}
```
well then this should be how you use brace patterned functionality at all times. One of my biggest bugbears with reading other peoples code (and this is especially true if they use CodeRush or Resharper) is the unnecessary terseness people add for no other reason than to display wizardry.
I am not saying the above is the best brace matching pattern however, use whatever one you feel comfortable with, what I would like to get across is that the pattern does not matter so much as the consistency of its use.
Personally, since C# is a terse language in comparison to, say VB.Net I would use long form statements or assignments (with the exception of var initialising) over more condense syntax to help aid later readability. |
62,126,513 | I am working on a program where the user can send me all sort of objects at runtime, and I do not know their type in advance (at compile time). When the object can be down-cast to an (F#) array, of *any* element type, I would like to perform some usual operations on the underlying array. E.g. `Array.Length`, `Array.sub`...
The objects I can get from the users will be of things like `box [| 1; 2; 3 |]` or `box [| "a"; "b"; "c" |]`, or any `'a[]`, but I do not know `'a` at compile time.
The following does not work :
```
let arrCount (oarr: obj) : int =
match oarr with
| :? array<_> as a -> a.Length
| :? (obj[]) as a -> a.Length
// | :? (int[]) as a -> a.Length // not an option for me here
// | :? (string[]) as a -> a.Length // not an option for me here
// | ...
| _ -> failwith "Cannot recognize an array"
```
E.g both `arrCount (box [| 1; 2; 3 |])` and `arrCount (box [| "a"; "b"; "c" |])` fail here.
The only solution I found so far is to use reflection, e.g. :
```
type ArrayOps =
static member count<'a> (arr: 'a[]) : int = arr.Length
static member sub<'a> (arr: 'a[]) start len : 'a[] = Array.sub arr start len
// ...
let tryCount (oarr: obj) =
let ty = oarr.GetType()
if ty.HasElementType && ty.BaseType = typeof<System.Array> then
let ety = ty.GetElementType()
let meth = typeof<ArrayOps>.GetMethod("count").MakeGenericMethod([| ety |])
let count = meth.Invoke(null, [| oarr |]) :?> int
Some count
else
None
```
My question: is there a way to use functions such as `Array.count`, `Array.sub`, etc... on arguments of the form `box [| some elements of some unknown type |]` without using reflection? | 2020/06/01 | [
"https://Stackoverflow.com/questions/62126513",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2518338/"
] | Is it legal? Yes. Is it error prone? **Yes.** That's why you are getting a warning.
The C/C++ standard has one token above all (processed first): `\`
This token removes the line break. Consider the following code:
```
1. // the below code is commented out \
2. despite not having a comment at the beginning of the line
3.
4. // it's important to be careful because \\
5. int not_compiled_code = 0;
6. // the above code is not compiled.
```
Despite stackoverflow's syntax highlighting, lines 2 and 5 are not compiled.
In case you're wondering, the next tokens are `//` and `/*`.
```
// /* incomplete block comment
int compiled_code = 0;
/*
// this entire line isn't commented */ int compiled_code_2 = 0;
```
>
> which compiler is right?
>
>
>
Both, because warnings are irrelevant to the standard. They compiled successfully and that's all that matters - they both conformed properly to the standard. | >
> which compiler is right?
>
>
>
Both. The warning is not about "legal usage of `\`" the warning is about multiline comment.
In C a `\` character on the end of the line means to ignore the newline. So the two lines:
```
// blabla\
abcabc
```
and:
```
// blabalabcbc
```
Are exactly equivalent. The double backslash `\\` is just a backslash `\` that is escaped by `\`, so it is first substituted by a backslash, then preprocessor detects backslashes followed by a newline and deletes newlines. That's why it's dangerous.
```
int a = 1;
// increase a \\
a++;
printf("%d\n", a); // will print `1`
``` |
247,589 | I will provide definitions for which I can't think of the word:
* *as though not trying one's best*
* *having the appearance of little effort*
The word is used to describe something that you look at and think, *"They're not really trying."*
I remember thinking this is a good vocab word, and darn it, I forgot it. This has been driving me crazy all day. | 2015/05/20 | [
"https://english.stackexchange.com/questions/247589",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/122348/"
] | If a metaphoric term would work, consider *[phoning it in](http://www.oxforddictionaries.com/us/definition/american_english/phone-it-in)*
>
> (informal) Work or perform in a perfunctory or unenthusiastic manner.
>
>
>
*Oxford Dictionaries Online* | [Lackluster](http://www.oxforddictionaries.com/definition/american_english/lackluster)
>
> Lacking in vitality, force, or conviction; uninspired or uninspiring:
>
>
> *No excuses were made for the team’s lackluster performance.*
>
>
> |
17,875,179 | I have following table:
```
Type1 Type2
A T1
A T2
A T1
A T1
A T2
A T3
B T3
B T2
B T3
B T3
```
I want output as:
```
Type1 T1 T2 T3
A 3 2 1
B 0 1 3
```
I tried using ROW\_NUMBER() OVER (ORDER BY) and CASE Statements but couldn't get desired output. Please Help. Thanks in advance. | 2013/07/26 | [
"https://Stackoverflow.com/questions/17875179",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1610216/"
] | Try to use PIVOT -
**Query 1:**
```
DECLARE @temp TABLE (Type1 CHAR(1), Type2 CHAR(2))
INSERT INTO @temp (Type1, Type2)
VALUES
('A', 'T1'),('A', 'T2'),
('A', 'T1'),('A', 'T1'),
('A', 'T2'),('A', 'T3'),
('B', 'T3'),('B', 'T2'),
('B', 'T3'),('B', 'T3')
SELECT *
FROM @temp
PIVOT
(
COUNT(Type2) FOR Type2 IN (T1, T2, T3)
) p
```
**Query 2:**
```
SELECT
Type1
, T1 = COUNT(CASE WHEN Type2 = 'T1' THEN 1 END)
, T2 = COUNT(CASE WHEN Type2 = 'T2' THEN 1 END)
, T3 = COUNT(CASE WHEN Type2 = 'T3' THEN 1 END)
FROM @temp
GROUP BY Type1
```
**Output:**
```
Type1 T1 T2 T3
----- ----------- ----------- -----------
A 3 2 1
B 0 1 3
``` | ```
SELECT Type1,
SUM(CASE WHEN Type2='T1' THEN 1 ELSE 0 END) AS T1,
SUM(CASE WHEN Type2='T2' THEN 1 ELSE 0 END) AS T2,
SUM(CASE WHEN Type2='T3' THEN 1 ELSE 0 END) AS T3
FROM your_table
GROUP BY Type1
``` |
56,130 | The answer to the riddle is two words.
The Riddle:
>
> I grow by consuming one thing
>
>
> The more I consume the larger I get
>
>
> Regardless of my size you don't see more of me
>
>
> I am lighter than what I consume
>
>
>
Hint:
>
> I am something real, something tangible that you can put your hands on, something that can become enormous.
>
>
> | 2017/10/19 | [
"https://puzzling.stackexchange.com/questions/56130",
"https://puzzling.stackexchange.com",
"https://puzzling.stackexchange.com/users/39761/"
] | Hazarding a guess you are
>
> an iceberg
>
>
>
I grow by consuming one thing
>
> Water - ocean icebergs are composed of mostly fresh water from the salty sea.
>
>
>
The more I consume the larger I get
>
> Yes
>
>
>
Regardless of my size you don't see more of me
>
> Only see 10% of you regardless of size - the tip of the iceberg.
>
>
>
> Or the answer may be more like pond ice. If the surface is frozen over the ice layer will increase in depth but the visible top remains the same.
>
>
>
I am lighter than what I consume
>
> Ice is less dense than water.
>
>
>
Hint: I am something real, something tangible that you can put your hands on, something that can become enormous.
>
> Ice is tangible. It could be small like an ice cube or titanic.
>
>
> | maybe you are
>
> A cloud ?
>
>
>
I grow by consuming one thing
>
> Grow in size by absorbing water
>
>
>
The more I consume the larger I get
>
> The more water comes in, the bigger it gets
>
>
>
Regardless of my size you don't see more of me
>
> ??? if "more of me" is used as "a bigger surface of me", could be because clouds grow in height (idk about this one ^^')
>
>
>
I am lighter than what I consume
>
> clouds fly
>
>
>
Hint | I am something real, something tangible that you can put your hands on, something that can become enormous.
>
> Not everybody can touch it, but it's made of water, which is tangible. And it can grow enormous as cloud can be kilometers long
>
>
> |
14,082,020 | How do you get the path to SignTool.exe when using Visual Studio 2012?
In Visual Studio 2010, you could use
```
<Exec Command=""$(FrameworkSDKDir)bin\signtool.exe" sign /p ... />
```
Where `$(FrameworkSDKDir)` is
```
"c:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\"
```
But in Visual Studio 2012, `$(FrameworkSDKDir)` is
```
"C:\Program Files (x86)\Microsoft SDKs\Windows\v8.0A\bin\"
```
and SignTool is in
```
"c:\Program Files (x86)\Windows Kits\8.0\bin\x64\"
```
Is there a way of getting the path to this directory other than hard coding (I've tried `FrameworkSDKDir` and `WindowsSDKDir`, but both point to the v8.0A directory).
*(I am aware of the [SignFile](http://msdn.microsoft.com/en-us/library/ms164304.aspx) [MSBuild](http://en.wikipedia.org/wiki/MSBuild) task, but I can't use that as it doesn't accept certificate passwords.)* | 2012/12/29 | [
"https://Stackoverflow.com/questions/14082020",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20198/"
] | I just ran into the same issue. Running the build from a Visual Studio 2012 Command Prompt worked, but it was failing in the IDE. Looking for a detailed or diagnostic log led me to [What is the default location for MSBuild logs?](https://stackoverflow.com/questions/11526552/what-is-the-default-location-for-msbuild-logs), which told me that Visual Studio can't give the diagnostic information I really needed.
Here's what I finally did to fix it.
Open a normal Command Prompt (not the Visual Studio Command Prompt), and run msbuild from that by fully-qualifying the path to MSBuild (%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe). This finally gave me the same error message (error code 9009) that I had been receiving in Visual Studio 2012.
Then, run the same build using "diagnostic" logging (which shows all property and item values) by appending the /v:diag switch.
From this output, I learned that it does have some new properties that I could use to get the location of signtool.exe (excerpt below):
```
windir = C:\Windows
windows_tracing_flags = 3
windows_tracing_logfile = C:\BVTBin\Tests\installpackage\csilogfile.log
WindowsSDK80Path = C:\Program Files (x86)\Windows Kits\8.0\
WIX = C:\Program Files (x86)\WiX Toolset v3.7\
```
So, my solution to this problem was to add the following to my \*.targets file:
```
<SignToolPath Condition=" Exists('$(WindowsSDK80Path)bin\x86\signtool.exe') and '$(SignToolPath)'=='' and '$(PROCESSOR_ARCHITECTURE)'=='x86' ">$(WindowsSDK80Path)bin\x86\signtool.exe</SignToolPath>
<SignToolPath Condition=" Exists('$(WindowsSDK80Path)bin\x64\signtool.exe') and '$(SignToolPath)'=='' and '$(PROCESSOR_ARCHITECTURE)'=='AMD64' ">$(WindowsSDK80Path)bin\x64\signtool.exe</SignToolPath>
```
Hope this helps you, too. I included the preamble of how I got to this point because there are other properties available that may be better suited for your purposes. | The following is a more generic approach that can be used to find and set the `SignToolPath` variable based upon the build machine's specific configuration; by reading the registry:
```
<PropertyGroup>
<WindowsKitsRoot>$([MSBuild]::GetRegistryValueFromView('HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows Kits\Installed Roots', 'KitsRoot81', null, RegistryView.Registry32, RegistryView.Default))</WindowsKitsRoot>
<WindowsKitsRoot Condition="'$(WindowsKitsRoot)' == ''">$([MSBuild]::GetRegistryValueFromView('HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows Kits\Installed Roots', 'KitsRoot', null, RegistryView.Registry32, RegistryView.Default))</WindowsKitsRoot>
<SignToolPath Condition="'$(SignToolPath)' == ''">$(WindowsKitsRoot)bin\$(Platform)\</SignToolPath>
</PropertyGroup>
```
This assumes that `$(Platform)` resolves to one of `arm`, `x86`, or `x64`. Replace the `$(Platform)` macro with the appropriate directory otherwise.
**EDIT** (2017.07.05):
Here is an updated `<PropertyGroup>` that defers to the new Windows 10 Kit and coerces the `($Platform)=='AnyCPU'` to `x86`:
```
<PropertyGroup>
<WindowsKitsRoot>$([MSBuild]::GetRegistryValueFromView('HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows Kits\Installed Roots', 'KitsRoot10', null, RegistryView.Registry32, RegistryView.Default))</WindowsKitsRoot>
<WindowsKitsRoot Condition="'$(WindowsKitsRoot)' == ''">$([MSBuild]::GetRegistryValueFromView('HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows Kits\Installed Roots', 'KitsRoot81', null, RegistryView.Registry32, RegistryView.Default))</WindowsKitsRoot>
<WindowsKitsRoot Condition="'$(WindowsKitsRoot)' == ''">$([MSBuild]::GetRegistryValueFromView('HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows Kits\Installed Roots', 'KitsRoot', null, RegistryView.Registry32, RegistryView.Default))</WindowsKitsRoot>
<SignToolPath Condition=" '$(SignToolPath)' == '' And '$(Platform)' == 'AnyCPU' ">$(WindowsKitsRoot)bin\x86\</SignToolPath>
<SignToolPath Condition="'$(SignToolPath)' == ''">$(WindowsKitsRoot)bin\$(Platform)\</SignToolPath>
</PropertyGroup>
``` |
13,207 | Whilst I understand why stars move across our skies,(Earth rotation) I struggle to understand why they do not appear to move relative to each other.
To explain: Take the best know constellation the Plough. It is a familiar site to most people. But it has been there apparently un-changed for years. If we (I mean earth, moon, stars and everything else ) are hurtling through space, then surely changes should be apparent unless we are all travelling in the same direction at exactly the same speed. | 2016/01/14 | [
"https://astronomy.stackexchange.com/questions/13207",
"https://astronomy.stackexchange.com",
"https://astronomy.stackexchange.com/users/10399/"
] | They do move - just far too slowly for you to detect by eye even over several human lifetimes.
>
> Space is big. Really big. You just won't believe how vastly, hugely, mind-bogglingly big it is. I mean, you may think it's a long way down the road to the chemist, but that's just peanuts to space
>
>
>
*Douglas Adams, "The Hitch-hikers Guide to the Galaxy"*
Even the closest stars are a very, very, very long way away so their apparent movement relative to each other is going to be very small.
You can see the same effect when looking out of a moving vehicle through the side windows. You see the objects closest to you rushing past, but objects on the horizon appear to move much more slowly. Now, scale that up by many orders of magnitude to interstellar distances and you'll see why the stars don't appear to move relative to each other.
There's software that simulates the night sky and you can run time backwards and forwards - if you wind it far enough you'll see the constellations change. | Here's a nice image of [Barnard's star](https://en.wikipedia.org/wiki/Barnard's_Star) moving against the stellar background:
[](https://i.stack.imgur.com/z0ge0.jpg)
From this interesting website: [AstroWright](http://sites.psu.edu/astrowright/2012/08/14/barnards-stars-planets/) |
4,296,469 | Suppose random variables $X\_{1}$ and $X\_{2}$ have some joint probability density function (pdf) $f(x\_{1}, x\_{2})$. I wish to find probability density of $Y\_{1} = \frac{X\_{1}}{X\_{2}}$. The textbooks say I can define an additional variable $Y\_{2} = X\_{2}$ and proceed.
My question, what if I define an additional variable in some other way, i.e. $Y\_{2} = g(X\_{1}, X\_{2})$ for some function $g$? Then the pdf for $Y\_{1}$ would be different, i.e. in general it is not unique...Why do we have this freedom in choosing an additional variable? What is the meaning of this? | 2021/11/04 | [
"https://math.stackexchange.com/questions/4296469",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/980184/"
] | >
> Surely these 2 integrals corresponding to marginal densities will be different,
>
>
>
**Sure that it is false.**
Given that you are not responding, I will show you how to do assuming a coherent support.
Let's assume that your joint density is the following
$$f\_{XY}(x,y)=8xy$$
where $0<x<y<1$
You have to derive the density of $Z=\frac{X}{Y}$. First observe that $Z \in (0;1)$
* Using the auxiliary variable as $U=X$ you will find the marginal Z in the following way
$$f\_Z(z)=\int\_0^z \frac{8u^3}{z^3}du=2z$$
* Using the auxiliary variable as $U=Y$ you will find the marginal Z in the following way
$$f\_Z(z)=\int\_0^18zu^3du=2z$$
as you can see the result is the same... I let you to understand the different integral bounds as an exercise.
Another useful exercise is to write down the joint density $f\_{UZ}(u,z)$ in both cases, writing down also its joint support. | what about this example. Let $f(x\_{1}, x\_{2}) = 8x\_{1}x\_{2}$. Define $Y\_{1} = \frac{X\_{1}}{X\_{2}}$ and $Y\_{2} = X\_{2}$. Then Jacobian of transformation is simply $y\_{2}$ and we have
$f\_{Y\_{1}, Y\_{2}}(y\_{1}, y\_{2}) = 8y\_{1}y\_{2}^{3},$ and marginal density
$f\_{Y\_{1}}(y\_{1}) = \int 8y\_{1}y\_{2}^{3} dy.$
Now suppose instead I take $Y\_{1} = \frac{X\_{1}}{X\_{2}}$ and $Y\_{2} = X\_{1}$. Then Jacobian is $\frac{y\_{2}}{y\_{1}}$, and we have
$f\_{Y\_{1}, Y\_{2}}(y\_{1}, y\_{2}) = 8\frac{y\_{2}^{3}}{y\_{1}^{3}}$, and marginal density
$ f\_{Y\_{1}}(y\_{1}) = \int \frac{y\_{2}^{3}}{y\_{1}^{3}} dy.$
Where integrals are taken over the domain of definition of $f$. Surely these 2 integrals corresponding to marginal densities will be different, regardless of the domain of definition of $f$? |
229,657 | In my world there are multiple continents with many cultures. In a far away continent, there are kingdoms that exist there. I was wondering how could they be medieval style like the mainland, and if it is even possible at all.
Things to consider:
* The new continent is not connected and is separated by sea
* The continent is discovered back in my world's medieval period
* Their food is similar to those of Europe
* They are not that very tribal, with the exception of a few nomad groups and pagan rituals | 2022/05/07 | [
"https://worldbuilding.stackexchange.com/questions/229657",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/95481/"
] | The question as asked is vague, and may want to be narrowed down, but here is my understanding of the question, and my best swing at answering; you appear to be asking 'What conditions would lead a medieval culture aesthetically similar to Europe's to develop independently on two entirely separate continents, and just how likely is that to happen?'
My answer - there needs to be large reserves of metals, especially iron but also copper, tin and gold, and a history of metallurgy. There needs to be a large and robust trade network, and domestic horses or similar animals. There needs to be a substantial winter in more than half of the available landmass. There needs to be a history of militaristic empire that pushes society towards designing standardized weaponry and protective structures like castles, walls and towers. As long as both continents meet these conditions without overlapping with one another, it feels realistic that both continents might have arrived at similar medieval eras at around the same time in a sort of parallel evolution.
However, it is important to understand just how diverse this image is, and has to be in order to exist in the first place. When you say 'medieval Europe,' you are including a vast world of differences. For nearly 700 years, muslim kingdoms controlled large portions of Spain; Italy was a mess of oligarchic and democratic city states fighting one another in wars mostly funded by trade with India and China and largely fought by mercenaries, some from as far away as england; Other areas might have been ruled by kings, or by popes, or by councils of nobles who elected their ruler; The boundaries by which we may now define 'Europe', 'Asia' and 'the Middle East' would have been drawn very differently, and those differences would be felt in the way people dressed, the design of their architecture, and the weapons and armor they used in combat. And that's just Europe - There are plenty of other parts of the world that had medieval eras, from Africa to continental Asia to Japan. Both of your continental areas must feature this level of diversity to be fully believable. There is no such thing as a medieval Europe without the backing of a larger world to compete with, trade with, to conquer and be conquered by.
Also, even if they are at a similar level of technology, their cultures will necessarily be different in big ways. Religions, languages, and value systems all will have developed independently. Certain things they will have in common - technology such as bows and crossbows, levers and pulleys, clockworks, as well as the use of gold as currency if it is available, all of these things have been known to develop independently in separate cultures, as they draw on natural facts (tension, gravity, and the fact that gold doesn't tarnish and thus retains its value). On the other hand, other technologies such as gunpowder, glassblowing or silk, depend on the presence of specific resources and the understanding of how to utilize them - and if one continent has one of these and the other doesn't, it will spell out a rather large difference. Even something that seems as small as what natural fibers and colors of dye are available to them will affect the way they look and feel.
In short, as long as you do some research and make your two continents feel enough like they have truly different histories, both in terms of the people and the animals and plants that live there, it can still feel realistic that both continents might feature medieval feeling societies. | [The Kingdom of Prester John](https://en.wikipedia.org/wiki/Prester_John):
==========================================================================
[Thule](https://en.wikipedia.org/wiki/Thule), lost [Norse colonies](https://en.wikipedia.org/wiki/Norse_colonization_of_North_America), etc. The Histories and mythologies of Europe are filled with references to supposed kingdoms across the sea, or just out of reach, or just over the poles. Even modern fantasy has such things, like the elves departing to their lands across the sea.
Any group of people sufficiently motivated to leave your continent will carry with them the traditions of that land, and if they crossed the Atlantic (for example) and colonized, then they would establish a beachhead of your culture wherever they went. They could have brought traditional seeds and plants, preserving traditional foods.
But don't make the mistake of thinking they will be clones of your existing society. A group motivated to leave home may be trying to preserve a particular culture. So they may be a snapshot of some ancient culture, evolved into something new in isolation. They may have fused with a local people and have peculiar new ideas even if they speak a similar language. Or they may have preserved some long-lost blasphemy thought driven out of the world for good. And naturally they will have picked up new foods, diseases, and possibly enemies for your explorers to deal with. |
59,146 | In the King James Version of Tehillim, we read :
Psalm 119:126 [KJV]
>
> "It is time for thee, Lord, to work: for [they] have made [void - thy law]."
>
**Who are "they" and What [specifically] is the voided "Law" in Psalm 119 verse 126?**
* Does "Thy Law" refer to **All** of His Commandments from [verse 6]?
* Psalm 119:6 [KJV] "Then shall I not be ashamed, when I have respect unto [All] thy [Commandments]." | 2021/04/18 | [
"https://hermeneutics.stackexchange.com/questions/59146",
"https://hermeneutics.stackexchange.com",
"https://hermeneutics.stackexchange.com/users/37964/"
] | A few verses earlier, we have:
>
> 119 All the **wicked of the earth** you discard like dross;
>
> therefore I love your statutes.
>
>
>
The "they" refers to the wicked people of the earth.
From the opening of the psalm, we have:
>
> 1 Blessed are those whose ways are blameless,
>
> who walk according to the **law of the Lord**.
>
>
>
The "law" refers to the law of the Lord.
The whole psalm with 176 verses talks in terms of generalities. I don't think the psalmist was trying to be specific. | Ps 119:126 is part of a series of similar verses that ask God to act in order to remove the lawless; for example:
* Ps 94:3 - How long, LORD, shall the wicked— How long shall the wicked triumph?
* Ps 4:2 - You sons of man, how long will my honor be treated as an insult? How long will you love what is worthless and strive for a lie? Selah
* Num 14:11 - And the LORD said to Moses, “How long will this people despise me? And how long will they not believe in me, in spite of all the signs that I have done among them?
* Dan 8:13 - Then I heard a holy one speaking, and another holy one said to the one who spoke, “For how long is the vision concerning the regular burnt offering, the transgression that makes desolate, and the giving over of the sanctuary and host to be trampled underfoot?”
* Ps 89:14 - How long, LORD? Will You hide Yourself forever? Will Your wrath burn like fire?
In Ps 119:126 we have another case where the Psalmist is pleading with God to stop the wicked and assert His divine justice for all to see. Ps 73 is an extended hymn on this subject of "When will you Acts, O LORD?" The entire stanza of "Ayin" has this same theme -
>
> 121 I have done what is just and right; do not leave me to my
> oppressors.
>
>
> 122 Ensure Your servant’s well-being; do not let the arrogant oppress
> me.
>
>
> 123 My eyes fail, looking for Your salvation, and for Your righteous
> promise.
>
>
> 124 Deal with Your servant according to Your loving devotion, and
> teach me Your statutes.
>
>
> 125 I am Your servant; give me understanding, that I may know Your
> testimonies.
>
>
> 126 It is time for the LORD to act, for they have broken Your law.
>
>
> 127 Therefore I love Your commandments more than gold, even the purest
> gold.
>
>
> 128 Therefore I admire all Your precepts and hate every false way.
>
>
>
Thus, we see a contrast between the frustration of the righteous of love God's law and the arrogance of the wicked who appear to prosper despite having contempt for the law, or "voiding" the law, or regarding the law as worthless, or ignoring the law. |
2,333,365 | my application requires the microsoft visual c++ redisributable package (vcredist\_x86.exe).
i have a custom action to run the vcredist\_x86.exe
i want it to run only if it's not already installed. i created a registry search to check it.
the question: how do i run this action with the check? when using the InstallExecuteSequence element, as shown below, the vcredist\_x86.exe crashes because you cannot run an msi while running a different msi
thanks,
Uzi | 2010/02/25 | [
"https://Stackoverflow.com/questions/2333365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/281144/"
] | Just don't do it, it's undefined behavior.
It might accidentially work because you write/read some memory the program doesn't actually use. Or it can lead to heap corruption because you overwrite metadata used by the heap manager for its purposes. Or you can overwrite some other unrelated variable and then have hard times debugging the program that goes nuts because of that. Or anything else harmful - either obvious or subtle yet severe - can happen.
Just don't do it - only read/write memory you legally allocated. | Generally speaking (different implementation for different platforms) when a malloc or similar heap based allocation call is made, the underlying library translates it into a system call. When the library does that, it generally allocates space in sets of **regions** - which would be equal or larger than the amount the program requested.
Such an arrangement is done so as to prevent frequent system calls to kernel for allocation, and satisfying program requests for Heap faster (This is certainly not the only reason!! - other reasons may exist as well).
Fall through of such an arrangement leads to the problem that you are observing. Once again, its not always necessary that your program would be able to write to a non-allocated zone without crashing/seg-faulting everytime - that depends on particular binary's memory arrangement. Try writing to even higher array offset - your program would eventually fault.
As for what you should/should-not do - people who have responded above have summarized fairly well. I have no better answer except that such issues should be prevented and that can only be done by being careful while allocating memory.
One way of understanding is through this crude example: When you request 1 byte in userspace, the kernel has to allocate a whole page atleast (which would be 4Kb on some Linux systems, for example - the most granular allocation at kernel level). To improve efficiency by reducing frequent calls, the kernel assigns this whole page to the calling Library - which the library can allocate as when more requests come in. Thus, writing or reading requests to such a **region** may not necessarily generate a fault. It would just mean garbage. |
70,047 | The Hubble constant, which roughly gauges the extent to which space is being stretched, can be determined from astronomical measurements of galactic velocities (via redshifts) and positions (via standard candles) relative to us. Recently a value of 67.80 ± 0.77 (km/s)/Mpc was published. On the scale of 1 A.U. the value is small, but not infinitesimal by any means (I did the calculation a few months ago, and I think it came out to about 10 meters / year / A.U.). So, can you conceive of a measurement of the Hubble constant that does not rely on any extra-galactic observations?
I ask because, whatever the nature of the expansion described by the Hubble constant, it seems to be completely absent from sub-galactic scales. It is as though the energy of gravitational binding (planets), or for that matter electromagnetic binding (atoms) makes matter completely immune from the expansion of space. The basis for this claim is that if space were also pulling atoms apart, I would naively assume we should be able to measure this effect through modern spectroscopy. Given that we are told the majority of the universe is dark energy, responsible for accelerating the expansion, I wonder, how does this expansion manifest itself locally?
Any thoughts would be appreciated. | 2013/07/04 | [
"https://physics.stackexchange.com/questions/70047",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/26438/"
] | We do measure the Hubble constant locally: everything that we know about it comes from observations of light in the vicinity of our telescopes. But if you restrict the experiments to a room with opaque walls, then no, it can't be measured locally, because it merely quantifies the average motion of galaxies on large scales, and there's nothing in the room that will tell you that. Note that **earlier answers to this question, including the accepted answer, are wrong**, inasmuch as they all suggest that it could be measured locally in principle if not in practice. **The paper by Cooperstock et al is also wrong**.
The error in Cooperstock et al is easy to explain. They assume that the cosmological FLRW metric is accurate at solar system scales. You can plug the FLRW metric into the Einstein field equations (or the Friedmann equations, which are the Einstein equations specialized to FLRW geometries) to see what this implies about the stress-energy tensor. What you'll find is that they've assumed that the solar system is filled uniformly with matter of a certain density and pressure. The force that they calculate is simply the local gravitational effect of the matter that they assumed was present. But it isn't actually there. It's elsewhere: it collapsed into stars and planets. When they treat the cosmological force as a perturbation on top of the usual solar-system forces, they're double-counting all of the matter, once at its actual location and once at the location where it hypothetically would be if it hadn't clumped. Matter only exerts a gravitational influence from its actual location.
General relativity is different from Newtonian gravity, but it's not *as* different as many people seem to imagine. It's still a theory of gravity: a force between massive objects that's mediated by a field. It's not a theory of test particles following geodesics on meaningless spacetime backgrounds. The FLRW geometry is not a background; it's the gravitational field of a uniform matter distribution. It could be roughly described as a bunch of Schwarzschild patches stitched together and then smoothed. In real life, there is no smoothing, and no FLRW geometry; there is only the (approximately) Schwarzschild local patches. There is no universal scale factor evolving to the ticks of the absolute, true and cosmological time; there is only local motion of ordinary gravitating objects. That this averages out, on huge scales, to a FLRW-like shape with local bumps is known to us, but irrelevant to nature, which only applies local physical laws independently in each spacetime neighborhood.
Measuring the Hubble constant in a sealed room is no different from measuring the abundance of helium in a sealed room. It will only tell you what's in the room. The abundance in the room won't tend to 25% over time. There's no subtle residual effect of 25% abundance that you can measure locally. The universe is about 25% helium because most of the helium from the first three minutes is still around, not because there's a local physical process that regulates the amount of helium.
What about dark energy? Dark energy, by assumption, doesn't clump at all. You can measure its gravitational effect in the room because it's *present* in the room. The acceleration you'll measure is not $\ddot a/a$, because $\ddot a/a$ incorporates the averaged effect of all matter, not just the stuff in the room. In the distant future, as $Ω\_Λ$ approaches $1$, the acceleration you measure will approach $\ddot a/a = H^2$, but there's no way for you to know that unless you look outside of the room and observe that there's nothing else out there. If dark energy clumps (by little enough to evade current experimental limits) then the amount in the room may be smaller or larger than the average. In that case you'll measure the effect of what's actually in the room, not the effect of the average that you're taking it to be a perturbation of. Nature doesn't do perturbation theory.
Same with dark matter. There may be some of it in the room, depending on what it's made of. If there is, the density will probably be larger than the universal average, but it could be smaller, or about equal. In any case, what you'll measure is what's actually in the room, not what would be there if dark matter didn't clump.
---
Here are some comments on specific parts of other answers.
>
> For two test particles released at a distance $\mathbf{r}$ from one another in an FRW spacetime, their relative acceleration is given by $(\ddot{a}/a)\mathbf{r}$.
>
>
>
That's correct. Assuming the F(L)RW geometry in GR is equivalent to assuming a $(\ddot{a}/a)\mathbf{r}$ field, or $(\ddot{a}/a)\mathbf{r}^2/2$ potential, in Newtonian gravity. By Poisson's equation that implies uniform matter of density $\ddot{a}/a = -\tfrac43 πGρ$ is present everywhere.
>
> Within the solar system, for example, such an effect is swamped by the much larger accelerations due to Newtonian gravitational interactions.
>
>
>
That's incorrect. The effect is absent in the solar system because the matter that would have caused it is absent. This is obviously true in Newtonian gravitation; it's also true in GR.
>
> The actual trend in the radius of the orbit over time, called the secular trend, is proportional to $(d/dt)(\ddot{a}/a)$
>
>
>
I think that this would be correct if the $(\ddot{a}/a)\mathbf{r}$ force actually existed.
Note, though, that if the force existed, it would be due to, and proportional to, the mass located inside the orbital radius, so you may as well say that the trend is proportional to $dM/dt$. This holds regardless of the nature of the mass; it could be a star losing mass to solar wind and radiation, for example. For a circular orbit $mv^2/r=GMm/r^2$, which gives $dr = d(GM)$ if you hold $v$ constant, so this seems reasonable.
If you added FLRW matter to the solar system, you wouldn't get this trend, because it would clump on much smaller time scales. To follow the Hubble expansion over long time scales it would have to behave totally unphysically: gravitationally influencing other matter but entirely uninfluenced by it, just sedately expanding independent of everything else. This happens when the FLRW matter is the only matter in the universe, since there's nothing to break the symmetry; otherwise it makes no sense.
>
> if you write down the Einstein equation for the case of a simple cosmological-constant dominated universe and a spherically symmetric matter source [...] you [...] get an instability in orbits whose radius is greater than some value $r\_∗$, which is proportional to $1/(ΛM)$. This outermost instability represents the expansion of the universe starting to dominate over objects orbiting very far from the star [...].
>
>
>
It represents the dark energy, which is present locally, starting to dominate. As you go to larger radii, the total contained dark energy goes up roughly as $r^3$, and $r\_\*$ is the radius at which the repulsive force from that equals the attractive force of the central mass. Mass outside that radius can be neglected by the shell theorem/Birkhoff's theorem. This doesn't tell you the Hubble constant or the scale factor; it only tells you the local density of dark energy, which as I mentioned before can be measured inside the opaque room. | Ben Crowell's answer is right, but I am adding a point in order to emphasize it, because this issue keeps coming up. Here is the point:
*The cosmological expansion is FREE FALL motion.*
What this means is that the clusters of galaxies on the largest scales are just moving freely. They are in the type of motion called 'free fall'. It means they are going along, with their velocity evolving according to whatever the net average gravity of the cosmos as a whole says. There is no "inexorable space expansion force" or anything like that. They are not being carried along on some cosmic equivalent of tectonic plates. They are just falling. In technical language, their worldlines are geodesic. This should help you to understand why forces within galaxies, and within ordinary bodies, will hold those galaxies and those bodies together in the normal way. It is not essentially different from objects falling to Earth under the local gravity: Earth's gravity offers a tiny stretching/squeezing effect, but this is utterly negligible compared to all the ordinary forces within materials.
If you could somehow switch off the gravitational attraction within the solar system and the galaxy and the local cluster, and all the electromagnetic and other forces, then, and only then, would the parts of the solar system begin to drift apart under cosmic free fall motion, commonly called the expansion of space. |
31,243,378 | I use different list in one page with each list have some Option button,
you can take a look at my codepen : `[http://codepen.io/harked/pen/WvMgXg][1]`
If we swipe the first card, it will show the option button.
If we swipe the second card, it will also show the option button.
Is there any way to prevent Option-Button to show while the other in another card is showing?
I mean the problem is like this pict : <http://www.nanonimos.com/IonOption.jpg>
Anyone? It would be greatly appreciated. | 2015/07/06 | [
"https://Stackoverflow.com/questions/31243378",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4789892/"
] | If anyone wants to get the MimeType from the actual URL of the file this code worked for me:
```
import MobileCoreServices
func mimeTypeForPath(path: String) -> String {
let url = NSURL(fileURLWithPath: path)
let pathExtension = url.pathExtension
if let uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension! as NSString, nil)?.takeRetainedValue() {
if let mimetype = UTTypeCopyPreferredTagWithClass(uti, kUTTagClassMIMEType)?.takeRetainedValue() {
return mimetype as String
}
}
return "application/octet-stream"
}
``` | iOS 14.0 +
----------
**Use the extensions**
```
import UniformTypeIdentifiers
extension NSURL {
public func mimeType() -> String {
if let pathExt = self.pathExtension,
let mimeType = UTType(filenameExtension: pathExt)?.preferredMIMEType {
return mimeType
}
else {
return "application/octet-stream"
}
}
}
extension URL {
public func mimeType() -> String {
if let mimeType = UTType(filenameExtension: self.pathExtension)?.preferredMIMEType {
return mimeType
}
else {
return "application/octet-stream"
}
}
}
extension NSString {
public func mimeType() -> String {
if let mimeType = UTType(filenameExtension: self.pathExtension)?.preferredMIMEType {
return mimeType
}
else {
return "application/octet-stream"
}
}
}
extension String {
public func mimeType() -> String {
return (self as NSString).mimeType()
}
}
```
Below iOS 14
------------
**MimeType.swift**
```
import Foundation
internal let DEFAULT_MIME_TYPE = "application/octet-stream"
internal let mimeTypes = [
"html": "text/html",
"htm": "text/html",
"shtml": "text/html",
"css": "text/css",
"xml": "text/xml",
"gif": "image/gif",
"jpeg": "image/jpeg",
"jpg": "image/jpeg",
"js": "application/javascript",
"atom": "application/atom+xml",
"rss": "application/rss+xml",
"mml": "text/mathml",
"txt": "text/plain",
"jad": "text/vnd.sun.j2me.app-descriptor",
"wml": "text/vnd.wap.wml",
"htc": "text/x-component",
"png": "image/png",
"tif": "image/tiff",
"tiff": "image/tiff",
"wbmp": "image/vnd.wap.wbmp",
"ico": "image/x-icon",
"jng": "image/x-jng",
"bmp": "image/x-ms-bmp",
"svg": "image/svg+xml",
"svgz": "image/svg+xml",
"webp": "image/webp",
"woff": "application/font-woff",
"jar": "application/java-archive",
"war": "application/java-archive",
"ear": "application/java-archive",
"json": "application/json",
"hqx": "application/mac-binhex40",
"doc": "application/msword",
"pdf": "application/pdf",
"ps": "application/postscript",
"eps": "application/postscript",
"ai": "application/postscript",
"rtf": "application/rtf",
"m3u8": "application/vnd.apple.mpegurl",
"xls": "application/vnd.ms-excel",
"eot": "application/vnd.ms-fontobject",
"ppt": "application/vnd.ms-powerpoint",
"wmlc": "application/vnd.wap.wmlc",
"kml": "application/vnd.google-earth.kml+xml",
"kmz": "application/vnd.google-earth.kmz",
"7z": "application/x-7z-compressed",
"cco": "application/x-cocoa",
"jardiff": "application/x-java-archive-diff",
"jnlp": "application/x-java-jnlp-file",
"run": "application/x-makeself",
"pl": "application/x-perl",
"pm": "application/x-perl",
"prc": "application/x-pilot",
"pdb": "application/x-pilot",
"rar": "application/x-rar-compressed",
"rpm": "application/x-redhat-package-manager",
"sea": "application/x-sea",
"swf": "application/x-shockwave-flash",
"sit": "application/x-stuffit",
"tcl": "application/x-tcl",
"tk": "application/x-tcl",
"der": "application/x-x509-ca-cert",
"pem": "application/x-x509-ca-cert",
"crt": "application/x-x509-ca-cert",
"xpi": "application/x-xpinstall",
"xhtml": "application/xhtml+xml",
"xspf": "application/xspf+xml",
"zip": "application/zip",
"epub": "application/epub+zip",
"docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
"mid": "audio/midi",
"midi": "audio/midi",
"kar": "audio/midi",
"mp3": "audio/mpeg",
"ogg": "audio/ogg",
"m4a": "audio/x-m4a",
"ra": "audio/x-realaudio",
"3gpp": "video/3gpp",
"3gp": "video/3gpp",
"ts": "video/mp2t",
"mp4": "video/mp4",
"mpeg": "video/mpeg",
"mpg": "video/mpeg",
"mov": "video/quicktime",
"webm": "video/webm",
"flv": "video/x-flv",
"m4v": "video/x-m4v",
"mng": "video/x-mng",
"asx": "video/x-ms-asf",
"asf": "video/x-ms-asf",
"wmv": "video/x-ms-wmv",
"avi": "video/x-msvideo"
]
internal func MimeType(ext: String?) -> String {
return mimeTypes[ext?.lowercased() ?? "" ] ?? DEFAULT_MIME_TYPE
}
extension NSURL {
public func mimeType() -> String {
return MimeType(ext: self.pathExtension)
}
}
extension URL {
public func mimeType() -> String {
return MimeType(ext: self.pathExtension)
}
}
extension NSString {
public func mimeType() -> String {
return MimeType(ext: self.pathExtension)
}
}
extension String {
public func mimeType() -> String {
return (self as NSString).mimeType()
}
}
```
**How to use**
--------------
```
let string = "https://homepages.cae.wisc.edu/~ece533/images/boat.png"
let mimeType = string.mimeType()
```
Workes with **NSURL**, **URL**, **NSString**, **String**
[Reference 1](https://developer.apple.com/documentation/uniformtypeidentifiers)
[Reference 2](https://gist.github.com/ngs/918b07f448977789cf69) |
175,402 | In the following example, the label is in the middle of the line. But the arrow, which acts as a marker, is not in the middle. Only its head but not the center of the arrow.
```
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{arrows,decorations.markings}
\begin{document}
\begin{tikzpicture}[
middlearrow/.style 2 args={
decoration={
markings,
mark=at position 0.5 with {\arrow{triangle 45}, \node[#1] {#2};}
},
postaction={decorate}
}
]
\draw[middlearrow={below}{+}] (0,0) -- (1,0);
\end{tikzpicture}
\end{document}
```
 | 2014/05/05 | [
"https://tex.stackexchange.com/questions/175402",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/51145/"
] | As noticed, the `markings` mechanism puts the arrow in the selected `position` taking as reference its arrowhead. The following example demonstrates it clearly:
```
\documentclass[tikz,border=10pt]{standalone}
\usepackage{tikz}
\usetikzlibrary{arrows,decorations.markings,plotmarks}
\begin{document}
\begin{tikzpicture}[
middlearrow/.style 2 args={
decoration={
markings,
mark=at position 0.5 with {\arrow{triangle 45}, \node[#1] {#2};}
},
postaction={decorate}
},
my mark/.style={
decoration={
markings,
mark=at position 0.5 with{\color{red}\pgfuseplotmark{x}},
},
postaction=decorate,
}
]
\draw[middlearrow={below}{+},my mark] (0,0) -- (1,0);
\draw[middlearrow={below}{+},my mark] (0,-1) -- (2,-1);
\draw[middlearrow={below}{+},my mark] (0,-2) -- (4,-2);
\end{tikzpicture}
\end{document}
```

What to do then? Steven showed one possibility. The same approach can be taken, easily, using only TikZ options, specifically `xshift`:
```
\documentclass[tikz,border=10pt]{standalone}
\usepackage{tikz}
\usetikzlibrary{arrows,decorations.markings,plotmarks}
\begin{document}
\begin{tikzpicture}[
middlearrow/.style 2 args={
decoration={
markings,
mark=at position 0.5 with {\arrow[xshift=3.333pt]{triangle 45}, \node[#1] {#2};}
},
postaction={decorate}
},
]
\draw[middlearrow={below}{+}] (0,0) -- (1,0);
\draw[middlearrow={below}{+}] (0,-1) -- (2,-1);
\draw[middlearrow={below}{+}] (0,-2) -- (4,-2);
\end{tikzpicture}
\end{document}
```

The "magic number" seems to be correct. To be really precise, one should go in `pgflibraryarrows.code.tex` file and compute the exact width of `triangle 45` arrow.
This solution does not prevent errors while changing line width. | Both the arrow and the plus sign were shifted `\makebox`es, and seem to work over various length spans. I'm guessing, however, that the actual size of the makeboxes will depend on the size of the arrow head.
```
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{arrows,decorations.markings}
\begin{document}
\begin{tikzpicture}[
middlearrow/.style 2 args={
decoration={
markings,
mark=at position 0.5 with {%
\makebox[4pt][r]{\arrow{triangle 45}}, \node[#1] {#2};}
},
postaction={decorate}
}
]
\draw[middlearrow={below}{\makebox[1pt][r]{+}}] (0,0) -- (1,0);
\draw[middlearrow={below}{\makebox[1pt][r]{+}}] (0,-.5) -- (2,-.5);
\draw[middlearrow={below}{\makebox[1pt][r]{+}}] (0,-1) -- (3,-1);
\end{tikzpicture}
\end{document}
```
 |
1,605,354 | I a developing a web application in c# in which i am using the below code.
Am getting "Access denied" when trying to open a file in client side.
```
String strPop = "<script language='javascript'>" + Environment.NewLine +
"window.open('C://myLocalFile.txt'," +
"'Report','height=520,width=730," +
"toolbars=no,scrollbars=yes,resizable=yes');" +
Environment.NewLine + "</script>" + Environment.NewLine;
Page.RegisterStartupScript("Pop", strPop);
```
What's the problem? and how to overcome it? | 2009/10/22 | [
"https://Stackoverflow.com/questions/1605354",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/125148/"
] | You cant access client side files with JavaScript , the only way to access files is to first upload it to the server or to a flash application. | JavaScript has strong restrictions about accessing files on the local file system, I think that you are maybe mixing up the client-side and server-side concepts.
JavaScript runs on the client-side, in the client's web browser.
I'm not sure about what you want to achieve, but:
* If you are trying to open a file on the *client* machine, you should upload it.
* If you are trying to open a file on your *server*, you should put it on an accessible location, within your web application. |
37,807,122 | I have a *Helper* that receives an array of elements and returns some other array based on the first one.
```
{{#each (sorted-strings myStrings) as |string|}}
{{string}}
{{/each}}
```
The implementation of the *Helper* can be something like:
```
// app/helpers/sorted-strings.js
import Ember from 'ember';
export function sortedStrings(params/*, hash*/) {
return params[0].sort();
}
export default Ember.Helper.helper(sortedStrings);
```
The *Helper* works ok, but if the original `myString` Array changes the changes are not affecting the already rendered list.
How can I combine the behaviour of a *ComputedProperty* and the result of a *Helper*? | 2016/06/14 | [
"https://Stackoverflow.com/questions/37807122",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/316700/"
] | After a lot of struggling I just figured out that the proper solution is to declare a *Component* instead of a *Helper*. This way I can explicitly declare a *Computed Property* that observes changes in the *myStrings* Array:
```
// app/components/sorted-strings.js
export default Ember.Component.extend({
myStrings: null,
sortedMyStrings: Ember.computed('myStrings', function() {
return this.get('myStrings').sort();
});
});
// app/templates/components/sorted-strings.hbs
{{#each sortedMyStrings as |string|}}
{{string}}
{{/each}}
// template
{{sorted-strings myStrings=myStrings}}
``` | Passing a computed property to the helper should work fine. Check out this [twiddle](https://ember-twiddle.com/537e37c6db0f8cab40d4c3f9a15965f0?openFiles=templates.application.hbs%2C).
Maybe your computed property is not getting updated properly. |
64,473,505 | I can figure out iterating through an array for similar numbers, but creating a function in order to do so through 3 arrays is stumping me for some reason. For the assignment I need to limit my built in functions to indexOf and .length.
For example:
```
var sample = [1,2,3,5,6], [2,3,4,5,6], [4,5,6,7,8]
function smallestCommonNumber(arr1, arr2, arr3){
}
```
I will need this function to iterate through the three ascending arrays and return the smallest of any pairs (must match all 3 arrays) and if not, return false. I know that using indexOf will return a specified item, but how would I use that for an unspecified array? | 2020/10/22 | [
"https://Stackoverflow.com/questions/64473505",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Assuming the arrays are *sorted with ascending* values as specified in the question.
Iterate each number in one of the arrays and check if it exists in both of the other arrays using `indexOf`, if not found it will return -1, here using `~` operator to shift -1 to 0 to get a falsy value.
Could just as well just check `.indexOf(..) > -1`.
```js
function smallestCommonNumber(arr1, arr2, arr3){
for (const number of arr1) {
if (~arr2.indexOf(number) && ~arr3.indexOf(number)) {
return number;
}
}
return false;
}
console.log(smallestCommonNumber([1,2,3,5,6], [2,3,4,5,6], [4,5,6,7,8]));
```
For a version that finds the smallest number without ascending arrays:
```js
function smallestCommonNumber(arr1, arr2, arr3){
let smallest = null;
for (const number of arr1) {
if (~arr2.indexOf(number) && ~arr3.indexOf(number)) {
smallest = number < smallest ? number : smallest ?? number;
}
}
return smallest ?? false;
}
console.log(smallestCommonNumber([6,5,3,2,1], [2,3,4,5,6], [4,5,6,7,8]));
``` | Do like:
```js
function inArray(value, array){
if(array.indexOf(value) === -1){
return false;
}
return true;
}
function least(){
let a = [...arguments], l = a.length, q = l-1, r = [];
for(let i=0,b; i<l; i++){
b = a[i];
for(let n=0,c,h; n<l; n++){
if(i !== n){
c = a[n]; h = [];
for(let v of c){
if(inArray(v, b))h.push(v);
}
if(h.length === q)r.push(...h);
}
}
}
return Math.min(...r);
}
const sample1 = [6,3,1,5,2], sample2 = [2,3,4,5,6], sample3 = [4,5,6,7,8];
console.log(least(sample1, sample2, sample3));
``` |
29,615,274 | I am trying to create a piece of code that allows me to ask the user to enter 5 numbers at once that will be stored into a list. For instance the code would would be ran and something like this would appear in the shell
```
Please enter five numbers separated by a single space only:
```
To which the user could reply like this
```
1 2 3 4 5
```
And then the numbers 1 2 3 4 5 would be stored into a list as integer values that could be called on later in the program. | 2015/04/13 | [
"https://Stackoverflow.com/questions/29615274",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4756717/"
] | Your best way of doing this, is probably going to be a list comprehension.
```
user_input = raw_input("Please enter five numbers separated by a single space only: ")
input_numbers = [int(i) for i in user_input.split(' ') if i.isdigit()]
```
This will split the user's input at the spaces, and create an integer list. | You can use something like this:
```
my_list = input("Please enter five numbers separated by a single space only")
my_list = my_list.split(' ')
``` |
40,541,537 | Hi i am newbie here and also for android development , i want to add progress bar while loading the page on webview , after loading that progress need to hide automatically, i dont know how to do it , help me guys
activity\_main.xml:
```
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="0dp"
android:paddingLeft="0dp"
android:paddingRight="0dp"
android:paddingTop="0dp"
tools:context="com.example.tamil.stagingsite.MainActivity">
<ProgressBar
android:id="@+id/progressBar"
style="@android:style/Widget.Material.Light.ProgressBar.Large"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" />
<WebView
android:id="@+id/activity_main_webview"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:animationCache="true"
android:background="@android:color/white">
</WebView>
</RelativeLayout>
```
MainActivity.java
```
package com.example.tamil.stagingsite;
import android.app.Activity;
import android.graphics.Bitmap;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;
public class MainActivity extends Activity {
private WebView mWebView;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
mWebView = (WebView) findViewById(R.id.activity_main_webview);
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mWebView.loadUrl("http://census-staging.herokuapp.com/");
mWebView.setWebViewClient(new WebViewClient());
mWebView.setWebViewClient(new MyAppWebViewClient());
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
@Override
public void onBackPressed() {
if (mWebView.canGoBack()) {
mWebView.goBack();
} else {
super.onBackPressed();
}
}
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
public Action getIndexApiAction() {
Thing object = new Thing.Builder()
.setName("Main Page") // TODO: Define a title for the content shown.
// TODO: Make sure this auto-generated URL is correct.
.setUrl(Uri.parse("http:staging.herokuapp.com/"))
.build();
return new Action.Builder(Action.TYPE_VIEW)
.setObject(object)
.setActionStatus(Action.STATUS_TYPE_COMPLETED)
.build();
}
@Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
AppIndex.AppIndexApi.start(client, getIndexApiAction());
}
@Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
AppIndex.AppIndexApi.end(client, getIndexApiAction());
client.disconnect();
}
}
``` | 2016/11/11 | [
"https://Stackoverflow.com/questions/40541537",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7139804/"
] | To add progress dialog while loading a page on Webview,Add the following code and no need to add the Progressbar in XML.
```
//Intialize the progress dialog:
WebView webview;
ProgressDialog progressDialog;
//Write the following code in OnCreate:
webview=(WebView)findViewById(R.id.webview);
progressDialog=new ProgressDialog(this);
progressDialog.setMessage("Loading");
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.show();
```
After loading the webpage, You have to dismiss the ProgressDialog.For that In OnPageFinish Dismiss the progressDialog.
```
webview.setWebViewClient(new WebViewClient()
{
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl("YOUR URL");
return true;
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
});
``` | initialize the progress bar in main activity and
make progress bar in visible your webviewclient onPageFinished method
```
mWebView.setWebViewClient(new MyAppWebViewClient(this));
```
and
```
private class MyAppWebViewClient extends WebViewClient {
private Context mContext;
public MyAppWebViewClient(Context context) {
this.mContext = context;
}
@Override
public void onPageFinished(final WebView view, String url) {
progressbar.setVisibility(View.GONE);
}
}
``` |
552,836 | I've been looking at dc to dc step up converters/voltage multipliers, and they all seem to make it ac or pulsed dc and reconvert it to dc at the end. Is there a way to step it up directly? A clock circuit is pulsing dc, for whoever got my question closed. | 2021/03/13 | [
"https://electronics.stackexchange.com/questions/552836",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/275065/"
] | Yes, there are switched capacitor voltage multipliers. In one type, you put a number of capacitors in parallel across the input voltage source. Then you reconnect them so they are applied to the load in series. In another approach called a charge pump, you put one capacitor in parallel across the input voltage, and then switch it so it is in series with the input voltage and an output capacitor. Both types are illustrated in the switched capacitor section of this article: <https://en.m.wikipedia.org/wiki/Voltage_doubler> | Short of putting a battery in series, no. |
19,522,275 | Here is an example OpenSearch description file:
```
http://webcat.hud.ac.uk/OpenSearch.xml
```
When I send a query as like that:
```
http://webcat.hud.ac.uk/perl/opensearch.pl?keyword=new&startpage=1&itemsperpage=20
```
I get a response which is compatible to OpenSearch. How can I implement OpenSearch specification at Java or is there any library for it or is there any xsd that I can generate a Java code from it? | 2013/10/22 | [
"https://Stackoverflow.com/questions/19522275",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/453596/"
] | According to the [OpenSearch website](http://www.opensearch.org/Community/OpenSearch_software)'s section on *"Reading OpenSearch"*, there is a Java library which can do this, called [Apache Abdera](http://abdera.apache.org/). I have not used it myself, so I cannot comment on its quality, but it should be worth looking into - apparently it can both interpret AND create OpenSearch responses, so this may be exactly what you're looking for.
Alternatively, there are quite a few very good XML parsers for Java (see [this question](https://stackoverflow.com/questions/373833/best-xml-parser-for-java) for some suggestions), so writing your own parser for a simple OpenSearch XML file shouldn't be *too* difficult, since the [full specification](http://www.opensearch.org/Specifications/OpenSearch/1.1) is available online.
As for an XSD, I can't find an "official" one, however there are XSD's for OpenSearch in various open source projects which have been tested and you can use, such as [this one](http://opensearchvalidator.codeplex.com/SourceControl/latest#TathamOddie.OpenSearchValidator.Logic/Resources/OpenSearchDescription.xsd), which is part of a project called "OpenSearch Validator."
Another potential choice for writing OpenSearch results is the very mature and widely-used [Apache Lucene](http://lucene.apache.org/) library, which is in the list of software "writing OpenSearch results" in the previously linked OpenSearch website. | [ROME](http://github.com/rometools/) also supports OpenSearch with its [ROME Module A9 OpenSearch](http://rometools.github.io/rome-modules/A9OpenSearch.html).
Sample usage:
```
SyndFeed feed = new SyndFeedImpl();
feed.setFeedType(feedType);
// Add the opensearch module, you would get information like totalResults from the
// return results of your search
List mods = feed.getModules();
OpenSearchModule osm = new OpenSearchModuleImpl();
osm.setItemsPerPage(1);
osm.setStartIndex(1);
osm.setTotalResults(1024);
osm.setItemsPerPage(50);
OSQuery query = new OSQuery();
query.setRole("superset");
query.setSearchTerms("Java Syndication");
query.setStartPage(1);
osm.addQuery(query);
Link link = new Link();
link.setHref("http://www.bargainstriker.com/opensearch-description.xml");
link.setType("application/opensearchdescription+xml");
osm.setLink(link);
mods.add(osm);
feed.setModules(mods);
// end add module
``` |
411,523 | I have installed the Windows 8 consumer preview and all working fine, with the exception of the communication apps (mail, calendar & people).
The apps were working during initial installation process, but at some point ceased to operate. The message I receive when launching is "Mail can't open", "Calendar can't open" and "People can't open". I also note that the Weather app doesn't work, and simply hangs on loading screen.
I have attempted install numerous times, but cannot establish the point at which the apps stop working. I assume it probably relates to one of the updates, but that is only a guess.
Has anyone else experienced this? Does anyone have any ideas on resolution?
Many thanks. | 2012/04/12 | [
"https://superuser.com/questions/411523",
"https://superuser.com",
"https://superuser.com/users/127919/"
] | I had the same problem but I resolved it, I found that the antivirus Firewall was the cause, it blocks all metro apps to connect to the network, disable it or change the Firewall rules. | Update: SOLVED!
The problem occurs if you tweak your background colors using a tool or manually. Restore all the default registry entries or default colors using the tool and poof! Problem is gone....
Hope this helps, Phew!
---
This's not exactly an answer but I've the very same problem.
And I've been looking for an answer and have tried the following.
1. Uninstall, re-install - doesn't fix.
2. Create new user on Consumer preview and try these apps/ re-install there. - doesn't fix
so 1 thing is for certain, the problem is not within the "Users or Users/name/appdata"
3. I replace all metro app files in my PC (taking ownership) for another working fresh Consumer Preview install on another PC (where the people/msgs/cal/email app works fine). - Still doesn't fix.
so the program files ain't the culprit either.
4. That leaves 2 things - the windows folder (the metro framework) and the registry.
Now the problem can't be with the metro framework because other apps work fine and the msgs/people/mail/cal app can be uninstalled which means it is not coded into the system.
So that leaves the registry, which should be the culprit. I have yet to try messing with the registry to solve this. Will edit this answer if I do find something.
Refresh apparently solves this but I don't want to be re-installing all my desktop apps. |
31,849,337 | I have an application where I use background images.
I don´t want my images to be stretched or deformed when I run my application on different screens with different ratios.
I already have different images for different screen sizes.
1. Can someone please explain to me how Android Studio handles the image sizes.
2. How can I make it that the image isn´t streched, but a sector that fits the screen is being displayed? | 2015/08/06 | [
"https://Stackoverflow.com/questions/31849337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4968411/"
] | As of Carbon 1.29 it is possible to do:
```
$period = CarbonPeriod::create('2018-06-14', '2018-06-20');
// Iterate over the period
foreach ($period as $date) {
echo $date->format('Y-m-d');
}
// Convert the period to an array of dates
$dates = $period->toArray();
```
See documentation for more details: <https://carbon.nesbot.com/docs/#api-period>. | As Carbon is an extension of PHP's built-in DateTime, you should be able to use DatePeriod and DateInterval, exactly as you would with a DateTime object
```
$interval = new DateInterval('P1D');
$to->add($interval);
$daterange = new DatePeriod($from, $interval ,$to);
foreach($daterange as $date){
echo $date->format("Ymd"), PHP_EOL;
}
```
**EDIT**
If you need to include the final date of the period, then you need to modify it slightly, and adjust `$to` before generating the DatePeriod
```
$interval = new DateInterval('P1D');
$daterange = new DatePeriod($from, $interval ,$to);
foreach($daterange as $date){
echo $date->format("Ymd"), PHP_EOL;
}
``` |
903,514 | I looked all over the web, and I saw many solutions to this issue, but none of them worked for me, and I don't know what to do anymore.
It's a win7 PC, professional edition x64. I'm using a Realtek network adapter.
Things I tried:
* removing the driver and re-installing
* Installing the IPv4 protocol
* restarting the computer
* in cmd: ipconfig/all, ipconfig/release, ipconfig/renew (I used to have IP conflicts, but not anymore)
* Made sure that the IP and DNS are chosen dynamically
* stopping the Bonjour service
* removing Bonjour from the windows firewall allowed programs
* Setting a static IP (but the addresses might have been wrong) | 2015/04/19 | [
"https://superuser.com/questions/903514",
"https://superuser.com",
"https://superuser.com/users/310772/"
] | This can have many causes, but the most common ones are:
* Incompatible mode (your wifi card is too old)
* Noisy signal (Something else running on the same channel? Gain too high?)
* Wrong wifi password (For some reason, it takes Win7 ages to figure this one out)
* The SSID isn't actually there anymore, but windows thinks it is. (SSID physically moved, or is switched off)
In addition, in my line of work where I have to switch between wireless networks a lot, I've found a bug where Win7 hangs on identifying like you described. This happens when disconnecting from a network, then trying to connect to that same network again. The workaround is to disconnect as normal, then select a different network, then select the one you want to connect to, and hit the connect button.
**Note:**
Are you sure the network is functioning as intended? Have you tested it with a different device? | I had the exact same issue. The solution for my laptop was:
Device Manager - Network Adapters - Realtek P Cle GBE Family Connector and found it had been disabled. I enabled it and restarted and it worked! |
9,841,215 | I would like to give points to my users who submit articles based on their articles word count.
But my page has many text area fields. Lets say message1,message2,message3
When the user fill textarea(message1,message2,message3) it will show like this in the bottom.
```
You have typed x words. Points per word : 0.2. Estimated point: xx
```
I also want to calculate overall points. So i would like to add points of message1,message2,message3 and display it as overall points.
I'm a jquery noob. So i'm not sure which variable i should call.
Here is the [jfiddle](http://jsfiddle.net/Viruthagiri/yZb7w/29/) code what i have so far.
Can someone help me? Thanks | 2012/03/23 | [
"https://Stackoverflow.com/questions/9841215",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1091558/"
] | Keep the count of every Textfield in an array that you can use to compute the overall sum.
I've edited your code, see the demo here: <http://jsfiddle.net/yZb7w/38/> | Another solution would be to have something like:
```
$('#testTextarea3').textareaCount(options3, function(data){
$('#showData3').html("You have typed <b>" + data.words + "</b> words. Points per word : <b> 0.2</b>. Estimated point: <b>" + (0.2 * data.words) +"</b>");
$(this).data("points",(0.2 * data.words));
});
```
This will store the points value per testTextarea. The next step you will do is have a totalScore textarea or some updating behavior for some component and extract stored scored from all the textAreas like:
```
$('#testTextarea3').data("points");
``` |
3,681,243 | I need to time some events in the app I'm working on. In Java i used to be able to call currentTimeMillis() but there doesnt seem to be a version in Objective-c. Is there a way to check there current time without creating a NSDate and then parsing this object everytime i need this information?
Thanks
-Code | 2010/09/09 | [
"https://Stackoverflow.com/questions/3681243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | To get very cheap very precise time, you can use [`gettimeofday()`](http://developer.apple.com/library/ios/#documentation/system/conceptual/manpages_iphoneos/man2/gettimeofday.2.html), which is a C Function of the BSD kernel. Please read the man page for full details, but here's an simple example:
```
struct timeval t;
gettimeofday(&t, NULL);
long msec = t.tv_sec * 1000 + t.tv_usec / 1000;
``` | The correct answer is [[NSDate date] timeIntervalSince1970]; this will give you current timestamp in milliseconds.
The answer given by @Noah Witherspoon returns current date but the year is not the current matching year. |
34,068,224 | I am stuck on trying to create an alias that will cd back a directory, make a new directory with a given name and then cd into it. Here is what I have so far:
alias cdmk="cd .. | mkdir '$1' | cd '$1'"
I just want to be able to type cdmk and then the name of the new directory I want to create and cd into.
Any help you can give would be much appreciated! | 2015/12/03 | [
"https://Stackoverflow.com/questions/34068224",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5635353/"
] | You can use
```
\(([^);]+)
```
The [regex demo is available here](https://regex101.com/r/dN5dC1/2).
Note the capturing group I set with the help of unescaped parentheses: the value captured with this subpattern is returned by the [`re.findall` method](https://docs.python.org/2/library/re.html#re.findall), not the whole match.
It matches
* `\(` - a literal `(`
* `([^);]+)` - matches and captures 1 or more characters other than `)` or `;`
[Python demo](https://ideone.com/BkHRrP):
```
import re
p = re.compile(r'\(([^);]+)')
test_str = "1. yada yada yada (This is a string; \"This is a thing\")\n2. blah blah blah (This is also a string)"
print(p.findall(test_str)) # => ['This is a string', 'This is also a string']
``` | I would suggest
```
^[^\(]*\(([^;\)]+)
```
Splitting it into parts:
```
# ^ - start of string
# [^\(]* - everything that's not an opening bracket
# \( - opening bracket
# ([^;\)]+) - capture everything that's not semicolon or closing bracket
```
Unless of course you wish to impose (or drop) some requirements on "blah blah blah" part.
You can drop the first two parts, but then it will match some things it probably shouldn't... or maybe it should. It all depends on what your objectives are.
P. S. Missed that you want to find all instances. So multiline flag needs to be set:
```
pattern = re.compile(r'^[^\(]*\(([^;\)]+)', re.MULTILINE)
matches = pattern.findall(string_to_search)
```
It is important to check for beginning of the line, because your input can be:
```
"""1. yada yada yada (This is a string; "This is a (thing)")
2. blah blah blah (This is also a string)"""
``` |
69,183,922 | I am trying to automate the scraping of a site with "infinite scroll" with Python and Playwright.
The issue is that Playwright doesn't include, as of yet, a scroll functionnality let alone an infinite auto-scroll functionnality.
From what I found on the net and my personnal testing, I can automate an infinite or finite scroll using the `page.evaluate()` function and some Javascript code.
For example, this works:
```
for i in range(20):
page.evaluate('var div = document.getElementsByClassName("comment-container")[0];div.scrollTop = div.scrollHeight')
page.wait_for_timeout(500)
```
The problem with this approach is that it will either work by specifying a number of scrolls or by telling it to keep going forever with a `while True` loop.
I need to find a way to tell it to keep scrolling until the final content loads.
This is the Javascript that I am currently trying in `page.evaluate()`:
```
var intervalID = setInterval(function() {
var scrollingElement = (document.scrollingElement || document.body);
scrollingElement.scrollTop = scrollingElement.scrollHeight;
console.log('fail')
}, 1000);
var anotherID = setInterval(function() {
if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
clearInterval(intervalID);
}}, 1000)
```
This does not work either in my firefox browser or in the Playwright firefox browser. It returns immediately and doesn't execute the code in intervals.
I would be grateful if someone could tell me how I can, using Playwright, create an auto-scroll function that will detect and stop when it reaches the bottom of a dynamically loading webpage. | 2021/09/14 | [
"https://Stackoverflow.com/questions/69183922",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12499866/"
] | The other solutions were a tad bit verbose and "overkill" for me and this is what worked for me.
Here's a two liner that took me a few migraines to come around to :)
**Note:** you are going to have to *put in your own selector*. This is just an example...
```
while page.locator("span",has_text="End of results").is_visible() is False:
page.mouse.wheel(0,100)
#page.keyboard.down(PageDown) also works
```
Literally just keep scrolling until some sort of unique selector is present. In this case a span tag with the string "End of results" (for the context of my use case) popped up when you scroll to the bottom.
I trust you can translate this logic for you own usage.. | the playwright has the `page.keyboard.down('End')` command, it will scroll to the end of the page. |
42,811,045 | I am practising some entry-level java 8 lambda functionality.
Given a list of messages, each containing a message offset, where all offsets must form a consecutive list of integers, I'm trying to find gaps to warn about. I get the feeling this all should be well doable with a nice lambda. But I can't get my head around it.
So, there's this working snippet:
```
private void warnAboutMessageGaps(final List<Message> messages) {
final List<Long> offsets = messages.stream()
.sorted(comparingLong(Message::getOffset))
.map(Message::getOffset)
.collect(toList())
;
for (int i = 0; i < offsets.size() - 1; i++) {
final long currentOffset = offsets.get(i);
final long expectedNextOffset = offsets.get(i) + 1;
final long actualNextOffset = offsets.get(i + 1);
if (currentOffset != expectedNextOffset) {
LOG.error("Missing offset(s) found in messages: missing from {} to {}", currentOffset + 1, actualNextOffset - 1);
}
}
}
```
What I can't figure out is how to make it so that I can do the "compare with previous/next object" in the lambda. Any pointers would be appreciated.
/edit: Suggestions about StreamEx and other third-party solutions, while appreciated, are not what I was looking for. | 2017/03/15 | [
"https://Stackoverflow.com/questions/42811045",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4347951/"
] | *for the present problem, this approach seems to be more suitable*
```
messages.stream().sorted( Comparator.comparingLong( Message::getOffset ) )
.reduce( (m1, m2) -> {
if( m1.getOffset() + 1 != m2.getOffset() )
LOG.error( "Missing offset(s) found in messages: missing from {} to {}", m1.getOffset(), m2.getOffset() );
return( m2 );
} );
```
This solution uses `reduce` away from its intended use. It solely uses the ability of `reduce` to go over all the pairs in a stream.
The result of `reduce` is **not** used. (It would be impossible to use the result any further, because that would require a mutable reduction.) | How about:
```
final List<Long> offsets = messages.stream().map(Message::getOffset).sorted().collect(toList());
IntStream.range(0, offsets.size() - 1).forEach(i -> {
long currentOffset = offsets.get(i);
if (offsets.get(i + 1) != currentOffset + 1) {
LOG.error("Missing offset(s) found in messages: missing from {} to {}", currentOffset + 1, offsets.get(i + 1) - 1);
}
});
```
Or All in one statement by [StreamEx](https://github.com/amaembo/streamex):
```
StreamEx.of(messages).mapToLong(Message::getOffset).sorted().boxed()
.pairMap((i, j) -> new long[] { i, j }).filter(a -> a[1] - a[0] > 1)
.forEach(a -> LOG.error("Missing offset(s) found in messages: missing from {} to {}", a[0] + 1, a[1] - 1));
```
Or All in one statement by [AbacusUtil](https://github.com/landawn/AbacusUtil):
```
Stream.of(messages).mapToLong(Message::getOffset).sorted()
.sliding0(2).filter(e -> e.size() == 2 && e.get(1) - e.get(0) > 1)
.forEach(e -> LOG.error("Missing offset(s) found in messages: missing from {} to {}", e.get(0) + 1, e.get(1) - 1));
``` |
4,122,361 | I am trying to show that $$\frac{1}{a^2+x^2} \ast \frac{1}{a^2+x^2}=\int\_{-\infty}^\infty\frac{1}{(a^2+t^2)(a^2+(x-t)^2) }dt = \frac{2\pi}{a(4a^2+x^2)}$$ I wrote out the integral for the convolution and it becomes a big exercise in partial fractions and integration of rational functions.
$$ \int(\frac{1}{a^2+t^2}) (\frac{1}{a^2+(x-t)^2}) dt=
\int\frac{x + 2 t}{x (4 a^2 + x^2) (a^2 + t^2)} + \frac{3 x - 2 t}{x (4 a^2 + x^2) (a^2 + x^2 - 2 xt + t^2)} dt =$$
$$=\frac{a (log(a^2 + t^2) - log(a^2 + (x - t)^2)) + x \cdot tan^{-1}(\frac{t}{a}) + x \cdot tan^{-1}(\frac{t - x}{a})}
{a x (4 a^2 + x^2)}
$$
Plugging in the bounds of plus/minus infinity makes the logs cancel out, and gives the 2$\pi x$ from the arctan terms.
My question: Is there a way to simplify / make this any easier using the properties of the convolution? Or are these problems just 'plug and chug' like back in my engineering days? | 2021/04/30 | [
"https://math.stackexchange.com/questions/4122361",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/623019/"
] | Here using Fourier transform may simplify things considerably:
Let $\phi(x)=\frac{1}{1+x^2}$, and $\phi\_a(x)=\frac{1}{a}\phi(a^{-1}x)=\frac{a}{a^2+x^2}$.
Recall that $\pi e^{-2\pi|t|}=\int e^{-2\pi itx}\frac{1}{1+x^2}\,dx=\widehat{\phi\_1}(t)$. Hence
$$\widehat{\phi\_a}(t)=\frac{1}{a}\int e^{-2\pi itx}\phi(xa^{-1})\,dx=\frac{1}{a}\int e^{2\pi ia t(a^{-1}x)}\phi(a^{-1}x)\,dx=\widehat{\phi\_1}(at)$$
Thus
$$\widehat{\phi\_a\*\phi\_a}(t)=(\widehat{\phi\_a}(t))^2=(\widehat{\phi\_1}(at))^2=\pi^2e^{-4\pi a|t|}$$
That is,
$$
I\_a=a^{-2}(\phi\_a\*\phi\_a)(x)=a^{-2}\pi^2\mathcal{F}^{-1}(e^{-4\pi a|t|})(x)=\frac{2\pi}{a(a^2+x^2)}$$ | Less elegant than @Quanto's answer, let us write
$$a^2+(x-t)^2=(t-r)(t-r)$$ with $r=(x+ia)$ and $r=(x-ia)$ and use partial fraction decomposition
$$\frac{1}{(a^2+t^2)(a^2+(x-t)^2) }=\frac{r s+r t+s t-a^2}{\left(a^2+r^2\right) \left(a^2+s^2\right) \left(t^2+a^2\right)}+$$
$$\frac{1}{\left(a^2+r^2\right) (r-s) (t-r)}-\frac{1}{\left(a^2+s^2\right) (r-s) (t-s)}$$ Three simple antiderivatives and then the result. |
17,981,834 | I installed SDL 1.2 long time ago with my package manager and now I have just installed from source the new SDL version (2.0).
Do you think it is safe to keep both version on the same OS? I need the old versions for other applications so I would prefer to have both..
PS I am on Linux.
Cheers! | 2013/07/31 | [
"https://Stackoverflow.com/questions/17981834",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1977035/"
] | To become familiar with state restoration I highly recommend the [WWDC 2013 session What's New in State Restoration](https://developer.apple.com/videos/wwdc/2013/#222). While state restoration was introduced a year earlier in iOS 6, iOS 7 brought some notable changes.
### Passing it forward
Using the "pass the baton" approach, at some point a root `NSManagedObjectContext` is created and an `NSPersistentStoreCoordinator` is attached. The context is passed to a view controller and subsequent child view controllers are in turn passed that root context or a child context.
For example, when the user launches the application the root `NSManagedObjectContext` is created and passed in to the root view controller, which manages an `NSFetchedResultsController`. When the user selects an item in the view controller a new detail view controller is created and an `NSManagedObjectContext` instance is passed in.

### Saving and Restoring State
State restoration changes this in ways that are significant to applications using Core Data in view controllers. If the user is on the detail view controller and sends the application to the background the system creates a restoration archive with information useful for reconstructing the state visible when they left. Information about the entire chain of view controllers is written out, and when the application is relaunched this is used to reconstruct the state.

When this happens it does not use any custom initializers, segues, etc. The `UIStateRestoring` protocol defines methods used for encoding and decoding state which allow for some degree of customization. Objects that conform to `NSCoding` can be stored in restoration archives and in iOS 7 state restoration was extended to model objects and data sources.
State restoration is intended to store only the information that is required to reconstruct the visible state of the application. For a Core Data application this means storing the information needed to locate the object in the correct persistent store.
On the surface, this seems simple. In the case of a view controller managing an `NSFetchedResultsController` this may mean storing the predicate and sort descriptors. For a detail view controller that displays or edits a single managed object the URI representation of the managed object would be added to the state restoration archive:
```
- (void) encodeRestorableStateWithCoder:(NSCoder *)coder {
NSManagedObjectID *objectID = [[self managedObject] objectID];
[coder encodeObject:[objectID URIRepresentation] forKey:kManagedObjectKeyPath];
[super encodeRestorableStateWithCoder:coder];
}
```
When the state is restored the UIStateRestoring method `-decodeRestorableStateWithCoder:` is called to restore the object from the archived information:
1. Decode the URI from the restoration archive.
2. Get a managed object ID for the URI from the persistent store coordinator
3. Get a managed object instance from the managed object context for that managed object ID
For example:
```
- (void) decodeRestorableStateWithCoder:(NSCoder *)coder {
NSURL *objectURI = nil;
NSManagedObjectID *objectID = nil;
NSPersistentStoreCoordinator *coordinator = [[self managedObjectContext] persistentStoreCoordinator];
objectURI = [coder decodeObjectForKey:kManagedObjectKeyPath];
objectID = [coordinator managedObjectIDForURIRepresentation:objectURI];
[[self managedObjectContext] performBlock:^{
NSManagedObject *object = [self managedObjectContext] objectWithID:objectID];
[NSOperationQueue mainQueue] addOperationWithBlock:^{
[self setManagedObject:object];
}];
}];
}
```
And this is where things become more complicated. At the point in the application life cycle where `-decodeRestorableStateWithCoder:` is called the view controller will need the *correct* `NSManagedObjectContext`.
Pass the Baton vs. State Restoration: FIGHT!
With the "pass the baton" approach the view controller was instantiated as a result of user interaction, and a managed object context was passed in. That managed object context was connected to a parent context or persistent store coordinator.
During state restoration that does not happen. If you look at the illustrations of what happens during "pass the baton" vs. state restoration they may look very similar - and they are. During state restoration data *is* passed along - the `NSCoder` instance that represents an interface to the restoration archive.
Unfortunately the `NSManagedObjectContext` information we require can't be stored as part of the restoration archive. `NSManagedObjectContext` *does* conform to `NSCoding`, however the important parts do not. `NSPersistentStoreCoordinator` does not, so it will not be persisted. Curiously, the `parentContext` property of an `NSManagedObjectContext` also will not (I would strongly suggest filing a radar on this).
Storing the URLs of specific `NSPersistentStore` instances and recreating an `NSPersistentStoreCoordinator` in each view controller may seem like an attractive option but the result will be a different coordinator for each view controller - which can quickly lead to disaster.
So while state restoration can provide the information needed to locate entities in an `NSManagedObjectContext`, it can't directly provide what is needed to recreate the context itself.
### So what next?
Ultimately what is needed in a view controller's `-decodeRestorableStateWithCoder:` is an instance of `NSManagedObjectContext` that has the same parentage that it did when state was encoded. It should have the same structure of ancestor contexts and persistent stores.
State restoration begins in the UIApplicationDelegate, where several delegate methods are invoked as part of the restoration process (`-application:willFinishLaunchingWithOptions:`, `-application:shouldRestoreApplicationState:`, `-didDecodeRestorableStateWithCoder:`, `-application:viewControllerWithRestorationIdentifierPath:coder:`). Each one of these is an opportunity to customize the restoration process from the beginning and pass information along - such as attaching an `NSManagedObjectContext` instance as an associated object reference to the `NSCoder` used for restoration.
If the application delegate object is responsible for creating the root context that object could be pushed down throughout the view controller chain once the launch process is complete (with or without state restoration). Each view controller would pass the appropriate `NSManagedObjectContext` instance to it's child view controllers:
```
@implementation UIViewController (CoreData)
- (void) setManagedObjectContext:(NSManagedObjectContext *)context {
[[self childViewControllers] makeObjectsPerformSelector:_cmd withObject:context];
}
@end
```
And each view controller that provided it's own implementation would create a child context of it's own. This has other advantages - any approach that has the users of a managed object context react to it changing makes it easier to create the context asynchronously. Creating a context itself is fast and lightweight, but adding the persistent stores to the root context is potentially very expensive and should not be allowed to run on the main queue. Many applications do this on the main queue in an application delegate method and end up being killed by the OS when opening the files of the store takes too long or a migration is required. Adding the persistent store on another thread and then sending the context to the objects that use it when it's ready can help prevent these kinds of problems.
Another approach may be to leverage the responder chain in the view controller. During state restoration the view controller could walk the responder chain to find the next `NSManagedObjectContext` up the chain, create a child context, and use that. Implementing this using an informal protocol is simple, and results in a solution that is flexible and adaptable.
The default implementation of the informal protocol would walk further up the responder chain:
```
@implementation UIResponder (CoreData)
- (NSManagedObjectContext *) managedObjectContext {
NSManagedObjectContext *result = nil;
if ([self nextResponder] != nil){
if ([[self nextResponder] respondsToSelector:@selector(managedObjectContext)]){
result = [[self nextResponder] managedObjectContext];
}
}
return result;
}
@end
```
And any object in the responder chain can implement `-managedObjectContext` to provide an alternate implementation. This includes the application delegate, which does participate in the responder chain. Using the informal protocol above, if a view or view controller calls `-managedObjectContext` the default implementation would go all the way to the application delegate to return a result unless some other object along the way provided a non-nil result.
You also have the option of using restoration class factories with state restoration to reconstruct the chain of managed object contexts during restoration.
These solutions are not appropriate for every application or situation, only you can decide what will work for you. | I have not done a ton with state restore but I would think along these lines:
* Does the app delegate get woken up first? Is there an opportunity for the app delegate to walk the view controllers?
* Can the view controller *pause* while it waits for the AppDelegate to give it the context?
Sounds like State Restoration might be a special case *but* I would explore the option of making the view controllers smart enough to wait for the MOC to appear before asking for data. Maybe even having a roll back state in the view controllers where they step back to a place where the view controller can wait for the context. |
336,854 | When I first saw this meme:
[](https://i.stack.imgur.com/pntYI.png)
I thought to myself, *yeah right*, but now I am not sure any more. So **was template meta programming in C++ discovered by accident** as the meme claims or was it intentional?
Did Bjarne & co actually make it without realizing the potential? | 2016/11/25 | [
"https://softwareengineering.stackexchange.com/questions/336854",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/173147/"
] | There is more to invention than giving a simple list of implications and with C++ Stroustrup aimed for generality:
>
> I'm not interested in a language that can only do what I can imagine
>
>
>
This is from [Did you really not understand what you were doing?](http://www.stroustrup.com/bs_faq.html#understand):
>
> This one seems very popular. Or rather, it seems to be popular to assert that I had no clue so that C++'s success is some kind of accident. Yes, such statements annoy me, because they dismiss my work over decades and the hard work of many of my friends.
>
>
> Let's first be perfectly clear: No, I did not anticipate the run-away success of C++ and no, I did not forsee every technique used with C++ or every application of C++. Of course not!
>
>
> However, statements like these are very misleading:
>
>
> * Bjarne doesn't understand C++!
> * Bjarne didn't anticipate RAII and deterministic destruction!
> * Bjarne didn't anticipate template-metaprogramming!
>
>
> I did outline the criteria for the design and implementation of C++. I did explicitly aim for generality: "I'm not interested in a language that can only do what I can imagine" and for efficiency "a facility must not just be useful, it must be affordable."
>
>
> [CUT]
>
>
> I was very surprised when Jeremy Siek first showed my the compile-time if that later became `std::conditional`, but I had aimed for generalty (and gotten Turing completeness modulo translation limits). I opposed restrictions to C++ immediately when Erwin Unruh presented what is widly believed to be the first template metaprogram to the ISO Standards committee's evolution working group. To kill template-metaprogramming, all I would have had to do was to say nothing. Instead my comment was along the lines "Wow, that's neat! We mustn't compromise it. It might prove useful." Like all powerful ideas, template-metaprogramming can be misused and overused, but that does not imply that the fundamental idea of compile-time computation is bad. And like all powerfuls ideas, the implications and techniques emerged over time with contributions from many individuals.
>
>
> | *The following excerpt is subject to: <https://creativecommons.org/licenses/by-sa/3.0/>*
>
> History of TMP
>
>
> Historically TMP is something of an accident; it was discovered during the process of standardizing the C++ language that its template system happens to be Turing-complete, i.e., capable in principle of computing anything that is computable. The first concrete demonstration of this was a program written by Erwin Unruh, which computed prime numbers although it did not actually finish compiling: the list of prime numbers was part of an error message generated by the compiler on attempting to compile the code.
>
>
>
Source: <https://en.wikibooks.org/wiki/C%2B%2B_Programming/Templates/Template_Meta-Programming#History_of_TMP> |
48,452,060 | I want to calculate the RMSE of two unequal data sets.
Dataset 1 has the dimensions 1067x1 and dataset 2 has the dimensions 2227x1.
How do I calculate the RMSE?
Thanks | 2018/01/25 | [
"https://Stackoverflow.com/questions/48452060",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8362417/"
] | The `antd` support recommends using `onValuesChange` in `Form.create()` <https://github.com/ant-design/ant-design/issues/20418>
I found this workaround that works for me:
```
<Radio.Group
onChange={(e: RadioChangeEvent) => {
form.setFieldsValue({ yourRadioFieldNameFromGetFieldDecorator: e.target.value }, () => {
handleChange();
});
}}
>
```
The callback ensures that field value is set. | You should really use `e.target.value` if you want the value immediately. since the value is not set yet (to the antd form yet) at the moment you click the radio.(the field needs to pass setStatus, setfeedback etc)
if you really want to use getFieldValue, you can do the setTime strick
```
setTimeout(() => console.log(this.props.form.getFieldValue('radio-group')), 0)
``` |
2,235,365 | Using Java 6 to get 8-bit characters from a String:
```
System.out.println(Arrays.toString("öä".getBytes("ISO-8859-1")));
```
gives me, on Linux: [-10, 28]
but OS X I get: [63, 63, 63, -89]
I seem get the same result when using the fancy new nio CharSetEncoder class. What am I doing wrong? Or is it Apple's fault? :) | 2010/02/10 | [
"https://Stackoverflow.com/questions/2235365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/231633/"
] | Maybe the character set for the source is not set (and thus different according to system locale)?
Can you run the same compiled class on both systems (not re-compile)? | Bear in mind that there's more than one way to represent characters. Mac OS X uses unicode by default, so your string literal may actually not be represented by two bytes. You need to make sure that you load the string from the appropriate incoming character set; for example, by specifying in the source a \u escape character. |
33,817,327 | Say I have some OCaml code where I need to use the `Str` module. If I run the code with the interpreter, then I have to put `#load Str.cma` to be able to use the `Str` module. But if I want to native-compile the code, then the `load` directive causes an error. How can I import the module in a way that will work in both cases?
I'm looking for either
(a) a way to include the module that works in both modes; or
(b) a way to load the module for the interpreter that will be ignored by the compiler, leaving me to specify it on the command line. | 2015/11/20 | [
"https://Stackoverflow.com/questions/33817327",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3722213/"
] | with the benefits of a context manager:
```
with requests_html.HTMLSession() as s:
try:
r = s.get('http://econpy.pythonanywhere.com/ex/001.html')
links = r.html.links
for link in links:
print(link)
except:
pass
``` | ```
from requests_html import HTMLSession
session = HTMLSession()
r = session.get('https://www.***.com')
r.html.links
```
[Requests-HTML](https://html.python-requests.org) |
28,563,621 | I have this SQL query:
```
SELECT * FROM [CMS_MVC_PREPROD].[dbo].[T_MEMBER] m
left outer join [CMS_MVC_PREPROD].[dbo].[T_COMPANY] c
ON m.Company_Id = c.Id
left outer join [CMS_MVC_PREPROD].[dbo].[T_ADRESSE] a
ON m.Id = a.Member_Id OR a.Company_Id = c.Id
```
But i could not translate it to Linq
I have some trouble with this line in particular:
```
ON m.Id = a.Member_Id OR a.Company_Id = c.Id
```
EDIT: I try this query from Ehsan Sajjad
```
from m in db.Member
join c in db.T_Company on m.Company_Id equals c.Id into a
from c in a.DefaultIfEmpty()
from ta in db.T_Address
where m.Id == ta.Member_Id || ta.Company_Id == c.Id
```
But it only returns members who have an address and i want all members. Maybe it will work with a full join
Thanks in advance | 2015/02/17 | [
"https://Stackoverflow.com/questions/28563621",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3830047/"
] | LINQ only supports equi-joins directly. You'll have to use a different query pattern:
```
from m in db.MEMBER
//add join to "c" here
from a in (
from a db.ADRESSE
where m.Id == a.Member_Id || a.Company_Id == c.Id
select a).DefaultIfEmpty()
select new { m, a }
```
Just a sketch. The trick is using `DefaultIfEmpty` on a subquery. Both L2S and EF can translate this to an `OUTER APPLY` which is equivalent to a `LEFT JOIN`. | You can write this way to make it work:
```
from m in db.Member
join c in db.T_Company on m.Company_Id equals c.Id into a
from c in a.DefaultIfEmpty()
from ta in db.T_Address
where m.Id == ta.Member_Id || ta.Company_Id == c.Id
``` |
43,658,274 | I never used Jasmine before but I'm required for this little project that I'm working on. Can't quite figure it out, any help would be appreciated. I have looked at various tutorials and googeled the problem but being new to this does not help.
JS source file
```
> $(document).ready(function(){
>
>
> $.ajax({ type: 'GET', dataType: "json", url: "db.php/realmadrids",
> success: showResponse, error: showError });
>
>
>
>
>
>
> console.debug("error"); function showResponse(responseData){
>
> //$("#get1").click(function getPlayers(responseData) {
> console.log('Image is clicked'); console.log(responseData);
> $.each(responseData.realmadrid, function(index, realmadrid){
> console.log(' is ');
> $("#playercontentRealMadrid").append("</br><strong> Full Name: </strong>" +realmadrid.PlayerName+ " "+realmadrid.PlayerLastName+"
> </br> <strong>Player Position: </strong>" +realmadrid.PlayerPosition+"
> </br><strong>Player Age: </strong>" +realmadrid.Age+"
> </br><strong>Player Height: </strong>" +realmadrid.Height+"
> </br><strong>Player Weight: </strong>" +realmadrid.Weight+"
> </br><strong>Team Name: </strong>" +realmadrid.TeamName+"</br>");
>
> console.log('Data should output'); // }); });
>
> console.log(responseData);
> }
> console.debug("hello");
>
> function showError(){ alert("Sorry, but something went wrong. Fix
> it!!!!") }
>
> });
```
Here is my test code:
>
>
> ```
> //Test Suite
> describe("Spy on my own AJAX call", function(){
>
> it("should make AJAX request with successful setting", function() {
>
> spyOn($, "ajax");
>
> expect($.ajax).toHaveBeenCalledWith({
> url:'db.php/realmadrids',
> type:'GET',
> dataType: "json",
> sucess: showResponse,
> error: showError
> });
>
> });
>
> });
>
> ```
>
> | 2017/04/27 | [
"https://Stackoverflow.com/questions/43658274",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7291306/"
] | I have the same issue in my Angular 7 project.
The below steps solved the issue.
add below code on top of the spec.ts file
```
declare var $: any;
```
A Karma plugin - adapter for jQuery framework.
```
npm install karma-jquery --save-dev
```
Add the '**karma-jquery**' in 'plugins' array in the karma.conf.js file
```
module.exports = function(config) {
config.set({
plugins: ['karma-jquery']
```
Add version of the jquery in frameworks array in the same file.
```
frameworks: ['jasmine', '@angular-devkit/build-angular','jquery-3.2.1']
``` | I'm using this approach, it's simple!
Into file karma.conf.ts I've put the path of jquery.
```
module.exports = function(config) {
config.set({
// list of files / patterns to load in the browser
files: [
'./node_modules/jquery/dist/jquery.min.js',
//..rest files
],
//rest karma options
});
};
```
Based on <https://stackoverflow.com/a/19073586/231391> |
38,717,543 | I have a large dataTable which contains ride information. Every row has a start datetime and an end datetime of the following format(yyyy-mm-dd HH:mm:ss). How can I use a datepicker for setting a filter range in dataTables? I want to have a datepicker which only selects a day and not the time. I've searched everywhere for the proper answer but I couldn't find it. Thanks in advance for helping.
For example I want to see all rows of July by selecting (01-07-2016 - 31-07-2016). | 2016/08/02 | [
"https://Stackoverflow.com/questions/38717543",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3397167/"
] | Using other posters code with some tweaks:
```
<table id="MainContent_tbFilterAsp" style="margin-top:-15px;">
<tbody>
<tr>
<td style="vertical-align:initial;"><label for="datepicker_from" id="MainContent_datepicker_from_lbl" style="margin-top:7px;">From date:</label>
</td>
<td style="padding-right: 20px;"><input name="ctl00$MainContent$datepicker_from" type="text" id="datepicker_from" class="datepick form-control hasDatepicker" autocomplete="off" style="cursor:pointer; background-color: #FFFFFF">
</td>
<td style="vertical-align:initial"><label for="datepicker_to" id="MainContent_datepicker_to_lbl" style="margin-top:7px;">To date:</label>
</td>
<td style="padding-right: 20px;"><input name="ctl00$MainContent$datepicker_to" type="text" id="datepicker_to" class="datepick form-control hasDatepicker" autocomplete="off" style="cursor:pointer; background-color: #FFFFFF">
</td>
<td style="vertical-align:initial"><a onclick="$('#datepicker_from').val(''); $('#datepicker_to').val(''); return false;" id="datepicker_clear_lnk" style="margin-top:7px;">Clear</a></td>
</tr>
</tbody>
</table>
<script>
$(document).ready(function() {
$(function() {
var oTable = $('#tbAD').DataTable({
"oLanguage": {
"sSearch": "Filter Data"
},
"iDisplayLength": -1,
"sPaginationType": "full_numbers",
"pageLength": 50,
});
$("#datepicker_from").datepicker();
$("#datepicker_to").datepicker();
$('#datepicker_from').change(function (e) {
oTable.draw();
});
$('#datepicker_to').change(function (e) {
oTable.draw();
});
$('#datepicker_clear_lnk').click(function (e) {
oTable.draw();
});
});
$.fn.dataTable.ext.search.push(
function (settings, data, dataIndex) {
var min = $('#datepicker_from').datepicker("getDate") == null ? null : $('#datepicker_from').datepicker("getDate").setHours(0,0,0,0);
var max = $('#datepicker_to').datepicker("getDate") == null ? null : $('#datepicker_to').datepicker("getDate").setHours(0,0,0,0);
var startDate = new Date(data[9]).setHours(0,0,0,0);
if (min == null && max == null) { return true; }
if (min == null && startDate <= max) { return true; }
if (max == null && startDate >= min) { return true; }
if (startDate <= max && startDate >= min) { return true; }
return false;
}
);
});
</script>
``` | Follow the link below and configure it to what you need. Daterangepicker does it for you, very easily. :)
<http://www.daterangepicker.com/#ex1> |
21,994,651 | I want to check if there is a certain value in an array of objects.
For example, if I have something like this:
```
[ { _id: 1,
name: foo },
{ _id: 2,
name: bar },
{ _id: 3,
name: foox },
{ _id: 4,
name: fooz },
]
var search = [1,25,33,4,22,44,5555,63]
```
then I want to check if one of the values in `search` is in one of the objects contained in the array of objects. | 2014/02/24 | [
"https://Stackoverflow.com/questions/21994651",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3093439/"
] | Use [`some`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/some) to iterate over the array of objects. If an id is found `some` short-circuits and doesn't continue with the rest of the iteration.
```js
const data=[{_id:1,name:'foo'},{_id:2,name:'bar'},{_id:3,name:'foox'},{_id:4,name:'fooz'}];
const search = [1,25,33,4,22,44,5555,63]
function finder(searh) {
return data.some(obj => {
return search.includes(obj._id);
});
}
console.log(finder(data, search));
``` | ```
var list = [ { _id: 1,
name: foo },
{ _id: 2,
name: bar },
{ _id: 3,
name: foox },
{ _id: 4,
name: fooz },
];
var isAnyOfIdsInArrayOfObject = function(arrayOfObjects, ids){
return arrayOfObjects.some(function(el) { return ids.indexOf(el._id) !== -1; });
}
``` |
3,853,087 | In Serre's A Course in Arithmetic, he writes the following lemma:
Lemma: Let $0 \rightarrow A \rightarrow E\rightarrow B\rightarrow 0$ be an exact sequence of commutative groups with $A$ and $B$ finite with orders $a$ and $b$ prime to each other. Let $B'$ be the set of $x\in E$ such that $bx=0$. The group $E$ is the direct sum of $A$ and $B'$.
Then in the proof, he says "since $bB'=0$, we have $bE\subset A$". I don't quite follow where this statement comes from. Can someone offer a hint? | 2020/10/05 | [
"https://math.stackexchange.com/questions/3853087",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/813593/"
] | Let $p:E\rightarrow B$ the projection. Remark that for every $x\in E$, whe have $p(bx)=0$ since the order of $B$ is $B$. This implies that $bx\in A$ since the sequence is exact, we deduce that a $abx =0$.
We have $1=ua+vb$ implies that for every $x\in E$, $x=uax+vbx$. We have $vbx=bvx\in A$, and $b(uax)=u(abx)=0$ im plies that $uax\in B'$. | **HINT.** Use exactness of the sequence. |
55,620 | Assumptions:
Technology equivalent to contemporary tech.
A city with a population of millions built from scratch.
There is a need for an inexpensive underground system that would transport cargo (at best everything from packages, food, garbage, construction materials, etc.) within the city and free the streets from cargo transport.
The system should be reliable and pay for itself in the long term. (At best it should be able to effectively handle different sizes of packages)
Questions:
1) Which technology should be realistically used? Tiny rail cars? Conveyor belts? Pneumatic post? Something else?
2) What is the biggest size of package that would be realistic?
3) Should such a cargo system in any way use the city metro system? | 2016/09/17 | [
"https://worldbuilding.stackexchange.com/questions/55620",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/25459/"
] | Look into Walt Disney's plans for the City of EPCOT, which is not the park by the same name we have today.
The central part of the city would route all automobile traffic to a series of roads underneath the public portion of the city, to reduce pedestrian traffic access, and allow for trucks and supplies to navigate the streets to basement cargo bays and garages for their buildings, while foot traffic would be at the ground floor\* and the only vehicles would be mass transit (People Movers as scene in Magic Kingdom in Walt Disney World for local commuting, with Monorails for rapid transit). One could modify this so that above ground roads\* are for private vehicles (personal cars) while lower roads were for bulk cars, and lay the underside roads inline with the aboveside roads for ease.
While not city management it's common knowledge that Magic Kingdom's public area is served by a series of underground hallways\* that run the length of the park and are able to remove garbage, place costumed characters and cast members dressed for specific theme lands, and restock gift shops without a single guest seeing an errant cast member.
\*Because all of these were intended to go in the Orlando area by Walt, the use of Underground is not the best term but the easiest. Florida has a high water table and structures in Florida do not have basements as they would be flooded almost instantly. EPCOT City and Magic Kingdom would have/were built with the "underground structures" being on the ground floor and then the public portion was the "second floor". THere's some discreet landscaping to hide this Around Magic Kingdom. | Whatever system you use will boil down to a few basic principles
----------------------------------------------------------------
1. When delivering a load of cargo going to one place, a single
larger transport vehicle is cheaper and equally fast per unit as
many small transports.
2. When delivering a load of cargo to many places, many small
transports is both faster and cheaper per unit than 1 large
transport making many sequential stops.
3. The less you need to pack and unpack between transports, the faster and
cheaper per unit your transport is.
So, the first part of answering your question is figuring out the optimal layout. If your city has a single massive port for ingoing and outgoing logistics managed by a single entity, then you can minimize the overhead of getting supplies in and out of the city to begin with. Instead of each corporation having their own distribution center, in your city you minimize waste on underloaded bulk freight by making them all share. This central hub would basically function like an Amazon warehouse just being a catch-all for all goods and services. From their you do not necessarily want to unpack all of your freight containers yet though. If you have an industrial district in one place, and residential district in another, then you can send individual freight containers closer to their final destination by just loading them right back on smaller subway trains to district hubs. From those hubs, cargo can be further divided up and sent on even smaller subway carts bringing goods directly to people's homes and buisnessess.
[](https://i.stack.imgur.com/SKmW4.png)
Your Regional Subways need to accommodate train car containers from 8x8.5x20 ft to 8x9.5x40 ft to make sure you never need to unpack one to get it to its right district and remain compatible with all international standards of shipping container sizes.
Your District Subways however are not your normal train system. They are more like tracks for self propelled mining carts that range in size from a shoe box for small parcels up to 4x6x12 ft carts designed for construction materials and large furniture. This way, instead of loading up a large truck and carrying your things to a lot of other stops before arriving at your home, you send the right sized vehicle for the job to pickup or deliver goods in just 1 stop.
Then every home or business has a basement that functions their own private receiving station. You get home from work, and your groceries are just sitting down there in a cart waiting for you to unpack it.
Why subway carts?
-----------------
**Pneumatic tubes:** They require a seal that causes more friction than wheels and more precise construction to make; so, the cost to make and operate them is more than traditional subways.
**Flying Drones:** They require less infrastructure, but are much more expensive to operate. Carts passively resist gravity by sitting on the ground, but flying drones need to expend a constant energy just not to fall. They are good for premium expedited shipping of small parcels, but if you are moving around heavy bulk things like furniture, garbage, plywood, etc. then you are wasting a lot of money on them
**Conveyor belts** They will either need to be way overpowered for most of what they transport or they will need to have complex transmission systems distributed every few feet which will break often due to constant gearing up and down. Either way, they are not as efficient. |
4,638,604 | I've been trying to write a server in C++ Unix style, but I'm stuck on a Windows machine. I started with MinGW, but it didn't compile right and told me that it couldn't find the "sys/socket.h" file. Which, of course, is necessary for the server to even work. I went searching for it, and I think somewhere said to install Cygwin instead, as it comes with lots of libraries. Okay, so I installed it. Every single library it could possibly offer me. Then I went to compile again, and it STILL can't find it. I went searching through the ENTIRE includes folder, and couldn't find the file. So I was a little miffed (3 hours down the drain for extra functionality I don't need), but I continued to search. I can't find it ANYWHERE. I find multiple references to using it, but I can't find ANYWHERE to download it. I've been searching for the past few hours now, and I've become very frustrated with everything because there are NO references to where I can get it (and I will NOT use winsock. That breaks compatibility if I remember right).
So, long story short, where can I download the 'socket.h'/'socket.c'/'socket.cpp' files? It would make my life (and I'm sure many others' lives) SO much easier, and I would really appreciate it! | 2011/01/09 | [
"https://Stackoverflow.com/questions/4638604",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/728194/"
] | Given that Windows has no sys/socket.h, you might consider just doing something like this:
```
#ifdef __WIN32__
# include <winsock2.h>
#else
# include <sys/socket.h>
#endif
```
I know you indicated that you won't use WinSock, but since WinSock is how TCP networking is done under Windows, I don't see that you have any alternative. Even if you use a cross-platform networking library, that library will be calling WinSock internally. Most of the standard BSD sockets API calls are implemented in WinSock, so with a bit of futzing around, you can make the same sockets-based program compile under both Windows and other OS's. Just don't forget to do a
```
#ifdef __WIN32__
WORD versionWanted = MAKEWORD(1, 1);
WSADATA wsaData;
WSAStartup(versionWanted, &wsaData);
#endif
```
at the top of main()... otherwise all of your socket calls will fail under Windows, because the WSA subsystem wasn't initialized for your process. | I would like just to add that if you want to use windows socket library you have to :
* at the beginning : call WSAStartup()
* at the end : call WSACleanup()
Regards; |
39,012,038 | I have the following tables:
```
CREATE TABLE source_table (
id int IDENTITY(1, 1) NOT NULL,
category varchar(255) NULL,
item int NULL,
counter int NULL,
length int NULL
);
CREATE TABLE dest_table(
id int IDENTITY(1, 1) NOT NULL,
from_item [int] NULL,
to_item [int] NULL,
length [int] NULL
);
```
The source table contains the following records:
```
INSERT INTO source_table SELECT 'A', 100, 1, 0
INSERT INTO source_table SELECT 'A', 101, 2, 10
INSERT INTO source_table SELECT 'A', 102, 3, 5
INSERT INTO source_table SELECT 'A', 103, 4, 7
INSERT INTO source_table SELECT 'A', 104, 5, 12
INSERT INTO source_table SELECT 'B', 101, 1, 0
INSERT INTO source_table SELECT 'B', 111, 2, 15
INSERT INTO source_table SELECT 'B', 114, 3, 6
INSERT INTO source_table SELECT 'B', 117, 4, 13
INSERT INTO source_table SELECT 'B', 119, 5, 8
```
The rows from the source table need to be transformed in such a way so that each record in the destination table would represent 2 rows from the source table.
What is the correct SQL syntax to transform the above rows as the following in the destination table?
```
100, 101, 10
101, 102, 5
102, 103, 7
103, 104, 12
101, 111, 15
111, 114, 6
114, 117, 13
117, 119, 8
``` | 2016/08/18 | [
"https://Stackoverflow.com/questions/39012038",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/524861/"
] | You could use the `lag` window function:
```
select *
from (select lag(item) over (partition by category order by item) as from_item,
item as to_item,
length
from source_table) base
where from_item is not null
```
To insert this into the destination table is standard. | ```
SELECT a.item, b.item, b.length
FROM source_table as a
INNER JOIN source_table b
ON a.id = b.id - 1
AND a.category = b.category
``` |
6,548,626 | I have a sub that is activated from a button on a userform. The basic procedure from the click is
1) Run my sub based off of user inputs
2) Select results sheet
3) Display my results
4) Unload my userform
I've run into a problem because I want to try and put bounds on an user input value and if the user inputs something out of the range a message box will pop up notifying them of the range. I've been able to accomplish this simple task through the use of an if/then loop. After the user exits out of the message box I want to keep the userform displayed along with the original user inputs and allow the user to change their input. But currently after the user clicks 'ok' on the message box, my click sub continues its procedure and unloads my userform and selects my results worksheets. Is there a simple one line code that I can put after my msgbox state to preserve the userform instead of making the user re-enter their values?
EDIT - The general gist of my code is as follows:
```
Private Sub CommandButton1_Click()
PropertySearch.Search
ActiveSheet.Name = "SearchResult"
Cells(1, 1).Select
Unload ILsearch
End Sub
Sub Search()
If (TextBox1 And TextBox2 <= 8) And (TextBox1 And TextBox2 > 0) Then
'
'Performs my desired function
'
Else: MsgBox ("Database only includes ionic liquids with a maximum of 8 carbons in cation")
End If
``` | 2011/07/01 | [
"https://Stackoverflow.com/questions/6548626",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I would turn Search into a function which returns true or false if the input is within bounds or not:
```
Function Search() AS Boolean
If (TextBox1 And TextBox2 <= 8) And (TextBox1 And TextBox2 > 0) Then
Search = True
Else
Search = False
EndIf
End Function
```
then you just exit the sub if input does not meet your bounds:
```
Private Sub CommandButton1_Click()
If(Not PropertySearch.Search) Then
MsgBox("your error message here")
Exit Sub
EndIf
' rest of the routine
End Sub
``` | There are about a thousand and one ways around this - the question is what behavior do you want the form to have?
Do you want it to self close after a certain amount of time?
Check out this example of timer [1](https://learn.microsoft.com/en-us/office/vba/language/reference/user-interface-help/timer-function)
Or look into Application.Ontime
```
Application.OnTime Now + TimeValue("00:00:10"), "unloadForm"
```
Where "unloadForm" is a sub in a normal module
```
Sub unloadForm()
Unload ILsearch
End Sub
```
Do you want to add a close form button?
```
Private Sub CommandButton1_Click ()
Unload Me
End Sub
```
Do you want the user to close the form manually with the red X in the top corner? Simply delete the line with `Unload`
Do you want to display a modal popup window that freezes Excel until closed and then your form unloads? Try addging `MsgBox "Hello"` before you unload the form.
And many many many more!
For example, I have several forms that use keyboard events. Escape can clear all fields and hide/unload the form while Enter does the same thing but also write the values to a table, Delete only clears the active control and doesn't hide the form, up and down arrows cycle through forms hiding the current and showing the previous/next while left and right function like tab/shift + tab. |
18,639,483 | As I'm currently in the process of making a forum system which is loading new posts/edits without having to refresh the page. Now, for the older browers which don't have an implentation of EventSource/WebSocket, I'd like to offer another option:
Every X seconds I'm GET'ing a PHP site which is echoing the five latest news. Afterwards, I'm simply checking which of those news weren't seen by the client yet and applying the changes to the page.
Now, my problem is: How would you determinate the X interval in which the client is retrieving new updates? I'd like to base it up the user's connections so that it isn't killing off his connection completely.
What would be your attempt at accomplishing this? | 2013/09/05 | [
"https://Stackoverflow.com/questions/18639483",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1955931/"
] | This code should open each div, and then close the previous one:
```
var currentPos = 0;
$('#yourButtonId').on('click', function () {
if (currentPos > 0)
$('#' + divnameids[currentPos - 1]).hide();
if (currentPos == 0) // hide the last tab when coming back to the start
$('#' + divnameids[divnameids.length - 1]).hide();
$('#' + divnameids[currentPos]).show();
currentPos += 1;
// Reset the current position to 0
if (currentPos >= divnameids.length)
currentPos = 0;
});
``` | ```
$(document).ready(function(){
$(".content-box-front").click(function(){
$(".full-content-back").fadeIn("slow");
$(".full-content-front").fadeIn("slow");
$(".content-box-front").fadeOut("slow");
$(".content-box-back").fadeOut("slow");
});
});
$(document).ready(function(){
$(".full-content-front").click(function(){
$(".full-content-back").fadeOut("slow");
$(".full-content-front").fadeOut("slow");
$(".content-box-front").fadeIn("slow");
$(".content-box-back").fadeIn("slow");
});
});
```
this should help put the name of the divs in where full-content.... is |
19,676,835 | I'm pretty new to XML and I was wondering how would I parse, sort, and print val1 to val4 in python? With my research I found `xml.dom` or `xml.etree` was used a lot but I'm having trouble finding the correct functions to use to parse the through the XML tree and print out what I need.
```
<a>
<b>
<c>
<d>
<item> val1 </item>
<item> val2 </item>
<item> val3 </item>
<item> val4 </item>
</d>
</c>
</b>
</a>
``` | 2013/10/30 | [
"https://Stackoverflow.com/questions/19676835",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1815710/"
] | I recently made a small python program to display some information from some XML files. I found that using [BeautifulSoup 4](http://www.crummy.com/software/BeautifulSoup/bs4/doc/) made XML extremely easy to parse. You can either download the source from the linked website and install it yourself, or follow the documentation to install the package `bs4` using `pip` or `easy_install`.
Using BS4:
```
soup = BeautifulSoup(xmlFileORString);
for item in soup.a.b.c.d.find_all('item'):
print(item.string)
```
**EDIT:** BS4 can also be compiled for Python 2.7 and the code is almost the exact same. | Use `lxml` package in python, because lxml supports to `xpath` which is very helpful for firing query on xml file. And it is fast to process large data from XML file
```
from lxml import etree
tree = etree.parse(XML_FILE_PATH)
root = self.tree.getroot()
```
To get `text` from node of xml :
```
nodes = tree.findall("//item")
text = [node.text for node in nodes]
```
You will get list i.e `[1,2,3,4]` , after that you can sort result list using `sorted(text)`
And for getting elements attributes, you can use -:
Suppose, `<item id="2" name="abc">1</item>`
```
entries = tree.xpath("//item[@id='2']")
```
You will get all attributes i.e `{'id':2, 'name':'abc'}` in `entries` |
13,214,252 | I am using the following code from castle windsor documentation.
I can't figure out how to pass in my configFile on my bootstrapper container installer that installs this installer.
```
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.AddFacility<LoggingFacility>(f => f.UseLog4Net("NameOfConfigFile"));
}
``` | 2012/11/03 | [
"https://Stackoverflow.com/questions/13214252",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35166/"
] | The difference is for types with no trivial default constructor, which is called for you by compiler in your class `B`. Your class `B` is equivalent to:
```
class B {
private:
SleepyInt a, b;
public:
// takes at least 20s
B(int a_var, int b_var) : a(), b()
// ^^^^^^^^^^
{
a = a_var;
b = b_var;
}
};
```
If you do not place member variable or base class constructor in initialization list - ithe default constructor is called for them. `int` is basic type - its default constructor costs nothing - so no difference in your example, but for more complex types constructor+assignment might cost more than just constructing.
Some funny example, just to illustrate the difference:
```
class SleepyInt {
public:
SleepyInt () {
std::this_thread::sleep_for(std::chrono::milliseconds( 10000 ));
}
SleepyInt (int i) {}
SleepyInt & operator = (int i) { return *this; }
};
class A {
private:
SleepyInt a, b;
public:
A(int a_var, int b_var):a(a_var), b(b_var) {};
};
class B {
private:
SleepyInt a, b;
public:
// takes at least 20s
B(int a_var, int b_var) {
a = a_var;
b = b_var;
}
};
``` | Initialization list is benefical reference types, member class objects, or const members. Otherwise it takes more time.
Look at my test code:
```
#include <iostream>
#include <ctime>
using namespace std;
class A{
int a;
public:
A(int a_):a(a_){}
};
class B{
int b;
public:
B(){
}
B(int b_){
b=b_;
}
};
class C{
B b;
public:
C(int c_):b(c_){
}
};
class D{
B b;
public:
D(int d_){
b=d_;
}
};
int main()
{
clock_t start1[10], start2[10], end1[10], end2[10];
for(int j=0;j<10;j++){
start1[j]=clock();
for(int i=0;i<100000;i++){
A *newA=new A(i);
delete newA;
}
end1[j]=clock();
start2[j]=clock();
for(int i=0;i<100000;i++){
B *newB=new B(i);
delete newB;
}
end2[j]=clock();
}
double avg1=0, avg2=0;
for(int i=0;i<10;i++){
avg1+=(end1[i]-start1[i]);
avg2+=(end2[i]-start2[i]);
}
cout << avg1/avg2 << endl;
for(int j=0;j<10;j++){
start1[j]=clock();
for(int i=0;i<100000;i++){
C *newC=new C(i);
delete newC;
}
end1[j]=clock();
start2[j]=clock();
for(int i=0;i<100000;i++){
D *newD=new D(i);
delete newD;
}
end2[j]=clock();
}
avg1=avg2=0;
for(int i=0;i<10;i++){
avg1+=(end1[i]-start1[i]);
avg2+=(end2[i]-start2[i]);
}
cout << avg1/avg2 << endl;
system("pause");
return 0;
}
```
Example outputs like this:
1.02391
0.934741 |
54,665,527 | When I tried to read a pickle file that saved by a former version of pandas, it yielded an `ImportError`.
>
> ImportError: No module named 'pandas.core.internals.managers';
> 'pandas.core.internals' is not a package
>
>
>
There was no hit on stackoverflow so i would like to share my solution for this particular problem. | 2019/02/13 | [
"https://Stackoverflow.com/questions/54665527",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4197348/"
] | This error comes off due to encoding of formerly saved pickle file. If you updated pandas to newly amended version, it produces this import error. | `conda update pandas`
If you use conda package manager. |
57,545,059 | I am working on a [react-native](https://facebook.github.io/react-native/) app and I have a problem when rendering some Arabic text that returned from API most of the times the text looks like rubbish (check screenshot 1)
And for a few times, it rendered correctly (check screenshot 2)
screenshot 1
[](https://i.stack.imgur.com/4QtSh.png)
screenshot 2
[](https://i.stack.imgur.com/GRF0B.png)
I checked the API response and it always returns the text correctly.
FYI I am using [axios](https://github.com/axios/axios) to fetch the data.
EDIT
====
Here is my axios code :
```
const headers = {
"Content-Type": "application/json",
Accept: "application/json"
};
const requestBody = {
msgUID: getMsgUID(),
uid: this.props.user.uid
};
axios
.post(Config.FETCH_VISITS_URL, requestBody, { headers: headers })
.then(response => response.data)
.then(response => {
console.log(JSON.stringify(response));
this.setState({
loading: false,
arrayOfVisits: response.visits
});
})
.catch(error => {
console.log(
"Error getting documnets",
error + " msgUID " + requestBody.msgUID
);
});
```
EDIT 2
======
Here is the API response:
```
{
"msgUID": "654894984984",
"responseTime": 1567253177771,
"size": 4,
"visits": [{
"visitExitTimestamp": "",
"changeHistory": [],
"entryType": {
"vehicleDetails": {},
"by": ""
},
"createdBy": "fz085jMMedPApY0tp9L1e7iqyfO2",
"visitEntryTimestamp": "",
"visitStatus": "new",
"visitTypeObject": {
"lastName": "السيد",
"durationAmount": "30",
"firstName": "علي",
"phoneNumber": "(123) 456 - 7890",
"notes": "Test",
"durationType": "days",
"type": "person"
},
"timestampFrom": "2019-08-28T16:56:00.000Z",
"isDeleted": false,
"key": "oTAJ8WbVh54tVaemVoz6",
"createTime": "2019-08-27T16:56:45.286Z",
"checkInTime": "",
"checkOutTime": ""
},
{
"visitExitTimestamp": "",
"changeHistory": [],
"entryType": {
"vehicleDetails": {},
"by": ""
},
"createdBy": "fz085jMMedPApY0tp9L1e7iqyfO2",
"visitEntryTimestamp": "",
"visitStatus": "new",
"visitTypeObject": {
"lastName": "",
"durationAmount": "30",
"firstName": "محمد",
"phoneNumber": "(123) 456 - 7890",
"notes": "Test",
"durationType": "days",
"type": "person"
},
"timestampFrom": "2019-08-28T16:46:00.000Z",
"isDeleted": false,
"key": "oTAJ8WbVh54tVaemVoz6",
"createTime": "2019-08-27T16:46:45.286Z",
"checkInTime": "",
"checkOutTime": ""
}
],
"status": 200,
"statusString": "OK"
}
```
below you can find the render method that I am using:
```
renderVisitorName(firstName,lastName) {
return (
<Text style={styles.name}>
{firstName + " " + lastName}
</Text>
);
}
```
I am only testing this on [Android](https://www.android.com/). | 2019/08/18 | [
"https://Stackoverflow.com/questions/57545059",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3711273/"
] | I have same problem like this and just upgrade ckeditor with command:
```
pip install django-ckeditor --upgrade
``` | I also had this problem and fixed it by including the path in the urls file with.
```py
urlpatterns = [
path('admin/', admin.site.urls),
path("ckeditor/", include('ckeditor_uploader.urls')), # <-- here
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
``` |
101,124 | Do angels make any requests of G-d besides praising and thanking Him? | 2019/03/21 | [
"https://judaism.stackexchange.com/questions/101124",
"https://judaism.stackexchange.com",
"https://judaism.stackexchange.com/users/17905/"
] | There were many questions about angels' nature on this site - are they real individualities or just G-d's messengers.
To consolidate those views especially on your question, I would like to differentiate between two different aspects of angels - a. the nature of angels and b. our perception of angels.
1. **The nature of angels** does not allow for deviating from Hashem's will. They are not separated self-sustained entities. They ARE G-d's will. As [I answered about Gabriel](https://judaism.stackexchange.com/a/100808/15579) they are named after their mission, they have no names for themselves and no "personalities" at all.
2. **The perception of angels in our eyes** - as we all tend to personify (anthropomorphism) everything around us, *we* depict angels as humanlike creature assigning to them all the qualities we humans have. All the interpretations of the angels as separated, self-aware, and self-willing (?) creatures are results of our imaginations, sort of "דברה התורה כלשון בני אדם". Those are parables and not reality, similar to what Rambam writes on the personification of G-d Himself in the Writings (Yesodey Hatora 1).
Based on this differentiation, we can say that the angels really don't have any requests as they have no will of their own, but we picture them as ones that have a sort of free thinking. | [Rashi](https://www.sefaria.org/Genesis.32.27?lang=bi&with=Rashi&lang2=en) on Gen 32:27, when the man/[angel](https://www.sefaria.org/Genesis.32.25?lang=bi&with=Rashi&lang2=en) asks Jacob to release him, writes
>
> כי עלה השחר FOR THE DAY BREAKETH, and I have to sing God’s praise at day (Chullin 91b; Genesis Rabbah 78:1).
>
>
>
So the answer would be that, yes, they pray, singing God's praises, every day. |
17,892,840 | I have been trying to achieve something which should pretty trivial and is trivial in *Matlab*.
I want to simply achieve something such as:
```
cv::Mat sample = [4 5 6; 4 2 5; 1 4 2];
sample = 5*sample;
```
After which sample should just be:
```
[20 24 30; 20 10 25; 5 20 10]
```
I have tried `scaleAdd`, `Mul`, `Multiply` and neither allow a scalar multiplier and require a matrix of the same "size and type". In this scenario I could create a Matrix of Ones and then use the scale parameter but that seems so very extraneous
Any direct simple method would be great! | 2013/07/27 | [
"https://Stackoverflow.com/questions/17892840",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2624574/"
] | OpenCV does in fact support multiplication by a scalar value with overloaded `operator*`. You might need to initialize the matrix correctly, though.
```
float data[] = {1 ,2, 3,
4, 5, 6,
7, 8, 9};
cv::Mat m(3, 3, CV_32FC1, data);
m = 3*m; // This works just fine
```
If you are mainly interested in mathematical operations, `cv::Matx` is a little easier to work with:
```
cv::Matx33f mx(1,2,3,
4,5,6,
7,8,9);
mx *= 4; // This works too
``` | For java there is no operator overloading, but the Mat object provides the functionality with a convertTo method.
```
Mat dst= new Mat(src.rows(),src.cols(),src.type());
src.convertTo(dst,-1,scale,offset);
```
[Doc on this method is here](https://docs.opencv.org/3.1.0/d3/d63/classcv_1_1Mat.html#a3f356665bb0ca452e7d7723ccac9a810) |
68,027,599 | I tried something like this
`sed 's/^[ \t]*//' file.txt | grep "^[A-Z].* "`
but it will show only the lines that start with words starting with an uppercase.
file.txt content:
Something1 something2
word1 Word2
this is lower
The output will be Something1 something2 but I will like for it to also show the second line because also has a word that starts with an uppercase letter. | 2021/06/17 | [
"https://Stackoverflow.com/questions/68027599",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16256617/"
] | With GNU `grep`, you can use
```sh
grep '\<[[:upper:]]' file
grep '\b[[:upper:]]' file
```
**NOTE**:
* `\<` - a leading word boundary (`\b` is a word boundary)
* `[[:upper:]]` - any uppercase letter.
See the [online demo](https://ideone.com/NjytnI):
```sh
#!/bin/bash
s='Something1 something2
word1 Word2
this is lower
папа Петя'
grep '\<[[:upper:]]' <<< "$s"
```
Output:
```sh
Something1 something2
word1 Word2
папа Петя
``` | >
> How do you display all the words
>
>
>
That's simple:
```
grep -wo '[A-Z]\w*'
``` |
43,104,814 | I have a detail report with interactive sorting on the headers.
After the report is refreshed, the user would like to highlight some rows of data that appear throughout the report in order to see if patterns are detectable.
Say, a vendor name that appears on multiple customer rows might indicate that they all shopped at the same vendor before their credit card was compromised. Highlighting that vendor name might make it easier to spot whether this is a problem vendor. They won't know what they want to highlight until they start perusing the data, so a run-time parameter won't work.
In the past I used BusinessObjects which had a control that could be used to trigger alerts (formatting changes).
Is there a way to hack such a thing in SSRS? | 2017/03/29 | [
"https://Stackoverflow.com/questions/43104814",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2812742/"
] | I found out how to use `ADODB.Stream` to solve this problem:
```
Const adTypeBinary = 1
Dim byteValue
With CreateObject("ADODB.Stream")
.Type = adTypeBinary
.Open
.LoadFromFile fileName
.Position = 4 ' could be any byte position
byteValue = Right(00 & Hex(AscB(.Read(1))), 2) ' Returns 0A
End With
' Print byteValue
WSCript.echo "Value = " & byteValue
``` | There are other questions/answers on SO regarding [reading binary files](https://stackoverflow.com/a/6087783/243925) in VBSCript, perhaps they will help you.
What's important to remember is that a binary file (as is any file) is a continuous stream of bytes. So rather than thinking about the "5th byte" of each line remember it will be the 5th, 10th, 15th etc. byte you are interested in.
This is why your hex viewer has an "Offset" column to show how far through the stream of bytes you are. |
7,034,908 | I'm new to using Propel ORM. I have generated code and am now trying to integrate the runtime with my PHP project. I am struggling with initializing the main `Propel` class. It appears that the usage should be:
```
require_once('propel/runtime/lib/Propel.php');
Propel::configure('/path/to/runtime/config.php');
Propel::initialize();
```
I cannot find any documentation on what the contents on the runtime configuration should be, other than this:
<http://www.propelorm.org/wiki/Documentation/1.6/RuntimeConfiguration>
However, this document shows an XML file, **not** a PHP file. Any ideas? | 2011/08/12 | [
"https://Stackoverflow.com/questions/7034908",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/199397/"
] | Change your (updated) CSS to the following and it should work:
```
#main {
width: 100%;
text-align: center;
}
``` | You have the #bigimage img within the #main div. Since the main div is 1024px wide, the 100% will always be 1024. The result here is that you'll always see 1024px. If you remove the width attribute from #main or change it to 100%, you should start to see what you're looking for. |
51,792 | I need to work with several teams and need to be able to share requirements and design documents. Most people won't be too technical, so I want to avoid source code tools. The main requirements are:
1. Easy sharing via links. I don't want people to have to install multple tools just to see a file or learn anything about svn checkout.
2. Permissions - I want to allow view only access to most people, with some having add/edit permissions. I don't want anyone to be able to permanently delete anything.
3. Revision History - I want to see who has added and edited files and be able to revert to previous versions.
I've tried Dropbox and SkyDrive, but they each have faults. Dropbox allows users to permanently delete files, and it will even delete the file from your local machine when it is synced. SkyDrive doesn't allow enough fine grained permissions or revision history. Do I need a CMS system like Drupal]? Would Sharepoint be the proper tool? I don't necessarily need an open source solution. The easier it is to set up and administer, the better. | 2009/10/06 | [
"https://superuser.com/questions/51792",
"https://superuser.com",
"https://superuser.com/users/-1/"
] | Use [Google Sites](http://sites.google.com) - it's easy to maintain and administer, and if done right, it can perform remarkably well as a simple intranet.
You can even create multiple sites, with one site catering for one project, and restricting team members to just that. | For me this look like a job for a wiki like [DokuWiki](http://www.dokuwiki.org/dokuwiki) or [MediaWiki](http://www.mediawiki.org).
* Online document editing
* Various level of permission
* Automatic version tracking; |
54,669,047 | I'm using Oracle Report Builder 9.0.4.1.0 and I have a heavy report that has defined a large number of queries. I think not all that queries are used in the report and are not linked to any layout object.
Is there a easy way to detect what queries (or other objects) aren't used at all in a specific report? Instead of delete the query, compile and run and verify one by one if are used or not?
Thanks | 2019/02/13 | [
"https://Stackoverflow.com/questions/54669047",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4524205/"
] | If there is an easy way to do that, I don't know it. A long time ago, when Reports 1.x was used, report was saved in the database so you could write a query to fetch metadata you're interested in. I never did that, though, but - that would be an option. Now, all you have is a RDF (or a JSP) file.
However, a few suggestions, if I may.
Open Paper Layout Editor. Click the repeating frame and observe its property palette as it contains information about the group it belongs to. "Group" can be viewed in Data Model layout.
As there aren't that many repeating frames, you should be able to eliminate queries that don't have any frames, i.e. don't contribute to the final result.
---
Another option is to put a condition
```
WHERE 1 = 2
```
into every query so that they won't return any rows. Run the report and check what's missing - then remove that condition so that you'd get values. Move on to second query, and so forth. That's a little bit tedious and time consuming, but should still be faster than deleting queries. | You can return a report results to an XML file. Each query with data will contain something in XML-s tags.
[enter image description here](https://i.stack.imgur.com/6tItz.png) |
1,264,992 | We have to transfer binary data using web service stack and in the process we have to sign web service requests/responses.
The main question is: what is the prefered way to do this?
Should we use MTOM and WS-Security?
From [ISSUE CXF-1904](https://issues.apache.org/jira/browse/CXF-1904) I have concluded that there are issues when one uses MTOM and WS-Security. CXF and axis2 use WSS4J and it seems that WSS4J does not work well with digitally signed messages when you use MTOM.
What about other web service stacks? | 2009/08/12 | [
"https://Stackoverflow.com/questions/1264992",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/122674/"
] | CXF can do WS-Security related things along with MTOM, but the attachments do not end up signed or encrypted. The SOAP message itself is signed/encrypted, but the attachments are not due to restrictions in WSS4J. (If SpringWS uses WSS4J, it would have the same restrictions)
Be default for security reasons when using the WSS4JOutInterceptor with CXF, we turn off MTOM to make sure they get inlined and then signed/encrypted. That's a security choice. The WSS4JOutInterceptor DOES have a flag (out.setAllowMTOM(true)) which would allow the MTOM to remain as attachments, but keep in mind, those attachments would not be "secured". | From <http://ws.apache.org/wss4j/attachments.html> :
WSS4J 2.0.0 introduces support for signing and encrypting SOAP message attachments, via the the SOAP with Attachments (SWA) Profile 1.1 specification. There is no support in WSS4J 1.6.x for signing or encrypting message attachments. Attachments can be signed and encrypted in WSS4J via either the "action"-based approach or via WS-SecurityPolicy, as covered in the sections below. |
24,092,328 | I've found very gentle way to increment limited variable, just:
```
++i %= range;
```
Unfortunately this trick doesn't work for decrement, because `-1 % v == -1`.
How can I improve this in C++? | 2014/06/07 | [
"https://Stackoverflow.com/questions/24092328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1565454/"
] | To avoid the negative modulus behaviour you can just make it positive first:
```
i = (i - 1 + range) % range;
```
However this is no good if `range` is bigger than half of INT\_MAX. (or whatever type `i` is).
This seems simpler:
```
i = (i ? i : range) - 1;
``` | This code should work for decrementing `i` through the interval [0, range)
```
--i = (i > 0) * (i % range);
``` |
935 | I have a view that I've created that selects blog posts based on a specific taxonomy term, creating a sort of "Featured Posts" view that I've embedded on the front page of my site. The issue I keep running into is trying to output the view so that each post is semantically marked up using some of the new HTML. I've tried the built-in "Rewrite this field's output", but it ignores the tags I use (ie, article, header, footer) and wraps everything in divs even when I deselect the placeholder tags.
Should I create a overriding views--view\_name.tpl.php to rewrite the output of each post as it appears in the view, or do I need to use preprocess hooks in the template.php to affect the output?
I should state that I have basic experience with writing PHP and preprocess hooks, but I can any resources I need to move me down the linke if I'm pointed in the right direction. | 2011/03/17 | [
"https://drupal.stackexchange.com/questions/935",
"https://drupal.stackexchange.com",
"https://drupal.stackexchange.com/users/20/"
] | You'll notice that in your view under the "Style Settings" block there is a link for Theme: Information. It will expose all the theme files that are called for your view. You can use generic to very detailed theme files that will only be use for your views display.
The first file name in Display output is views-view.tpl.php. That will apply to all views and displays. The next one in the list is views-view--[view name].tpl.php. It will only apply to your view. It keeps drilling down until it gets as specific as possible. views-view--[view name]--default.tpl.php is the last one in the list and only applies to the default display of the view. Clicking the Display output: link will expose the template code that views uses. Simply copy and create a new template file with one of the suggested in the list. It's usually best to be as specific as possible. The template file can go anywhere in your theme and views will pick it up as long as you rescan template files in the theming information and save the view. There are view templates, row templates, field templates and field specific templates.
Once you learn how to manipulate view template files it will really open up your design possibilities. | Fences looks like a great module (for Drupal 7) to control views output markup:
Project page:
<http://drupal.org/project/fences>
From the project page:
>
> "Fences is a an easy-to-use tool to specify an HTML element for each
> field. This element choice will propagate everywhere the field is
> used, such as teasers, RSS feeds and Views. You don't have to keep
> re-configuring the same HTML element over and over again every time
> you display the field."
>
>
>
I like this bit particularly (great for debugging output):
>
> "Best of all, Fences provides *leaner markup than Drupal 7 core*! And
> can get rid of the *extraneous classes* too!"
>
>
>
This is also nice - reducing repetition of work:
>
> "This kind of tool is needed in order to create semantic HTML5 output
> from Drupal. Without such a tool, you have to create custom field
> templates in your theme for every field. :("
>
>
>
They've considered the popular alternatives too:
>
> Similar projects include **Semantic fields**, **Field Wrappers** and a
> tool inside the **Display Suite** extras. But we think this approach
> is Morefasterbetter™.
>
>
>
Credit to Drupal user [rhache](http://drupal.org/user/64478) for mentioning the [Fences Drupal module](http://drupal.org/project/fences) in their [comment](http://drupal.org/node/1013876#comment-6338768) on this question [Is Semantic Views module obsoleted by Views 3?](http://drupal.org/node/1013876) |
159,620 | I'm trying to learn calculus here, but I know I have to set the $h$ equal to 0 and find the time at when it's equal to 0, but I have no idea what to do after. Here is the question. How do I find out the velocity at that time?
>
> If a rock is thrown upward on the planet Mars with a velocity of $10\;m/s$, its height (in meters) after $t$ seconds is given by $H = 10t − 1.86t^2$. Find the velocity of the rock when it hits the ground.
>
>
> | 2012/06/17 | [
"https://math.stackexchange.com/questions/159620",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/17863/"
] | First we find the time(s) when the rock is at ground level. So set $10t-1.86t^2=0$ and solve for $t$. We get $t=0$ and $t=\frac{10}{1.86}$.
The velocity at time $t$ is the derivative of the displacement function $H(t)$. So the velocity at time $t$ is $10-(2)(1.86)t$. Substitute the value of $t$ we found above.
**Remark:** We can solve the problem *instantly* without calculus. The initial velocity is $10$. So by symmetry the velocity when it hits the ground on its return trip must be $-10$. | Find the positive root of $H(t)=10t-1.86t^2$. Let $t\_1$ be that root. Then evaluate $H'(t\_1)$.
Added: Plot of the height function $H(t)=10t-1.86t^2$ (in meters) vs. time $t$ (in seconds)

Added 2: Plot of $H(t)$ (black, in meters) and $H'(t)=10-3.72t$ (blue, in m/s) vs. time $t$ (in seconds)
 |
1,044,085 | ```
[ExternalException (0x80004005): A generic error occurred in GDI+.]
IpitchitImageHandler.Data.ImageRepository.AddNewTempImage(Stream image, String extension, Guid PageId, Guid ImageId, ImageTransformCollection toDoTransforms) +1967
IpitchitImageHandler.Data.ImageRepository.AddNewTempImage(Stream image, String extension, Guid PageId, Guid ImageId) +85
IpitchitWeb.Sell.Controls.UploadImagesSubstep.UploadImages(Object sender, EventArgs e) in F:\Documents and Settings\Vjeran\My Documents\Visual Studio 2008\Projects\Ipitchit\IpitchitWeb\Sell\Controls\UploadImagesSubstep.ascx.cs:88
System.Web.UI.WebControls.LinkButton.OnClick(EventArgs e) +111
System.Web.UI.WebControls.LinkButton.RaisePostBackEvent(String eventArgument) +79
System.Web.UI.WebControls.LinkButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +175
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1565
```
my code is:
```
public void AddNewTempImage(Stream image, string extension, Guid PageId, Guid ImageId,
ImageTransformCollection toDoTransforms)
{
//mapping steam to memory stream so it does support the seek
MemoryStream targetStream = new MemoryStream(ReadStream(image, 1024));
Image ImageToTransform=null;
Image transformedImage = null;
string storagePath = ImageTransformManager.Config.StorageServerPhysicalPath;
Uri storageUrl = new Uri(ImageTransformManager.Config.StorageServerUrl);
//string TempPath = Path.Combine(storagePath, GenerateFileName(extension));
//SaveStream(TempPath, image);
//File.WriteAllBytes(TempPath, ReadStream(image, 1024));
if (!HttpContext.Current.User.Identity.IsAuthenticated)
throw new Exception("Nonauthenticated users image submition is not supported");
try
{
foreach (ImageTransform transform in toDoTransforms)
{
ImageRepositoryTempImage newimage = new ImageRepositoryTempImage();
newimage.ImageGuid = ImageId;
newimage.PageGuid = PageId;
newimage.CreatedBy = HttpContext.Current.User.Identity.Name;
newimage.CreatedDate = DateTime.UtcNow;
newimage.Format = transform.OutputType;
newimage.Width = transform.Width;
newimage.Height = transform.Height;
newimage.Watermark = transform.UseWaterMark;
string filename = GenerateFileName(transform.OutputType);
string fullStoragePath = Path.Combine(storagePath, Path.Combine(transform.StorageFolder, filename));
string fullStorageUrl = CombineUri(storageUrl, Path.Combine(transform.StorageFolder, filename));
newimage.PhysicalStoragePath = fullStoragePath;
newimage.StoragePath = fullStorageUrl;
CheckOrAddImageTransform(transform);
var ImgRepTransform = GetTransformation(transform);
newimage.ImageRepositoryTransformation = ImgRepTransform;
newimage.TransformId = ImgRepTransform.Id;
Bitmap uploaded = new Bitmap(image);
ImageToTransform = (Image)uploaded.Clone();
uploaded.Dispose();
transformedImage = transform.Transform(ImageToTransform);
AddNewTempImage(newimage);
//adding named watermark and transformation
string wname = ImageTransformManager.Config.WaterMarkName;
string wpath = ImageTransformManager.Config.WaterMarkPath;
ChechOrAddWaterMark(wname, wpath);
if (!(string.IsNullOrEmpty(wname) && string.IsNullOrEmpty(wpath)))
newimage.ImageRepositoryWaterMark = GetWatermark(wname, wpath);
transformedImage.Save(fullStoragePath, GetFormat(newimage.Format));
}
}
catch (System.Exception ex)
{
ErrorHandling.LogErrorEvent("Add new temp image method", ex);
throw ex;
}
finally
{
//File.Delete(TempPath);
if (ImageToTransform!=null)
ImageToTransform.Dispose();
image.Dispose();
targetStream.Dispose();
if (transformedImage != null)
transformedImage.Dispose();
}
}
```
On my local machine everything works - but still happens.. on server (2003) - i have folder permissions .. and everything... | 2009/06/25 | [
"https://Stackoverflow.com/questions/1044085",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/121113/"
] | I hate that error with a passion.
Generic Error is possibly the most useless error description ever written.
When I've encountered it the problem as always been related to file IO.
Here is the list of fixes I keep in my notes- Not sure if these apply but they usually do the trick for me.
* Check File path
+ Make sure that the parent directory exists
+ Ensure that path includes both the filename and extension
+ Use server.MapPath() to create the path
* Make sure that the file isn't being written back to it's source. Close and reopen the stream if necessary.
My apologies if i stole this list from somewhere else. It has been in my notebook for awhile and I can't remember where it came from. | Make sure **IIS\_WPG** has the correct **permissions** on your **upload folder** and also **ASPNET**.
I just had the same problem and this fixed it.
Don't forget to propagate the permissions through your sub folders if required too ( I may have forgotten that.. :) ) |
82,879 | I tried to look around for an answer to this problem but don't know how to ask the proper question in a search engine. I've been working on a song and realized recently that while I had been working on the song in the key of Em (E, F#, G, A, B, C, D) I had accidentally placed D# notes in several of my melodies. The confusing part is it sounds fine and I didn't even notice until I looked closer. What's more, if I change them to D it sounds off key and if I change them to E it just sounds wrong for what the melody is supposed to be doing. I don't have much music theory knowledge but this confused what I thought I knew. Am I misunderstanding something here? Any help and clarification would be appreciated. | 2019/04/17 | [
"https://music.stackexchange.com/questions/82879",
"https://music.stackexchange.com",
"https://music.stackexchange.com/users/59211/"
] | You'll most likely find that the chord used where D♯ fits better is either B major or B7. That has the D♯ in it. The D ♮ will fit in other places, notably when going from an Em chord to an Am. It's the reason centuries ago that the natural minor scale morphed into the harmonic minor, with a raised leading note ( here, the D♯), and later, because there was then a great big jump of a tone ane a half created, the 6th note of that natural minor got sharpened too, to remove a big jump.
All the minor scales have the same first five notes, but the melodic minor (classical) has the same 6 and 7 as the parallel major scale. | >
> I tried to look around for an answer to this problem but don't know how to ask the proper question in a search engine.
>
>
>
So you are writing a piece in e-minor and obviously you know what is e-minor, you know the scale of e-minor is and you know that there are D and D#.
>
> I had accidentally placed D# notes in several of my melodies.
>
>
>
Why sounds D# more harmonic?
As you will see you are not the first that The human mind already in earlier times of music history obviouly wanted to have a tension to the final note (the root) and so they constructed a leading tone by augmenting the 7th degree.
**This was the "invention" of the harmonic minor scale.**
>
> What's more, if I change them to D it sounds off key and if I change them to E it just sounds wrong for what the melody is supposed to be doing.
>
>
>
By augmenting of the seventh degree was a gap of 1+1/2 tone between the 6th and the 7th degree: in e-minor between C-D#.
So to become a more "natural" ending and easier to sing (for instruments it didn't matter) but also for listening they augmented the 6th degree too. This was only needed when the melody was leading upward to the upper octave. In a downward melodic formula the leading tone was not needed and so
**the the melodic minor scale had been developped.**
You are free to use all kind of the 3 scales at your "gusto".
Just looking for **e-minor:**
here is explained the e-minor (and all minor scales have 3 variant models)
<https://en.wikipedia.org/wiki/E_minor>
>
> I don't have much music theory knowledge but this confused what I thought I knew. Am I misunderstanding something here?
>
>
>
If you want to continue composing my advice is to read first the basics of music theory (scales, chords, harmony).
and again:
>
> I tried to look around for an answer to this problem but don't know how to ask the proper question in a search engine.
>
>
>
I was looking up *developpement of melodic and harmonic minor* and found this link:
<https://study.com/academy/lesson/harmonic-minor-scale-formula-modes-quiz.html> |
24,453,225 | I am using `column chart` with `drilldown`. Here is my [JSFIDDLE](http://jsfiddle.net/phpdeveloperrahul/6juNE/).
Now my problem is:
* I want to remove hyperlink like formatting from the labels on x-axis
and dataLabels
As you would be able to notice from my fiddle that I have already tried to apply formatting on the x-axis labels by using the code like:
```
xAxis: {
type: 'category',
labels:{
style:{
color: 'red',
textDecoration:"none"
}
}
},
```
and used following code to format dataLabels:
```
plotOptions: {
series: {
borderWidth: 0,
dataLabels: {
enabled: true,
format: '{point.y:.1f}%',
style:{
color: 'blue',
textDecoration:"none"
}
}
}
}
```
But the problem is: The formatting only works for that x-axis labels and dataLabels **that does not have drilldown data**. While it works on all the x-axis labels and dataLabels of drilldowned data !
Useful references:
<http://api.highcharts.com/highcharts#xAxis.labels.style>
<http://api.highcharts.com/highcharts#series.data.dataLabels>
Any help would be greatly appreciated ! | 2014/06/27 | [
"https://Stackoverflow.com/questions/24453225",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2833516/"
] | We can use drilldown option to control the drilldown.
```
drilldown: {
//for axis label
activeAxisLabelStyle: {
textDecoration: 'none',
fontStyle: 'italic'
},
//for datalabel
activeDataLabelStyle: {
textDecoration: 'none',
fontStyle: 'italic'
}
}
```
[Reference:<http://jsfiddle.net/gh/get/library/pure/highcharts/highcharts/tree/master/samples/highcharts/drilldown/labels/][1]> | In case you have a chart where only a selection of columns have drilldowns, Sebastian Bochan's answer needs to be modified so that all columns have the same label:
```
(function (H) {
//DATALABELS
H.wrap(H.Series.prototype, 'drawDataLabels', function (proceed) {
var css = this.chart.options.drilldown.activeDataLabelStyle;
proceed.call(this);
css.textDecoration = 'none';
css.fontWeight = 'normal';
css.cursor = 'default';
css.color = 'blue';
H.each(this.points, function (point) {
if (point.dataLabel) { // <-- remove 'point.drilldown &&'
point.dataLabel
.css(css)
.on('click', function () {
return false;
});
}
});
});
})(Highcharts);
```
**Also note** that these settings are global, so also affect any other charts you may have. |
6,559,081 | I am making a login in page and i am a beginner programmer i need to know what function to compare the passwords with then if they do not match tell the user that they dont match and then i need to encrypt them to be sent to the database
Thank you
This is what i have so far:
```
<?php
$Firstname = $_POST['Firstname'];
$Lastname = $_POST['Lastname'];
$Email = $_POST['Email'];
$password = $_POST['password'];
$password2 = $_POST['password2'];
if ($&&$password&&$Email&&$Firstname&&$Lastname)
{
if int strcmp ( string $password , string $password2 )
{
$connect = mysql_connect("localhost","root","power1") or die("couldn't connect!");
mysql_select_db("members") or die ("couldnt find db!");
INSERT INTO users (Firstname, Lastname, Email, password,...)
VALUES ($Firstname, $Lastname, $Email, $password, $password2,...)
}
else
die("Your Passswords do not match")
}
else
die("Please enter your credentials");
?>
``` | 2011/07/02 | [
"https://Stackoverflow.com/questions/6559081",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/826336/"
] | You can use a function such as md5 (http://php.net/manual/en/function.md5.php) in order to calculate the hash of the password and compare the hashes (and store the password as a hash in the db) | Well, first of all, you generally **[hash](http://en.wikipedia.org/wiki/Hash_function)** a password, you don't encrypt it. A popular hash algorithm is **md5**, PHP provides a built in function to make a md5 hash: [md5](http://php.net/manual/en/function.md5.php)
It is best practise to salt the hashes of the passwords you store. You should do some reading on that topic, for example [here](https://stackoverflow.com/questions/674904/salting-your-password-best-practices).
Then you would hash the user input with md5 and compare that value with the password-hash stored in the database.
To answer your first question, comparing the two passwords on registration is fairly simple:
```
$password = trim($_POST['password']);
$password2 = trim($_POST['password2']);
if($password1 === $password2){
echo "Passwords match";
}else{
echo "Password do not match";
}
``` |
2,515,155 | >
> Let $n \in \mathbb{N}$ be odd. Show that:
> $$\Aut(\mathbb{Z}/{n\mathbb{Z}}) \cong \Aut(\mathbb{Z}/{2n\mathbb{Z}})$$
>
>
>
$\DeclareMathOperator{\Aut}{Aut}$
My attempt:
An automorphism $f \in \Aut(\mathbb{Z}/{n\mathbb{Z}})$ is uniquely represented by $f(1)$ since $1$ generates $\mathbb{Z}/{n\mathbb{Z}}$. $f(1)$ has to be a generator of $\mathbb{Z}/{2n\mathbb{Z}}$, which means $2n$ and $f(1)$ are relatively prime.
Thus, $\Aut(\mathbb{Z}/{n\mathbb{Z}})$ and $(\mathbb{Z}/{n\mathbb{Z}})^\times$ are actually isomorphic via the isomorphism $i \mapsto f\_i$, where $f\_i$ is an automorphism of $\mathbb{Z}/{n\mathbb{Z}}$ having $f\_i(1) = i$.
Since we can similarly deduce that $\Aut(\mathbb{Z}/{2n\mathbb{Z}}) \cong (\mathbb{Z}/{2n\mathbb{Z}})^\times$, we have reduced the problem to showing that $$(\mathbb{Z}/{n\mathbb{Z}})^\times =
(\mathbb{Z}/{2n\mathbb{Z}})^\times$$
Since $n$ and $2$ are relatively prime, we have:
$$\phi(2n) = \phi(2)\phi(n) = \phi(n)$$
Hence, both groups are of the same order, $\phi(n)$.
Now, I'm aware of the fact that $(\mathbb{Z}/{p\mathbb{Z}})^\times$ is a cyclic group if $p$ is prime, but that is certainly not the case for $2n$, so we cannot easily conclude that they are isomorphic.
The only thing that comes to mind is to try to find what the elementary divisors for an Abelian group of order $\phi(n)$ could be. For example, $\phi(n)$ is even for $n \ge 3$ so there exists a unique element of order $2$ in both groups, which is $-1$. So the isomorphism would send $-1$ to $-1$.
How should I proceed here? | 2017/11/11 | [
"https://math.stackexchange.com/questions/2515155",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/144766/"
] | The length of the crease is 16 inches.
[](https://i.stack.imgur.com/kZM9m.jpg) | Hint:
[](https://i.stack.imgur.com/lsFon.png)
(This space intentionally left blank.) |
6,666,038 | I have an ASP.net WebForms page that has a lot of content on the top of the screen. It has a link button that will post back to the page and show another section of the page. When the page refreshes, I would like to set focus and scroll down to this section of the page.
I tried doing
```
txtField.Focus()
```
in my code behind and it will set focus and try to scroll there, but then scrolls right back to the top. The focus is still on my text box but the position of the screen is at the very top. The Link is at the top of the screen which is causing the postback. I want to scroll to the very bottom of the screen. It does this briefly and then scrolls right back to the top.
I have tried setting
```
Page.MaintainScrollPositionOnPostback = false;
```
but that doesn't seem to help either.
Is there some way I can force it to go to a specific position?
Is it possible to add an anchor tag to the URL when I postback using a button or link button? | 2011/07/12 | [
"https://Stackoverflow.com/questions/6666038",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/143919/"
] | `Page.MaintainScrollPositionOnPostBack = true;` should take you back to the same position on the screen, but you could use AJAX, or you could use `SetFocus()` to focus on a specific control after the postback:
<http://msdn.microsoft.com/en-us/library/ms178232.aspx> | I have
```
<asp:MultiView ID="mvAriza" runat="server">
<asp:View ID="View14" runat="server">
............ .......
</asp:View>
</asp:MultiView>
```
on \*.aspx page. And on the \*.aspx.cs page on a button click.
```
Page.SetFocus(mvAriza.ClientID);
```
It works great. |
46,373,421 | I have built a Ping Pong game using JavaScript and am trying to have the scores updated on the 'scoreboard' after each match. Presently, the scores for both players on the scoreboard are on a some sort of a counter loop and will not stop. I would like to have 1 win added for the winning player's stats to the scoreboard after each match. How can I have the correct total number of wins reflected for each player on the scoreboard. Your help would be much appreciated!
[Link to Fiddle](https://jsfiddle.net/1nm4554L/)
```
<body>
<h1>Ping Pong</h1>
<canvas id="gameCanvas" width="800" height="600"></canvas>
<div id="sb">
<h1>SCOREBOARD</h1>
<ul>
<li>Player 1: <span id="player_1">0</span></li>
<li> Player 2: <span id="player_2">0</span></li>
</ul>
</div>
<script>
var count1_final = 0;
var count2_final = 0;
var canvas;
var canvasContext;
var ballX = 50;
var ballY = 50;
var ballSpeedX = 10;
var ballSpeedY = 4;
var player1Score = 0;
var player2Score = 0;
const WINNING_SCORE = 2;
var showingWinScreen = false;
var paddle1Y = 250;
var paddle2Y = 250;
const PADDLE_THICKNESS = 10;
const PADDLE_HEIGHT = 100;
function calculateMousePos(evt) {
var rect = canvas.getBoundingClientRect();
var root = document.documentElement;
var mouseX = evt.clientX - rect.left - root.scrollLeft;
var mouseY = evt.clientY - rect.top - root.scrollTop;
return {
x:mouseX,
y:mouseY
};
}
function handleMouseClick(evt) {
if(showingWinScreen) {
player1Score = 0;
player2Score = 0;
showingWinScreen = false;
}
}
window.onload = function() {
canvas = document.getElementById('gameCanvas');
canvasContext = canvas.getContext('2d');
var framesPerSecond = 30;
setInterval(function() {
moveEverything();
drawEverything();
}, 1000/framesPerSecond);
canvas.addEventListener('mousedown', handleMouseClick);
canvas.addEventListener('mousemove',
function(evt) {
var mousePos = calculateMousePos(evt);
paddle1Y = mousePos.y - (PADDLE_HEIGHT/2);
});
}
function ballReset() {
var count1_final = 0;
var count2_final = 0;
if(player1Score >= WINNING_SCORE ||
player2Score >= WINNING_SCORE) {
showingWinScreen = true;
}
ballSpeedX = -ballSpeedX;
ballX = canvas.width/2;
ballY = canvas.height/2;
}
function computerMovement() {
var paddle2YCenter = paddle2Y + (PADDLE_HEIGHT/2);
if(paddle2YCenter < ballY - 35) {
paddle2Y = paddle2Y + 6;
} else if(paddle2YCenter > ballY + 35) {
paddle2Y = paddle2Y - 6;
}
}
function moveEverything() {
if(showingWinScreen) {
return;
}
computerMovement();
ballX = ballX + ballSpeedX;
ballY = ballY + ballSpeedY;
if(ballX < 0) {
if(ballY > paddle1Y &&
ballY < paddle1Y+PADDLE_HEIGHT) {
ballSpeedX = -ballSpeedX;
var deltaY = ballY
-(paddle1Y+PADDLE_HEIGHT/2);
ballSpeedY = deltaY * 0.35;
} else {
player2Score++; // must be BEFORE ballReset()
ballReset();
}
}
if(ballX > canvas.width) {
if(ballY > paddle2Y &&
ballY < paddle2Y+PADDLE_HEIGHT) {
ballSpeedX = -ballSpeedX;
var deltaY = ballY
-(paddle2Y+PADDLE_HEIGHT/2);
ballSpeedY = deltaY * 0.35;
} else {
player1Score++; // must be BEFORE ballReset()
ballReset();
}
}
if(ballY < 0) {
ballSpeedY = -ballSpeedY;
}
if(ballY > canvas.height) {
ballSpeedY = -ballSpeedY;
}
}
function drawNet() {
for(var i=0;i<canvas.height;i+=40) {
colorRect(canvas.width/2-1,i,2,20,'white');
}
}
function drawEverything() {
// next line blanks out the screen with black
colorRect(0,0,canvas.width,canvas.height,'black');
if(showingWinScreen) {
canvasContext.fillStyle = 'white';
if(player1Score >= WINNING_SCORE) {
canvasContext.fillText("Player 1 Won", 350, 200);
// var count1 = 0;
// var count1_final = count1 + 1;
// player1final_score++;
count1_final++;
document.getElementById("player_1").innerHTML = count1_final;
console.log(count1_final)
} else if(player2Score >= WINNING_SCORE) {
canvasContext.fillText("Player 2 Won", 350, 200);
// var count2 = 0;
// var count2_final = count2 + 1;
// player2final_score++;
count2_final++;
// console.log(player2final_score)
document.getElementById("player_2").innerHTML = count2_final;
console.log(count2_final)
}
canvasContext.fillText("Play Again", 350, 500);
return;
}
drawNet();
// this is left player paddle
colorRect(0,paddle1Y,PADDLE_THICKNESS,PADDLE_HEIGHT,'white');
// this is right computer paddle
colorRect(canvas.width-PADDLE_THICKNESS,paddle2Y,PADDLE_THICKNESS,PADDLE_HEIGHT,'white');
// next line draws the ball
colorCircle(ballX, ballY, 10, 'white');
canvasContext.fillText(player1Score, 100, 100);
canvasContext.fillText(player2Score, canvas.width-100, 100);
}
function colorCircle(centerX, centerY, radius, drawColor) {
canvasContext.fillStyle = drawColor;
canvasContext.beginPath();
canvasContext.arc(centerX, centerY, radius, 0,Math.PI*2,true);
canvasContext.fill();
}
function colorRect(leftX,topY, width,height, drawColor) {
canvasContext.fillStyle = drawColor;
canvasContext.fillRect(leftX,topY, width,height);
}
</script>
</head>
</body>
body {
background: #283048; /* fallback for old browsers */
background: -webkit-linear-gradient(to right, #859398, #283048); /* Chrome 10-25, Safari 5.1-6 */
background: linear-gradient(to right, #859398, #283048); /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */
}
h1 {
color: white;
text-align: center;
}
#gc {
float: left;
}
#sb {
float: right;
margin-right: 50px;
border: 2px solid;
padding: 20px;
}
``` | 2017/09/22 | [
"https://Stackoverflow.com/questions/46373421",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5041196/"
] | After battling for several hours with this error and trying various solutions, my solution turned out to be different than others here so I'm adding it for others who may benefit.
I tried:
- ALWAYS\_EMBED\_SWIFT\_STANDARD\_LIBRARIES = YES
- LD\_RUNPATH\_SEARCH\_PATHS = $(inherited) @executable\_path/Frameworks
No luck. Turned out the issue was more basic. My project has multiple build targets and somehow the setting for Host Application had gotten unset.
[](https://i.stack.imgur.com/rSanF.jpg) | Try restarting Xcode. I tried everything else and this is what stopped the problem. |
31,695,890 | **UPDATE:**
I changed my script to this and it works. Way simpler and it works.
```
function myFunction(valor) {
var elementos = document.getElementsByClassName("inner");
var i;
for (i = 1; i < elementos.length+1; i++) {
document.getElementById("age"+i).style.visibility = "hidden";
}
document.getElementById("age"+valor).style.visibility = "visible";
}
```
---
I have this script:
```
function myFunction(valor) {
alert("Has seleccionado " + valor);
var elementos = document.getElementsByClassName("inner");
//alert ("Tienes " + elementos.length + " elementos.");
var i;
for (i = 1; i < elementos.length + 1; i++) {
var sty = document.getElementById("age" + i);
//alert("age"+i);
if (getComputedStyle(sty).getPropertyValue("visibility") == "hidden") {
document.getElementById("age" + valor).style.visibility = "visible";
} else {
document.getElementById("age" + i).style.visibility = "hidden";
}
}
}
```
That I control with a slider control. What I'm doing is hiding or showing some divs with depending of what I choose from the slider.
This is how I paint my data before trying to hide or shsow elements with the slider:
```
$(window).load(function() {
$.getJSON('http://xxxxx/xxxxx.json', function(data) {
var output = "<ul class='lista'><div class='outer'>";
for (var i in data.lbclassic) {
output += "<div style='visibility:hidden;' class='inner'id=" + "age" + data.lbclassic[i].ageinweeks + ">" + "<p>" + data.lbclassic[i].ageinweeks + "--" + data.lbclassic[i].cumul + "--" + data.lbclassic[i].perhh + "--" + data.lbclassic[i].perhd + "--" + data.lbclassic[i].eggweightinweek + "--" + data.lbclassic[i].eggmasscumul1 + "--" + data.lbclassic[i].eggmassinweek + "--" + data.lbclassic[i].eggmasscumul + "</p></div>";
}
output += "</div></ul>";
document.getElementById("placeholder").innerHTML = output;
});
});
```
This works great until one point - once I get to the last element (90 in this case), it won't show up. | 2015/07/29 | [
"https://Stackoverflow.com/questions/31695890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5123792/"
] | Matlab's `reshape` function is pretty handy (and fast), but always reads and writes *complete* columns. So for your problem, some additional steps are necessary.
Here is how you can do it:
```
m = 5 % columns of submatrix
n = 4 % rows of submatrix
k = 50 % num submatrixes in matrix column
l = 50 % num submatrixes in matrix row
A = rand(m*k,n*l); % rand(250,200)
```
Reshape the matrix into a four dimensional matrix (dimensions x1,x2,x3,x4), where each submatrix is located in the x1-x3 plane. The submatrix columns from the original matrix are then in x2 direction, and the submatrix rows in x4 direction.
```
B = reshape(A,[m,k,n,l]); % [4,50,5,50]
```
Permute ('transpose') the 4D matrix, so that each submatrix is located in the x1-x2 plane. (`reshape` first reads columns, then rows, then 3rd dimension, etc.)
```
C = permute(B,[1,3,4,2]); % For column-wise reshaping, use [1,3,2,4]
```
Reshape the 4D matrix into the desired 2D output matrix.
```
D = reshape(C,m,[]);
``` | Thought I'd add another approach that uses indices and one built-in function `zeros`. Maybe this way won't have any unnecessary error checks or reshaping operations. Turns out it's more efficient (see below).
```
%submatrix size
m = 5;
n = 4;
%repeated submatrix rows and cols
rep_rows = 50;
rep_cols = 50;
% big matrix
A = rand(m * rep_rows, n * rep_cols);
% create new matrix
C = zeros(m, (n * rep_cols) * rep_rows);
for k = 1:rep_rows
ind_cols = (n * rep_cols) * (k - 1) + 1: (n * rep_cols) * k;
ind_rows = m * (k - 1) + 1: m * k;
C(:, ind_cols) = A(ind_rows, :);
end
```
I decided to time the three answers here and found this approach to be significantly faster. Here is the test code:
```
% Bastian's approach
m = 5; % columns of submatrix
n = 4; % rows of submatrix
k = 50; % num submatrixes in matrix column
l = 50; % num submatrixes in matrix row
A = rand(m*k,n*l); % rand(250,200)
% start timing
tic
B = reshape(A,[m,k,n,l]); % [4,50,5,50]
C = permute(B,[1,3,4,2]); % For column-wise reshaping, use [1,3,2,4]
D = reshape(C,m,[]);
toc
% stop timing
disp(' ^^^ Bastian');
% Matt's approach
n = 50; % rows
m = 50; % columns
% start timing
tic
X = mat2cell(A,repmat(5,1,n),repmat(4,1,m));
X = reshape(X.',1,[]);
X = cell2mat(X);
toc
% stop timing
disp(' ^^^ Matt');
% ChisholmKyle
m = 5;
n = 4;
rep_rows = 50;
rep_cols = 50;
% start timing
tic
C = zeros(m, (n * rep_cols) * rep_rows);
for k = 1:rep_rows
ind_cols = (n * rep_cols) * (k - 1) + 1: (n * rep_cols) * k;
ind_rows = m * (k - 1) + 1: m * k;
C(:,ind_cols) = A(ind_rows, :);
end
toc
% stop timing
disp(' ^^^ this approach');
```
Here is the output on my machine:
```
Elapsed time is 0.004038 seconds.
^^^ Bastian
Elapsed time is 0.020217 seconds.
^^^ Matt
Elapsed time is 0.000604 seconds.
^^^ this approach
``` |
57,850,483 | The new share sheet on iOS13 shows a preview/thumbnail of the item being shared on its top left corner.
When sharing an UIImage using an UIActivityViewController I would expect a preview/thumbnail of the image being shared to be displayed there (like e.g. when sharing an image attached to the built in Mail app), but instead the share sheet is showing my app's icon.

What code/settings are required to show a thumbnail of the image being exported in the share sheet?
I have set up the UIActivityViewController as follows:
```
let image = UIImage(named: "test")!
let activityVC = UIActivityViewController(activityItems: [image], applicationActivities: nil)
activityVC.popoverPresentationController?.sourceView = self.view
self.present(activityVC, animated: true, completion: nil)
``` | 2019/09/09 | [
"https://Stackoverflow.com/questions/57850483",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10060753/"
] | Just pass the image urls to `UIActivityViewController` not the `UIImage` objects.
For example:
```
let imageURLs: [URL] = self.prepareImageURLs()
let activityViewController = UIActivityViewController(activityItems: imageURLs, applicationActivities: nil)
self.present(activityViewController, animated: true, completion: nil)
```

You can see that the image name and the image properties are shown in the top of the `UIActivityViewController`. Hope it helps! | This code is only available for iOS 13 as a minimum target. I added a code example to use a share button in a SwiftUI view in case other people need it. This code also work for iPad.
You can use this class `LinkMetadataManager` and add the image of your choice. The very important part, is that you **must have your image in your project directory**, not in a Assets.xcassets folder. Otherwise, it won't work.
When everything will be setup, you will use the button this way in your SwiftUI view.
```
struct ContentView: View {
var body: some View {
VStack {
ShareButton()
}
}
}
```
This is the class that will be sharing your application with the Apple Store link. You can share whatever you want from that. You can see how the image is added using `LPLinkMetadata` as it is the part that interests you.
```
import LinkPresentation
// MARK: LinkMetadataManager
/// Transform url to metadata to populate to user.
final class LinkMetadataManager: NSObject, UIActivityItemSource {
var linkMetadata: LPLinkMetadata
let appTitle = "Your application name"
let appleStoreProductURL = "https://apps.apple.com/us/app/num8r/id1497392799" // The url of your app in Apple Store
let iconImage = "appIcon" // The name of the image file in your directory
let png = "png" // The extension of the image
init(linkMetadata: LPLinkMetadata = LPLinkMetadata()) {
self.linkMetadata = linkMetadata
}
}
// MARK: - Setup
extension LinkMetadataManager {
/// Creating metadata to population in the share sheet.
func activityViewControllerLinkMetadata(_ activityViewController: UIActivityViewController) -> LPLinkMetadata? {
guard let url = URL(string: appleStoreProductUR) else { return linkMetadata }
linkMetadata.originalURL = url
linkMetadata.url = linkMetadata.originalURL
linkMetadata.title = appTitle
linkMetadata.iconProvider = NSItemProvider(
contentsOf: Bundle.main.url(forResource: iconImage, withExtension: png))
return linkMetadata
}
/// Showing empty string returns a share sheet with the minimum requirement.
func activityViewControllerPlaceholderItem(_ activityViewController: UIActivityViewController) -> Any {
return String()
}
/// Sharing url of the application.
func activityViewController(_ activityViewController: UIActivityViewController,
itemForActivityType activityType: UIActivity.ActivityType?) -> Any? {
return linkMetadata.url
}
}
```
Use this extension of `View` to trigger the share sheet on a SwiftUI view.
```
import SwiftUI
// MARK: View+ShareSheet
extension View {
/// Populate Apple share sheet to enable user to share Apple Store link.
func showAppShareSheet() {
guard let source = UIApplication.shared.windows.first?.rootViewController else {
return
}
let activityItemMetadata = LinkMetadataManager()
let activityVC = UIActivityViewController(
activityItems: [activityItemMetadata],
applicationActivities: nil)
if let popoverController = activityVC.popoverPresentationController {
popoverController.sourceView = source.view
popoverController.permittedArrowDirections = []
popoverController.sourceRect = CGRect(
x: source.view.bounds.midX,
y: source.view.bounds.midY,
width: .zero,
height: .zero)
}
source.present(activityVC, animated: true)
}
}
```
Then, create a `ShareButton` as a component to use it in any of your SwiftUI view. This is what is used in the ContentView.
```
import SwiftUI
// MARK: ShareButton
/// Share button to send app store link using the Apple
/// classic share screen for iPhone and iPad.
struct ShareButton: View {
@Environment(\.horizontalSizeClass) private var horizontalSizeClass
var body: some View {
ZStack {
Button(action: { showAppShareSheet() }) {
Image(systemName: "square.and.arrow.up")
.font(horizontalSizeClass == .compact ? .title2 : .title)
.foregroundColor(.accentColor)
}
.padding()
}
}
}
``` |
50,966,011 | I am using Angular 6 and I added the material components to my project following the steps in this [Guide](https://material.angular.io/guide/getting-started). But when I use the stepper component in my code I get the following exception in the console:
```
NewReqComponent.html:16 ERROR TypeError: _this._driver.validateStyleProperty is not a function
at browser.js:844
at Array.forEach (<anonymous>)
at browser.js:843
at Array.forEach (<anonymous>)
at AnimationAstBuilderVisitor.push../node_modules/@angular/animations/fesm5/browser.js.AnimationAstBuilderVisitor._validateStyleAst (browser.js:840)
at AnimationAstBuilderVisitor.push../node_modules/@angular/animations/fesm5/browser.js.AnimationAstBuilderVisitor.visitStyle (browser.js:780)
at AnimationAstBuilderVisitor.push../node_modules/@angular/animations/fesm5/browser.js.AnimationAstBuilderVisitor.visitState (browser.js:678)
at browser.js:657
at Array.forEach (<anonymous>)
at browser.js:655
```
I used the component like this:
```
<mat-horizontal-stepper>
<mat-step label="step1">step1</mat-step>
<mat-step label="step2">step2</mat-step>
</mat-horizontal-stepper>
```
and the app.module.ts:
```
imports: [
BrowserModule,
BrowserAnimationsModule,
RouterModule.forRoot(appRoutes) ,
FormsModule, HttpClientModule ,
FormWizardModule ,
ArchwizardModule,
MatStepperModule
],
``` | 2018/06/21 | [
"https://Stackoverflow.com/questions/50966011",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4497657/"
] | It seems that there is a mismatch between the angular version and the material version.
Please make sure to update the angular to the latest.
try to set it to 6.0.6 version and I think it will works fine. | you are required to upgrade Angular.json. Run these commands and that's it.
```
$ ng update @angular/cli
$ ng update @angular/core
$ ng update @angular/material
``` |
4,014,982 | I have a method which I will accept either a single object or a list of objects. I want to add whatever is passed to another list. Currently, my method looks like this:
```
def appendOrExtend(self, item):
if type(item).__name__ == "list":
self.list.extend(item)
else:
self.list.append(item)
```
It seems to me that there should be a more Pythonic way of achieving this, could you suggest one? | 2010/10/25 | [
"https://Stackoverflow.com/questions/4014982",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | ```
def append(self, item):
self.list.append(item)
def extend(self, item):
self.list.extend(item)
```
Bottom line: Don't have a method to do both things. It confuses and makes your method less useful, instead of more useful. It's also harder to test and to maintain. Also the user of your function already knows if she wants to use append or extend, so by providing a single method you're discarding the information your caller/user already knows.
Another way to write is using packing/unpacking argument syntax:
```
def append(self, *items):
self.list.extend(items)
```
that way you can call the method as
```
x.append('single item')
```
or
```
x.append(*list_of_items)
``` | You can also do this while keeping the if test:
```
if not isinstance(item, list):
item = [item]
self.list.extend(item)
``` |
129,565 | Apple (AAPL) recently announced that they'll undergo a 4:1 stock split. Here are the relevant dates per a [CNBC article](https://www.cnbc.com/2020/07/30/apple-stock-split-announced.html):
>
> The shares will be distributed to shareholders at the close of business on August 24, and trading will begin on a split-adjusted basis on August 31.
>
>
>
Let's say that I own 10 AAPL. If we take this statement literally at face value, it sounds like my brokerage account would credited with 30 additional stocks (giving me 40 total) on August 24 at the pre-split market value that's nearly $440 (as of August 5), and that the market price in the neighborhood of $100 would take effect on August 31. I do not believe that's what will happen for stockholders, so I'm trying to decipher the following questions since the article itself did not clearly articulate that from my perspective:
* When will the new shares from the split be credited to my brokerage account?
* When will the new stock price be reflected?
* If I was interested in purchasing a share on Wednesday, August 26, would that be at the post-split value? Or would there be any other nuances to that transaction? | 2020/08/05 | [
"https://money.stackexchange.com/questions/129565",
"https://money.stackexchange.com",
"https://money.stackexchange.com/users/101642/"
] | Your confusion appears to be due to a poor summary in the [CNBC article](https://www.cnbc.com/2020/07/30/apple-stock-split-announced.html). Where they had:
>
> The shares **will be distributed to shareholders at the close of business on August 24**, and trading will begin on a split-adjusted basis on August 31.
>
>
>
The actual [Apple announcement](https://www.apple.com/newsroom/2020/07/apple-reports-third-quarter-results) linked in that article contains:
>
> The Board of Directors has also approved a four-for-one stock split to make the stock more accessible to a broader base of investors. Each Apple **shareholder of record at the close of business on August 24, 2020** will receive three additional shares for every share held on the record date, and trading will begin on a split-adjusted basis on August 31, 2020.
>
>
>
(Both emphases mine).
So the CNBC quote is really saying the extra shares will be distributed to "*people who are shareholders at the close of business on August 24*", not that the distribution *takes place* on the 24th.
In fact, both quotes are – I believe – slightly misleading. From [Stock Split Announcements](http://www.rightline.net/home/stocksplits.html) on *Rightline.net*:
>
> **Key Dates For Splitting Stocks**
>
>
> **Split Record Date** – This is probably the most confusing term within a split announcement. The reason for this is that many investors are used to associating this date with a "cash" dividend. To receive a "cash" dividend you must own the stock on the record date. In the case of a stock split, the record date is meaningless. This in itself can make the record date key since those that don't understand this may be scrambling to go out purchase the stock in hopes of taking part in the split.
>
>
> **Split Pay Date** – This is the date that the stock dividend or split will be paid.
>
>
> **Split Execution Date** – This date is not often found in a split announcement, but it will always be the first trading day following the "split pay date." For example, if the pay date is on a Friday, then you can expect to see the affect of the split when the market opens on the following Monday. On this date the stock price will be adjusted and you should see the additional shares in your brokerage account. Brokerages can vary as to when they will reflect additional split shares in your account. Some will reflect it immediately on the execution date and others will wait several days until the actual certificates are received.
>
>
>
So, as Apple's *Execution Date* is 31st August (Monday), then the *Pay Date* will be 28th August (Friday). By Monday morning shares will have "magically" multiplied by four and the share price will have dropped to a quarter of its previous figure.
Any trades before the Monday will be at the current (pre-split) price, and be for "un-split" shares. However, if settlement is not until the Monday or Tuesday, the number of shares that "land" will have increased: if you bought 100 shares at $440 each, you will end up with 400 shares, each worth $110 (assuming no *other* change in the share price). | >
> When will the new shares from the split be credited to my brokerage account?
>
>
>
>
> When will the new stock price be reflected?
>
>
>
Let’s assume that as of the Record Date (August 24, 2020) an investor owns 100 shares of Apple common stock and that the market price of Apple stock is $400 per share, so that the investment in Apple is worth $40,000. Let’s also assume that Apple’s stock price doesn’t move up or down between the Record Date and the time the split actually takes place. Immediately after the split, the investor would own 400 shares of Apple stock, but the market price would be $100 per share instead of $400 per share. The investor’s total investment value in Apple would remain the same at $40,000 until the stock price moves up or down.
>
> If I was interested in purchasing a share on Wednesday, August 26, would that be at the post-split value? Or would there be any other nuances to that transaction?
>
>
>
If you buy shares on or after the Record Date but before the Ex Date, you will purchase the shares at the pre-split price and will receive (or your brokerage account will be credited with) the shares purchased. Following the split, you will receive (or your brokerage account will be credited with) the additional shares resulting from the stock split.
I didn't write that text by myself, its taken out of the offical apple investors page.
See <https://investor.apple.com/faq/#StockSplit2> |
42,725,413 | I am wondering if it is possible to deploy `react.js` web app that I've built to a share hosting site that does not have `node.js` installed?
I use `webpack` to build the application and it creates normal `html, js, css` file. I uploaded the static folder that includes all those `html, js(bundle.js) and css` files, but when I request the site, the server reply with `404` bundle.js not found response. | 2017/03/10 | [
"https://Stackoverflow.com/questions/42725413",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3301668/"
] | Yes you sure can put react on a shared hosting provider.
Seeing as you're getting a 404 error (not found), you are probably referencing your react file/bundle incorrectly. It might not even be named `bundle.js` if you're using a boilerplate to create your application.
Can you give more information? What does your index.html file look like? What does your directory structure look like? If you are able to post these files I can tell you what the issue is.
**Update:**
The answer below should be accepted. (Although this would assume that you have the ability to make a build which you have not verified or not.)
Make a build using the build command through whatever boilerplate you used. Deploy those files on your shared hosting server. Make sure that index.html is at the root of where your server is expecting the root to be and your app should be live. | For deploying a react app on a shared hosting you need to create a production build. Production build is a pack of all your react code and its dependencies.
in most shared hosting we put our site/app inside a public\_html directory so if we hit [www.yourdomain.com](http://www.yourdomain.com) it serves the code from public\_html directory.
so if your react app is ready to go, edit your package.json file add a new key value:
"homepage":"http://yourdomain.com"
then create a build using following command:
npm run build
after running the command you will see a new directory named build in your app root. It will contain js and css for the app and a index.html file. You need to upload all the content inside build directory to public\_html directory, and that's all, go to your domain and your app will be working just fine. |
6,711,592 | I'm curious about the purpose of the methods [`getItem`](http://developer.android.com/reference/android/widget/Adapter.html#getItem%28int%29) and [`getItemId`](http://developer.android.com/reference/android/widget/Adapter.html#getItemId%28int%29) in the class Adapter in the Android SDK.
From the description, it seems that `getItem` should return the underlying data. So, if I have an array of names `["cat","dog","red"]` and I create an adapter *`a`* using that, then *`a.getItem(1)`* should return "dog", correct? What should *`a.getItemId(1)`* return?
If you've made use of these methods in practice, could you provide an example? | 2011/07/15 | [
"https://Stackoverflow.com/questions/6711592",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/56944/"
] | If you implement `getItemId`correctly then it might be very useful.
Example :
You have a list of albums :
```
class Album{
String coverUrl;
String title;
}
```
And you implement `getItemId` like this :
```
@Override
public long getItemId(int position){
Album album = mListOfAlbums.get(position);
return (album.coverUrl + album.title).hashcode();
}
```
Now your item id depends on the values of **coverUrl** and **title** fields and if you change then and call `notifyDataSetChanged()` on your adapter, then the adapter will call getItemId() method of each element and **update only thouse items which id has changed.**
This is very useful if are doing some "heavy" operations in your `getView()`.
BTW : if you want this to work, you need to make sure your `hasStableIds()` method returns false; | I would like to mention that after implementing `getItem` and `getItemId` you can use [ListView.getItemAtPosition](http://developer.android.com/reference/android/widget/AdapterView.html#getItemAtPosition%28int%29) and [ListView.getItemIdAtPosition](http://developer.android.com/reference/android/widget/AdapterView.html#getItemIdAtPosition%28int%29) to directly access you data, instead of going through the adapter. This may be particularly useful when implementing an onClick listener. |
31,594,349 | What's the best practice for having different environments for lambda functions, i.e. dev/prod
Should I just have two lambda functions one called myFunction-prod and myFunction-dev or is there a better way to create environments.
I saw that Amazon API Gateway has a notion of "Stages" which accommodates separation of dev, staging and production versions of code.
Is there a similar notion with Amazon Lambda? | 2015/07/23 | [
"https://Stackoverflow.com/questions/31594349",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/611750/"
] | During re:Invent 2015 (Oct); versioning and aliases has been added to lambda; this [official doc](http://docs.aws.amazon.com/lambda/latest/dg/versioning-aliases.html) describes very well how to use this for prod and dev.
p.s. In order to test on the live data (w/o affecting the prod); I use SNS fan-out pattern (subscribing both prod and dev lambda's to the same SNS topic). | Just to add to Neil's you can also use Stage Variables to link to the respective Lambda Alias i.e. the dev stage will use the DEV alias of your lambda function while the prod stage will use the PROD alias of your lambda function. More about stage variables here
[Working with Stage Variables in Amazon API Gateway](http://docs.aws.amazon.com/apigateway/latest/developerguide/stage-variables.html) |
14,470,115 | I have just started learning Haskell using "Learn you a Haskell for Great Good".
I am currently reading "Types and Typeclasses" chapter, so my knowledge is pretty .. non-existent.
I am using Sublime Text 2 with SublimeHaskell package which builds/checks file on every save.
The problem: I'm trying to make function type declaration like this:
```
funcName :: [Char] -> [Char]
```
I'm getting this warning:
>
> Warning: Use String
> Found:
> [Char] -> [Char]
> Why not:
> String -> String
>
>
> Build FAILED
>
>
>
Can you explain to me why is it a bad idea to use Char array instead of String or give me a link to an explanation of possible repercussions etc. I've googled and found nothing.
P.S. I'm a C# developer, I understand the difference between char array and strings in c-like languages. | 2013/01/22 | [
"https://Stackoverflow.com/questions/14470115",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1435744/"
] | `String` is nothing more than a type alias for `[Char]`, so there is no practical between the two - it's simply a matter of readability. | You seem to be running HLint on your code automatically, and treating any HLint warnings as fatal errors. As [the HLint author says](http://neilmitchell.blogspot.co.uk/2009/09/how-i-use-hlint.html) "Do not blindly apply the output of HLint". `String` and `[Char]` are exactly the same, as everyone says, it's a question of which looks nicer. I would tend to use `String` if I'm operating on contiguous lists of characters I want to treat as a block (most of the time), and explicitly use `[Char]` when the characters don't make sense combined in a run (far rarer). HLint divides all hints into error (fix) and warning (think), so perhaps it might be best only to build fail on error hints. |
490,861 | I have loose measures of average speed in different positions (speed is in the x axis given particularities of my own problem)
[](https://i.stack.imgur.com/VTnzI.png)
How can I estimate a fitting curve for 'instantaneous speed at each position' vs. 'position' ?
I guess the first step is to fit an average speed curve.
What then?
My plot shows that the average speed around 1000m changes from about 1.01m/s to 1.05m/s, which means that instantaneous speed at that region must have been considerably higher to compensate for the 0-800m region moving slowly. | 2019/07/10 | [
"https://physics.stackexchange.com/questions/490861",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/236547/"
] | The problem lies in the boundary conditions. Ignoring factors of $G$ and $\pi$, gauss's law of gravitation relates the gravitational potential $\Phi$ to the mass density $\rho$ by
$$\rho=-\nabla^2 \Phi. $$
In order to have a unique, well-defined solution, we need to specify boundary conditions for $\Phi$. Usually, we *assume* that $\rho$ dies off sufficiently quickly at spatial infinity that a reasonable choice of boundary condition is $\Phi(|\vec x|\to\infty)=0$ is. The shell theorem relies on this assumption. However in your example $\rho$ does not die off at infinity and is instead non-zero everywhere and therefore the shell theorem fails.
Often when a given scenario in physics doesn't, but almost, satisfies the 'if' part of a theorem, it can be helpful to try and modify the problem so that it does. Therefore we can use a window function $W\_\epsilon(x-x\_0)$ that dies off quickly as $x\to\infty$ but $\lim\_{\epsilon\to0} W\_\epsilon =1$ to regulate the charge density. [e.g. take $W\_\epsilon(x-x\_0)=e^{-\epsilon (\vec x-\vec x\_0)^2}$.] Then we can replace your uniform charge density $\rho$ by
$$\rho\to\rho\_{\epsilon,x\_0}\equiv \rho W\_\epsilon(x-x\_0) .$$
In this case, the shell theorem does hold. However, the result we get is not regulator-independent, that is if we solve for $\Phi\_{\epsilon,x\_0}$ using the charge distribution $\rho\_{\epsilon,x\_0}$ and then send $\epsilon \to0$, we find that our answer still depends on choice of $x\_0$.
This is the mathematically rigorous way to see that there really is an ambiguity when applying the shell theorem to such a situation!
Edit: There seems to be some debate in the comments as to whether the shell theorem should be proved with forces or with Gauss's law. In reality, it doesn't matter, but I will address what goes wrong if you just use forces. Essentially, Newton's laws are only guaranteed to be valid if there is a finite amount of matter in the universe. Clearly if there is uniform mass density throughout all of space, then there is an infinite amount of matter, so the shell theorem fails. The requirement that $\rho(|\vec x|\to \infty)\to 0$ 'sufficiently quickly' from above is more precisely that $\int d^3 x \rho(x) <\infty$, which is just the condition that there is a finite amount of matter in the universe. | From a very quick skim it seems the existing answers are excellent, so I'll instead contribute some of the physics and philosophy literature. I too was concerned by this issue after reading a certain paper (Peacock 2001, incidentally), until I discovered centuries of thought preceded me!
Your concern was apparently first raised by Bishop Berkeley, in discussion with Newton himself. Much later Seeliger (1890s) sharpened and popularised the critique. See Norton (1999), "The cosmological woes of Newtonian gravitation theory" for history. Norton also discusses the analogous issue for Coulomb's law of electric force.
Remarkably, Newtonian cosmology was only worked out *after* the general relativistic case, by Milne and also McCrea. Here I particularly mean the rate of expansion, which closely resembles the relativistic Friedmann equations incidentally. [I'm assuming a homogeneous and isotropic universe. Otherwise, see Buchert & Ehlers (1997).] But again your objection was raised. Finally, Heckmann & Schucking (1955) are credited with making Newtonian cosmology ~~great again~~ rigorous.
Norton was yet another who independently raised the centuries-old objections. Malament (1995) defended by describing 3 formulations of Newtonian gravity: the $1/r^2$ force law, Poisson's equation, and Newton-Cartan theory. Norton (1995) concurred, yet added that acceleration becomes relative! Tipler (1996a, 1996b) has nice papers from the same time. Wallace (2017) looks interesting, such as the section title "2. Non-uniqueness of solutions to Poisson's equation". |
3,176,593 | I'm having a hard time understanding how to find all solutions of the form $a\_n = a^{(h)}\_n+a\_n^{(p)}$
I show that $a\_n=n2^n \to a\_n=2(n-1)2^{n-1} +2^n=2^n(n-1+1)=n2^n$.
I can show that $a\_n^{(h)}$ characteristic equation $r-2=0 \to a\_n^{(h)}=\alpha2^n$
But I'm stuck on $a\_n^{(p)}$ characteristic equation $C2^n=2C\cdot2^{n-1}+2^n$
Simplifies to $C \neq C+1$, Looking online I saw that the solution is $a\_n=c\cdot2^n+n2^n$, but I'm not sure how to get there. | 2019/04/06 | [
"https://math.stackexchange.com/questions/3176593",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/584468/"
] | Your homogeneous solution has $2^n$ in it already. When this happens, for the particular solution part, we cannot just use $C2^n$ (you have seen what happens if we do). Instead, *the rule in this scenario is to modify the guess by **multiplying by $\boldsymbol{n}$**, i.e. try $a\_n^{(p)}=C\color{red}{n}\cdot 2^n$*. | Here is another take.
Let $b\_n=2^n$. Then
$$
a\_n=2a\_{n-1}+2b\_{n-1}, \quad b\_n=2b\_{n-1}, \quad b\_0=1
$$
and so
$$
\pmatrix{
a\_n \\ b\_n
}
=
\pmatrix{
2 & 2 \\ 0 & 2
}
\pmatrix{
a\_{n-1} \\ b\_{n-1}
}
=
2
\pmatrix{
1 & 1 \\ 0 & 1
}
\pmatrix{
a\_{n-1} \\ b\_{n-1}
}$$
which gives
$$
\pmatrix{
a\_n \\ b\_n
}
=
2^n
\pmatrix{
1 & 1 \\ 0 & 1
}^n
\pmatrix{
a\_0 \\ b\_0
}
=
2^n
\pmatrix{
1 & n \\ 0 & 1
}
\pmatrix{
a\_0 \\ b\_0
}
$$
Therefore,
$$
a\_n = a\_0 2^n + n 2^n
$$ |
57,101,028 | I have a large ingestion pipeline, and sometimes it takes awhile for things to progress from source to the Elasticsearch index. Currently, when we parse our messages with Logstash, we parse the `@timestamp` field based on when the message was written by the source. However, due to large volumes of messages, it takes a currently unknown and possibly very inconsistent length of time to travel from the source producer before it's ingested by Logstash and sent to the Elasticsearch index.
Is there a way to add a field to the Elasticsearch output plugin for Logstash that will mark when a message is sent to Elasticsearch? | 2019/07/18 | [
"https://Stackoverflow.com/questions/57101028",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4949938/"
] | You can try to add a ruby filter as your last filter to create a field with the current time.
```
ruby {
code => "event.set('fieldName', Time.now())"
}
``` | You can do it in an [ingest pipeline](https://gist.github.com/cdahlqvist/e713b39f0c17d85e613f56408a7facd5). That means the script is executed in elasticsearch, so it has the advantage of including any delays caused by back-pressure from the output. |
8,444,184 | Is it possible to somehow listen to, and catch, all the touch events occurring in an app?
The app I'm currently developing will be used in showrooms and information kiosks and I would therefore like to revert to the start section of the app if no touches has been received for a given couple of minutes. A sort of screensaver functionality, if you will. I'm planning to implement this by having a timer running in the background, which should be reset and restarted every time a touch event occurs somewhere in the app. But how can I listen to the touch events? Any ideas or suggestions? | 2011/12/09 | [
"https://Stackoverflow.com/questions/8444184",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/543224/"
] | You can use a tap gesture recognizer for this. Subclass `UITapGestureRecognizer` and import `<UIKit/UIGestureRecognizerSubclass.h>`. This defines `touchesBegan:`, `touchesMoved:`, `touchesEnded:` and `touchesCancelled:`. Put your touch-handling code in the appropriate methods.
Instantiate the gesture recognizer in `application:didFinishLaunchingWithOptions:` and add it to `UIWindow`. Set `cancelsTouchesInView` to `NO` and it'll pass all touches through transparently.
Credit: [this post](http://b2cloud.com.au/tutorial/monitoring-all-ios-touches/). | In Swift 4.2
1. Create subclass of UIApplication object and print user action:
```
import UIKit
class ANUIApplication: UIApplication {
override func sendAction(_ action: Selector, to target: Any?, from sender: Any?, for event: UIEvent?) -> Bool {
print("FILE= \(NSStringFromSelector(action)) METHOD=\(String(describing: target!)) SENDER=\(String(describing: sender))")
return super.sendAction(action, to: target, from: sender, for: event)
}
}
```
2. In AppDelegate.swift file you will find application entry point @UIApplicationMain Comment that and Add new swift file **main.swift**
and add following code to main.swift file
>
> import UIKit
>
>
> UIApplicationMain(
> CommandLine.argc, CommandLine.unsafeArgv,
> NSStringFromClass(ANUIApplication.self), NSStringFromClass(AppDelegate.self))
>
>
>
ANUIApplication is class where we added action logs.
AppDelegate is default app delegate where we wrote application delegate methods.(Helpful for tracking action and file name in big project) |
7,273,424 | I am extremely OCD when it comes to the layout of my code, and it's a pain to press the down arrow key and Tab a hundred times in a row. Does anyone use a text editor that has the function of indenting chunks of code at the same time? Such as, if I have this:
```
<div>
<img src="blahblah" style="float:left" />
<span>Hey it's a picture.</span>
</div>
<div>
<img src="somephoto" style="float:right" />
<span>Another picture</span>
</div>
```
...then I come back later and want to wrap both divs in another div, but it comes out like this:
```
<div>
<div>
<img src="blahblah" style="float:left" />
<span>Hey it's a picture.</span>
</div>
<div>
<img src="somephoto" style="float:right" />
<span>Another picture</span>
</div>
</div>
```
When I want it to look like this:
```
<div>
<div>
<img src="blahblah" style="float:left" />
<span>Hey it's a picture.</span>
</div>
<div>
<img src="somephoto" style="float:right" />
<span>Another picture</span>
</div>
</div>
```
Obviously this is a minor example, but when it comes to large files this becomes quite a hassle. I use Bluefish on Ubuntu and Notepad++ on Windows, and neither seem to come with the capability to indent a block of code all at once. What are your thoughts? | 2011/09/01 | [
"https://Stackoverflow.com/questions/7273424",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/857256/"
] | Any decent text editor, including Notepad++, can do this.
Select the lines and press `Tab`. | Yup go with Notepad++, its brilliant. Dont forget Shift + Tab too though, just as useful:) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.