text:
Q: for loop in Return I'm a beginner in C++ and i have a problem that i dont know how to solve it,
I have an int function that few parameters should be return on it:
int sphere(const float & X,const float & Y,const float & Z,
           const int & Px, const int & Py, const int & Pz,
           const int & diameterOfSphere, const int & number)
{
     return pow(Px-X,2) + pow(Py+(diameterOfSphere * (number - 1))-Y,2)
             + pow(Pz-Z,2) <= pow(diameterOfSphere/2,2);
}

in this function, the integer "number" may should be start from 2 to for example 100. I need to do something that if i choose 100 for "number", the return statement should be repeated 99 times and separated by a plus ( + ).
for example i can do it manually but it is needed to write a lot of codes which is not logical
for example, i did it manually for just three times
 return (pow(Px-X,2)+pow((Py+(diameterOfSphere * 2))-Y,2)+pow(Pz-Z,2)
   <= pow(diameterOfSphere/2,2))

  + (pow(Px-X,2)+pow((Py+(diameterOfSphere * 3))-Y,2)+pow(Pz-Z,2)
   <= pow(diameterOfSphere/2,2))

  + (pow(Px-X,2)+pow((Py+(diameterOfSphere * 4))-Y,2)+pow(Pz-Z,2)
   <= pow(diameterOfSphere/2,2))

  + (pow(Px-X,2)+pow((Py+(diameterOfSphere * 5))-Y,2)+pow(Pz-Z,2)
   <= pow(diameterOfSphere/2,2)) ;

Is there any easier way? I know i have to use a loop but i dont know how to do it in this case
Thanks a lot

A: Don't use pow() to do spheres squares, pow() is an exponential function that is quite slow. Break your formula and format your lines to make code readable. Your point's coordinates are integer, is that intentional? This variant is not only more readable, it's more likely to be optimized by compiler:
int sphere(const float & X,const float & Y, const float & Z,
           const int & Px, const int & Py, const int & Pz,
           const int & diameterOfSphere, const int & number)
{
 const float dx = Px - X;
 const float dy = Py + diameterOfSphere * (number - 1) - Y;
 const float dz = Pz - Z;
 const float D = dx*dx + dy*dy + dz*dz;

 return D <= 0.25 * diameterOfSphere*diameterOfSphere;
}

Now if I understood you right, you need a recursion or a loop that emulates recursion. You actually can call function from itself, do you know that?
int sphere(const float & X,const float & Y, const float & Z,
           const int & Px, const int & Py, const int & Pz,
           const int & diameterOfSphere, const int & number)
{
 const float dx = Px - X;
 const float dy = Py + diameterOfSphere * (number - 1) - Y;
 const float dz = Pz - Z;
 const float D = dx*dx + dy*dy + dz*dz;

 if(!(number>0))
        return 0;
 return D <= 0.25 * diameterOfSphere*diameterOfSphere
            + sphere(X,Y,Z,Px,Py,Pz,diameterOfSphere, number -1);
}

Negative side of recursion a) each function call fills stack with variables and parameters stored b) there is an extra call that returns immediately.
Py + diameterOfSphere * (number - 1) - Y expression throws me back, is that a mistake? Pretty much it almost never would cause comparison to be true. And it's still not clear what you're trying to do with those comparisons. So, while I modified code so it would be equal to your idea, it looks chaotic\senseless. The >= or <= would return  1 or 0 as result. Or did you mean this?
return ( D <= 0.25 * diameterOfSphere*diameterOfSphere )
            + sphere(X,Y,Z,Px,Py,Pz,diameterOfSphere, number -1);


text:
Q: How do I solve this problem with my code? C# I've tried adding a ) where it says to, but that adds more problems. The error I get states:

Assets/LevelComplete.cs(12,64): error CS1026: ) expected.

What I'm trying to do here is use the if statement to find out if the Active Scene is in the specific range. Also, for a little more context, All I need is a range, and not the code to pick a number in that range if that helps.
using System;
using UnityEngine;
using UnityEngine.SceneManagement;

public class LEvelComplete : MonoBehavior
{
    public void LoadNextLevel()
    {
        int Active12 = Range(1, 3);
        int Load34 = UnityEngine.Random.Range(3, 5);

        if (SceneManager.GetActiveScene().buildIndex = Active12
        {
            SceneManager.LoadScene(Load34);
        }
    }
}

A: using System;
using UnityEngine;
using UnityEngine.SceneManagement;
using Random = UnityEngine.Random;

public class question_63947858_script_error : MonoBehaviour
{
    public void LoadNextLevel()
    {
        int Active12 = Random.Range(1, 3);
        int Load34 = Random.Range(3, 5);

        if (SceneManager.GetActiveScene().buildIndex == Active12)
        {
            SceneManager.LoadScene(Load34);
        }
    }
}

Things wrong:

*

*MonoBehaviour was spelled wrong

*System was clashing  with UnityEngine namespace. So disambiguated with Random = UnityEngine.Random

*No parentheses after the if statement

*=  changed to == in the if statement

A:
"find out if the Active Scene is in the specific range."

...
var scene = SceneManager.GetActiveScene();
if (scene.buildIndex >= 1 && scene.buildIndex <= 3)

... or if you prefer Linq:
if (Active12.Contains(SceneManager.GetActiveScene().buildIndex))

See also How to elegantly check if a number is within a range?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there a way to restrict snippets to work under certain path I have a file structure like below
         main
           |
      -------------
     |             |
  Folder1        Folder2

I have below JS snippets in my extension I want this to be available only on all the js files under Folder1 and similarly, I have some snippets that I want to be available only on the JS files under Folder2
"Print to console": {
    "scope": "javascript,typescript",
    "prefix": "log",
    "body": [
        "console.log('$1');",
        "$2"
    ],
}

don't want to do any manual changes to my vs code it should drive from the vs code extensions
I have gone through the documentation but still no luck, could someone please confirm if this is possible?


text:
Q: Implement a relationship between two linearlayouts in android I have two LinearLayouts in my application side by side. In 1st LinearLayout (left side),I have some name lists.I want to implement the connection or relationship between them in such a way that when I clicked on one of the name list items, a text message or some design will display into the 2nd Linear Layout (right side).
I have implemented OnClickListener with Toast but I don't have an idea to display a text message or some design into the 2nd Linear Layout.
Thanks in advance for any help!
<LinearLayout
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:id="@+id/relLayoutMiddle"  android:orientation="horizontal"
            android:layout_below="@+id/relLayoutTopBar"
            android:layout_above="@+id/relLayoutBottomBar">

            <!-- Items List-->
            <LinearLayout
                android:orientation="vertical"
                android:layout_width="80dp"
                android:layout_height="fill_parent"
                android:layout_marginRight="5dp"
                android:background="@drawable/border_design">
                <ListView
                    android:id="@+id/item_List" android:scrollbars="none"
                    android:layout_width="match_parent"
                    android:focusable="true"
                    android:layout_height="fill_parent">
                </ListView>
            </LinearLayout>

            <!-- Display Items-->
            <LinearLayout
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:layout_weight="1" android:layout_marginLeft="5dp"
                android:background="@drawable/border_design">
                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:text="Items  will be Display here"/>
            </LinearLayout>
        </LinearLayout>

A: you should have an id for every view that you want to work with in your Java code. then you can find that view with findViewById method in your activity.
so for your view , you should consider an id for your second textView for example tvDisplay, and then in your onClickListener you should set text into your textView by a code like this:
((TextView)findViewById(R.id.tvDisplay)).setText("hello")

A: Supposedly, you have implemented the code to check if a list item is clicked, you only need to assign an id to your target text view. Ex:
<TextView
 android:id="@+id/targetID"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:text="Items  will be Display here"/>

Then you need to find the TextView using its id in code. Ex:
TextView tv = (TextView)View.findViewById(R.id.targetID);

And change the content of tv using :
 tv.setText("What you want to write here");

Note: The code isn't meant to copy paste. It is a suggestion or approach you can take.

A:  listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            textView.setText(listview.getItemAtPosition(position).toString());
        }

use this code and implement listview click listener

A: You can use this way to implement it.
In XML layout :
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:id="@+id/relLayoutMiddle"
    android:orientation="horizontal">

    <!-- Items List-->
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="80dp"
        android:layout_height="fill_parent"
        android:layout_marginRight="5dp">
        <ListView
            android:id="@+id/item_List"
            android:scrollbars="none"
            android:layout_width="match_parent"
            android:focusable="true"
            android:layout_height="fill_parent">
        </ListView>
    </LinearLayout>

    <!-- Display Items-->
    <LinearLayout
        android:id="@+id/ll_second"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_weight="1"
        android:layout_marginLeft="5dp">
        <TextView
            android:id="@+id/tv_message"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="Items  will be Display here"/>
    </LinearLayout>
</LinearLayout>

In the code :
    final String[] names = {"one", "two", "three"};
    llSecond = findViewById(R.id.ll_second);
    tvMessage = findViewById(R.id.tv_message);
    ListView lvItem = findViewById(R.id.item_List);
    lvItem.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_activated_1, android.R.id.text1, names));
    lvItem.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            // display a text message that selected in ListView into TextView
            tvMessage.setText(names[position]);

            // Or call user defined function that make to second LinearLayout dynamically with programmatical.
            // makeLayout();
        }
    });


text:
Q: Php multidimensional array output I have an example:
$foo = array(1 => array(1=> 'lol',2=>'lolol'),2=>array(1 => 'sda', 2 => 'dss'));

How can I output this...what need to be passed to the loop, give me an example please.Thank you

A: Here are some ways. You didn't say how you needed the output.
print_r($foo);

var_dump($foo);

foreach($foo AS $key => $value)
{

    print_r($value);

}


text:
Q: Hibernate Validator and apache bval - which validator to load? Project has both bval and hibernate validator 5.3.6Final.
bval comes from a 3rd party jar dependency
When trying to load Validator - its defaulting to bval and fails at validation constraint defined by hibernate annotation.
final Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
        ValidatorFactory cf = Validation.buildDefaultValidatorFactory();
        final Set<ConstraintViolation<AdminLoginFormImpl>> violations = validator.validate(this)

*

*How to load exclusively hibernate validator ?

*Can they even co-exist ?
Exception seen ::
No compliant org.hibernate.validator.constraints.Length ConstraintValidator found for annotated element of type java.lang.String

javax.validation.UnexpectedTypeException: No compliant org.hibernate.validator.constraints.Length ConstraintValidator found for annotated element of type java.lang.String

org.apache.bval.jsr.job.ComputeConstraintValidatorClass.findAnnotatedElementValidator(ComputeConstraintValidatorClass.java:171)

A: Apparently, your code uses one of the Hibernate Validator-specific constraints so using Apache BVal won't work.
If your code doesn't use any Apache BVal-specific features, I would stick to Hibernate Validator and exclude Apache Bval from the dependencies.
In any case, only one of the implementations will be used so you should only have one.


text:
Q: Why does std::rc::Rc need PhantomData? I know that PhantomData is intended to consume a lifetime or type parameter in a data type definition that would otherwise go unused. I was recently looking over the definition of Rc in the Rust std lib and noticed that it seems to employ PhantomData, but it looks like T is being used in the sibling field ptr as an NonNull<RcBox<T>>. The docs say that NonNull is "*mut T but non-zero and covariant." and go on to further extend that definition with the statement:

Unlike *mut T, NonNull<T> is covariant over T. If this is incorrect for your use case, you should include some PhantomData in your type to provide invariance, such as PhantomData<Cell<T>> or PhantomData<&'a mut T>.

Hence, is it needed for variance or is it more because NonNull is effectively a raw pointer and PhantomData is needed to consume the elided lifetime as this answer seems to imply?

A: PhantomData is used here to tell the drop checker that dropping Rc<T> may cause a value of type T to be dropped.
When we announce that we may drop a value of type T, the drop checker ensures that any lifetimes in T outlive the struct itself. It is this check that prevents the following code from compiling. In this case, the generic argument to Rc is PeekOnDrop<&'a u8>, which has lifetime 'a.
use std::{fmt, rc::Rc};

struct PeekOnDrop<T: fmt::Debug>(T);

impl<T: fmt::Debug> Drop for PeekOnDrop<T> {
    fn drop(&mut self) {
        println!("{:?}", self.0);
    }
}

struct SelfReferential<'a> {
   value: Box<u8>,
   rc: Option<Rc<PeekOnDrop<&'a u8>>>,
}

fn main() {
    let mut sr = SelfReferential {
        rc: None,
        value: Box::new(1),
    };

    sr.rc = Some(Rc::new(PeekOnDrop(&*sr.value)));

    // `sr` would be dropped here, which could drop `value` before `rc`.
    // The destructor of `PeekOnDrop` would then try to inspect the (dangling)
    // reference, resulting in UB!
}

For a full explanation of the underlying logic here, see the nomicon, but note that without PeekOnDrop, the previous example compiles just fine. This is because Rc<T> declares in its Drop impl that its generic parameter T is #[may_dangle]. In doing so, it promises that its Drop impl does nothing with the value of T that it owns except (maybe) drop it. Only when the drop checker recursively checks the Drop impl of PeekOnDrop and finds that it may access T does an error occur.
For completeness, here's an example of an undefined program that lies by asserting that PeekOnDrop's Drop impl does not access T using #[may_dangle]. The same undefined behavior would be exhibited in the original example if Rc did not use PhantomData to declare that it may drop a value of T.


text:
Q: python regex comma separated group I have a string that I am trying to create a group of only the items that have commas. So far, I am able to create a group, what I'm trying to do is ensure that the string contains the word nodev. If the string doesn't contain that word, a match should show, otherwise, the regex should not match anything.
String:
"/dev/mapper/ex_s-l_home /home  ext4    rw,exec,auto,nouser,async    1  2"

Regex that matches the comma delimited group:
([\w,]+[,]+\w+)

I've tried this regex but with no luck:
(?!.*nodev)([\w,]+[,]+\w+)

I'm using https://pythex.org/ and am expecting my output to have one match that contains "rw,exec,auto,nouser,async". This way I plan on appending ,nodev to the end of the string if it doesn't contain it.
Looking for a regex only solution(no functions)

A: >>> import re
>>> s = "/dev/mapper/ex_s-l_home /home  ext4    rw,exec,auto,nouser,async    1  2"
>>> s2 = "/dev/mapper/ex_s-l_home /home  ext4    rw,exec,auto,nodev,nouser,async    1  2"
>>> re.findall(r'(?<=\s)(?!.*nodev)(?=\S*,\S*)\S+', s)
['rw,exec,auto,nouser,async']
>>> re.findall(r'(?<=\s)(?!.*nodev)(?=\S*,\S*)\S+', s2)
[]

To append ,nodev:
>>> re.sub(r'(?<=\s)(?!.*nodev)(?=\S*,\S*)\S+', r'\g<0>,nodev', s)
'/dev/mapper/ex_s-l_home /home  ext4    rw,exec,auto,nouser,async,nodev    1  2'
>>> re.sub(r'(?<=\s)(?!.*nodev)(?=\S*,\S*)\S+', r'\g<0>,nodev', s2)
'/dev/mapper/ex_s-l_home /home  ext4    rw,exec,auto,nodev,nouser,async    1  2'

pythex demo

A: Complete regex solution.
For this to work, you need to import regex module.
>>> import regex
>>> s = " /dev/mapper/ex_s-l_home /home  ext4 rw,exec,auto,nouser,async    1  2 rw,exec,nodev,nouser,async    1  2 nodevfoo bar"
>>> m = regex.findall(r'(?<=^|\s)\b(?:(?!nodev)\w+(?:,(?:(?!nodev)\w)+)+)+\b(?=\s|$)', s)
>>> m
['rw,exec,auto,nouser,async']


text:
Q: How to find the elapsed time between send and receive data? I am using the System.Timers.Timer class. And I enable when I send a message and disable when I receive the message. How do I calculate how much time has elapsed. I have set the interval as 1 sec
Basically I retransmit data after 1000 sec again if I do not  recive an ACK. I retransmit 5 times max until I get a Ack. If I receive and something before 150ms then I stop retrnsmission.
Here's the code:
timer1.interval = 1000;
port.Write(data)
timer1.enabled = true;

event handler for the received data.
timer1.enabled=false;

A: Use Stopwatch instead.
Stopwatch clock = Stopwatch.StartNew();
port.Write(data);

and in the handler
clock.Stop();
Console.WriteLine( clock.Elapsed );

A: That's not what the System.Timers.Timer class is for. Take a look at System.Diagnostics.Stopwatch instead.

A: The Timer class is not for measuring elapsed time - it's for generating an event on a regular, timed basis.
What you probably want is the Stopwatch class (visit the link):
var sw = new Stopwatch();
sw.Start();
port.Write(data);
sw.Stop();
var elapased = sw.Elapsed;  // elapsed is a TimeSpan

The Elapsed property is a TimeSpan which has methods and properties for evaluating the amount of time passed in different ways.


text:
Q: How to hide all link that connect to a particular breed in netlogo Greeting,
This is the scenario:
I have 2 breed namely: "dog" and "cat"
Links are established within dog breed only and cat breed only, and temporarily there is no cross linkages.
I am looking for a way to hide dog breed and links that is associated with dog only. I would like to add that the links are not randomly generated, they are known links given to the breed. The purpose of doing it this way is that I am doing a network calculation on each breed individually using nw:mean-path-length
In netlogo documentation, I will be using
ask dog[ hide-turtle ] to hide the dog breed. However, I do not know how to hide link associated with dog only. And similarly, I will be using  ask dog[ show-turtle ] to make dog breed appear again(with the links associated with dog too) and use ask cat[ hide-turtle ] for my calculation on the other breed.
Thanks for helping out!

A: ask dogs [ ask my-links [ hide-link ] ]

...will hide the dogs' links.
That being said, if you want to perform calculations on a separate part of a network, you will need to use nw:set-context: just hiding the turtles and links won't affect the results of primitives like nw:mean-path-length.


text:
Q: SQL Query to Laravel Eloquent I have this query below and i want to convert it to Laravel Eloquent. I have tried with no success.
select A.client_id, max(A.purchase_date)
from gym_client_purchases A
left Join gym_clients B on B.id = A.client_id
group by A.client_id
order By max(A.purchase_date) desc

I tried this but i get the oldest record from each user.
$this->data['expiringSubscriptions'] = Gym::select('first_name', 'last_name', 'gym_client_purchases.*')
->leftJoin('gym_clients', 'gym_clients.id', '=', 'client_id')
->groupBy('client_id')
->orderBy('gym_client_purchases.purchase_date', 'desc')
->get();

Could anyone guide me to convert my queries?
Thank you.

A: You didn't mention any models, so here it is using the query builder.
$results = DB::table('gym_client_purchases gcp')
    ->selectRaw('gcp.client_id, MAX(gcp.purchase_date) AS max_purchase_date')
    ->leftJoin('gym_clients gc', 'gc.id', '=', 'gcp.client_id')
    ->groupBy('gcp.client_id')
    ->orderBy('max_purchase_date', 'desc');

Haven't run it - but that should be basically it.


text:
Q: Interactive, non interactive shells and expansion If I execute the test [[ ! (-z "") ]] interactively, or non interactively by bash -c '[[ ! (-z "") ]]', I obtain the same result, that is echo $? gives me 1.
But if I forget a space in the above expression, giving [[ !(-z "") ]], I don't obtain the same result anymore. More precisely,
set -x; [[ !(-z "") ]]; echo $?

gives me
+ [[ -n !(-z ) ]]
+ echo 0
0

while
bash -c 'set -x; [[ !(-z "") ]]; echo $?'

gives me
+ [[ -z '' ]]
+ echo 1
1

So my question is: why interactive and non interactive shells don't give the same expansion, and so the same result in this case (or other similar ones)?

A: It's quite complicated.
At first please note globbing doesn't work inside [[ ]]. If you run something like
set -x; [[ / == /* ]]; echo $?

then you will see /* doesn't expand there like in echo /*.
Now there is extglob shell option. It looks like in your case it's enabled in interactive shells, disabled in non-interactive ones. (Compare Where is bash's "shopt extglob" turned on for my interactive shell?)

If the extglob shell option is enabled using the shopt builtin, several extended pattern matching operators are recognized. […]
!(pattern-list)
Matches anything except one of the given patterns.

(source)
Inside [[ ]] the operator is recognized but it doesn't expand. How do I know? I can make the shell not recognize it:
shopt -u extglob
set -x; [[ !(-z "") ]]; echo $?

Now I get -bash: !: event not found. This indicates ! has different meaning:

!
Start a history substitution, except when followed by a space, tab, the end of the line, = or ( (when the extglob shell option is enabled using the shopt builtin).

(source)
This differs between interactive and non-interactive shells:

When the shell is running interactively, it changes its behavior in several ways.
[…]
7. Command history […] and history expansion […] are enabled by default.

(source)
Next step is to disable history:
shopt -u extglob
set +o history
set -x; [[ !(-z "") ]]; echo $?

And here you go, the result is like in your non-interactive shell.

Can we do this the other way around? Can we make a non-interactive shell behave like an interactive one?
At first let's check what happens when a new shell is forced to be interactive:
bash -ic 'set -x; [[ !(-z "") ]]; echo $?'

It behaves as expected, like your interactive shell. Now let's enable extglob for non-interactive shell:
bash -c 'shopt -s extglob; set -x; [[ !(-z "") ]]; echo $?'

And it doesn't work! It still behaves like your non-interactive shell with extglob disabled. The explanation is simple, yet not obvious: globbing is performed for the entire line before shopt does its job. When the option gets changed it's already too late. Let's split the command into two lines then:
bash -c 'shopt -s extglob
         set -x; [[ !(-z "") ]]; echo $?'

Now it behaves like your interactive shell.

The last mystery is this:

+ [[ -n !(-z ) ]]

Where did -n come from in your interactive shell? My hypothesis is based on the observation that [[ "random-string" ]] is treated as [[ -n "random-string" ]] (check it with set -x). I guess when you run [[ !(-z "") ]] and extglob is enabled, the fact that the !( ) operator is recognized but not expanded makes the entire !(-z "") string stay there as one word, i.e. your command becomes something like
set -x; [[ "!(-z )" ]]; echo $?

This command (in interactive or non-interactive shell) behaves like the one you run in the interactive shell.


text:
Q: why is this setTimeout not working I'm just getting into Java. I'm working on a simple script to open a window, then close it after a short delay. I've tried various connotations of the following with no avail. The function works (in that it opens, then closes the window) but the delay fails to happen.
function manualWindow(){
testWindow = window.open("popup.php","interaction","resizable=0,width=800,height=600,status=0");
setTimeout(testWindow.close(),5000);
}

thank you

A: You want:
setTimeout(function() { testWindow.close(); },5000);

You current code is executing that function as soon as it is hit and then trying to run it's return value after the delay. By wrapping it up in the function it will be run correctly after 5 seconds.
Example:
<html>
<head></head>
<body>
<script type="text/javascript">
    function manualWindow(){
       testWindow = window.open("http://www.google.co.uk","interaction","resizable=0,width=800,height=600,status=0");
       setTimeout(function() { testWindow.close() },5000);
    }

    manualWindow();
</script>
</body>
</html>

A: You are not using setTimeout correctly. Try this:
function manualWindow(){
   testWindow = window.open("popup.php","interaction","resizable=0,width=800,height=600,status=0");
   setTimeout(function() { testWindow.close(); },5000);
}

A: Firstly, you're defining your code within an anonymous function. This construct:
(function() {
  ...
)();

does two things. It defines an anonymous function and calls it. There are scope reasons to do this but I'm not sure it's what you actually want.
You're passing in a code block to setTimeout(). The problem is that update() is not within scope when executed like that. It however if you pass in a function pointer instead so this works:
(function() {
  $(document).ready(function() {
    update();
  });
});

because the function pointer update is within scope of that block.
But like I said, there is no need for the anonymous function so you can rewrite it like this:

A: I think your code is missing the qutoes in the first parameter testWindow.close().This can be corrected in the following way:
function manualWindow() {
    testWindow = window.open("http://www.google.com", "interaction", "resizable=0,width=800,height=600,status=0");
    setTimeout('testWindow.close()',5000);
}

manualWindow();

I found this link may help you a bit https://developer.mozilla.org/en/DOM/window.setTimeout


text:
Q: Gaming PC Shutdown while gaming (GPU > 80°C) Some random French guy here, I have since June 2015 the following computer :

*

*CPU Quad-Core Intel Core i7 4th Gen (Intel Core i7-4790K (4.0 GHz
/ 4.4 GHz Turbo - Cache 8 Mo)

*Motherboard Gigabyte GA-Z97X-Gaming 3 (Intel Z97 Express)

*16 Go RAM DDR3 1600 MHz

*NVIDIA GeForce GTX 970 4Go

*SSD 240 Go Serial ATA 6Gb/s

*HDD Seagate Barracuda 7200.14 SATA 6Gb/s 1 To

*NZXT Phantom Case

*PSU 650W LDLC QS-650+ Quality Select 80PLUS Gold

*Fan for CPU Noctua NH-U12P SE2

(If needed, bought from this website, but it's in French > https://www.ldlc.com/fiche/PB00100625.html)
No problem back then, this PC is quite powerful and all, but since some weeks, it restarts when gaming, like a security overheating or else.
I've made multiple tests, and here what I've found so far:

*

*CPU is always under 50°C, even under 40°C most of the time, during gaming too.

*GPU is increasing to 80° pretty quickly (less than 1mn), and cannot go over since the computer force a shutdown.

*I don't see any anomaly with the fans, I've boosted them to full speed, and can see/hear the difference

*I've made a full clean up of the hardware, even dismounted PSU to clean everything.

While I first thought it could be the GPU, I don't really think so, because I've ran FurMark to benchmark the GPU like hell, up to 83°C for several minutes, and nothing happened, computer was fine, no shutdown or reboot for overheating.
And when I was playing (Elite Dangerous mainly, no problem for 2 years), when GPU was going over 80°C, PC would shutdown, but yesterday, during game loading, GPU was around 65°C, and it crashed too.
So now I think it could be a PSU problem, but from that, I don't really know how to check (I have a multimeter, but I'm not an elec guy, just a developer).
Also, even if I don't think it, maybe it's a software problem, I've formatted my computer yesterday evening, I'll do some new tests this evening (UTC+01).
Also, I've ordered some thermal paste, dunno if my GPU has by default, even though, I'll check that and replace/add it, cannot be worse with it (I should just change to a 1080Ti, meh).
Dunno what more I could do, I'm here to seek your help! =)

A: Well, problem has been solved, so here were my problems:

*

*PSU was indeed failing, but after getting a new one from my supplier, computer now couldn't even boot.

*So the other problem was RAM, one of them was completely dead. Removed it and since computer works like a charm.


text:
Q: Which past tense of "to light" should I use here? I know that there are two ways to form the past tense of to light (i.e. lit/lighted). Which one is appropriate for the sentence below?

His thoughts lighted our way.

or

His thoughts lit our way.

A: I have a feeling that the best word for here is "lighted". "Lighted" is used more when referring to something illuminating another.
When generally referring to a source of light that brightens up the room, "lighted" is preferred:

The lantern lighted the whole room.

"Lit" is generally more used for "setting on fire" :

He lit the paper and threw it in the bin.
  The little spark lit the straw, and the whole barn burned down.

Also,"lit" has an alternative meaning:

Slang . under the influence of liquor or narcotics; intoxicated (usually followed by up ).

Thus, I feel that "lighted" would be best here.

His thoughts lighted our way.

"Light" has two meanings, one meaning "to cause to take fire", and the other "to illuminate".  When referring to "light" in the first sense, the past would be "lit":

He tried to light his cigar/ He lit his cigar

When referring to "light" in the second sense, "lighted"(often along with "up" is used:

His words were a light to my future/His words lighted up my future.

A: This is easy. Lighted and lit are synonymous and can be used in place of each other. There is no rule to use one or the other. Pick either.

A: Lit is British English and lighted is American English, the same thing with dreamt and dreamed respectively.


text:
Q: Salesforce mobile sdk issue I have used salesforce mobile sdk(version 4.3) in my ios native app. In the login screen of salesforce I have changed from production to sandbox environments.While switching the environments I am getting blue screen, after killing the app it is working fine.
I am getting this error :

INFO com.salesforce <SFSecurityLockout>: App requested passcode screen cancel.  Screen is not displayed.

A: This is really old version. Current Salesforce Mobile SDK is in version 7.0. Update to that and see if it helps.


text:
Q: 2 properties pointing to the same class in EF code first I have a discussion object which in it self has a ParentDiscussion and TopParentDiscussion:
 public class Discussion
    {
        [Key]
        public Guid ID { get; set; }
        public String Message { get; set; }
        public virtual Discussion ParentDiscussion { get; set; }
        public virtual Discussion TopParentDiscussion { get; set; }

    }

Both Parent and TopParent are optional. I wrote the following situation with the Fluent API and it works.
        modelBuilder.Entity<Discussion>().HasOptional<Discussion>(a => a.ParentDiscussion).WithOptionalDependent().Map(a => a.MapKey("TopParentId"));
        modelBuilder.Entity<Discussion>().HasOptional<Discussion>(a => a.TopParentDiscussion).WithOptionalDependent().Map(a => a.MapKey("ParentId"));

But how can I write this solution without the fluent api, so with data annotations.
I tried this:
        //Foreign Keys
        public Guid? ParentId { get; set; }
        public Guid? TopParentId { get; set; }

        //Relationships

        [ForeignKey("ParentId")]
        public virtual Discussion ParentDiscussion { get; set; }
        [ForeignKey("TopParentId")]
        public virtual Discussion TopParentDiscussion { get; set; }

But it gives me the following error:
Unable to determine the principal end of an association between the types 'Model.Discussion' and 'Model.Discussion'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.

A: You cannot map this with Data annotations because you don't expose foreign key property and reverse navigation property.
Correct mapping with fluent API is:
modelBuilder.Entity<Discussion>()
            .HasOptional<Discussion>(a => a.ParentDiscussion)
            .WithMany()
            .Map(a => a.MapKey("TopParentId"));
modelBuilder.Entity<Discussion>()
            .HasOptional<Discussion>(a => a.TopParentDiscussion)
            .WithMany()
            .Map(a => a.MapKey("ParentId"));

Because you want probably want a discussion to be parent of more then one other discussion.


text:
Q: Change making problem with Euro system and Greedy algorithm Prove that the Euro system $c = (200, 100, 50, 20, 10, 5, 2, 1)$ is canonical.
To do this I am using Definition 2 and Theorem 2 from https://arxiv.org/pdf/0809.0400.pdf which state:

Definition 2: A coin system \$ is non-canonical if there is an $x$ with
$\vert GRD_\$(x) \vert $ $>$ $\vert OPT_\$(x) \vert$, and such $x$ is called a counterexample of \$.
Theorem 2: Let $\$_1 = \langle c_m, c_{m-1}, · · · , c_2, 1 \rangle$ and $\$_2 = \langle c_{m+1}, c_m, · · · , c_2, 1\rangle $ be two coin systems such that $\$_1$ is canonical but $\$_2$ is not. Then there is some $k$ such that $k·c_m < c_{m+1} < (k+1)·c_m$ and $(k+1)·c_m$ is a counterexample of $\$_2$.

I attempt this proof by choosing $\$_1 = (100, 50, 20, 10, 5, 2, 1)$ and $\$_2=c$.
Assuming by contradiction that $c$ is non-canonical then Theorem 2 leads us to finding $k=3$ and therefore our counterexample would be $x=400$.
In this case, $GRD_\$(400)=(2,0,0,0,0,0,0,0)$ and $OPT_\$(400)=(2,0,0,0,0,0,0,0)$ which is a contradiction to Definition 2 so $c$ is canonical.
Question
My question is, how can I easily show that my chosen $\$_1$ is canonical. Furthermore, is there a way to prove Theorem 2?


text:
Q: Analyses of mixed variables (cart) I'm relatively new to statistics, and am currently working some data collected as a part of an interview survey. I have a response variable in ordinal form, which mostly looks into people's perceptions of an animal, and a range of predictor variables that include discrete numeric, ordinal and binary variables. I have a couple of questions regarding the analyses:
Would it be appropriate to use Classification and Regression trees to analyse the data? If yes, is there a limit on the number of predictor variables that can be used for sample sizes of 50 and 139 (two sets of data to be analysed separately)?
Would it make sense to use MDS or Factor analysis to reduce the number of variables?

A: You have mentioned a number of analytic approaches but its hard to tell whether they are appropriate since you don't specify the objectives of your study. If your purpose is to build a model that predicts the response category that a case with a given set of predictors will fall into, then using classification trees might be appropriate. The goals of MDS and Factor analysis is to detect meaningful underlying dimensions that allow the explanation of observed similarities or dissimilarities between the investigated objects/cases. They are useful for data reduction as you suggest but you have to consider whether it is really necessary depending on the number of variables in your data (you dont give a clue) set and what use/interpretation is intended for you work.

A: A solid approach to take would be to use a lasso regression.  This type of regression perform variable selection for you, so you won't need to use MDS or factor analysis before modeling.


text:
Q: Where on Stack Exchange can I ask questions about publicity of scientific research/advances? Where on Stack Exchange can I ask questions about publicity of scientific research/advances? For example, I want to ask why research advances such as this one rarely go beyond the lab, even though they may have enormous potential.

A: The academia stack exchange will answer questions about how scientific research gets published, and why some research gets published while other research doesn't.
In this specific case, if you want to ask the chemistry community if the science behind that article is legit and/or whether or not it would pass the tests required for publication, you could try the chemistry stack exchange.
There is also a proposal for a stack exchange on materials science which already has example questions about solar cells, energy storage, materials for batteries and materials for energy conversion, but it will need about 65 more experienced stack exchange users to commit to it, in order for it to get launched.


text:
Q: String parsing with regular expressions I have a following string that I would like to parse into either a List or a String[].
(Test)(Testing (Value))

End result should be Test and Testing (Value)

A: If I understood correctly that you need Test and Testing (Value), then here is regexp:
\(([^\)]+)\)\((.+)\)

and masked version of it ready for java string:
\\(([^\\)]+)\\)\\((.+)\\)

A: Please read this section of php manual. It tells you about recursive patterns, which can be used to match nested things, and about the related problems. Google it for more information.

A: This question is really vague, but under one reasonable interpretation, this is the solution that can take care of arbitrary nesting depth in a certain format:
    String text = "(T)(T(V))(1(2(3)2)1)(a*(b+(c-d))+(e/f))";
    String[] parts = text.split("(?<=\\))(?=\\()");
    System.out.println(java.util.Arrays.toString(parts));
    // prints "[(T), (T(V)), (1(2(3)2)1), (a*(b+(c-d))+(e/f))]"

Basically you want to split between )( (using assertions). Won't work for all cases, e.g. ((.)(.)), but like many people have said, the requirements of the question is vague, and the general balanced parenthesis problem is not solvable with Java regex.
See also

*

*regular-expressions.info/Lookarounds

A: /**
 * Parse string:
 *              when '$' symbol is encountered it deletes it's previous character and the '$' symbol itself
 *              when '@' symbol is encountered it erases the text previous to it and the '@' symbol itself
 * @author Rama Bolishetty
 * @date Feb 27, 2016
 */
package com.ram.utilities;

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ParseString {
    private static final Pattern dollarSymborPattern = Pattern.compile("[a-zA-Z0-9]{0,1}[$]{1}");
    private static final Pattern atSymbolPattern = Pattern.compile("[a-zA-Z0-9$]{0,}[@]{1}");

    public static String parseString(String inputString) {
        String parsedString = inputString;
        Matcher m = atSymbolPattern.matcher(parsedString);
        String matcher = replaceMatcher(m);
        parsedString = matcher != null ? matcher : parsedString;
        m = dollarSymborPattern.matcher(parsedString);
        parsedString = replaceMatcher(m);
        parsedString = matcher != null ? matcher : parsedString;
        return parsedString;
    }

    private static String replaceMatcher(Matcher m) {
        if (m.find()) {
            return m.replaceAll("");
        }
        return null;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String inputString = scanner.nextLine();
        long sTime, eTime;
        System.out.println("STime:" + (sTime = System.currentTimeMillis()) + "\nParsed String:"
                + ParseString.parseString(inputString) + "ETime:" + (eTime = System.currentTimeMillis()));
        System.out.println("Total milliseconds:" + (eTime - sTime));
        scanner.close();
    }
}


text:
Q: How to use regexp in MATLAB to strictly match a substring and not a larger string containing that substring? I would like to find whether a cell contains the substring foo and only this string (nothing before, nothing after) in a series of cells that may contain foobar.
I am currently using regexp in MATLAB and would like to tweak the searched pattern regexp to exclude cells that contain a string that contains the substring I defined.
I know it kind of goes against the very idea of regexp, but I am fairly certain there is a way to do what I want.
As a MWE, here is a snippet of the data I have (in cell format), called potentialfields:
'horaracha'
'sol'
'presmax'
'horapresmax'
'presmin'
'horapresmin'

and the regexp expression that I am currently using:
selected_fields={'sol','presmin'};
diffset=setdiff(potentialfields,selected_fields);
pattern=strjoin(diffset,'|');
idx_to_delete=~cellfun(@isempty,regexp(potentialfields,pattern));

The expected output of idx_to_delete is the following:
1 0 1 1 0 1

At the moment, the output is 1 0 1 1 1 1 because horapresmin contains presmin.
Thank you very much in advance.

A: regexp is overkill here, ismember is an in-built function specifically designed for finding exact strings in a cell
idx_to_delete = ismember( potentialfields, selected_fields );

If you're really set on regexp you can use the start anchor (^) and end anchor ($) like so:
pattern = ['^(', strjoin( selected_fields, '|' ), ')$'];
idx_to_delete2 = ~cellfun( @isempty, regexp( potentialfields, pattern ) );

A: You can build the word boundary based regex dynamically:
pattern = strcat('\<(', strjoin(diffset,'|'), ')\>')
idx_to_delete=~cellfun(@isempty,regexp(potentialfields,pattern))

With strjoin(diffset,'|'), you get the alternation pattern created, and the \<(...)\> is a grouping construct wrapped with word boundaries to only match whole words where word boundaries apply to every alternative start and end char.


text:
Q: Different background color for different pages in rails So I'm using an application.html.erb file which is basically the layout for every page in my website. But I want the homepage to have a white background and the rest of the pages to have a different background. The problem is, if I wrap the entire homepage file in a div, it only wraps the "yield" place and so it shows as a box with a white background within a larger box with a gray background. So how can I change the entire background of the homepage and leave the rest?
Thanks!

A: Expanding on the answer provided by @muffinista:
You can use an instance variable set in the controller to determine when to put the 'homepage' class on the body tag. So:
def index
  @home_page = true
  # existing code
end

and in the layout:
<body class="<%= @home_page ? 'homepage' : ''%>">
 <%= yield %>

A: Consider putting a special class on the body tag (or perhaps your main wrapper) of your homepage, then do it in CSS.  So you can have on your homepage:

hi!

Then on your other pages:

i am not a homepage!

And in your CSS:
body {
 // some general css
}

body.homepage {
 // some css for homepage elements
 background-color: #000000;
}

UPDATE: you can use a helper like this to make life easier:
def body_class
  @body_class || ''
end

Then in your homepage views, put something like this at the top:
<% @body_class = "homepage" %>

Obviously this depends on the specifics of your app, but it works fine for me.

A: Just to add to the accepted answer, if you need to set different backgrounds for multiple pages, it would make sense and add readability to move the code for finding an appropriate background into a partial:
<body class= <%=render partial: "layouts/background" %> >
_background.html.erb:
    <%- if @main_page_background OR @stylish_background %>
       "main_page_background"
      <%- elsif @dark_background %>
        "dark_page_background"
      <%- else %>
        ""
    <% end %>


text:
Q: What's the difference between "::" and "sys" schemas? As far as I know, BOL exmaple on fn_trace_getinfo used to use
:: instead of sys schema in the example like following
From
    SELECT * FROM ::fn_trace_getinfo(default)

To
    SELECT * FROM sys.fn_trace_getinfo(default)

Are there any differences between those two?
And what does :: mean?

A: OK, i hope this (UDF starting with fn_...) helps
From the page it seems that :: would tell Sql Server that this has to be a System UDF, and will only be found in Master DB.

Q:
I've read frequently how stored
  procedures we create shouldn't be
  named with sp_ since SQL Server will
  first check the master db before the
  current db when trying to find the sp
  to execute. I always nodded and
  thought how I was glad I hadn't done
  that. For some reason it never clicked
  that UDF behavior could be the same.
I have several UDFs that start fn_...
  When I reference a UDF as dbo.fn_...
  does SQL Server check the master db
  for these and only upon not finding
  them check the current db? If so, is
  there a performance hit for this?
A:
No. To call a system-supplied UDF, you
  need to use ::, so that is what SQL
  Server looks for. All system-supplied
  UDFs are table functions, as scalar
  system functions are not UDFs at all.

A: Even the SQL Experts are not sure. It changed from SQL Server 2000 to SQL Server 2005
My random guess is the user/schema separation in SQL Server 2005 removed the need for a shorthand system schema


text:
Q: When are finite-index subgroups of a Lie group closed? Let $G$ be a Lie group (or, if necessary, a reductive Lie group) and $H$ a subgroup of $G$. If $\lbrack G:H\rbrack < \infty$, is it true that $H$ is closed? If not, are there any broad assumptions on $G$ which make this true?

A: Yes, this is true. It suffices to show that any homomorphism $\pi : G \to F$ from a Lie group $G$ to a finite group $F$ (with the discrete topology) is continuous, or equivalently has the property that its kernel contains the connected component $G_0$ of the identity in $G$. To prove this it suffices to show that some neighborhood $U$ of the identity in $G$ is contained in the kernel. Pick a neighborhood $U$ which is contained in the image of the exponential map $\exp : \mathfrak{g} \to G$. Then for any $g \in U$ there exists some one-parameter subgroup $\varphi : \mathbb{R} \to G_0$ such that $\varphi(1) = g$. I claim that the composition $\pi \circ \varphi : \mathbb{R} \to F$ is constant, from which the conclusion follows.
But this is clear. The image of any such homomorphism is necessarily a divisible group, and the trivial group is the only divisible finite group.

A: If $H\subseteq G$ is finite index, then $H$ is made out of components of $G$.  In particular, $H$ is closed (and open) in $G$.
(This proof is heavily borrowed from The Lie theory of connected Pro-Lie groups, by Hoffman and Morris, though I honestly couldn't tell you what a Pro-Lie group is!)
Lemma 0:  We may assume $G$ is connected.
Proof:  If $G^0$ denotes the identity component of $G$, then $H\cap G^0 \subseteq G^0$ is finite index.  This follows because the inclusion map $i:G^0\rightarrow G$ induces an injective map $i:G^0/(H\cap G^0)\rightarrow G/H$.   The map $i$ is injective, because if $i([g_1]) = i([g_2])$, then $g_1 = g_2 h$ for some $h\in H$.  Then $g_2^{-1} g_1 = h\in H$.  Since $G^0$ is a subgroup of $G$, this implies  $h\in G^0$, so $g_1 \cong g_2 \in G^0/(H\cap G^0).$  Since $i$ is injective, we have $|G^0/(H\cap G^0)|\leq |G/H| = [G:H]$.
Lemma 1:  $G$ is generated by its divisible subgroups.
Proof:  There is an open set $U\subseteq G$ for which the exponential map $\exp:\mathfrak{g}\rightarrow G$ is onto.  Since every connected Lie group is generated by an open set around $e$, it's enough to show that every element in $U$ lies in a divisible subgroup of $G$.
But, if $u = \exp(X)\in U$, then $u$ lies in the divisible subgroup $\{exp(tX):t\in \mathbb{R}\}$.
Lemma 2:  We may assume wlog that $H$ is normal.
Proof:
Suppose $G = g_1 H \cup ... \cup g_n H$.  Then $N = \bigcap_{i=1}^n g_i H g_i^{-1}$ is finite index and normal.
Lemma 3:  $H = G$.
Proof:  Assuming $H$ is normal, we have a group homomorphism $\pi:G\rightarrow G/H$ onto a finite group.  But since $G$ is generated by its divisible subgroups, so is $\pi(G) = G/H$.  But since $G/H$ is finite, it has no nontrivial divisible groups.  Thus, $G/H$ is trivial, i.e., $H = G$.


text:
Q: Orderitems Javascript Button replacement for Lightning Currently I have the following as a javascript list button that allows the user to selected records:
{!REQUIRESCRIPT('/soap/ajax/29.0/connection.js')}
var selectedRecords = {!GETRECORDIDS( $ObjectType.OrderItem )};
sforce.connection.deleteIds(selectedRecords);
navigateToUrl(window.location.href);

I need to replace this button so that it works in lightning.
I am not sure what the best approach would be, since OrderItem does not support list controllers and the default Edit All and Add products are being used by users.
I tried a flow but I cannot get the selected records.  Is anyone able to suggest an approach to get the selected records to pass into the a flow?


text:
Q: Initial expression is of incorrect type, expected: Messaging.SingleEmailMessage but was: List The below code gave me his error: Initial expression is of incorrect type, expected: Messaging.SingleEmailMessage but was: List<Messaging.SingleEmailMessage>
How do I rectify this?
Code:
public class TestEmailNotification {
    @AuraEnabled
    public static void sendMail() {
        List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
        EmailTemplate templateid = [SELECT Id FROM EmailTemplate WHERE Name = :'xyz' LIMIT 1];
        System.debug(templateid);
        if (templateid != null) {

            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

            mail.setToAddresses(getEmailAddresses());
            mail.setTemplateId(templateid.Id);
            mail.setSenderDisplayName(UserInfo.getUserName());

//mail.setSubject('This is the subject');

//mail.setPlainTextBody('This is the body.');

            mails.add(mail);
            Messaging.sendMail(new Messaging.SingleEmailMessage[] {
                    mails
            });
        }
    }

    public static List<String> getEmailAddresses() {

        List<String> idList = new List<String>();

        List<String> mailToAddresses = new List<String>();

        Group g = [SELECT (SELECT UserOrGroupId FROM GroupMembers) FROM Group WHERE Name = 'abc'];

        for (GroupMember gm : g.GroupMembers) {

            idList.add(gm.UserOrGroupId);

        }

        User[] usr = [SELECT Email FROM User WHERE Id IN :idList];

        for (User u : usr) {
            System.debug(u);
            System.debug(u.Email);
            mailToAddresses.add(u.Email);

        }

        return mailToAddresses;
    }

}

A: Throwing this into an IDE highlights the error as being on the following line:
Messaging.sendMail(new Messaging.SingleEmailMessage[] {
    mails
});

That's because you're trying to statically initialize an array from a declared sequence of array entries but you're actually sending in the array of entries as an array.
Change this line to:
Messaging.sendMail(mails);

Another point worth noting; the emails you are sending will count towards your external email daily limit even though the email addresses are coming from User records. Why? Because you are using the setToAddresses method instead of the setTargetObjectId method. If you switch to the latter, these sent emails will not count to your daily email limit. See this previous Q&A for more detail.


text:
Q: How I start React project through terminal? I am trying to create a new react-app using, npx create-react-app <app name> like this:
npx create-react-app new-app

But after downloading it is hanging over. I mean it is doing nothing. I've reinstalled node.js so that it is the latest version.
Final result I'm getting is:
    Creating a new React app in D:\DesktopD\aapp.

    Installing packages. This might take a couple of minutes.
    Installing react, react-dom, and react-scripts with cra-template...

    > core-js@2.6.11 postinstall D:\DesktopD\aapp\node_modules\babel-runtime\node_modules\core-js
    > node -e "try{require('./postinstall')}catch(e){}"

    > core-js@3.6.5 postinstall D:\DesktopD\aapp\node_modules\core-js
    > node -e "try{require('./postinstall')}catch(e){}"

    > core-js-pure@3.6.5 postinstall D:\DesktopD\aapp\node_modules\core-js-pure
    > node -e "try{require('./postinstall')}catch(e){}"

    + cra-template@1.0.3
    + react-scripts@3.4.3
    + react@16.13.1
    + react-dom@16.13.1
    added 1596 packages from 745 contributors and audited 1600 packages in 162.58s

    71 packages are looking for funding
      run `npm fund` for details

    found 0 vulnerabilities

When I command "npm start" following errors are occuring:

$ npm start
npm ERR! missing script: start

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\2019\AppData\Roaming\npm-cache\_logs\2020-10-11T06_03_19_532Z-debug.log

Here is the above mentioned Log file.

0 info it worked if it ends with ok
1 verbose cli [
1 verbose cli   'D:\\NodeJs\\node.exe',
1 verbose cli   'D:\\NodeJs\\node_modules\\npm\\bin\\npm-cli.js',
1 verbose cli   'start'
1 verbose cli ]
2 info using npm@6.14.8
3 info using node@v12.19.0
4 verbose stack Error: missing script: start
4 verbose stack     at run (D:\NodeJs\node_modules\npm\lib\run-script.js:155:19)
4 verbose stack     at D:\NodeJs\node_modules\npm\lib\run-script.js:63:5
4 verbose stack     at D:\NodeJs\node_modules\npm\node_modules\read-package-json\read-json.js:116:5
4 verbose stack     at D:\NodeJs\node_modules\npm\node_modules\read-package-json\read-json.js:436:5
4 verbose stack     at checkBinReferences_ (D:\NodeJs\node_modules\npm\node_modules\read-package-json\read-json.js:391:45)
4 verbose stack     at final (D:\NodeJs\node_modules\npm\node_modules\read-package-json\read-json.js:434:3)
4 verbose stack     at then (D:\NodeJs\node_modules\npm\node_modules\read-package-json\read-json.js:161:5)
4 verbose stack     at ReadFileContext.<anonymous> (D:\NodeJs\node_modules\npm\node_modules\read-package-json\read-json.js:350:20)
4 verbose stack     at ReadFileContext.callback (D:\NodeJs\node_modules\npm\node_modules\graceful-fs\graceful-fs.js:123:16)
4 verbose stack     at FSReqCallback.readFileAfterOpen [as oncomplete] (fs.js:261:13)
5 verbose cwd D:\DesktopD\my-app3
6 verbose Windows_NT 10.0.17763
7 verbose argv "D:\\NodeJs\\node.exe" "D:\\NodeJs\\node_modules\\npm\\bin\\npm-cli.js" "start"
8 verbose node v12.19.0
9 verbose npm  v6.14.8
10 error missing script: start
11 verbose exit [ 1, true ]

Here is the package.json file:

{
  "name": "aapp",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "cra-template": "1.0.3",
    "react": "16.13.1",
    "react-dom": "16.13.1",
    "react-scripts": "3.4.3"
  }
}

A: 71 Packages needs funding which means these lists of the modules you have need contributions or donations of money to their projects.You can turn these off by this command
npm config set fund false --global

also stop core-js by this command
npm install --no-fund core-js


text:
Q: How to fix this error when using React Context I'm trying to implement React-context in my application to get rid of the props drilling. While creating the contextProvider, I'm getting the following error-
 "Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports".
const SharedThemeContext = React.createContext();
export class SharedThemeProvider extends Component {

  static propTypes = {
    children: PropTypes.func.isRequired
  }
  constructor(props) {
    super(props);

    this.state = {
      isOpen: false,
      message: '',
    };
  }

  openSnackbar = (message) => {
    this.setState({
      message,
      isOpen: true,
    });
  };

  closeSnackbar = () => {
    this.setState({
      message: '',
      isOpen: false,
    });
  };

  render() {
    const { children } = this.props;

    return (
      <SharedThemeContext.Provider
        value={{
          openSnackbar: this.openSnackbar,
          closeSnackbar: this.closeSnackbar,
          snackbarIsOpen: this.state.isOpen,
          message: this.state.message,
        }}
      >

        {children}
      </SharedThemeContext.Provider>
    );
  }
}

export const SharedThemeConsumer = SharedThemeContext.Consumer;

A: Do the warnings provide any information?


text:
Q: List of tuples in Haskell with case of sequences I'm learning about Monads in Haskell and I'm trying to go all the way up from a function (coupleUp3) to the minimun case m of ... (coupleUp1) something like what I saw in the computerphile's video https://www.youtube.com/watch?v=t1e8gqXLbsU&t=1173s.
However, I got stuck and the result is always for
[1..3]

 something like:
[(1,1), (2,2), (3,3)]

 and that's not what I want, I'd like something like
[(1,1),(1,2),(1,3),(2,1),...,(3,3)]

 which is what the other functions do. Here's the code and I just searching for ideas of how to implement the function coupleUp1 that way. You can see what I'm tryin' to do looking at coupleUp3 and coupleUp2. Thank's!
coupleUp3 :: [a] -> [(a, a)]
coupleUp3 x = do
  y <- x
  z <- x
  return (y, z)

coupleUp2 :: [a] -> [(a, a)]
coupleUp2 x = (x >>= (\y ->
               x >>= (\z ->
               return (y, z))))

 coupleUp1 :: [a] -> [(a, a)]
 coupleUp1 x = case x of
                []     -> []
                (y:ys) -> case ys of
                            []     -> []
                            (z:zs) -> (y, z):coupleUp1 ys

A: List comprehensions and do notation:
f xs = [(y, z) | y <- xs, z <- xs]

f xs = do
  y <- xs
  z <- xs
  pure (y, z)

Desugar to the bind operator >>=:
f xs = xs >>= \ y -> xs >>= \ z -> pure (y, z)

And the definitions of >>= and pure can be inlined for a given monad:
f xs = concatMap (\ y -> concatMap (\ z -> [(y, z)]) xs) xs

And then broken down a bit:
f xs = concat $ map (\ y -> map (\ z -> (y, z)) xs) xs

If you want to go further than this, you can inline some simple definitions of concat and map:
f xs = concat' $ map' (\ y -> map' (\ z -> (y, z)) xs) xs
  where
    concat' (xs:xss) = xs ++ concat' xss
    concat' [] = []

    map' f (y:ys) = f y : map' f ys
    map' f [] = []

And then rewrite it step by step, simplifying and inlining until you end up with something like this:
-- Expanding…

f xs = concat' $ map1 xs
  where
    concat' [] = []
    concat' (xs:xss) = xs ++ concat' xss

    -- Previously "map' (\ y -> …)".
    map1 (y:ys) = map2 y xs : map1 ys
    map1 [] = []

    -- Previously "map' (\ z -> …)".
    -- (Takes "y" as an explicit argument; previously,
    -- it was implicitly captured by the lambda.)
    map2 y (z:zs) = (y, z) : map2 y zs
    map2 y [] = []

-- Fully expanded.
-- (With renamed functions for clarity.)

f xs = pairWithSelf xs
  where
    pairWithSelf (y:ys) = pairEachWith y xs ++ pairWithSelf ys
    pairWithSelf [] = []

    pairEachWith y (z:zs) = (y, z) : pairEachWith y zs
    pairEachWith y [] = []

Now this definition says very literally what it does: "to pair a list with itself (f), for every element of the list (pairWithSelf), pair that element with every element of the list (pairEachWith)".
The (++) in pairWithSelf comes from inlining concat, and the recursion in pairWithSelf and pairEachWith comes from inlining the two levels of map. You can't easily "collapse" this down into a single non-nested recursive function because the solution inherently involves nested iteration over the list.
Also, this is a fairly tedious process because you're essentially doing by hand, symbolically, what the language would be doing for you automatically during optimisation or at runtime.
Because you have a recursive structure, you can't really make this any more "primitive". (Well, you could use fix to make the local functions pairWithSelf and pairEachWith into anonymous lambdas, and that might be a good exercise to learn about fix.)
In addition, this process is working backward from how you'd typically do it in Haskell: we usually want to find the most generic and high-level implementation with the least use of explicit recursion possible.
Going back to a higher level, when you see this common pattern of binding two independent actions (lists, in this case) and combining the results with a pure function:
do
  x <- xs
  y <- ys
  pure (combine x y)

Then you can replace it with Applicative functions. Here, combine is the pair constructor (,) and xs and ys are the same, so you could write either of these:
f xs = liftA2 (,) xs xs
f xs = (,) <$> xs <*> xs

This usage of Applicative is very common in ordinary Haskell code, whenever you need a computation shaped like a "Cartesian product" (e.g. a pair table or multiplication table) or you want to pass the results of monadic actions to a pure function without explicitly binding a name with a bind statement <- in do notation.


text:
Q: How are photons absorbed by electrons? I study physics in high school and I was told about the Photoelectric Effect and Compton Effect, and there is something that seems strange to me: How does a photon physically absorbed an electron and pass it its energy? Is that an interaction? Are any force is applied?
EDIT: I fixed the question, I did not mean an actual collision between two bodies, it was an analogy for the energy transfer.
Thanks

A: Ah, the electric force is present in those effects, but in a more local form. I believe understanding that alternate form is the solution to your question.
The electric force is often first encountered as an inverse-square law between distant charges. This is perhaps the description you know: two charges instantaneously experience repulsion or attraction when separated by some distance.
However, this "action at a distance" was theoretically unappealing to many physicists, who desired a local description of nature. Sure enough, physicists found a way to expand and reformulate E&M as a theory about electric and magnetic fields: because fields spread throughout space, a charge will generate a field which propagates outward and then interacts locally with other charges (and vice-versa), all without any action at a distance! This formalism also let's us fuse electric and magnetic forces into a single electromagnetic force, and in doing so reveals the existence of electromagnetic waves. These waves were identified as superpositions of photons, the fundamental constituent of light. In fact, any electromagnetic field may be reinterpreted as a swarm of (mostly 'virtual') photons.
All that is to say: charges do not interact directly with each other, but via the exchange of photons. Charges absorb and emit photons, and that's how they experience the electromagnetic force. The same interaction that admits this pushing and pulling is the same interaction that appears in the photoelectric and Compton effects.

A: So, the way we see the photoelectric effect in High school is more like the phenomenological ideas that lead to quantum mechanics. But quantum mechanics actually does not treat light as a particle in the sense that we think of a ball with a given mass and energy going and hitting another one. Quantum mechanics rather use the "wave" functions. Now the wave function can be a superposition of many Sine and Cosine-like wave functions(eigenbases in the momentum or the coordinate space) and as you may know, superposition of sins and cosines produces "beats" which we call the wave packets in quantum mechanics. Now, these wave packets of arbitrary shapes are what we call photons.. So now coming to your problem, the quantum mechanical wave function of a light wave is still propagating like a field. The only difference is that the dynamics we use is quantum mechanics.
PS: I think the quantum mechanics is not "Quantum" in terms of what we think when we are in high school. In my opinion (I have not studied QFT and creation-annihilation operators are the closest truly quantised treatment I have seen so far), most of the discreteness in quantum mechanics emerges from the solutions of the "wave" equations. You never really tell the math to be discrete(like you would in logic or any other mathematical field). Not to say there is no discreteness, I only want to emphasise that most of the thinking and math is still "wave" mechanics driven.


text:
Q: PHP Mysql radio buttons selection Can someone help me please, I am trying to implement a simple php MySQL survey, but I am stuck on this, how do I store the specific selection in MySQL that users select.
How satisfied are you:

    <colgroup width="70%"></colgroup>
    <colgroup width="6%">
    </colgroup>

           Dissatisfied
           Satisfied
           Very Satisfied

           Technician's ability to understand the unique nature of your problem?
           <input name="satisfaction" value="Dissatisfied"  type="radio">
           <input name="satisfaction" value="Satisfied"  type="radio">
           <input name="satisfaction" value="Very Satisfied"  type="radio">

A: for this what you need will need a form to submit data selection. You will need two php files
The first one is to built a form of radio buttons. I had removed table's elements for neat view then we set the URL of the second page .Can also be a single page if you want but this is more easier.
feedback.php
 <form action="add.php" method="post" accept-charset="utf-8">
     <input name="satisfaction" value="Dissatisfied"  type="radio">Dissatisfied

     <input name="satisfaction" value="Satisfied"  type="radio">Satisfied

     <input name="satisfaction" value="Very Satisfied"  type="radio">Very Satisfied

     <input type='submit' value="submit">
</form>

In the second page we catch what we had posted from first page.
add.php
  $result= $_POST['satisfaction'];
  echo $result;

using $result to store in your database. Good luck

A: As simple as :
1st, Add this line before the table tag:
<form method="post" action="">

2nd, this one at the end of your code:
<input type="submit" name="submit" value="Submit">
</form>

Then you can have this code for inserting in the DB.
if ($stmt = $mysqli->prepare("INSERT INTO TABLENAME(COLUMN NAME) values (?)")) {
     $stmt->bind_param('s', $satisfaction);

    $satisfaction=$_POST['satisfaction'];

     $stmt->execute();

    $stmt->close();
}


text:
Q: Background image of html button I want to create HTML button with some text and also want to put background image for that button.I am trying following code but thats not working. I have placed test.png in my www directory
<!DOCTYPE html>
<html>
<body>
<input type="button" name="test" value="test" style="background:url('test.png') no-repeat 0 0; width:100px;height=50px;background-color: transparent" ></input>
</body>
</html>

A: you have defined height like this height=50px; this is a wrong syntax.
Right syntax while writing css in style attribute: height:50px;
Edited:
Also check the path of the image is correct or the image exists on the given path.

A: I've used following HTML and everything works.
<input type="button" name="test" value="test" style=" background: url('http://www.training-industry.co.uk/assets/images/Take_Test.png') no-repeat 0 0;
width:130px;
height:130px;
background-color: transparent;" />

Look at this fiddle and compare with your code: http://jsfiddle.net/ssqfK/1

A: try background-image instead of background

A: background:url('test.png') no-repeat 0 0; width:100px; height=50px; background-color: transparent
Should be:
background:transparent url('test.png') no-repeat 0 0; width:100px; height:50px;"
On a side note, you should try to avoid inline style where possible.

A: try this :
<input type="button" name="test" value="test" style="background:transparent url('test.png') no-repeat 0 0; width:100px;height:50px;" />

ALso, be careful with the height:50px instead of height=50px


text:
Q: MySQL Partitioning based on ID and Week I have a table
CREATE TABLE `acme`.`partitioned_table` (
  `id` INT NULL,
  `client_id` INT NOT NULL,
  `create_datetime` INT NOT NULL,
  `some_val` VARCHAR(45) NULL);

I'd like to partition this table in such a way that each client's data is stored in its own partition based on the client_id AND each partition can only contain data for 1 week based on the create_datetime. This is done so we can drop weekly one week's worth of data based each client's own retention policy.
For example, some clients would like to have 3 months of data while others may have longer data retention policies.
I am having a hard time being new to MySQL to come up with a proper partitioning strategy. How can I partition by Week based on the INT column.  To throw a curve ball this might be hosted on AWS RDS later.
Many thanks in advance,
M

A: Your clients x weeks level of partitioning would lead to a lot of partitions.  This implies a lot of disk space and queries will be slower.
Your requirement for "separate storage" would be better handled by either separate tables or separate databases.
If you also need to do queries across all clients, we need to discuss things further.
One of the "guidelines" for partitioning is not to partition a table with less than a million rows.
If a client's table is big enough to justify partitioning, see http://mysql.rjweb.org/doc.php/partitionmaint for more discussion.  If not big enough, then either simply do the DELETE, or see this for more options:  http://mysql.rjweb.org/doc.php/deletebig .
There are a lot of DATETIME functions that are messy if you use INT:
`create_datetime` INT


text:
Q: Chromedp golang send ctrl+a Автоматизирую работу в браузере и столкнулся с необходимостью отправлять комбинации клавиш. Например shift+end
Пробовал
if err := chromedp.Run(ctx, chromedp.SendKeys(`#element`, kb.shift+kb.End)); err != nil {
   panic(err)
}

Но в таком случае отправляет по очереди, а не одновременно. Необходимо отправлять события нажатия клавиш keyDown и KeyUp, но просмотрев весь интернет и почитав множество примеров я не смог разобраться, как это работает и воспроизвести.
Пробовал отправлять события нажатия подобным образом:
if err := chromedp.Run(ctx, input.DispatchKeyEvent(input.KeyDown).WithKey(kb.Shift)); err != nil {
    panic(err)
}

Но так же не происходит нужного мне результата.


text:
Q: How to set Image source to Image in code behind I'm having trouble getting the Source of my Image set in the code-behind. Here's my XAML:

        <StackPanel Name="stkPanel" Height="1200" Width="478" HorizontalAlignment="Center" VerticalAlignment="Top" RenderTransformOrigin="0.723,0.509">
            <Image Loaded="imgPicture_Loaded_1" x:Name="imgPicture"   ImageOpened="ImgSelectedPicture_ImageOpened_1" Stretch="UniformToFill" Height="309" Width="413" HorizontalAlignment="Center" VerticalAlignment="Top" Margin="0,30,0,0"></Image>
        </StackPanel>

And the code-behind:
 private void imgPicture_Loaded_1(object sender, RoutedEventArgs e)
    {
        imgPict = (sender as Image);
        //ScrollViewer scroll = this.LayoutRoot.Children[2] as ScrollViewer;

        imgPict.Source = new BitmapImage(new Uri("/project;component/Images/avatar.png", UriKind.RelativeOrAbsolute));
        //bindPicture(imgPict);

    }

Can anyone see what I'm doing wrong?

A: First, what i don't understand is the image path "/project;component/Images/avatar.png" don't think the ";" sign makes the path valid. This should work for you:
<StackPanel Name="stkPanel" Height="1200" Width="478" HorizontalAlignment="Center"                 VerticalAlignment="Top" RenderTransformOrigin="0.723,0.509">
           <Image Loaded="imgPicture_Loaded" x:Name="imgPicture"  Stretch="UniformToFill"
             Height="309" Width="413" HorizontalAlignment="Center" VerticalAlignment="Top"
             Margin="0,30,0,0"></Image>
 </StackPanel>

then in the code behind
private void imgPicture_Loaded(object sender, RoutedEventArgs e)
 {
    imgPicture.Source = new BitmapImage(new
                          Uri("/Images/StoreLogo.png",UriKind.Relative));
 }

You can set the image's "Copy to Output Directory" property to "Copy always".


text:
Q: How to change default value STRINGs automatically generated by pandoc such as "Contents" from ToC and "Chapter" from --chapters I'm using rmarkdown in RStudio to create a dynamic pdf document.
Where and how can I define the prefixes to be used by Pandoc in a rmarkdown, knitr pdf output generation in place of those default values automatically being assumed?
For instance, in the table of contents automatically created, I don´t want the default value assumed as "Contents". The same for the automatic prefix added for each chapter created, instead of "Chapter 'X'" I want to use my own language for that.
Is that possible to set this globally by any pandoc-args passed thru the YAML?
Is there any ChapterPrefix and/or equivalent "TOCPrefix"?


text:
Q: Delete row from one table if I have a dependent tables and know value in the third I know room guid (cda32057-b658-4660-a492-7d7838f7a692) in the table room. How do I delete the associated row in the image table (image_id 212).
image
+--------------+------------------------------------------+
| image_id(PK) |                image_name                |
+--------------+------------------------------------------+
|      212     | 62f07048-5080-4d05-a15d-dcc37df8b7eb.jpg |
|              |                                          |
+--------------+------------------------------------------+

image_room
+--------------+--------------+
| image_id(PK) | room_id(PK)  |
+--------------+--------------+
|      212     |      192     |
|              |              |
+--------------+--------------+

room
+-------------+-----------+--------------------------------------+
| room_id(PK) | room_name |              room_guid               |
+-------------+-----------+--------------------------------------+
| 192         | test      | cda32057-b658-4660-a492-7d7838f7a692 |
+-------------+-----------+--------------------------------------+

A: Please try:
DELETE FROM image
WHERE image.image_id IN
            (SELECT image_room.image_id
             FROM image_room
                  INNER JOIN room
                        ON image_room.room_id = room.room_id
             WHERE room.room_guid = @__your_GUID__)

A: Try this
DELETE FROM IMAGE  WHERE IMAGE_ID IN (SELECT I.IMAGE_ID FROM IMAGE I,ROOM R WHERE I.IMAGE_ID=IR.IMAGE_ID AND IR.ROOM_ID=R.ROOM_ID AND ROOM_GUID='cda32057-b658-4660-a492-7d7838f7a692')

A: You can use join to delete the data, in addition its better to delete the association data from the image_room as well
If you want to delete data for a particular guid you can do so as
delete
i,ir from image i
join image_room ir on ir.image_id = i.image_id
join room r on r.room_id = ir.room_id
where r.room_guid = '{your input}'

Now the above query will also delete the associated record from the image_room if you do not want that to be deleted then just remove ir from the delete clause and it will become as delete i from ...


text:
Q: Completion block isn't called when updating UIPageViewController during rotation I'm trying to update the current page in UIPageViewController during rotation as following:
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
    NSArray *controllers = @[someViewController];
    UIPageViewControllerNavigationDirection direction = UIPageViewControllerNavigationDirectionForward;

    [self.pageController setViewControllers:controllers direction:direction animated:YES completion:^(BOOL finished) {
        /// This completion block isn't called ever in this case.
    }];
}

But, for some reason, the completion block isn't called ever in this case, while it's called as expected when I call the same method with same parameters from other places.
Could anyone confirm this strange behavior, and if it's a bug in UIPageViewController or just a misuse of me?
Update
I found out that if I change the parameter animated to NO the completion block will be called as expected! So, it seems more to me that it's a bug with UIPageViewController.

A: Having the same issue, found the following thing: if someViewController is the current visible controller or pageController.viewControllers?.first and animated flag is set to true, then setViewControllers is called without invoking the completion handler. The easiest way is to call setViewControllers with animated flag set to false. No animations will be shown, but the completion handler will be invoked anyway. But in most cases you need animations to be shown. Thus, the only possible workaround here is to check if the viewController to be set isn't the visible one. If it is, you should call setViewControllers with animated flag set to false:
let completionBlock: (Bool) -> Void
let isAnimated = (newController != pageController.viewControllers?.first)

pageController.setViewControllers([newController],
                                  direction: .forward,
                                  animated: isAnimated,
                                  completion: completionBlock)

Hope that helps you!

A: If keeping the animation is needed, an another option is to wrap in UIView.animation which provides an animation completion callback. That callback will be called regardless of rotation and will actually indicate if the setViewControllers animation was cancelled due to a rotation.
Here's an extension method that encapsulates the solution:
extension UIPageViewController {

    /// A drop-in replacement of `setViewControllers`. It fixes `viewControllers` not displaying properly
    /// if the change animation was cancelled by iOS, which happens everytime the device is rotated.
    ///
    /// See `UIPageViewController.setViewControllers` for parameter details.
    ///
    /// More Info: https://stackoverflow.com/q/19268005/2191796
    @objc
    func setViewControllersPatched(_ viewControllers: [UIViewController]?, direction: UIPageViewController.NavigationDirection, animated: Bool, completion: ((Bool) -> Void)?) {
        if animated {
            // Track if completion gets called - since it's not guaranteed
            // See: https://stackoverflow.com/q/19268005/2191796
            var wasCompletionCalled = false

            // Wrap in an animation block with it's own completion block that is guaranteed and will indicate if the inner animation gets cancelled
            // The duration needs to be longer than the `setViewControllers` animation, otherwise `animationWasCancelled` will always be true.
            UIView.animate(withDuration: 0.4) {
                self.setViewControllers(viewControllers, direction: direction, animated: animated) { animationSkippedByUser in
                    wasCompletionCalled = true

                    completion?(animationSkippedByUser)
                }
            } completion: { animationWasCancelled in
                // When `setViewControllers` is called and a rotation occurs, `animationWasCancelled` will be true - since iOS cancelled the animation.
                if animationWasCancelled && !wasCompletionCalled {
                    print("UIPageViewController.setViewControllersPatched: Issue detected with canceled animation, fixing by setting view controllers without animation.")
                    self.setViewControllers(viewControllers, direction: .forward, animated: false, completion: completion)
                }
            }
        } else {
            // There is no layout/rotation issue when there is no animation - So just pass on the parameters
            setViewControllers(viewControllers, direction: direction, animated: animated, completion: completion)
        }
    }
}

How to Use:
Replace setViewControllers with setViewControllersPatched.

A: try it as:
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
    [self newMethod];
  // or  [self performSelector:@selector(newMethod) withObject:self afterDelay:0.01];
}

- (void)newMethod{
    NSArray *controllers = @[someViewController];
    UIPageViewControllerNavigationDirection direction = UIPageViewControllerNavigationDirectionForward;

    [self.pageController setViewControllers:controllers direction:direction animated:YES          completion:^(BOOL finished) {
        ///
    }];
}


text:
Q: FETCH SYS_REFCURSOR with recursive WITH ORA-32042 I have table with this definition:
create table my_tab as
  select '1' p, '2' c from dual
  union
  select '1' p, '3' c from dual
  union
  select '4' p, '5' c from dual
  union
  select '4' p, '6' c from dual
  union
  select '4' p, '2' c from dual
  union
  select '7' p, '3' c from dual
  union
  select '8' p, '4' c from dual;

I two TYPEs (Тhis is just for information. I simplified the example as much as possible!):
TYPE TObj_OUT AS OBJECT(File_Name VARCHAR2(128),
                            File_Records NUMBER,
                            Session_ID NUMBER,
                            Instanse_ID NUMBER);
CREATE OR REPLACE type TObj_OUT_NT AS TABLE OF TObj_OUT;

Package that print content from SYS_REFCURSOR(return some dummy data just for example):
CREATE OR REPLACE FUNCTION print_info(ip_Select IN SYS_REFCURSOR
                                     ) RETURN TObj_OUT_NT PIPELINED AS
      TYPE TROW IS TABLE OF VARCHAR2(32767);
      v_rows    TROW;
   BEGIN
      LOOP
        FETCH ip_Select BULK COLLECT INTO v_rows LIMIT 100;
         FOR i IN 1 .. v_rows.COUNT LOOP
            DBMS_OUTPUT.put_line(v_rows(i));
         END LOOP;
         EXIT WHEN ip_Select%NOTFOUND;
      END LOOP;
      CLOSE ip_Select;
      PIPE ROW (TObj_OUT('bb', 0, 0, 5));
      RETURN;
END print_info;

I have tried this:
declare
v_cnt number(8);
my_cursor SYS_REFCURSOR;
begin

open my_cursor for with t1(p,
    c) as
     (select distinct null p, t.p as c
        from my_tab t
      union all
      select t.p, t.c
        from t1
        join my_tab t
          on t.p = t1.c)
    select p || c from t1;

SELECT file_records
    into v_cnt
    FROM TABLE(
print_info(
-- cursor start
cursor(
-- FIRST QUERY
with t1(p,
    c) as
     (select distinct null p, t.p as c
        from my_tab t
      union all
      select t.p, t.c
        from t1
        join my_tab t
          on t.p = t1.c)
    select p || c from t1
--FIRST_QUERY END
--SECOND QUERY
--select p||c from my_tab
--SECONF QUERY END
)
-- cursor end
-- my_cursor
));
end;

When I execute block I receive this error:

ORA-32042: recursive WITH clause must reference itself directly in one of the UNION ALL branches
ORA-06512: at "PRINT_INFO", line 9
ORA-06512: at line 17

BUT when i comment code from cursor start to cursor end
-- cursor start
cursor(with t1(p,
    c) as
     (select distinct null p, t.p as c
        from my_tab t
      union all
      select t.p, t.c
        from t1
        join my_tab t
          on t.p = t1.c)
    select p || c from t1)
-- cursor end

and uncomment line
-- my_cursor

It works fine!
If comment FIRST QUERY and uncomment SECOND QUERY It works fine again!
I can't understand where is the problem!

A: It's a bug with cursor expressions + ANSI -> native transformation.
Your case may be simplified just to one SQL statement.
SQL> select cursor(with t1(p, c) as (select distinct null p, t.p as c
  2                                    from my_tab t
  3                                  union all
  4                                  select t.p, t.c
  5                                    from t1
  6                                    join my_tab t
  7                                      on t.p = t1.c)
  8           select p || c from t1) c from dual;
select cursor(with t1(p, c) as (select distinct null p, t.p as c
*
ERROR at line 1:
ORA-00604: error occurred at recursive SQL level 1
ORA-32042: recursive WITH clause must reference itself directly in one of the
UNION ALL branches

SQL> select * from table(dbms_xplan.display_cursor(format => 'basic'));

PLAN_TABLE_OUTPUT
--------------------------------------------------------------------------------
EXPLAINED SQL STATEMENT:
------------------------
select cursor(with t1(p, c) as (select distinct null p, t.p as c
                           from my_tab t
 union all                                 select t.p, t.c
                     from t1                                   join
my_tab t                                     on t.p = t1.c)
select p || c from t1) c from dual

Plan hash value: 956860371

------------------------------------------------------------
| Id  | Operation                                 | Name   |
------------------------------------------------------------
|   0 | SELECT STATEMENT                          |        |
|   1 |  VIEW                                     |        |
|   2 |   UNION ALL (RECURSIVE WITH) BREADTH FIRST|        |
|   3 |    SORT UNIQUE                            |        |
|   4 |     TABLE ACCESS FULL                     | MY_TAB |
|   5 |    VIEW                                   |        |
|   6 |     HASH JOIN                             |        |
|   7 |      RECURSIVE WITH PUMP                  |        |
|   8 |      TABLE ACCESS FULL                    | MY_TAB |
|   9 |  FAST DUAL                                |        |
------------------------------------------------------------

26 rows selected.

SQL> select cursor(with t1(p, c) as (select distinct null p, t.p as c
  2                                    from my_tab t
  3                                  union all
  4                                  select t.p, t.c
  5                                    from t1, my_tab t
  6                                   where t.p = t1.c)
  7           select p || c from t1) c from dual;

C
--------------------
CURSOR STATEMENT : 1

CURSOR STATEMENT : 1

P|
--
1
8
7
4
12
13
42
45
46
73
84
42
45
46

14 rows selected.

SQL> select * from table(dbms_xplan.display_cursor(format => 'basic'));

PLAN_TABLE_OUTPUT
--------------------------------------------------------------------------------
EXPLAINED SQL STATEMENT:
------------------------
select cursor(with t1(p, c) as (select distinct null p, t.p as c
                           from my_tab t
 union all                                 select t.p, t.c
                     from t1, my_tab t
where t.p = t1.c)          select p || c from t1) c from dual

Plan hash value: 2529699678

------------------------------------------------------------
| Id  | Operation                                 | Name   |
------------------------------------------------------------
|   0 | SELECT STATEMENT                          |        |
|   1 |  VIEW                                     |        |
|   2 |   UNION ALL (RECURSIVE WITH) BREADTH FIRST|        |
|   3 |    SORT UNIQUE                            |        |
|   4 |     TABLE ACCESS FULL                     | MY_TAB |
|   5 |    HASH JOIN                              |        |
|   6 |     RECURSIVE WITH PUMP                   |        |
|   7 |     TABLE ACCESS FULL                     | MY_TAB |
|   8 |  FAST DUAL                                |        |
------------------------------------------------------------

24 rows selected.

So first query (with ANSI join syntax) failed however second one (with native join syntax) completed successfully.
The difference in query plans is VIEW operation for the first query (ID = 5).
It informs us that inline view has been created during query transformation.
Let's have a look at transformed queries in trace file for event 10053.
select cursor(with "T1"("P", "C")
              as((select "from$_subquery$_004"."QCSJ_C000000000400001_2" "P",
                         "from$_subquery$_004"."QCSJ_C000000000400003_3" "C"
                    from (select "T1"."P" "QCSJ_C000000000400000",
                                 "T1"."C" "QCSJ_C000000000400002",
                                 "T"."P"  "QCSJ_C000000000400001_2",
                                 "T"."C"  "QCSJ_C000000000400003_3"
                            from "T1" "T1", "MY_TAB" "T"
                           where "T"."P" = "T1"."C") "from$_subquery$_004")
                 union all (select distinct null "P", "T"."P" "C"
                    from "MY_TAB" "T")) select "T1"."P" || "T1"."C"
              "P||C" from "T1" "T1") "C"
  from "SYS"."DUAL" "DUAL"

select cursor(with "T1"("P", "C")
              as((select "T"."P" "P", "T"."C" "C"
                    from "T1" "T1", "MY_TAB" "T"
                   where "T"."P" = "T1"."C") union all
                 (select distinct null "P", "T"."P" "C"
                    from "MY_TAB" "T")) select "T1"."P" || "T1"."C"
              "P||C" from "T1" "T1") "C"
  from "SYS"."DUAL" "DUAL"

You see that join has been transformed in the first query into additional inline view with where clause and if you try to run first query it fails with ORA-32042.


text:
Q: Python SFTP Paramiko: catch Wrong Hostname Error I am currently testing an exception for when the username or host is wrong but I don't know which exception I should catch.
I tried BadHostkeyException but apparently that was wront.
If I catch socket.gaierror then that would be to vague.
I am getting this Output:
  File "./sFTPscript10.py", line 141, in connSFTP
    c.connect( hostname = config.host, username = config.username, pkey = k )
  File "/usr/local/lib/python3.6/site-packages/paramiko/client.py", line 340, in connect
    to_try = list(self._families_and_addresses(hostname, port))
  File "/usr/local/lib/python3.6/site-packages/paramiko/client.py", line 204, in _families_and_addresses
    hostname, port, socket.AF_UNSPEC, socket.SOCK_STREAM
  File "/usr/lib64/python3.6/socket.py", line 745, in getaddrinfo
    for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno -2] Name or service not known

My Code:
def connSFTP(config,logger_info,logger_error,resetConnSFTP,logger_error_mail,reset):
    #Fehleroptionen 1. Pfad zum SSH-KeyError
                        #-SSH-Key vorhanden?
                    #2.Host und/oder Username ist falsch
    try:
        k = paramiko.RSAKey.from_private_key_file(config.ssh_key_filepath) #SSH KEY
        c = paramiko.SSHClient()
        c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        c.connect( hostname = config.host, username = config.username, pkey = k )
        sftp = c.open_sftp()
        logger_info.info('Connected with '+ config.host)

        return sftp

    except (paramiko.BadHostKeyException) as err:
        print('Username or Host is wrong' + str(err))

A: You can see yourself that the exception is socket.gaierror. There's no more specific exception.
You can check the errno for more specific error (-2 in your case). But note that it won't be platform independent.
except socket.gaierror as e:
    print(e.errno)


text:
Q: Error with tweepy OAuthHandler I'm new here and kind of unexperienced with python, so sorry if the question is trivial.
I have this simple script, to fetch followers of a given twitter user:
import time
import tweepy

consumer_key="xxx"
consumer_secret="yyy"
access_token="zzz"
access_token_secret="www"

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)

of course xxx,yyy,etc are being set in my script with API key, secret, access token etc
I get this error:
c:\Development>c:\Python27\python.exe get_followers.py
Traceback (most recent call last):
File "get_followers.py", line 4, in
auth = tweepy.OAuthHandler('xxx', 'yyy')
AttributeError: 'module' object has no attribute 'OAuthHandler'

Is anyone able to help me?
Can't understand what am I doing wrong.
Thanks
Andrea

A: The tweepy module object has no attribute 'OAuthHandler',You should import like this,
from tweepy.auth import OAuthHandler

auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)

Reference here https://github.com/tweepy/tweepy/blob/master/tweepy/auth.py#L29


text:
Q: mysql with DRBD on rackspace I am trying to set up a failover secondary MySQL server that is a mirror of my primary MySQL server using DRBD. The problem is that I am on a rackspace cloud server and I need a second partition on both the primary and secondary servers that I will replicate with DRBD. Rackspace does not allow me to create a second partition. I am left with the default single partition. How can I mirror using DRBD?

A: Coincidently there is a blog post related to doing this by a Rackspace employee:
http://rackerhacker.com/redundant-cloud-hosting-configuration-guide/setting-up-a-redundant-database-and-caching-layer/

A: You cannot if you can't make add another partition or change a currently mounted partition..
My not look into mysql replication?


text:
Q: how to fix htmlspecialchars invalid multibyte sequence in argument if data is an ascii type in yii app? my data to display is an ascii type based from
mb_detect_encoding of PHP, i have tried CHtml::encode($str); when displaying the data, but am getting that invalid multibyte sequence argument, what's the best thing to do with this ?


text:
Q: How come my react app is not rendering despite correct configuration? I'm trying to launch a single page webapp, but I'm having some issues getting firebase to behave. I used create-react-app to initially create the project.
What's essentially happening is that index.html loads but the app is not rendered. You can see here: https://pokerstudy.online/
index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import {BrowserRouter} from 'react-router-dom';

import ReactGA from 'react-ga';

import firebase from 'firebase';

ReactGA.intialize('UA-134743808-1', { standardImplementation: true });
ReactGA.pageview(window.location.pathname + window.location.search);

ReactDOM.render(<BrowserRouter><App /></BrowserRouter>, document.getElementById('root'));

serviceWorker.unregister();

firebase.json
{
  "hosting": {
    "public": "build",
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ],
    "rewrites": [
      {
        "source": "**",
        "destination": "/index.html"
      }
    ]
  },
  "storage": {
    "rules": "storage.rules"
  }
}

Any help would be appreciated!


text:
Q: Linq query SUM and COUNT I have a SQL Server Order table with two columns (itemPriceType1 and itemPriceType2). I need to get the total count and the sum of the two columns in a Linq query or a lambda expression.
Order tTable
    SELECT *
      ,[userID] as id
      ,[itemPriceType1] as itemCost1
      ,[itemPriceType2] as itemCost2
  FROM order;

Query result:

Desired result:
I want to get the total COUNT and the total SUM.
Eg.
Count = 4
Sum = 700

My attempt
var result1 = (from col1 in db.Orders
               where col1.itemPriceType1 != 0
               select col1).Count();

var result2 = (from col1 in db.Orders
               where col1.itemPriceType2 != 0
               select col1).Count();

ViewBag.count = (result1+result2);

In the above query gives me the correct count which is 4. Question, how can I improve this query? And possibly get the sum as well?

A: One way is to perform operation on one property, perform on the other and add up both results:
To get the count:
var count = db.Orders.Count(o => o.itemPriceType1 != 0) +
            db.Orders.Count(o => o.itemPriceType2 != 0);

And the sum:
var sum = db.Orders.Sum(o => o.itemPriceType1) +
          db.Orders.Sum(o => o.itemPriceType2);


text:
Q: Google Charts - Display two or more donuts rings in one donut chart I am using Google Charts. I have the below code.
var newData = google.visualization.arrayToDataTable([
  ['Major', 'Degrees'],
  ['Business', 2], ['Education', 2],
  ['Social Sciences & History', 2], ['Health', 2],
  ['Psychology', 2]]);
var newData2 = google.visualization.arrayToDataTable([
  ['Major', 'Degrees'],
  ['Business', 2], ['Education', 3],
  ['Social Sciences & History', 1], ['Health', 2],
  ['Psychology', 4]]);
var options = { pieSliceText: 'none'};
var chartDiff = new google.visualization.PieChart(document.getElementById('donutchart'));
var diffData2 = chartDiff.computeDiff(newData, newData2);
chartDiff.draw(diffData2, options);

I am getting the following output.
http://tinypic.com/r/1ggizc/8
I would like to get the do-nut chart like the below image.
http://tinypic.com/r/169rbpz/8
Is there any other way to get the donut charts as shown in the second link above. I would like it only in Google charts please. Suggestion in code modification or complete code change is also fine.
Thanks in advance.


text:
Q: persistent menu in facebook will automatically appear in a thread if the person has been away I was reading facebook documentation about persistent menu, I see that they mentioned "The menu will automatically appear in a thread if the person has been away for a certain period of time and returns."
facebook documentation here
However I cannot get that to work, can someone help me with that?

A: @ChrisB - The menu never automatically appears in the thread when the person has been away and returns.

A: Based on my experience, it isn't guaranteed that the menu is updated automatically every time we access. Sometimes it doesn't seem to work somehow. It also might be effected by network condition. Facebook haven't announced such a situation officially at least
But there is no other way to update it forcibly. What we can do is just to hope it works on the all users' phone and, to know there is the case it doesn't work.
I think recently it almost works well though.