text:
Q: Unbound DataGridView add row with checkbox error This is a Windows forms program.  I have an unbound DataGridView control with four columns; Feature ID as string, Parts as string, Flats as string and ShowOnEst as boolean. The columns were defined in the form designer and the boolean column is, indeed, set to be a checkbox with tristate set to false.
The user selects a product from a list box and this code is executed to populate the grid
grdFeat.Rows.Clear()
For i = 0 To curProduct.lstFeatures.Count - 1
    With (curProduct.lstFeatures(i))
        grdFeat.Rows.Add(.FeatureId, .Parts, .Flats, .ShowOnEst)
    End With
Next

If AllowUserToAddRows is false, everthing is good.  Setting AllowUserToAddRows to true, however, results in the following error:
FormatException
Value '' cannot be converted to type 'Boolean'.
The error is NOT triggered in my code.  It's displayed in a new tab titled "No Source Available".
It seems pretty clear that the process that adds the new editing row is trying to set the checkbox to a string value, or perhaps NULL. I'm very new (a few months) to vb.net, so I suspect I'm overlooking some simple setting somewhere, but after several hours of trying to find it, I'm starting to feel a little foolish here.
I'd give you a list of things I've tried already, but it's a long one. :) I even tried to go around the issue by adding a new row manually, .add("","","",False), but that too gives the same error, even though I'm telling it what to put in the checkbox.
What am I missing?  Also, can someone point me to an explanation of how that new editing row thingy works?

A: From what you explained, I have no real explanation for the problem.
A workaround may be to set  AllowUserToAddRows to false before populating the DataGridView and set it to true after.

A: Found it.  Hope it helps someone else...
The rows being added are uncommitted rows.  To solve it, capture the row added index, set the current cell and notify that the added row is dirty:
grdFeat.Rows.Clear()
For i = 0 To curProduct.lstFeatures.Count - 1
    With (curProduct.lstFeatures(i))
        Dim p = grdFeat.Rows.Add(.FeatureId, .Parts, .Flats, .ShowOnEst)
    End With
    grdFeat.CurrentCell = grdFeat.Rows(p).Cells(0)
    grdFeat.NotifyCurrentCellDirty(True)
Next

Well, with further experimentation, this isn't a total fix. The problem is still there, but at least now handling the DataError event allows me to do something with it in code.  Without these lines, the error occurs before the DataError event is triggered.
Still puzzled.


text:
Q: Creating a LoRaWAN gateway with multiple nodes? I'm working with a project to collect temperature data from about 50 cabins that are located close together. It therefore seems easiest to use 50 Lora nodes with temperature sensors and one gateway.
So I'm searching for a way to use multiple Lora nodes to create a sensor network. From what I've gathered it might be more cost and time effective to buy a readymade gateway such the Dragino. But I can't seem to find any good guides on how to create a small Lora node? I live in Europe and therefore want to use 433Hz frequency. I'm thinking something like a RFM96 and an Arduino nano should do the trick? Or is there easier solutions?
Since there is little documentation about this I hope others can find this useful as well.
Thanks in advance!

A: Maybe if......
The 50 cabins each send temperature data once every 10 minutes using battery power this could be handled by a system that does not rely on a receive protocol to tell the "transmitter" when to transmit. This could massively sustain battery life because you are not wasting several mA of current continuously keeping the radio listening.
In the 9 minutes, 59.9 seconds between transmissions your battery consumption could be as low as a few microamps. During transmission (0.1 seconds) you might need 20 mA so the average current is: -
Background (say 10 uA) plus 20 mA/6600 = 10 uA + 3 uA = 13 uA.
Channel usage per cabin transmitter is 0.1 seconds every 660 seconds so, with 50 transmitters this means the channel average utilization is 5/660 = 0.75%. Each transmitter could randomly time its transmission based on a unique address so that on average it was ten minutes (with plus or minus 5 minutes as the random factor).
Collision probability would be low but you'd get a cabin's temperature the next time in all probability. It's all down to how you want to play it.
This type of system would use 50 transmitters and one receiver. The receiver does all the data collection for the 50 cabins.
Quite cheap (I would use FM) transmitters could be used but each would need a little MCU to format the transmission with preamble, address, payload data and checksum. The little MCU would also do the random timing thing.
The receiver (AC powered) would convert a received transmission back to the payload data (having proven that the checksum tallied) and the address of the cabin would also be detected in the transmission.
Similar question.
Maybe a LoRa module could be put into shut-down mode to conserve battery life thus you get a similar solution that wouldn't require an MCU to format the data to make it suitable for a transmission?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Attaching spaces closed subset proof closedness Let $X$ and $Y$ be non empty topological spaces. Consider $X\coprod Y = (X\cup 0) \cup (Y\times 1)$. We define a topology on $X\coprod Y$ by declaring $U$ is open in $X\coprod Y$ if and only if $\iota_{1}^{-1}(U)$  is open in $X$ and $\iota_2^{-1}(U)$ is open in $Y$. Here, $\iota_1:X\rightarrow X\coprod Y$ is given by $\iota_1(x)=(x,0)$  and $\iota_2$ is defined similarly. In particular, $\iota_2(y)=(y,1)$.
Now let $A\subseteq X$ be closed. Suppose $f:A\rightarrow Y$ is continuous.  Then we may consider the adjunction space $X\cup_f Y= (X\coprod Y)/((a,0)\sim (f(a),1))$  which identifies $a$ with $f(a)$ for all $a\in A$.
We may abuse notation and write $(a,0)$ as $a$ and $(f(a),1)$ as $f(a)$.
Problem:
Let $X$ be space space and $A$ non empty closed subset of $X$. Let $f:A\rightarrow Y$ be continuous. Assume $C\subseteq X\coprod Y$ is such that $\iota_1^{-1}(C)$ is closed in $X$. Then
$q(C)$ is closed in $X\cup_f Y$ if and only if $\iota_{2}^{-1}(C)\cup f(\iota_{1}^{-1}(C)\cap A)$ is closed in $Y$.
My attempt: If $q(C)$ is closed in $X\cup_f Y$ then $q^{-1}q(C)$ is closed in $X\coprod Y$ . In particular, $\iota_{2}^{-1}q^{-1}q(C)$ is closed in $Y$. As $\iota_{2}^{-1}q^{-1}q(C)= \iota_{2}^{-1}(C)\cup f(\iota_{1}^{-1}(C\cap A))$, the result then follows.
Is this proof correct? Why is the assumption $\iota_{1}^{-1}(C)$ closed important?
Note that $q$ is the canonical projection map

A: Your proof of the "only if" is correct, now you have to prove the other direction. By going backwards on your proof, we already know that if $i_2^{-1}(C) \cup f(i_1^{-1}(C \cap A))$ is closed, then so is $i_2^{-1}q^{-1}q(C)$, we are now left to show that $i_1^{-1}q^{-1}q(C)$ is closed to conclude that $q^{-1}q(C)$ is closed in $X \sqcup Y$, which will imply that $q(C)$ is closed. Now since
$$i_1^{-1}q^{-1}q(C) = i_1^{-1}(C) \cup f^{-1}(i_2^{-1}(C) \cup f(i_1^{-1}(C \cap A)) $$
then by the hypothesis that $i_1^{-1}(C)$ is closed, that $f$ is continuous and that $i_2^{-1}(C) \cup f(i_1^{-1}(C \cap A)$ is closed, we conclude that $i_1^{-1}q^{-1}q(C)$ is closed.


text:
Q: How do I get the result of an RetryTemplate.execute in Spring java? I'm fairly new to java and spring and I'm trying to figure out how to receive the result of an RetryTemplate.execute command. I would like to return a false if the execute command fails, and a true if it succeeds. I've tried assigning the values of res in the execute function but all i got was an error saying that java: local variables referenced from a lambda expression must be final or effectively final
heres my code:
private boolean forward(String message) {
        boolean res;
        retryTemplate.execute(retryCallback -> {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);

            ResponseEntity<String> responses = restTemplate.postForEntity(kafkaForwarderSetting.getUrlEndpoint(),
                    new HttpEntity<>(message, headers), String.class);

            if (responses.getStatusCodeValue() > 300) {
                throw new ForwarderException("Error occurred while forwarding message to endpoint!",
                        retryCallback.getLastThrowable());
            }
            // SET res to true
            return true;
        }, recoveryCallback -> {

            // SET res to false
            return false;
        });

        return res;
    }

From the documentation, it seems that execute returns <T, E extends Throwable> on the retryTemplate and whenever I return the value (such as the return true; on line 12), I should be able to access that very value.
However I don't know how to get it and printing out the retryTemplate itself gives me org.springframework.retry.support.RetryTemplate@5d65976d

A: The compiler error
local variables referenced from a lambda expression must be final or effectively final

means that in Java, you cannot change the reference of a variable declared outside of a lambda inside of it.
To circumvent this, you can use MutableBoolean from the Apache Commons Lang 3 library.
First, include the library into your pom.xml:
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.8.1</version>
</dependency>

Then, import MutableBoolean into your class using
import org.apache.commons.lang3.mutable.MutableBoolean;

Now, replace
boolean res;

with
final MutableBoolean res = new MutableBoolean();

The final is optional, but good practice.
To set the value, write
res.setValue(true);

or
res.setValue(false);

You can use one of the three following methods to retrive the value after your lambda:
boolean isFalse = res.isFalse();
boolean isTrue = res.isTrue();
Boolean value = res.getValue();

Note that res.getValue() will give you a boxed Boolean, while the other two methods give you an unboxed boolean. These are great for if-statements.
I hope this helps.


text:
Q: Drawer navigation in react native I use drawer navigation in react native with expo and use eas build:Android for apk then i open this apk file in my phone then it's crashing,it can not open
Please tell me anyone how to solve this?


text:
Q: Overloading a method with delegates in c# Is there some way I can "overload" a function using delegates? I'd like to have a system in place wherein I can pass an anonymous function in a constructor and save it in a member variable. Data type isn't really an issue, but the passed functions can have one or two parameters. I've tried using (params double[] vals) in the delegate definition, but that complicates the passed anonymous functions and allows more parameters than should be allowed.
So I've created two empty methods to hold the two types. As an example:
public class OpWrapper
{
    public int operands;      //the number of operands this operator needs.
    public int precedence;    //the precedence this operator gets when calculating.
    public bool rightAssoc;   //whether or not this operator is right associative (true) or left associative (false).

    public delegate double evalDelegate(double a, double b);
    public delegate double calcDelegate(double a);
    public evalDelegate eval; //method used for two value inputs. Assigned in constructor.
    public calcDelegate calc; //method used for single value input. Assigned in constructor.

    //constructor initializes all variables.
    public OpWrapper(int o, int p, evalDelegate f, bool a = false)
    {
        operands = o;
        precedence = p;
        rightAssoc = a;
        eval = new evalDelegate(f);
    }
    //overloaded constructor assigns the proper method.
    public OpWrapper(int o, int p, calcDelegate f, bool a = false)
    {
        operands = o;
        precedence = p;
        rightAssoc = a;
        calc = new calcDelegate(f);
    }

    public double evaluate(params double[] values)
    {
        //do stuff
        if (operands == 1)
        {
            return calc(values[0]);
        }
        else
        {
            return eval(values[0], values[1]);
        }
        //more stuff
    }

}

Ultimately, what I'd like to do is more like this:
public class OpWrapper
{
    public int operands;      //the number of operands this operator needs.
    public int precedence;    //the precedence this operator gets when calculating.
    public bool rightAssoc;   //whether or not this operator is right associative (true) or left associative (false).

    public delegate double evalDelegate(double a, double b);
    public delegate double calcDelegate(double a);
    public ???????? calc; //method that does the passed function.

    //constructor initializes all variables.
    public OpWrapper(int o, int p, evalDelegate f, bool a = false)
    {
        operands = o;
        precedence = p;
        rightAssoc = a;
        eval = new evalDelegate(f);
    }
    //overloaded constructor assigns the proper method.
    public OpWrapper(int o, int p, calcDelegate f, bool a = false)
    {
        operands = o;
        precedence = p;
        rightAssoc = a;
        calc = new calcDelegate(f);
    }

    public double evaluate(params double[] values)
    {
        //do stuff
        if (operands == 1)
        {
            return calc(values[0]);
        }
        else
        {
            return calc(values[0], values[1]);
        }
        //more stuff
    }

}

I'm not tremendously familiar with C#, yet, but surely there is a way to do something like this without having to define an instance of one delegate or the other that will just go unused.

A: .Net provides some useful delegate types out of the box; namely Action for a void returning method and Func for one retaining an argument. These provide type safety over anonymous delegates and provide a clean approach to what you need which appears to be something like the Command or the Strategy pattern.
You can also use expressions to declare delegates inline as follows:
public void InvokeAction(Action invoke)
{
    invoke();
}

InvokeAction(() => Console.WriteLine(...));

=> essentially means 'into' and if you had arguments you would declare them before the arrow:
(arg1, arg2) => ...

Expressions and Action/Func have all but taken over from anonymous delegates in modern .Net coding.
If you have a property of type Action on a class you call it as a method directly.
public Action Calc { get; set; }

Calc = () => Console.WriteLine(...);

Calc();

A: this will help you. In this i have just initialise your calc variable as object which is base type of all types (int,class,delegates etc) and in evaluate method i have cast it from object to its appropriate type.
public class OpWrapper
{
    public int operands;      //the number of operands this operator needs.
    public int precedence;    //the precedence this operator gets when calculating.
    public bool rightAssoc;   //whether or not this operator is right associative (true) or left associative (false).

    public delegate double evalDelegate(double a, double b);
    public delegate double calcDelegate(double a);
    public object calc; //method that does the passed function.

    //constructor initializes all variables.
    public OpWrapper(int o, int p, evalDelegate f, bool a = false)
    {
        operands = o;
        precedence = p;
        rightAssoc = a;
        calc = new evalDelegate(f);
    }
    //overloaded constructor assigns the proper method.
    public OpWrapper(int o, int p, calcDelegate f, bool a = false)
    {
        operands = o;
        precedence = p;
        rightAssoc = a;
        calc = new calcDelegate(f);
    }

    public double evaluate(params double[] values)
    {
        //do stuff
        if (operands == 1)
        {
            return (calc as calcDelegate)(values[0]);
        }
        else
        {
            return (calc as evalDelegate)(values[0], values[1]);
        }
        //more stuff
    }

}

A: I'll throw my hat into the ring...
Here is how you would use a Func.
public class OpWrapper
{
    public int operands;      //the number of operands this operator needs.
    public int precedence;    //the precedence this operator gets when calculating.
    public bool rightAssoc;   //whether or not this operator is right associative (true) or left associative (false).

    public object func;

    //constructor initializes all variables.
    public OpWrapper(int p, Func<double, double> f, bool a = false)
    {
        //No need to pass in o, we can infer from context that its a single parameter
        operands = 1;
        precedence = p;
        rightAssoc = a;
        func = f;
    }
    //overloaded constructor assigns the proper method.
    public OpWrapper(int p, Func<double, double, double> f, bool a = false)
    {
        //No need to pass in o, we can infer from context that its a double parameter
        operands = 2;
        precedence = p;
        rightAssoc = a;
        func = f;
    }

    public double evaluate(params double[] values)
    {
        if (values.Length != operands)
            throw new InvalidOperationException("Invalid number of operands");

        //do stuff
        if (operands == 1)
        {
            return ((Func<double, double>)func)(values[0]);
        }
        else
        {
            return ((Func<double, double, double>)func)(values[0], values[1]);
        }
        //more stuff
    }

}

Note that I removed "o" from the call, and that I used casting to choose the right operation (and checked if the proper number of operands was provided).


text:
Q: Big difference in run time for two machines - how to handle? I have a script i wrote (its pretty long so i wont paste it unless you would like to)
maybe its not the most efficient code - it does some kind of bfs on certain data that been held in a dict.

The major issue is that I wrote it on my PC and tested it with the regular python 2.7 version I have installed, but it will running on a server that is supposed to have much better performance over my PC. However it's running X4 times slower on the server and its really interesting why (measured time of running with time()).

I need to write some more on this scripts for my research and run them on large data sets and I wish to know how to resolve the performance issue.
Maybe I need higher priority in the UNIX machine or something?
Thanks,
Tomer
Windows = Intel Core 2 Quad CPU @2.66Ghz - 4GbRam with 64bit windows 7
UNIX = 16 processors of Intel(R) Xeon(R) CPU E7320  @ 2.13GHz with 64GB RAM

A: I am not sure about your code, (It will be good if you paste it and others will tell you code optimizations.) but definitely you can do following things,

*

*there can be 2 possibilities, either one of the method/statement/module is slow or whole code is slow.
check that by adding logger statements and find out culprit/time taking method. if possible tune it or improve it.

*As you said, your code is not optimal well then make it optimal (paste it here if you find culprit method, experts will suggest you on that). optimal code isn't a magic.

*Same code can take different execution times on different OSes/platform because of platform changes/implementations. before you directly run, have a look at the setting and tunings possible.

*If you have such powerful processing power (quad core) then try utilizing it by making your code suitable for it (use multithreading, parallel execution, efficient data structures etc.)
That will help you, hope this helps.


text:
Q: Why do we have to conform both UIViewController and UITableViewDataSource? Currently, I want to have a separated class for data only. However, I cannot just declare a class like this:
class DataSource: UITableViewDataSource

It would give me a lot of error. And, I have to do this instead:
class DataSource: UIViewController, UITableViewDataSource

So, why? I come from Java background, so I don't understand why I have to implement A to implement B. I tried reading the official documents from Apple, but I could not find the answer.
Edit: here is the error:
Type 'DataSource' does not conform to protocol 'UITableViewDataSource'
Type 'DataSource' does not conform to protocol 'NSObjectProtocol'

and, XCode suggests a solution to fix it is to add "@objc " at the beginning of the override function. The error still there after the fix though.
Edit 2: I am aware that I need to implement 2 functions for the data source to work. However, it will not work without implementing UIViewController.

It will work after adding UIViewController!

A: Protocol UITableViewDataSource comes from NSObjectProtocol. So you have to make your class inherit from NSObject to conform to the NSObjectProtocol. Vanilla Swift classes do not. But many parts of UIKit expect NSObjects. And you have to implement the required methods of this protocol. Try below code:
class DataSource: NSObject, UITableViewDataSource {

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        return UITableViewCell()
    }
}


text:
Q: Write an own layer with trainable parameters in Tensorflow I want to write an easy, own Exponentiation layer in Tensorflow 2. It should take n inputs [x_1, ..., x_n] and output some powers [x_1^e_1, ..., x_n^e_n], where e_1, ..., e_n are trainable parameters.
For example, this Exponentiation layer together with a Dense layer (with output dimension 1) could learn any function of the form a_1x_1^e_1+...+a_nx_n^e_n, which is a simple extension of normal, linear regression.
However, I have no luck with getting t to work. So far, I have written the following:
import tensorflow as tf

class Exponent(tf.keras.layers.Layer):
    def __init__(self):
        super().__init__()

    def build(self, input_shape):
        self.exp = self.add_weight(name='Exponent', shape=input_shape, initializer=tf.constant_initializer(value=1.), trainable=True)
        super().build(input_shape)

    def call(self, inputs, training=False):
        return tf.math.pow(inputs, self.exp)

I can instantiate an object of this class, and everything works fine.
e = Exponent()
e.build(input_shape=(2,))
e([[1., 2.]]) # works fine

If I try to embed it in a model, it throws an error when trying to predict (or also fit):
model = tf.keras.Sequential([
    Exponent(),
    tf.keras.layers.Dense(1)
])

model.compile(
    loss='mse',
    optimizer='sgd'
)

model.predict([[1., 2., 3.]])

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-401-2ea9d74ffa37> in <module>
      9 )
     10
---> 11 model.predict([[1., 2., 3.]])

~\AppData\Roaming\Python\Python37\site-packages\tensorflow\python\keras\engine\training.py in _method_wrapper(self, *args, **kwargs)
    128       raise ValueError('{} is not supported in multi-worker mode.'.format(
    129           method.__name__))
--> 130     return method(self, *args, **kwargs)
    131
    132   return tf_decorator.make_decorator(

~\AppData\Roaming\Python\Python37\site-packages\tensorflow\python\keras\engine\training.py in predict(self, x, batch_size, verbose, steps, callbacks, max_queue_size, workers, use_multiprocessing)
   1597           for step in data_handler.steps():
   1598             callbacks.on_predict_batch_begin(step)
-> 1599             tmp_batch_outputs = predict_function(iterator)
   1600             if data_handler.should_sync:
   1601               context.async_wait()

~\AppData\Roaming\Python\Python37\site-packages\tensorflow\python\eager\def_function.py in __call__(self, *args, **kwds)
    778       else:
    779         compiler = "nonXla"
--> 780         result = self._call(*args, **kwds)
    781
    782       new_tracing_count = self._get_tracing_count()

~\AppData\Roaming\Python\Python37\site-packages\tensorflow\python\eager\def_function.py in _call(self, *args, **kwds)
    821       # This is the first call of __call__, so we have to initialize.
    822       initializers = []
--> 823       self._initialize(args, kwds, add_initializers_to=initializers)
    824     finally:
    825       # At this point we know that the initialization is complete (or less

~\AppData\Roaming\Python\Python37\site-packages\tensorflow\python\eager\def_function.py in _initialize(self, args, kwds, add_initializers_to)
    695     self._concrete_stateful_fn = (
    696         self._stateful_fn._get_concrete_function_internal_garbage_collected(  # pylint: disable=protected-access
--> 697             *args, **kwds))
    698
    699     def invalid_creator_scope(*unused_args, **unused_kwds):

~\AppData\Roaming\Python\Python37\site-packages\tensorflow\python\eager\function.py in _get_concrete_function_internal_garbage_collected(self, *args, **kwargs)
   2853       args, kwargs = None, None
   2854     with self._lock:
-> 2855       graph_function, _, _ = self._maybe_define_function(args, kwargs)
   2856     return graph_function
   2857

~\AppData\Roaming\Python\Python37\site-packages\tensorflow\python\eager\function.py in _maybe_define_function(self, args, kwargs)
   3211
   3212       self._function_cache.missed.add(call_context_key)
-> 3213       graph_function = self._create_graph_function(args, kwargs)
   3214       self._function_cache.primary[cache_key] = graph_function
   3215       return graph_function, args, kwargs

~\AppData\Roaming\Python\Python37\site-packages\tensorflow\python\eager\function.py in _create_graph_function(self, args, kwargs, override_flat_arg_shapes)
   3073             arg_names=arg_names,
   3074             override_flat_arg_shapes=override_flat_arg_shapes,
-> 3075             capture_by_value=self._capture_by_value),
   3076         self._function_attributes,
   3077         function_spec=self.function_spec,

~\AppData\Roaming\Python\Python37\site-packages\tensorflow\python\framework\func_graph.py in func_graph_from_py_func(name, python_func, args, kwargs, signature, func_graph, autograph, autograph_options, add_control_dependencies, arg_names, op_return_value, collections, capture_by_value, override_flat_arg_shapes)
    984         _, original_func = tf_decorator.unwrap(python_func)
    985
--> 986       func_outputs = python_func(*func_args, **func_kwargs)
    987
    988       # invariant: `func_outputs` contains only Tensors, CompositeTensors,

~\AppData\Roaming\Python\Python37\site-packages\tensorflow\python\eager\def_function.py in wrapped_fn(*args, **kwds)
    598         # __wrapped__ allows AutoGraph to swap in a converted function. We give
    599         # the function a weak reference to itself to avoid a reference cycle.
--> 600         return weak_wrapped_fn().__wrapped__(*args, **kwds)
    601     weak_wrapped_fn = weakref.ref(wrapped_fn)
    602

~\AppData\Roaming\Python\Python37\site-packages\tensorflow\python\framework\func_graph.py in wrapper(*args, **kwargs)
    971           except Exception as e:  # pylint:disable=broad-except
    972             if hasattr(e, "ag_error_metadata"):
--> 973               raise e.ag_error_metadata.to_exception(e)
    974             else:
    975               raise

ValueError: in user code:

    C:\Users\robkuble\AppData\Roaming\Python\Python37\site-packages\tensorflow\python\keras\engine\training.py:1462 predict_function  *
        return step_function(self, iterator)
    C:\Users\robkuble\AppData\Roaming\Python\Python37\site-packages\tensorflow\python\keras\engine\training.py:1452 step_function  **
        outputs = model.distribute_strategy.run(run_step, args=(data,))
    C:\Users\robkuble\AppData\Roaming\Python\Python37\site-packages\tensorflow\python\distribute\distribute_lib.py:1211 run
        return self._extended.call_for_each_replica(fn, args=args, kwargs=kwargs)
    C:\Users\robkuble\AppData\Roaming\Python\Python37\site-packages\tensorflow\python\distribute\distribute_lib.py:2585 call_for_each_replica
        return self._call_for_each_replica(fn, args, kwargs)
    C:\Users\robkuble\AppData\Roaming\Python\Python37\site-packages\tensorflow\python\distribute\distribute_lib.py:2945 _call_for_each_replica
        return fn(*args, **kwargs)
    C:\Users\robkuble\AppData\Roaming\Python\Python37\site-packages\tensorflow\python\keras\engine\training.py:1445 run_step  **
        outputs = model.predict_step(data)
    C:\Users\robkuble\AppData\Roaming\Python\Python37\site-packages\tensorflow\python\keras\engine\training.py:1418 predict_step
        return self(x, training=False)
    C:\Users\robkuble\AppData\Roaming\Python\Python37\site-packages\tensorflow\python\keras\engine\base_layer.py:985 __call__
        outputs = call_fn(inputs, *args, **kwargs)
    C:\Users\robkuble\AppData\Roaming\Python\Python37\site-packages\tensorflow\python\keras\engine\sequential.py:386 call
        outputs = layer(inputs, **kwargs)
    C:\Users\robkuble\AppData\Roaming\Python\Python37\site-packages\tensorflow\python\keras\engine\base_layer.py:982 __call__
        self._maybe_build(inputs)
    C:\Users\robkuble\AppData\Roaming\Python\Python37\site-packages\tensorflow\python\keras\engine\base_layer.py:2643 _maybe_build
        self.build(input_shapes)  # pylint:disable=not-callable
    <ipython-input-357-5a69bae7457e>:8 build
        self.exp = self.add_weight(name='Exponent', shape=input_shape, initializer=tf.constant_initializer(value=2.), trainable=True)
    C:\Users\robkuble\AppData\Roaming\Python\Python37\site-packages\tensorflow\python\keras\engine\base_layer.py:614 add_weight
        caching_device=caching_device)
    C:\Users\robkuble\AppData\Roaming\Python\Python37\site-packages\tensorflow\python\training\tracking\base.py:750 _add_variable_with_custom_getter
        **kwargs_for_getter)
    C:\Users\robkuble\AppData\Roaming\Python\Python37\site-packages\tensorflow\python\keras\engine\base_layer_utils.py:145 make_variable
        shape=variable_shape if variable_shape else None)
    C:\Users\robkuble\AppData\Roaming\Python\Python37\site-packages\tensorflow\python\ops\variables.py:260 __call__
        return cls._variable_v1_call(*args, **kwargs)
    C:\Users\robkuble\AppData\Roaming\Python\Python37\site-packages\tensorflow\python\ops\variables.py:221 _variable_v1_call
        shape=shape)
    C:\Users\robkuble\AppData\Roaming\Python\Python37\site-packages\tensorflow\python\ops\variables.py:67 getter
        return captured_getter(captured_previous, **kwargs)
    C:\Users\robkuble\AppData\Roaming\Python\Python37\site-packages\tensorflow\python\distribute\distribute_lib.py:2857 creator
        return next_creator(**kwargs)
    C:\Users\robkuble\AppData\Roaming\Python\Python37\site-packages\tensorflow\python\ops\variables.py:67 getter
        return captured_getter(captured_previous, **kwargs)
    C:\Users\robkuble\AppData\Roaming\Python\Python37\site-packages\tensorflow\python\distribute\distribute_lib.py:2857 creator
        return next_creator(**kwargs)
    C:\Users\robkuble\AppData\Roaming\Python\Python37\site-packages\tensorflow\python\ops\variables.py:67 getter
        return captured_getter(captured_previous, **kwargs)
    C:\Users\robkuble\AppData\Roaming\Python\Python37\site-packages\tensorflow\python\distribute\distribute_lib.py:2857 creator
        return next_creator(**kwargs)
    C:\Users\robkuble\AppData\Roaming\Python\Python37\site-packages\tensorflow\python\ops\variables.py:67 getter
        return captured_getter(captured_previous, **kwargs)
    C:\Users\robkuble\AppData\Roaming\Python\Python37\site-packages\tensorflow\python\eager\def_function.py:685 variable_capturing_scope
        lifted_initializer_graph=lifted_initializer_graph, **kwds)
    C:\Users\robkuble\AppData\Roaming\Python\Python37\site-packages\tensorflow\python\ops\variables.py:264 __call__
        return super(VariableMetaclass, cls).__call__(*args, **kwargs)
    C:\Users\robkuble\AppData\Roaming\Python\Python37\site-packages\tensorflow\python\eager\def_function.py:226 __init__
        initial_value() if init_from_fn else initial_value,
    C:\Users\robkuble\AppData\Roaming\Python\Python37\site-packages\tensorflow\python\ops\init_ops_v2.py:263 __call__
        self.value, dtype=dtype, shape=shape)
    C:\Users\robkuble\AppData\Roaming\Python\Python37\site-packages\tensorflow\python\framework\constant_op.py:264 constant
        allow_broadcast=True)
    C:\Users\robkuble\AppData\Roaming\Python\Python37\site-packages\tensorflow\python\framework\constant_op.py:275 _constant_impl
        return _constant_eager_impl(ctx, value, dtype, shape, verify_shape)
    C:\Users\robkuble\AppData\Roaming\Python\Python37\site-packages\tensorflow\python\framework\constant_op.py:321 _constant_eager_impl
        return _eager_fill(shape.as_list(), t, ctx)
    C:\Users\robkuble\AppData\Roaming\Python\Python37\site-packages\tensorflow\python\framework\constant_op.py:54 _eager_fill
        dims = convert_to_eager_tensor(dims, ctx, dtypes.int32)
    C:\Users\robkuble\AppData\Roaming\Python\Python37\site-packages\tensorflow\python\framework\constant_op.py:98 convert_to_eager_tensor
        return ops.EagerTensor(value, ctx.device_name, dtype)

    ValueError: Attempt to convert a value (None) with an unsupported type (<class 'NoneType'>) to a Tensor.

Do you see, why there is a none type appearing somewhere? Thank you very much!
Best
Robert

A: The first dimension in the input_shape argument of the build method corresponds to the batch size, which typically is None (this means that the network can work with batches of any size). For example, when calling model.predict([[1., 2., 3.]]) the input_shape will be (None, 3).
This means you need to change your implementation of the build method slightly to use input_shape[-1] instead of input_shape
...

  def build(self, input_shape):
    self.exp = self.add_weight(name='Exponent', shape=input_shape[-1], initializer=tf.constant_initializer(value=1.), trainable=True)
    super().build(input_shape)


text:
Q: DATEPART and DATEFIRST alternative for redshift I'm trying to run
SELECT DATEPART(week, date(date)), MIN(date)

in Redshift with the start day being Saturday. I tried using different syntax for SET DATEFIRST but it seems like it's not supported (or I just can't find the correct syntax for redshift). Are there any alternatives available?
The documentation page only shows information for extracting a specific dow (day of week): https://docs.aws.amazon.com/redshift/latest/dg/r_DATE_PART_function.html

A: The date_trunc() function will truncate a timestamp to any number of levels including "week".  If memory serves a date_trunc to a week will set the result to midnight of the Monday before the given timestamp.
Now you want it to truncate to Saturday, 2 days earlier, and this is doable by adding 2 days before the date_trunc and then subtracting 2 days after.  Like this (untested so forgive any typos):
date_trunc('week', <your-timestamp> + interval '2 days') - interval '2 days'


text:
Q: Swift function textfield got focus OSX Currently I am having multiple textfields in a view. If the user taps at one of them there should be a function responding to the event. Is there a way on how to do react (if a textfield got the focus)? I tried it with the NSTextFieldDelegate method but there is no appropriate function for this event.
This is how my code looks at the moment:
class ViewController: NSViewController, NSTextFieldDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

        let textField = NSTextField(frame: CGRectMake(10, 10, 37, 17))
        textField.stringValue = "Label"
        textField.bordered = false
        textField.backgroundColor = NSColor.controlColor()
        view.addSubview(textField)

        textField.delegate = self

        let textField2 = NSTextField(frame: CGRectMake(30, 30, 37, 17))
        textField2.stringValue = "Label"
        textField2.bordered = false
        textField2.backgroundColor = NSColor.controlColor()
        view.addSubview(textField2)

        textField2.delegate = self

    }

    func control(control: NSControl, textShouldBeginEditing fieldEditor: NSText) -> Bool {
        print("working") // this only works if the user enters a charakter
        return true
    }

}

The textShouldBeginEditing function only handles the event if the user tries to enter a character but this isn't what I want. It has to handle the event if he clicks on the textfield.
Any ideas, thanks a lot?
Edit
func myAction(sender: NSView)
{
    print("aktuell: \(sender)")
    currentObject = sender
}

This is the function I want to call.

A: 1) Create a subclass of NSTextField.
import Cocoa

class MyTextField: NSTextField {

    override func mouseDown(theEvent:NSEvent) {
        let viewController:ViewController = ViewController()
        viewController.textFieldClicked()
    }
}

2) With Interface building, select the text field you want to have a focus on.  Navigate to Custom Class on the right pane.  Then set the class of the text field to the one you have just created.
3) The following is an example for ViewController.
import Cocoa

class ViewController: NSViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override var representedObject: AnyObject? {
        didSet {
        // Update the view, if already loaded.
        }
    }

    func textFieldClicked() -> Void {
        print("You've clicked on me!")
    }
}

4) Adding text fields programmatically...
import Cocoa

class ViewController: NSViewController {

    let myField:MyTextField = MyTextField()

    override func viewDidLoad() {
        super.viewDidLoad()

        //let myField:MyTextField = MyTextField()
        myField.setFrameOrigin(NSMakePoint(20,70))
        myField.setFrameSize(NSMakeSize(120,22))
        let textField:NSTextField = NSTextField()
        textField.setFrameOrigin(NSMakePoint(20,40))
        textField.setFrameSize(NSMakeSize(120,22))
        self.view.addSubview(myField)
        self.view.addSubview(textField)
    }

    override var representedObject: AnyObject? {
        didSet {
        // Update the view, if already loaded.
        }
    }

    func textFieldClicked() -> Void {
        print("You've clicked on me!")
    }
}

A: I know it's been answered some while ago but I did eventually find this solution for macOS in Swift 3 (it doesn't work for Swift 4 unfortunately) which notifies when a textfield is clicked inside (and for each key stroke).
Add this delegate to your class:-
NSTextFieldDelegate

In viewDidLoad() add these:-
imputTextField.delegate = self

NotificationCenter.default.addObserver(self, selector: #selector(textDidChange(_:)), name: Notification.Name.NSTextViewDidChangeSelection, object: nil)

Then add this function:-
    func textDidChange(_ notification: Notification) {
        print("Its come here textDidChange")
        guard (notification.object as? NSTextView) != nil else { return }
        let numberOfCharatersInTextfield: Int = textFieldCell.accessibilityNumberOfCharacters()
        print("numberOfCharatersInTextfield = \(numberOfCharatersInTextfield)")
}

Hope this helps others.


text:
Q: Why measuring a differential signal requires a differential probe? I am planning to measure an RS485 signal with an oscilloscope. Since I want to see the signal that is "seen" by the receiver side, I was planning to plug the reference terminal of probe to Sig(-), and the measurement terminal to Sig(+).
However, I saw in many places that a differential probe should be used for measuring differential signals, and I couldn't understand the reason.
Measuring differential signal with single ended probe
What is the reason? Why does a differential probe exist after all, since all measurements in electronics are inherently differential?

A:
I am planning to measure an RS485 signal with an oscilloscope.

And...

In my application, the transmitter circuit's reference ground(also the
  signal's ground) and...

Here's the contradiction. There are two basic signals in RS485 - they are differential and balanced and they need to be so. If they are not then it's not RS485. Then you say that the transmitter's reference ground is also the signal ground and that cannot be so for RS485.
If you are trying to measure a proper RS485 signal, you should not connect one of the transmit lines to the oscilloscope ground reference because that will load imbalance the signal (at best) or at worst short that signal out.
Use two single ended probes for each of the transmitted signals and subtract the signals using the oscilloscope features.


text:
Q: Is there an option to use a public, trusted CA for Secure Cloud SQL communication? Currently when you create a Cloud SQL instance, a self signed certificate is created per the Google Cloud SQL documentation.
Is there a way to choose a different Certificate Authority so my communications are signed by a trusted third party?
Below is a sample of the current cert created by Google when the instance is created.

Common Name: Google Cloud SQL Server CA
Organization: Google, Inc
Country: US
Valid From: November 26, 2018
Valid To: November 23, 2028
Issuer: Google Cloud SQL Server CA, Google, Inc
Serial Number: 0 (0x0)

A: You can connect to your instances using your own CA certificate.
If you have a MySQL instance, follow the steps in this page of the Google Cloud SQL documentation, where it says Connect to your Cloud SQL instance using SSL, but skip the creation of a new client certificate in the beginning.
You need to have the certificate in a text file (such as server-ca.pem) that you'll pass as a flag --ssl-ca=[CERTIFICATE-FILENAME] to the mysql command.
For PostgreSQL, follow these steps instead, again skipping the beginning and using your own CA cert. The cert file would be then indicated when running psql, which takes a string as an argument, including sslrootcert=[CERTIFICATE-FILENAME] in that string.


text:
Q: Http Post Angularjs causing internal server error via Web API I am having a simple http post insert operation from angularjs via web API. But I dont know why I keep getting internal server error. http GET functions are working fine. But for the http post, the data is inserting successfully into database via WebAPI but response from service is not being received. Getting internal server error 500.
WebAPI
 // POST: api/Website/InsertEmployee
[ResponseType(typeof(Employee))]
[HttpPost]
public IHttpActionResult InsertEmployee(Employee employee)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    objCSADBEntities.Employee.Add(employee);
    objCSADBEntities.SaveChanges();

    return CreatedAtRoute("DefaultApi", new { id = employee.EmployeeID }, employee);
}

Angularjs Service
(function () {

    var app = angular.module('myApp');

    app.factory('websiteService', ['$http', function ($http) {
        var factory = [];

        factory.insertEmployee = function (webAPIHostName,employee) {
            var request = $http({
                method: 'POST',
                url: webAPIHostName + '/Website/InsertEmployee',
                data: employee
            })
            return request;
        }

        return factory;
    }
   ]);
})();

Angularjs Controller(Where service is called there I am getting internal server error 500)
var employee = {
    EmployeeID: 1,
    Name: 'Test',
    Phone: '111-111-1111'
};

var insertEmployee = websiteService.insertEmployee($scope.webAPIHostName , employee);
insertEmployee.then(function (response) {
    alert("Submitted Employee Successfully.");
    //success response here
}, function (error) {
    // error handling here
});

A: Can you verify using fiddler or postman that your API call is returning what you expect? Once you can verify the WebAPI is returning the valid HttpStatus (200 to < 400), then you can check your front-end code (angularjs). Call webAPIHostName + '/Website/InsertEmployee' and add the JSON body (assuming its JSON) to your fiddler call. Change the Method to POST, and include in your header
Content-Type: application/json
If your response is not what you expect, try changing your API return from
return CreatedAtRoute("DefaultApi", new { id = employee.EmployeeID }, employee);

to
return Request.CreateResponse(HttpStatusCode.OK, employee);

If you can verify that your POST is working as expected, then check your angularjs.
As for Angularjs, your http call can be updated to
angular.module('myApp').factory('websiteService', ['$http', function ($http) {
    var insertEmployee;

    insertEmployee = function (webAPIHostName, employee) {
        return $http.post(webAPIHostName + '/Website/InsertEmployee', JSON.stringify(employee));
    }

    return {
        insertEmployee: insertEmployee
    };
}]);

// Angular Controller

var employee = {
    EmployeeID: 1,
    Name: 'Test',
    Phone: '111-111-1111'
};

websiteService.insertEmployee($scope.webAPIHostName , employee)
    .then(function (response) {
        alert("Submitted Employee Successfully.");
        //success response here
      }, function (error) {
        // error handling here
    });


text:
Q: How do you delete all the nodes on the right of a linked list when a value greater than 'x' is encountered? I don't see solution to this specific question on stackoverflow. So I'm posting this.
My requirement is to delete all the nodes on the right of a linked list when a value greater than 'x' is encountered?
For Ex.
Sample Input:
Linked list has values: 5 1 2 6 and x = 5
Output: 5 1 2
Sample Input
Linked list has values: 7 1 2 6 and x = 6
Output: null (since 7 is greater than 6, it should delete all the nodes on the right)
Sample Input:
Linked list has values: 5 4 7 6 and x = 6
Output: 5 4
I came up with this solution, but I'm trying to find an optimal solution
//head is the root node, nodes greater that "value" should be deleted
      Node Delete(Node head, int value) {
      // Complete this method

       Node cur = head;
       Node prev = null;

      if(cur == null)
           return head;

     if(cur != null && cur.data > value )
       {
         while(cur != null)
         {
          prev = cur;
          cur = cur.next;
         }
          prev.next = cur;
          head = prev;
          return head;
       }
      else
      {
         while(cur != null && cur.data <= value)
         {
          prev = cur;
          cur = cur.next;
         }
         if(cur != null && cur.data > value)
         {
           while(cur != null)
           {
               cur = cur.next;
           }
           prev.next = cur;
           return head;
         }
          prev.next = null;
          return head;
      }

    }

A: Here is a simple O(n) solution in Javascript-style pseudocode,
with several identifiers renamed for clarity.
function deleteGreater(head, value) {
    if (head == null) return null;
    if (head.data > value) {
        deallocate(head); //discard the entire list
        return null;
    }

    var current = head;

    while (true) {
        if (current.next == null) return head; //end of list
        if (current.next.data > value) break;
        current = current.next;
    }

    deallocate(current.next); //discard the rest of the list
    current.next = null;
    return head;
}

I trust you can convert it to any language you want.
For languages with garbage collection, you can remove the deallocate() calls.
For languages without garbage collection, override the object's deallocation method to make sure that it also deallocates the next property.

A: In language like Java which have garbage collection, it is as simple as to set the next of last element to null which in worst case will be of O(n) (which will happen when matched with last element)
Node deleteGreaterThan(Node head, int value){
   if(head==null || head.data>value)return null;//if head is itself greater than value
   Node temp = head;
   while(temp.next != null && temp.next.data<=value){
      temp= temp.next;
   }
   temp.next = null;
   return head;
}

head = deleteGreaterThan(head, 5);

I guess in language like c, you might have to explicitly delete each element and free the memory, no experience with c, so can't say much, even in that case it will only be O(n)

A: Like @100rabh said, in a language without garage collection you need to free every single node you allocated.  Here is an example in C of how to do that.  Notice that calling Delete is still O(n) because we actually update the previous node's next pointer while freeing the current node.
#include <malloc.h>
#include <stdio.h>

struct _Node {
  struct _Node *next;
  int data;
};

typedef struct _Node Node;

Node* Build(int value)
{
  int i;
  Node *ptr, *head=NULL;

  for (i=1; i<value; i++)
  {
    if(head==NULL)
    {
      head=malloc(sizeof(Node));
      ptr=head;
    }
    else
    {
      ptr->next=malloc(sizeof(Node));
      ptr=ptr->next;
    }
    ptr->data=i;
    ptr->next=NULL;
    printf("Build: node=%p {data=%d next=%p}\n", ptr, ptr->data, ptr->next);
  }
  return head;
}

void Print(Node *head)
{
  Node *ptr=head;
  while(ptr!=NULL)
  {
    printf("Print: node=%p {data=%d, next=%p}\n", ptr, ptr->data, ptr->next);
    ptr=ptr->next;
  }
}

/*
 * We can't pass head or ptr->next directly
 * Because then we can't update it's value when we free what it points to
 * So we pass the pointer to head or ptr->next instead
 * Here we actually update head or ptr->next to point to the next node until we are finished
 */
void Free(Node **ptr)
{
  Node *temp;

  if(ptr==NULL) return;

  while(*ptr!=NULL)
  {
    temp=*ptr;
    *ptr=(*ptr)->next;

    printf("Free: node=%p {data=%d next=%p}\n",temp,temp->data,temp->next);
    temp->data=-temp->data;
    temp->next=NULL;
    free(temp);
  }
}

/*
 * We can't pass head or ptr->next directly
 * Because then we can't update it's value when we free what it points to
 * So we pass the pointer to head or ptr->next instead
 * Nothing gets updated in this function - Free does all the updating
 */
void Delete(Node **ptr, int value)
{
  if(ptr==NULL) return;

  while(*ptr!=NULL)
  {
    if((*ptr)->data>value)
    {
      printf("Delete: node=%p {data=%d node=%p}\n",*ptr,(*ptr)->data,(*ptr)->next);
      Free(ptr);
      return;
    }
    ptr=&(*ptr)->next;
  }
}

int main(void)
{
  Node *head=Build(10);
  Print(head);
  Delete(&head, 5);
  Print(head);
  Free(&head);
  return 0;
}


text:
Q: Is there a convex polyhedron without triangulation? I'm thinking about such question.

It there a convex polyhedron $P$ that is not a union of disjoint simplices which vertices are vertices of $P$?

It's not true for convex polygons.
I belive that answer is "yes", but can't imagine a proper example.
P.S. The question arose when some of my students tried to prove Carathéodory's theorem in $\mathbb{R}^3$.


text:
Q: I'm looking for a book about teens with powers The book is about the following characters:

*

*A guy who has flight, super strength and invulnerability to blunt damage.

*A super smart girl.

*A guy who has a black hole / wormhole in his abdomen.

*A girl with cat-like abilities.

*A girl who sticks to things.

It starts in a coffee shop with a poetry slam followed by a fight with an ice-wielding guy. It turns out that the kids are part of an experiment where a serum replaces the polio vaccine given to them as kids.
I've been looking for this book for years, if anyone could help that would be awesome.


text:
Q: Unity - Shift to sprint friends, new dev asking, I looked through a lot of sites and tried a lot of different scripts separate scripts from player movement and other scripts to no avail and came up with this as a conglomeration of what I've seen but it also doesn't work, at all. I couldn't find anything in subreddits or this. I know my normal movement code is probably ugly but it works. I hope you can help thank you!
TO clarify this is making the player sprint while holding down the shift key thank you for those who reminded me to elaborate.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(UnityEngine.AI.NavMeshAgent))]
public class PlayerMovement : MonoBehaviour
{
    UnityEngine.AI.NavMeshAgent agent;
    private Rigidbody rb;
    public float movementSpeed = 5.0f;
    public float clockwise = 1000.0f;
    public float counterClockwise = -5.0f;
    public float Speed = 5.0f;
    public Vector3 jump;
    public float jumpForce =1.0f;
    public float shiftSpeed = 10.0f;

    public bool isGrounded;

    void Start()
    {
        rb = GetComponent<Rigidbody>();
        jump = new Vector3(0.0f, 1.0f, 0.0f);
        agent = GetComponent<UnityEngine.AI.NavMeshAgent>();
    }

    void OnCollisionStay()
    {
        isGrounded = true;
    }

    void Update()
    {
        if (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.UpArrow))
        {
            transform.position += transform.forward \* Time.deltaTime \* movementSpeed;

        }
        else if (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.UpArrow) && Input.GetKey(KeyCode.LeftShift))
        {
            transform.position += transform.forward \* Time.deltaTime \* shiftSpeed;
        }
        else if (Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.DownArrow))
        {
            transform.position -= transform.forward \* Time.deltaTime \* movementSpeed;

        }
        else if (Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.DownArrow) && Input.GetKey(KeyCode.LeftShift))
        {
            transform.position += transform.forward \* Time.deltaTime \* shiftSpeed;
        }
        else if (Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow))
        {
            GetComponent<Rigidbody>().position += Vector3.left \* Time.deltaTime \* movementSpeed;
        }
        else if (Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow) && Input.GetKey(KeyCode.LeftShift))
        {
            transform.position += transform.forward \* Time.deltaTime \* shiftSpeed;
        }
        else if (Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow))
        {
            GetComponent<Rigidbody>().position += Vector3.right \* Time.deltaTime \* movementSpeed;
        }
        else if (Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow) && Input.GetKey(KeyCode.LeftShift))
        {
            transform.position += transform.forward \* Time.deltaTime \* shiftSpeed;
        }
        if (Input.GetKeyDown(KeyCode.Space) && isGrounded)
        {
            rb.AddForce(jump \* jumpForce, ForceMode.Impulse);
            isGrounded = false;
        }
    }
}

A: I assume what you are asking is "How to make my player move faster when I hold down the shift key?"
I would suggest having two constants for walking speed and running speed. Then another variable that changes based on if the shift key is held:
private const float walkSpeed = 5.0f;
private const float runSpeed = 10.0f;

private float moveSpeed = walkSpeed;    // Our current movement speed

//...

void Update() {

    //...

    if (Input.GetKey(KeyCode.LeftShift) {
        // Set current speed to run if shift is down
        moveSpeed = runSpeed;
    }
    else {
        // Otherwise set current speed to walking speed
        moveSpeed = walkSpeed;
    }

}


text:
Q: Increasing the number of outbound TCP connections I am developing a small test client for websockets. I am using Ubuntu 11.04 . I have read
 https://stackoverflow.com/questions/410616/increasing-the-maximum-number-of-tcp-ip-connections-in-linux and I have done the following
sudo sysctl -w  net.ipv4.tcp_fin_timeout=10
sysctl -w net.ipv4.ip_local_port_range="1024 65535"

As I understand these are for inbound connections and not outbound.
When I type
ulimit -n
unlimited

My client and servers run on different boxes. Even with all the above I am not able to cross beyound 1000 connections from a box . If there is a different tip let me know
ANSWER
I figured this by typing ulimit -a which shows all the kernel limits .
ulimit -n
unlimited

while
ulimit -a

returns the value for nofile as 1024. I set the limits in the /etc/security/limits.conffile in the format
 <user> soft nofile 8192
 <user> hard nofile 65000

and things worked for user

A: I figured this by typing ulimit -a which shows all the kernel limits . ulimit -n returns unlimited while ulimit -a returns the value for nofile as 1024. I set the limits in the /etc/security/limits.conf file in the format **  soft nofile 8192  hard nofile 65000 and things worked


text:
Q: dynamic tsql in sql 2005 Hi i am using the following dynamic sql:
declare @cmd nvarchar(4000)

set @cmd=

'select ''exec msdb.dbo.sp_update_job @job_id=''''''
+ convert(nvarchar(255), job_id)+ '''''',

@owner_login_name=''''sa'''';''
from msdb..sysjobs'

exec sp_executesql @cmd

but all it is doing is printing as exec .......
I want to execute the results not just print it.
What should i do?
Regards
Manjot

A: Remove the 'Select' !  (and also remove some escaped single quotes)
In other words...
set @cmd=
   'exec msdb.dbo.sp_update_job @job_id='''
   + convert(nvarchar(255), job_id)
   + ''', @owner_login_name=''sa'';'

Note: not quite sure where this last thing fits (probably at the end of the sp_update_job statement.
   -- from msdb..sysjobs'

Essentially what was going on, with the SELECT statement was that the dynamic SQL being executed was a select statement which happen to select a string dynamically crafted.  SQL would then print that string, just as if the SELECT statement had been, say:
select 'Once upon a time, a very poor lumberjack..."

(Whatever is in the string after select doesn't affect SQL in any way)
Now, as is more obvious with Remus' nice formatting of the question, the dyanamic SQL statement itself seems to be wrong, but at least SQL will try to execute it, now...

A: How about:
DECLARE @sql NVARCHAR(MAX);

SELECT @sql = COALESCE(@sql, '') + '
    EXEC msdb.dbo.sp_update_job @job_id = '''
    + CONVERT(NVARCHAR(255), job_id)
    + ''', @owner_login_name = ''sa'';'
FROM msdb.dbo.sysjobs;

EXEC sp_sqlexec @sql;

NOTE that sp_sqlexec is undocumented and unsupported.  To do this in a supported way, why not just create a cursor, it is much easier to follow and debug (no sea of red and no "invisible" SQL):
DECLARE @j UNIQUEIDENTIFIER;

DECLARE c CURSOR FOR
    SELECT job_id FROM msdb.dbo.sysjobs;

OPEN c;

FETCH NEXT FROM c INTO @j;

WHILE @@FETCH_STATUS = 0
BEGIN
    EXEC msdb.dbo.sp_update_job
        @job_id = @j,
        @owner_login_name = 'sa';

    FETCH NEXT FROM c INTO @j;
END

DEALLOCATE c;

Or ever easier, since msdb.dbo.sysjobs is not technically a system table, and you can edit it directly:
UPDATE msdb.dbo.sysjobs
    SET owner_sid = SUSER_SID('sa');


text:
Q: c#- Rollback database before deleting I have Table Student: ID, Name, Image, PathFileImage.
There are 2 cases when delete record from Student:

*

*Case 1: when delete record, if delete image file of student by PathFileImage successful then done.

*Case 2: when delete record, if delete image file of student by PathFileImage failed then rollback database before deleting.

Ex: There are 10 records in Student. I delete 3 records.

*

*In case 1: after deleting, there are 7 records.

*In case 2: after deleting, there are still 10 records.

Could anyone help me to use Transaction to rollback database in case 2?
Thanks all so much for reading!


text:
Q: boost conditional not working on thread safe queue with two producers and one consumer I have two threads that add to a "thread safe" queue. However when the second thread attempts to "push" contents. The consumer is not notified that contents are available. The queue continues to grow but the notify_one() never notifies the conditional in the consuming method. Why is this?
#ifndef CONCURRENT_QUEUE_H
#define CONCURRENT_QUEUE_H

#include <queue>
#include <boost/thread.hpp>

template<typename Data>
class concurrent_queue {
private:
    std::queue<Data> the_queue;
    mutable boost::mutex the_mutex;
    boost::condition_variable the_condition_variable;
public:
    void push(Data const& data) {
        boost::mutex::scoped_lock lock(the_mutex);
        the_queue.push(data);
        lock.unlock();
        the_condition_variable.notify_one();
    }

    void wait_and_pop(Data& popped_value) {
        boost::mutex::scoped_lock lock(the_mutex);
        while(the_queue.empty()) {
            the_condition_variable.wait(lock);
        }

        popped_value=the_queue.front();
        the_queue.pop();
    }
};
#endif

This code does work in Fedora 14 using boost 1.51.0, however it does not work in boost 1.50.0 in windows 7.
INCLUDEPATH += \
    . \
    /home/mehoggan/Devel/x86-fps/boost_1_50_0/include

LDFLAGS += -Wl,-rpath=/home/mehoggan/Devel/x86-fps/boost_1_50_0/lib

LIBS += \
    -L/home/mehoggan/Devel/x86-fps/boost_1_50_0/lib \
    -lboost_system \
    -lboost_thread \
    -lz

#ifndef CONCURRENT_QUEUE_H
#define CONCURRENT_QUEUE_H

#include <queue>
#include <boost/thread.hpp> // Using boost 1.50.0

template<typename Data>
class concurrent_queue {
private:
    std::queue<Data> the_queue;
    mutable boost::mutex the_mutex;
    boost::condition_variable the_condition_variable;
public:
    void push(Data const& data) {
        boost::mutex::scoped_lock lock(the_mutex);
        the_queue.push(data);
        lock.unlock();
        the_condition_variable.notify_all();
    }

    void wait_and_pop(Data& popped_value) {
        boost::mutex::scoped_lock lock(the_mutex);
        while(the_queue.empty()) {
            the_condition_variable.wait(lock);
        }

        popped_value=the_queue.front();
        the_queue.pop();
    }
};
#endif

concurrent_queue<int> the_queue;

void thread1func() {
    do {
        the_queue.push(1);
    } while (true);
}

void thread2func() {
    do {
        the_queue.push(2);
    } while (true);
}

void thread3func() {
    do {
        int read;
        the_queue.wait_and_pop(read);

        std::cout << "I read from thread " << read << std::endl;
    } while (true);
}

int main(int argc, char *argv[]) {
    boost::thread thread1 = boost::thread(thread1func);
    boost::thread thread2 = boost::thread(thread2func);
    boost::thread thread3 = boost::thread(thread3func);

    thread1.join();
    thread2.join();
    thread3.join();
}

A: Your Makefile doesn't seem to use -pthread/-mthreads. In general don't expect your code to work at all if you are not asking for the compiler to generate multi-threaded code.


text:
Q: How to fix Google DataFlow Pipeline (args) null pointer exception? I'm trying to run a really simple dataflow job, just taking some data in BigQuery, processing it a bit and putting it in a new bigquery table
Pipeline p = Pipeline.create(
                PipelineOptionsFactory.fromArgs(args).withValidation().create());
p.apply(BigQueryIO.Read.fromQuery("SELECT * FROM realtime.status_6_output_11"));
        p.run();
However whenever I run it I get the following pretty undescriptive NullPointerException:
Exception in thread "main" java.lang.NullPointerException
    at java.util.regex.Matcher.getTextLength(Matcher.java:1283)
    at java.util.regex.Matcher.reset(Matcher.java:309)
    at java.util.regex.Matcher.<init>(Matcher.java:229)
    at java.util.regex.Pattern.matcher(Pattern.java:1093)
    at com.google.cloud.dataflow.sdk.util.IOChannelUtils.getFactory(IOChannelUtils.java:174)
    at com.google.cloud.dataflow.sdk.io.BigQueryIO$Read$Bound.apply(BigQueryIO.java:553)
    at com.google.cloud.dataflow.sdk.io.BigQueryIO$Read$Bound.apply(BigQueryIO.java:387)
    at com.google.cloud.dataflow.sdk.runners.PipelineRunner.apply(PipelineRunner.java:74)
    at com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner.apply(DirectPipelineRunner.java:247)
    at com.google.cloud.dataflow.sdk.Pipeline.applyInternal(Pipeline.java:367)
    at com.google.cloud.dataflow.sdk.Pipeline.applyTransform(Pipeline.java:274)
    at com.google.cloud.dataflow.sdk.values.PBegin.apply(PBegin.java:47)
    at com.google.cloud.dataflow.sdk.Pipeline.apply(Pipeline.java:156)
    at com.noraway.conductor.NormalizedPipeline.main(NormalizedPipeline.java:42)

I think there's a problem with my command line arguments (don't have any right now) but I'm not sure what that would be.

A: It looks like there is a missing --tempLocation for BigQuery to use.  The obscure error message is fixed as part of https://github.com/GoogleCloudPlatform/DataflowJavaSDK/issues/313.


text:
Q: Sum daily values into monthly values I am trying to sum daily rainfall values into monthly totals for a record over 100 years in length. My data takes the form:
Year     Month     Day     Rain
1890       1        1         0
1890       1        2       3.1
1890       1        3       2.5
1890       1        4      15.2

In the example above I want R to sum all the days of rainfall in January 1890, then February 1890, March 1890.... through to December 2010. I guess what I'm trying to do is create a loop to sum values. My output file should look like:
Year    Month    Rain
1890      1       80.5
1890      2       72.4
1890      3       66.8
1890      4       77.2

Any easy way to do this?
Many thanks.

A: You can use dplyr for some pleasing syntax
library(dplyr)

df %>%
  group_by(Year, Month) %>%
  summarise(Rain = sum(Rain))

A: In some cases it can be beneficial to convert it to a time-series class like xts, then you can use functions like apply.monthly().
Data:
df <- data.frame(
  Year = rep(1890,5),
  Month = c(1,1,1,2,2),
  Day = 1:5,
  rain = rexp(5)
)

> head(df)
      Year Month Day      rain
    1 1890     1   1 0.1528641
    2 1890     1   2 0.1603080
    3 1890     1   3 0.5363315
    4 1890     2   4 0.6368029
    5 1890     2   5 0.5632891

Convert it to xts and use apply.monthly():
library(xts)
dates <- with(df, as.Date(paste(Year, Month, Day), format("%Y %m %d")))
myXts <- xts(df$rain, dates)

> head(apply.monthly(myXts, sum))
                [,1]
1890-01-03 0.8495036
1890-02-05 1.2000919


text:
Q: plotting glm interactions: "newdata=" structure in predict() function My problem is with the predict() function, its structure, and plotting the predictions.
Using the predictions coming from my model, I would like to visualize how my significant factors (and their interaction) affect the probability of my response variable.
My model:
m1  <-glm ( mating ~  behv * pop +
                      I(behv^2) * pop + condition,
                      data=data1, family=binomial(logit))

mating: individual has mated or not (factor, binomial: 0,1)
pop: population (factor, 4 levels)
behv: behaviour (numeric, scaled & centered)
condition: relative fat content (numeric, scaled & centered)
Significant effects after running the glm:
pop1
condition
behv*pop2
behv^2*pop1
Although I have read the help pages, previous answers to similar questions, tutorials etc., I couldn't figure out how to structure the newdata= part in the predict() function. The effects I want to visualise (given above) might give a clue of what I want: For the "behv*pop2" interaction, for  example, I would like to get a graph that shows how the behaviour of individuals from population-2 can influence whether they will mate or not (probability from 0 to 1).

A: Really the only thing that predict expects is that the names of the columns in newdata exactly match the column names used in the formula. And you must have values for each of your predictors. Here's some sample data.
#sample data
set.seed(16)
data <- data.frame(
    mating=sample(0:1, 200, replace=T),
    pop=sample(letters[1:4], 200, replace=T),
    behv = scale(rpois(200,10)),
    condition = scale(rnorm(200,5))
)

data1<-data[1:150,]     #for model fitting
data2<-data[51:200,-1]  #for predicting

Then this will fit the model using data1 and predict into data2
model<-glm ( mating ~  behv * pop +
    I(behv^2) * pop + condition,
    data=data1,
    family=binomial(logit))

predict(model, newdata=data2, type="response")

Using type="response" will give you the predicted probabilities.
Now to make predictions, you don't have to use a subset from the exact same data.frame. You can create a new one to investigate a particular range of values (just make sure the column names match up. So in order to explore behv*pop2 (or behv*popb in my sample data), I might create a data.frame like this
popbbehv<-data.frame(
    pop="b",
    behv=seq(from=min(data$behv), to=max(data$behv), length.out=100),
    condition = mean(data$condition)
)

Here I fix pop="b" so i'm only looking at the pop, and since I have to supply condition as well, i fix that at the mean of the original data. (I could have just put in 0 since the data is centered and scaled.) Now I specify a range of behv values i'm interested in. Here i just took the range of the original data and split it into 100 regions. This will give me enough points to plot. So again i use predict to get
popbbehvpred<-predict(model, newdata=popbbehv, type="response")

and then I can plot that with
plot(popbbehvpred~behv, popbbehv, type="l")

Although nothing is significant in my fake data, we can see that higher behavior values  seem to result in less mating for population B.


text:
Q: Correctly simulating a Poisson process at population level I have a string sequence that undergoes random mutation per position with $P_{mutate}=0.001$. So to determine mutation of a specific position I can use the following, where $x$ is a uniformly distributed random variable in the range $[0,1]$:
$x \leq P_{mutate}$
As I would rather than generate random numbers per string element, I would like to calculate first the number of positions that will undergo mutation given $P_{mutate}$ and the sequence length. To do this, I reckon that (where $n$ is the number of mutated positions and $l$ is the sequence length):
$n = \lfloor\frac{P_{mutate}\cdot l}{x}\rfloor$
But this is clearly wrong, as the result is completely different. I am looking for a computationally simple solution that avoids generating random variables per position.


text:
Q: How to limit OpenERP "my timesheet" project list? I'm setting up OpenERP 7.0 using timesheet module, and I want that any user can see only projects assigned to him when he writes his timesheet, using section My timesheet.
My problem is that when I log as a user, in My timesheet > tab Summary, when I and Add a line I can see all projects and analytic accounts.  But, If I use My timesheet > tab Details, I can see only internal projects.
I tried

*

*ACL section (as said here),

*group properties,

*user technical options,

but I failed. The different behaviour of tabs Summaryand Details make me think there is some error in OpenERP code.
How can I managed the project listed for a user?

A: You have to use domain rules.
You can find a good answer and explanation here: Understanding OpenERP Domain Filter?
To configure a domain rule, go to Settings >> Technical >> Security >> Record Rules
In other hand, if you want to create your domain rules as you install your module, it might be useful to have them stored in a XML file.
I'll leave you an example of one I'm using.
<?xml version="1.0"?>
<openerp>
    <data>
        <!-- ########################### OPINIONS ############################# -->
        <!-- everyone can see issued opinions, but can't edit them -->
        <record id="proc_uc_see_issued_opinions_rule" model="ir.rule">
            <field name="name">See issued opinions rule</field>
            <field name="model_id" ref="model_opinion"/>
            <field name="domain_force">[('state','=','issued')]</field>
            <field name="perm_read" eval="True"/> <!-- can see -->
            <field name="perm_write" eval="False"/> <!-- can't change it -->
            <field name="perm_unlink" eval="False"/>
            <field name="perm_create" eval="False"/>
            <!--<field name="global" eval="True"/>-->
            <field name="global" eval="0" />
            <field name="groups" eval="[(6,0,[ref('processos_uc.group_processos_user')])]"/>
        </record>

        <!-- consultant can see and edit his opinion requests -->
        <record id="proc_uc_see_own_opinions_rule" model="ir.rule">
            <field name="name">See own opinions rule</field>
            <field name="model_id" ref="model_opinion"/>
            <field name="domain_force">['|',('consultant_uid','=',user.id),('consultant_uid','=',False)]</field>
            <field name="perm_read" eval="True"/>
            <field name="perm_write" eval="True"/>
            <field name="perm_unlink" eval="True"/>
            <field name="perm_create" eval="True"/>
            <field name="global" eval="0" />
            <field name="groups" eval="[(6,0,[ref('processos_uc.group_processos_user')])]"/>
        </record>
(...)
        <!-- managers can do anything on opipions! -->
        <record id="proc_uc_managers_can_do_anything_opinions_rule" model="ir.rule">
            <field name="name">Managers can do anything on opinions rule</field>
            <field name="model_id" ref="model_opinion"/>
            <field name="domain_force">[(1,'=',1)]</field>
            <field name="perm_read" eval="True"/>
            <field name="perm_write" eval="True"/>
            <field name="perm_unlink" eval="True"/>
            <field name="perm_create" eval="True"/>
            <field name="global" eval="0" />
            <field name="groups" eval="[(6,0,[ref('processos_uc.group_processos_manager')])]"/>
        </record>
     </data>
</openerp>

Hope this will help!

A: Try this:
You can get the project list whichever employee has assigned.
def default_project(self, cr, uid, context=None):
    cr.execute('''select project_id from project_team_members where uid=%s and is_active='t' limit 1''',(uid,))
    project_id=cr.fetchone()
    if project_id:
        return project_id and project_id[0] or False
    return False

_defaults = {
        'project_id':default_project,
        }


text:
Q: The term 'else' is not recognized as the name of a cmdlet We have an issue with the If / Else structure in PowerShell. Our scripts that work on former Windows versions (up to Windows Server 2012 R2), do not work on the newer versions.
To simplify things, let's take an example from the PowerShell help (Get-Help about_If):
if ($a -gt 2)
{
    Write-Host "The value $a is greater than 2."
}
else
{
    Write-Host "The value $a is less than or equal to 2, is not created or is not initialized."
}

On Windows Server 2012 R2 (PowerShell version based on $PSVersionTable.PSVersion is 5.1.14409.1018) the result is, as expected:
The value  is less than or equal to 2, is not created or is not initialized.

However, newer PowerShell Versions, like 5.1.14393.2879 (Windows Server 2016) or 5.1.17763.503 (Windows Server 2019) seem not to understand the same syntax:
else : The term 'else' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

Note, that event these newer PowerShell versions have the very same example for If / Then, so officially nothing should have been changed.
Yes, I know I could easily re-write the condition as:
if ($a -gt 2) {
    Write-Host "The value $a is greater than 2."
} else {
    Write-Host "The value $a is less than or equal to 2, is not created or is not initialized."
}

But we have a lot of scripts, and I really would like to avoid to revisit, and fix and test all of them, if there is a way to have PowerShell to understand the other format either. Is this behavior documented officially in the PowerShell language specification, or should we consider it to be a bug?
The example we currently have in the web-based documentation, has another format, but it does not work either (same error) with the newer versions:
if ($a -gt 2) {
    Write-Host "The value $a is greater than 2."
}
else {
    Write-Host ("The value $a is less than or equal to 2," + " is not created or is not initialized.")
}

I've found a page discussing a similar issue, but it does not match exactly our case.
Very annoying. Thanks for your help in advance.
Update 1: If I save the script into a .ps1 file, and execute the file, then it seems to work. I have only the problem, if I copy / paste the code block from the editor (Notepad in my case).
Update 2:
$PSVersionTable results:
Name                           Value
----                           -----
PSVersion                      5.1.17763.503
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.17763.503
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1

By copy-pasting the condition from Notepad into the PowerShell console I have this error in the newer versions (I had no error with  Windows Server 2012 R2):
if ($a -gt 2)
>> {
>>     Write-Host "The value $a is greater than 2."
>> }
PS C:\Scripts> else
else : The term 'else' is not recognized as the name of a cmdlet, function, script file, or operable program. Check
the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ else
+ ~~~~
    + CategoryInfo          : ObjectNotFound: (else:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

Update 3:
As always, the devil is in the details. I've pasted the content into the console by using the right mouse button, since in WS2012R2 (and older) the standard key combination for pasting Ctrl+V did not work, and resulted in a ^V. So I got used to pasting the script into the console by clicking the right mouse button (and on WS2012R2 selecting Paste from the context menu). Apparently, the paste funtionality has been implemented differently, and the content is interpeted line-by-line for the right-click, but interpreted as a block when pasted using Ctrl+V. Nice. Have learned something new again. Thank you all for your support, and for the ideas!

A: This is true in any version when run at the command prompt, but when run in a script it should work fine.  I've confirmed this in Server 2016, with a script, even with a blank line before else, and in unicode, utf8, or ansi format.
Demo at the command prompt, pasting by clicking right mouse button.  Using control v to paste works.
Ok, if I paste with control v in the ISE, it actually works without error.
PS C:\Users\js> if (0) { 'ran if' }

PS C:\Users\js> else { 'ran else' }

else : The term 'else' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify
that the path is correct and try again.
At line:1 char:1
+ else { 'else' }
+ ~~~~
    + CategoryInfo          : ObjectNotFound: (else:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

A: I'm posting my test outcome as an answer since there is not enough space in the comment section (hope it's ok for the community).
Tested in PowerShell console on Windows Server 2019 (Version 1809 OS Build 17763.107).
> $PSVersionTable

Name                           Value
----                           -----
PSVersion                      5.1.17763.1
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.17763.1
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1

Ran example on PowerShell prompt:
> if ($a -gt 2)
>> {
>>     Write-Host "The value $a is greater than 2."
>> }
>> else
>> {
>>     Write-Host "The value $a is less than or equal to 2, is not created or is not initialized."
>> }
The value  is less than or equal to 2, is not created or is not initialized.

Code is working.
UPDATE 1
Also tested in Windows Server 2016 (Version 1607, OS Build 14393.2969):
PS C:\> $PSVersionTable

Name                           Value
----                           -----
PSVersion                      5.1.14393.2969
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.14393.2969
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1

Ran example on PowerShell prompt:
PS C:\> if ($a -gt 2)
>> {
>>     Write-Host "The value $a is greater than 2."
>> }
>> else
>> {
>>     Write-Host "The value $a is less than or equal to 2, is not created or is not initialized."
>> }
The value  is less than or equal to 2, is not created or is not initialized.

UPDATE 2
The problem is situated in how you paste the code to your PowerShell console. If you use Ctr+V (which was added in newer versions of the standard PowerShell console host) the code is pasted as the whole block:
PS C:\> if ($a -gt 2)
>> {
>>     Write-Host "The value $a is greater than 2."
>> }
>> else
>> {
>>     Write-Host "The value $a is less than or equal to 2, is not created or is not initialized."
>> }

But if you're pasting the code via right click - edit - paste to the PowerShell console it seems that the, if block and else block, are pasted in the operations, and it seems that there is a CRLF "injected" after the if block. So the if gets computed and * afterward* the else block is pasted to the console, which of course triggers the error:
PS C:\> if ($a -gt 2)
>> {
>>     Write-Host "The value $a is greater than 2."
>> }
PS C:\> else
else : The term 'else' is not recognized as the name of a cmdlet, function, script file, or operable program. Check
the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ else
+ ~~~~
    + CategoryInfo          : ObjectNotFound: (else:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

PS C:\> {
>>     Write-Host "The value $a is less than or equal to 2, is not created or is not initialized."
>> }

The problem can also be seen since there is a new prompt PS C:\> at the else and also at the scope of the else.
This problem is related to the "standard" PowerShell console host (is not PowerShell engine related). If you perform the copy operations (via mouse or shortcut) in the PowerShell ISE the problem doesn't occur.
Hope that helps.

A: Powershell seems to consider the else block as separate statement, not attached to if.
Modified my code to use the end of the if and else in the same line.
if (condition) {
 } else {
   #else code
}

A: I have the same issue
Interesting that if you open posh and run the following to not load your profile:
start-process powershell.exe -Args -noprofile

and then paste in your if -> then, in the new window and formatted the old way, then it works fine...
PS C:\WINDOWS\system32> $this = "blah"
>> $that = "blah2"
>>
>> if ($this) {
>>     $that
>> }
>> else {
>>     $that
>> }
blah2

PS C:\WINDOWS\system32> $psversiontable

Name                           Value
----                           -----
PSVersion                      5.1.19041.1682
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.19041.1682
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1

A: I have found Ctrl+V works &
Right Mouse Button Click on the Address Bar > Edit > Paste does not


text:
Q: How to remember authorization when parsing a site on nodejs cookies i go to the site and look for an authorization form, if I find it, then I log in, if not, then I do the actions I need
let cookie_ = fs.readFileSync("cookies.json");//I am looking for a file with saved cookies
cookie = JSON.parse(cookie_);//Converting to json

nightmare
.goto('https://site.ru/login')//I go to the site
.cookies.set(cookie)//I substitute cookies from the file
.evaluate(function () {
    return document.querySelector('input[id="email"]');//I am looking for a field to enter mail
})
.then(function (page) {
    if(page) {//I check if there is a field for entering mail
        f().then(function (cookies) {//We get the result from the function
            require('fs').writeFileSync(//And write to file
                'cookies.json',
                JSON.stringify(cookies)
            );
        })

    } else {
        console.log('You are logged in');
    }
})
async function f() {//I call the function if we are not authorized
        return new Promise((resolve, reject) => {
            nightmare
                .goto('https://site.ru/login')
                .type('input[id="email"]', 'login')//Enter mail
                .type('input[id="password"]', 'passord')//Enter your password
                .click('.btn.btn-danger')//Click on the authorization button
                .wait(2000)//We wait 2 seconds
                .cookies.get()//We receive cookies
                .then(resolve)

        });
    }

The file is created, cookies are written, but with the next attempts to run the script, the authorization form still appears
I also tried first to go to - goto('about: blank') then set cookies and then go to goto('https://site.ru/login')
Error - UnhandledPromiseRejectionWarning: Error: Setting cookie failed

A: Unfortunately, it was not possible to solve the problem through nightmare
Solved with puppeteer
Example - saving cookies to file
const puppeteer = require('puppeteer')
const fs = require('fs');

(async () => {
  const browser = await puppeteer.launch()
  const page = await browser.newPage()

  await page.goto('https://github.com/login')

  await page.type('#login_field', process.env.GITHUB_USER)
  await page.type('#password', process.env.GITHUB_PWD)

  await page.waitForSelector('.js-cookie-consent-reject')
  await page.click('.js-cookie-consent-reject')
  await page.$eval('[name="commit"]', (elem) => elem.click())
  await page.waitForNavigation()

  const cookies = await page.cookies()
  const cookieJson = JSON.stringify(cookies)

  fs.writeFileSync('cookies.json', cookieJson)

  await browser.close()
})()

Reading cookies from a file
const puppeteer = require('puppeteer')
const fs = require('fs');

(async () => {
  const browser = await puppeteer.launch()
  const page = await browser.newPage()

  const cookies = fs.readFileSync('cookies.json', 'utf8')

  const deserializedCookies = JSON.parse(cookies)
  await page.setCookie(...deserializedCookies)

  await page.goto(`https://github.com/${process.env.GITHUB_USER}`)

  await browser.close()
})()

Article


text:
Q: Segmentation fault when getch() is called Got this issue on termux (Android Linux terminal emulator) .
Here it is the ENTIRE code:
#include <ncurses.h>
int main() {
    initscr();
    getch();
    endwin();
}

I then compiled using this line:
g++ -lncurses prog.cpp

The package is ncurses-dev 6.1.20180331 (latest version)
P.S. even with refresh() it doesn't work.

A: The program must end if initscr returns null.
If initscr returns null, then it is not safe to execute further code in the program.
WINDOW * mainwin;

if ( (mainwin = initscr()) == NULL ) {
    /* Error handling here */
    exit(EXIT_FAILURE);
}

Reference:
http://www.paulgriffiths.net/program/c/srcs/curin1src.html


text:
Q: PHP If minimum value I have a while loop in PHP and I need to find the lowest number in a column of a table.
I have tried this:
$sql="SELECT * from pages order by menu_order ASC ";
$rs=mysql_query($sql,$conn) or die(mysql_error());
while($result=mysql_fetch_array($rs))
{
echo ''.$result["title"].'';
if($result["sequence"] == min)
{
//do something here
}
else
{
//do something else
}
}

but that didn't work - any ideas?

A: To find the min, try this one following,
$sql   = "SELECT * from pages order by menu_order ASC LIMIT BY (0,1)";
$r     = mysql_query($sql); // I don't like mysql_*
$d     = mysql_fetch_assoc($r);
$min   = $d['sequence'];

Now we know the min value. Let's implement it :)
$sql="SELECT * from pages order by menu_order ASC ";
$rs=mysql_query($sql,$conn) or die(mysql_error());
while($result=mysql_fetch_array($rs))
{
    echo ''.$result["title"].'';

    if($result["sequence"] == $min)   // Note that it's $min
    {
    //do something here
    }
    else
    {
    //do something else
    }
}

A: Try like this:
$sql="SELECT * FROM pages ORDER BY menu_order ASC LIMIT 1";
$rs=mysql_query($sql,$conn) or die(mysql_error());

A: You can use SQL to query the minimum value without needing to any extra PHP code.
$sql="SELECT MIN(sequence) FROM pages";

Run that query and you'll get the minimum value from the sequence field.


text:
Q: Do-while loop not paying attention to the while in java I'm trying to write a do while loop that will read a file that the user input and read it out and will loop until the user types end. The do part is working, but my while just isn't being activated and I'm struggling to figure out why.
public static void readingFiles() throws Exception {
    BufferedReader reader = null;
    Scanner input = null;
    boolean fileFound = true;
    do {
        System.out.print("Enter a file name or Type END to exit: ");

        input = new Scanner(System.in);

        if(input.hasNextLine())
                {
                    try {
                        File f = new File(input.nextLine());
                        reader = new BufferedReader(new FileReader(f));
                        String str = null;

                        while((str = reader.readLine()) != null)
                        {
                            System.out.println(str);
                        }

                    }
                    catch (FileNotFoundException e)
                    {
                        System.out.println("File Not Found. Please try again.");
                        fileFound = false;
                        continue;
                    }
                    catch (IOException e)
                    {
                        System.out.println("There was an IOException. Please try again.");
                        continue;
                    }
                    catch (Exception e)
                    {
                        System.out.println("There was an exception. Please try again.");
                        continue;
                    }
                    finally
                    {
                        {
                        if(fileFound)
                            reader.close();
                        }
            }
        }
     } while(!input.nextLine().equalsIgnoreCase("end"));
}

I've tried using an if statement before my input.hasNextLine() but then it would ignore the rest of the whole program and do nothing and only typing end would work. I've tried using && in my current if statement too but that didn't work. And I tried using a boolean that I set to true if string contained end. I think the problem may be in the input.hasNextLine but I'm not sure why or what to change it to?
Thanks for any help

A: Calling input.nextLine() again will not preserve your previous input string.
Store it in a variable, and compare that
public static void readingFiles() throws Exception {
    BufferedReader reader = null;
    String filename = null;
    Scanner input = new Scanner(System.in);
    boolean fileFound = true;
    do {
        System.out.print("Enter a file name or Type END to exit: ");
         if(input.hasNextLine()) {
             filename = input.nextLine();
                try {
                    File f = new File(filename);
                    // reader =
           ...
    } while (!filename.equalsIgnoreCase("end");


text:
Q: Trying to move Drupal install TO subdirectory Okay, so I've searched everywhere and while I can find plenty of stuff about moving a Drupal install out of a subdirectory I can't find anything on moving one into a subdirectory. I've recently taken over this project and it was developed without me so I've been landed in it here.
The problem is that the site was developed in the root of a dev server and I now have someone who wants it in a subdir. I've changed the base url in the htaccess and I've tried manually changing references in the CSS and DB but I can't be sure I've caught everything (modules etc).
What I want to know is, is there a way to force every link relative to the root to be relative to root/example instead. Basically everything that was once at www.example.com is now at www.example.com/subdirectory.
Thanks.

A: There's two pieces to this.  The first you've already done: configuring htaccess to set a base url that includes the subdirectory.
Unfortunately, you may have quite a few references in the node content (especially embedded images) that will stop working.
A relatively simple solution to this would be to include a <base href="foo.com/dir" /> tag in your site theme, but this isn't a great fix in the long term.
You can try modifying your database directly, through queries such as the following (use with care, backup your database ahead of time, etc):
UPDATE field_revision_body SET body_value = REPLACE(body_value, 'devdomain.com', 'proddomain.com/subdir') (add http:// into those queries)
You may also need to update the paths in your files table to reflect the new locations on disk, especially if you're using multisite.
Alternately, have you considered using the Backup & Migrate module to move content from the dev server to a new install at the new instance?


text:
Q: Does (M) Power Query have a Union of Tables? I am learning M (Power Query Language).  I'd like to use M to parse JSON from REST APIs.  For example one can use the Stack Overflow REST API.  I can see how to drill down into a simple JSON string using say
let
    Source = Json.Document("{ ""glossary"": { ""title"": ""example glossary"", ""GlossDiv"": { ""title"": ""S"", ""GlossList"": { ""GlossEntry"":
        { ""ID"": ""SGML"", ""SortAs"": ""SGML"", ""GlossTerm"": ""Standard Generalized Markup Language"", ""Acronym"": ""SGML"",
          ""Abbrev"": ""ISO 8879:1986"", ""GlossDef"": { ""para"": ""A meta-markup language, used to create markup languages such as DocBook."",
          ""GlossSeeAlso"": [""GML"", ""XML""] }, ""GlossSee"": ""markup"" } } } } }"),
    glossary = Source[glossary],
    GlossDiv = glossary[GlossDiv],
    GlossList = GlossDiv[GlossList],
    GlossEntry = GlossList[GlossEntry],
    ConvertedToTable = Record.ToTable(GlossEntry)
in
    ConvertedToTable

But what happens when I have a list from which I want to drill in and fetch a subproperty and then I want to return all of those like a SQL UNION query.  Actually it is more of a For Each type query.
So here is my non-working query that does not do a union but unfortunately glues the second record onto the side
let
    Source = "{""items"":["
       {""tags"":[""vba"",""permissions""],""owner"":
             {""reputation"":49,""user_id"":9073241,""user_type"":""registered"",""accept_rate"":86,""display_name"":""Kam""},
        ""is_answered"":false,""view_count"":4,""answer_count"":0,""score"":0,""question_id"":48229549},
       {""tags"":[""excel"",""vba"",""excel-vba""],""owner"":
             {""reputation"":18,""user_id"":9057704,""user_type"":""registered"",""accept_rate"":29,""display_name"":""Gregory""},
        ""is_answered"":false,""view_count"":6,""answer_count"":0,""score"":0,""question_id"":48229590}
       ]}",
    #"Parsed JSON" = Json.Document(Source),
    items = #"Parsed JSON"[items],
    item0 = items{0},
    owner0 = item0[owner],
    item1 = items{1},
    owner1 = item1[owner],
    #"Converted to Table" = Table.Combine( {Record.ToTable(owner0), Record.ToTable(owner1) })
in
    #"Converted to Table"

What I am really aiming for is this output but not limited to 2 records, but all the records from the list.  (The above sample source has been simplified from this REST API StackOverflow questions tagged VBA)
reputation  user_id user_type   accept_rate display_name
49          9073241 registered  86          Kam
18          9057704 registered  29          Gregory

A: I think you want to pivot your tables before you try to combine them. Try this query, for example.
let
    Source1 = Json.Document("{""tags"":[""vba"",""permissions""],""owner"":
             {""reputation"":49,""user_id"":9073241,""user_type"":""registered"",""accept_rate"":86,""display_name"":""Kam""},
        ""is_answered"":false,""view_count"":4,""answer_count"":0,""score"":0,""question_id"":48229549}"),
    Owner1 = Table.Pivot(Record.ToTable(Source1[owner]), List.Distinct(Record.ToTable(Source1[owner])[Name]), "Name", "Value"),
    Source2 = Json.Document("{""tags"":[""excel"",""vba"",""excel-vba""],""owner"":
             {""reputation"":18,""user_id"":9057704,""user_type"":""registered"",""accept_rate"":29,""display_name"":""Gregory""},
        ""is_answered"":false,""view_count"":6,""answer_count"":0,""score"":0,""question_id"":48229590}"),
    Owner2 = Table.Pivot(Record.ToTable(Source2[owner]), List.Distinct(Record.ToTable(Source2[owner])[Name]), "Name", "Value"),
    #"Appended Query" = Table.Combine({Owner1, Owner2})
in
    #"Appended Query"

If you just want to expand all of the owners, try a query more like this:
let
    Source = "{""items"":[{""tags"":[""vba"",""permissions""],""owner"":{""reputation"":49,""user_id"":9073241,""user_type"":""registered"",""accept_rate"":86,""display_name"":""Kam""},""is_answered"":false,""view_count"":4,""answer_count"":0,""score"":0,""question_id"":48229549},{""tags"":[""excel"",""vba"",""excel-vba""],""owner"":{""reputation"":18,""user_id"":9057704,""user_type"":""registered"",""accept_rate"":29,""display_name"":""Gregory""},""is_answered"":false,""view_count"":6,""answer_count"":0,""score"":0,""question_id"":48229590}]}",
    #"Parsed JSON" = Json.Document(Source),
    items = #"Parsed JSON"[items],
    #"Converted to Table" = Table.FromList(items, Splitter.SplitByNothing(), null, null, ExtraValues.Error),
    #"Expanded Column1" = Table.ExpandRecordColumn(#"Converted to Table", "Column1", {"owner"}, {"owner"}),
    #"Expanded owner" = Table.ExpandRecordColumn(#"Expanded Column1", "owner", {"reputation", "user_id", "user_type", "display_name"}, {"reputation", "user_id", "user_type", "display_name"})
in
    #"Expanded owner"